1: <?php
2: /**
3: * DataTables PHP libraries.
4: *
5: * PHP libraries for DataTables and DataTables Editor, utilising PHP 5.3+.
6: *
7: * @author SpryMedia
8: * @copyright 2012 SpryMedia ( http://sprymedia.co.uk )
9: * @license http://editor.datatables.net/license DataTables Editor
10: * @link http://editor.datatables.net
11: */
12:
13: namespace DataTables\Editor;
14: if (!defined('DATATABLES')) exit();
15:
16: use
17: DataTables,
18: DataTables\Editor,
19: DataTables\Editor\Field;
20:
21:
22: /**
23: * Join table class for DataTables Editor.
24: *
25: * The Join class can be used with {@link Editor::join} to allow Editor to
26: * obtain joined information from the database.
27: *
28: * For an overview of how Join tables work, please refer to the
29: * {@link http://editor.datatables.net/manual/php/ Editor manual} as it is
30: * useful to understand how this class represents the links between tables,
31: * before fully getting to grips with it's API.
32: *
33: * @example
34: * Join the parent table (the one specified in the {@link Editor::table}
35: * method) with the table *access*, with a link table *user__access*, which
36: * allows multiple properties to be found for each row in the parent table.
37: * <code>
38: * Join::inst( 'access', 'array' )
39: * ->link( 'users.id', 'user_access.user_id' )
40: * ->link( 'access.id', 'user_access.access_id' )
41: * ->field(
42: * Field::inst( 'id' )->validator( 'Validate::required' ),
43: * Field::inst( 'name' )
44: * )
45: * </code>
46: *
47: * @example
48: * Single row join - here we join the parent table with a single row in
49: * the child table, without an intermediate link table. In this case the
50: * child table is called *extra* and the two fields give the columns that
51: * Editor will read from that table.
52: * <code>
53: * Join::inst( 'extra', 'object' )
54: * ->link( 'user.id', 'extra.user_id' )
55: * ->field(
56: * Field::inst( 'comments' ),
57: * Field::inst( 'review' )
58: * )
59: * </code>
60: */
61: class Join extends DataTables\Ext {
62: /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
63: * Constructor
64: */
65:
66: /**
67: * Join instance constructor.
68: * @param string $table Table name to get the joined data from.
69: * @param string $type Work with a single result ('object') or an array of
70: * results ('array') for the join.
71: */
72: function __construct( $table=null, $type='object' )
73: {
74: $this->table( $table );
75: $this->type( $type );
76: }
77:
78:
79: /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
80: * Private properties
81: */
82:
83: /** @var DataTables\Editor\Field[] */
84: private $_fields = array();
85:
86: /** @var array */
87: private $_join = array(
88: "parent" => null,
89: "child" => null,
90: "table" => null
91: );
92:
93: /** @var string */
94: private $_table = null;
95:
96: /** @var string */
97: private $_type = null;
98:
99: /** @var string */
100: private $_name = null;
101:
102: /** @var boolean */
103: private $_get = true;
104:
105: /** @var boolean */
106: private $_set = true;
107:
108: /** @var string */
109: private $_aliasParentTable = null;
110:
111: /** @var array */
112: private $_where = array();
113:
114: /** @var boolean */
115: private $_whereSet = false;
116:
117: /** @var array */
118: private $_links = array();
119:
120: /** @var string */
121: private $_customOrder = null;
122:
123:
124: /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
125: * Public methods
126: */
127:
128: /**
129: * Get / set parent table alias.
130: *
131: * When working with a self referencing table (i.e. a column in the table contains
132: * a primary key value from its own table) it can be useful to set an alias on the
133: * parent table's name, allowing a self referencing Join. For example:
134: * <code>
135: * SELECT p2.publisher
136: * FROM publisher as p2
137: * JOIN publisher on (publisher.idPublisher = p2.idPublisher)
138: * <code>
139: * Where, in this case, `publisher` is the table that is used by the Editor instance,
140: * and you want to use `Join` to link back to the table (resolving a name for example).
141: * This method allows that alias to be set. Fields can then use standard SQL notation
142: * to select a field, for example `p2.publisher` or `publisher.publisher`.
143: * @param string $_ Table alias to use
144: * @return string|self Table alias set (which is null by default), or self if used as
145: * a setter.
146: */
147: public function aliasParentTable ( $_=null )
148: {
149: return $this->_getSet( $this->_aliasParentTable, $_ );
150: }
151:
152:
153: /**
154: * Get / set field instances.
155: *
156: * The list of fields designates which columns in the table that will be read
157: * from the joined table.
158: * @param Field $_... Instances of the {@link Field} class, given as a single
159: * instance of {@link Field}, an array of {@link Field} instances, or multiple
160: * {@link Field} instance parameters for the function.
161: * @return Field[]|self Array of fields, or self if used as a setter.
162: * @see {@link Field} for field documentation.
163: */
164: public function field ( $_=null )
165: {
166: if ( $_ !== null && !is_array($_) ) {
167: $_ = func_get_args();
168: }
169: return $this->_getSet( $this->_fields, $_, true );
170: }
171:
172:
173: /**
174: * Get / set field instances.
175: *
176: * An alias of {@link field}, for convenience.
177: * @param Field $_... Instances of the {@link Field} class, given as a single
178: * instance of {@link Field}, an array of {@link Field} instances, or multiple
179: * {@link Field} instance parameters for the function.
180: * @return Field[]|self Array of fields, or self if used as a setter.
181: * @see {@link Field} for field documentation.
182: */
183: public function fields ( $_=null )
184: {
185: if ( $_ !== null && !is_array($_) ) {
186: $_ = func_get_args();
187: }
188: return $this->_getSet( $this->_fields, $_, true );
189: }
190:
191:
192: /**
193: * Get / set get attribute.
194: *
195: * When set to false no read operations will occur on the join tables.
196: * @param boolean $_ Value
197: * @return boolean|self Name
198: */
199: public function get ( $_=null )
200: {
201: return $this->_getSet( $this->_get, $_ );
202: }
203:
204:
205: /**
206: * Get / set join properties.
207: *
208: * Define how the SQL will be performed, on what columns. There are
209: * basically two types of join that are supported by Editor here, a direct
210: * foreign key reference in the join table to the parent table's primary
211: * key, or a link table that contains just primary keys for the parent and
212: * child tables (this approach is usually used with a {@link type} of
213: * 'array' since you can often have multiple links between the two tables,
214: * while a direct foreign key reference will typically use a type of
215: * 'object' (i.e. a single entry).
216: *
217: * @param string|string[] $parent Parent table's primary key names. If used
218: * with a link table (i.e. third parameter to this method is given, then
219: * an array should be used, with the first element being the pkey's name
220: * in the parent table, and the second element being the key's name in
221: * the link table.
222: * @param string|string[] $child Child table's primary key names. If used
223: * with a link table (i.e. third parameter to this method is given, then
224: * an array should be used, with the first element being the pkey's name
225: * in the child table, and the second element being the key's name in the
226: * link table.
227: * @param string $table Join table name, if using a link table
228: * @returns Join This for chaining
229: * @deprecated 1.5 Please use the {@link link} method rather than this
230: * method now.
231: */
232: public function join ( $parent=null, $child=null, $table=null )
233: {
234: if ( $parent === null && $child === null ) {
235: return $this->_join;
236: }
237:
238: $this->_join['parent'] = $parent;
239: $this->_join['child'] = $child;
240: $this->_join['table'] = $table;
241: return $this;
242: }
243:
244:
245: /**
246: * Create a join link between two tables. The order of the fields does not
247: * matter, but each field must contain the table name as well as the field
248: * name.
249: *
250: * This method can be called a maximum of two times for an Mjoin instance:
251: *
252: * * First time, creates a link between the Editor host table and a join
253: * table
254: * * Second time creates the links required for a link table.
255: *
256: * Please refer to the Editor Mjoin documentation for further details:
257: * https://editor.datatables.net/manual/php
258: *
259: * @param string $field1 Table and field name
260: * @param string $field2 Table and field name
261: * @return Join Self for chaining
262: * @throws \Exception Link limitations
263: */
264: public function link ( $field1, $field2 )
265: {
266: if ( strpos($field1, '.') === false || strpos($field2, '.') === false ) {
267: throw new \Exception("Link fields must contain both the table name and the column name");
268: }
269:
270: if ( count( $this->_links ) >= 4 ) {
271: throw new \Exception("Link method cannot be called more than twice for a single instance");
272: }
273:
274: $this->_links[] = $field1;
275: $this->_links[] = $field2;
276:
277: return $this;
278: }
279:
280:
281: /**
282: * Specify the property that the data will be sorted by.
283: *
284: * @param string $order SQL column name to order the data by
285: * @return Join Self for chaining
286: */
287: public function order ( $_=null )
288: {
289: // How this works is by setting the SQL order by clause, and since the
290: // join that is done in PHP is always done sequentially, the order is
291: // retained.
292: return $this->_getSet( $this->_customOrder, $_ );
293: }
294:
295:
296: /**
297: * Get / set name.
298: *
299: * The `name` of the Join is the JSON property key that is used when
300: * 'getting' the data, and the HTTP property key (in a JSON style) when
301: * 'setting' data. Typically the name of the db table will be used here,
302: * but this method allows that to be overridden.
303: * @param string $_ Field name
304: * @return String|self Name
305: */
306: public function name ( $_=null )
307: {
308: return $this->_getSet( $this->_name, $_ );
309: }
310:
311:
312: /**
313: * Get / set set attribute.
314: *
315: * When set to false no write operations will occur on the join tables.
316: * This can be useful when you want to display information which is joined,
317: * but want to only perform write operations on the parent table.
318: * @param boolean $_ Value
319: * @return boolean|self Name
320: */
321: public function set ( $_=null )
322: {
323: return $this->_getSet( $this->_set, $_ );
324: }
325:
326:
327: /**
328: * Get / set join table name.
329: *
330: * Please note that this will also set the {@link name} used by the Join
331: * as well. This is for convenience as the JSON output / HTTP input will
332: * typically use the same name as the database name. If you want to set a
333: * custom name, the {@link name} method must be called ***after*** this one.
334: * @param string $_ Name of the table to read the join data from
335: * @return String|self Name of the join table, or self if used as a setter.
336: */
337: public function table ( $_=null )
338: {
339: if ( $_ !== null ) {
340: $this->_name = $_;
341: }
342: return $this->_getSet( $this->_table, $_ );
343: }
344:
345:
346: /**
347: * Get / set the join type.
348: *
349: * The join type allows the data that is returned from the join to be given
350: * as an array (i.e. working with multiple possibly results for each record from
351: * the parent table), or as an object (i.e. working which one and only one result
352: * for each record form the parent table).
353: * @param string $_ Join type ('object') or an array of
354: * results ('array') for the join.
355: * @return String|self Join type, or self if used as a setter.
356: */
357: public function type ( $_=null )
358: {
359: return $this->_getSet( $this->_type, $_ );
360: }
361:
362:
363: /**
364: * Where condition to add to the query used to get data from the database.
365: * Note that this is applied to the child table.
366: *
367: * Can be used in two different ways:
368: *
369: * * Simple case: `where( field, value, operator )`
370: * * Complex: `where( fn )`
371: *
372: * @param string|callable $key Single field name or a closure function
373: * @param string|string[] $value Single field value, or an array of values.
374: * @param string $op Condition operator: <, >, = etc
375: * @return string[]|self Where condition array, or self if used as a setter.
376: */
377: public function where ( $key=null, $value=null, $op='=' )
378: {
379: if ( $key === null ) {
380: return $this->_where;
381: }
382:
383: if ( is_callable($key) && is_object($key) ) {
384: $this->_where[] = $key;
385: }
386: else {
387: $this->_where[] = array(
388: "key" => $key,
389: "value" => $value,
390: "op" => $op
391: );
392: }
393:
394: return $this;
395: }
396:
397:
398: /**
399: * Get / set if the WHERE conditions should be included in the create and
400: * edit actions.
401: *
402: * This means that the fields which have been used as part of the 'get'
403: * WHERE condition (using the `where()` method) will be set as the values
404: * given.
405: *
406: * This is default false (i.e. they are not included).
407: *
408: * @param boolean $_ Include (`true`), or not (`false`)
409: * @return boolean Current value
410: */
411: public function whereSet ( $_=null )
412: {
413: return $this->_getSet( $this->_whereSet, $_ );
414: }
415:
416:
417:
418: /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
419: * Internal methods
420: */
421:
422: /**
423: * Get data
424: * @param Editor $editor Host Editor instance
425: * @param string[] $data Data from the parent table's get and were we need
426: * to add out output.
427: * @param array $options options array for fields
428: * @internal
429: */
430: public function data( $editor, &$data, &$options )
431: {
432: if ( ! $this->_get ) {
433: return;
434: }
435:
436: $this->_prep( $editor );
437: $db = $editor->db();
438: $dteTable = $editor->table();
439: $pkey = $editor->pkey();
440: $idPrefix = $editor->idPrefix();
441:
442: $dteTable = $dteTable[0];
443: $dteTableLocal = $this->_aliasParentTable ? // Can be aliased to allow a self join
444: $this->_aliasParentTable :
445: $dteTable;
446: $joinField = isset($this->_join['table']) ?
447: $this->_join['parent'][0] :
448: $this->_join['parent'];
449:
450: // This is something that will likely come in a future version, but it
451: // is a relatively low use feature. Please get in touch if this is
452: // something you require.
453: if ( count( $pkey ) > 1 ) {
454: throw new \Exception("MJoin is not currently supported with a compound primary key for the main table", 1);
455: }
456:
457: $pkey = $pkey[0];
458: $pkeyIsJoin = $pkey === $joinField || $pkey === $dteTable.'.'.$joinField;
459:
460: // Sanity check that table selector fields are read only, and have an name without
461: // a dot (for DataTables mData to be able to read it)
462: for ( $i=0 ; $i<count($this->_fields) ; $i++ ) {
463: $field = $this->_fields[$i];
464:
465: if ( strpos( $field->dbField() , "." ) !== false ) {
466: if ( $field->set() !== Field::SET_NONE && $this->_set ) {
467: echo json_encode( array(
468: "sError" => "Table selected fields (i.e. '{table}.{column}') in `Join` ".
469: "must be read only. Use `set(false)` for the field to disable writing."
470: ) );
471: exit(0);
472: }
473:
474: if ( strpos( $field->name() , "." ) !== false ) {
475: echo json_encode( array(
476: "sError" => "Table selected fields (i.e. '{table}.{column}') in `Join` ".
477: "must have a name alias which does not contain a period ('.'). Use ".
478: "name('---') to set a name for the field"
479: ) );
480: exit(0);
481: }
482: }
483: }
484:
485: // Set up the JOIN query
486: $stmt = $db
487: ->query( 'select' )
488: ->distinct( true )
489: ->get( $dteTableLocal.'.'.$joinField.' as dteditor_pkey' )
490: ->get( $this->_fields('get') )
491: ->table( $dteTable .' as '. $dteTableLocal );
492:
493: if ( $this->order() ) {
494: $stmt->order( $this->order() );
495: }
496:
497: $this->_apply_where( $stmt );
498:
499: if ( isset($this->_join['table']) ) {
500: // Working with a link table
501: $stmt
502: ->join(
503: $this->_join['table'],
504: $dteTableLocal.'.'.$this->_join['parent'][0] .' = '. $this->_join['table'].'.'.$this->_join['parent'][1]
505: )
506: ->join(
507: $this->_table,
508: $this->_table.'.'.$this->_join['child'][0] .' = '. $this->_join['table'].'.'.$this->_join['child'][1]
509: );
510: }
511: else {
512: // No link table in the middle
513: $stmt
514: ->join(
515: $this->_table,
516: $this->_table.'.'.$this->_join['child'] .' = '. $dteTableLocal.'.'.$this->_join['parent']
517: );
518: }
519:
520: $res = $stmt->exec();
521: if ( ! $res ) {
522: return;
523: }
524:
525: // Map to primary key for fast lookup
526: $join = array();
527: while ( $row=$res->fetch() ) {
528: $inner = array();
529:
530: for ( $j=0 ; $j<count($this->_fields) ; $j++ ) {
531: $field = $this->_fields[$j];
532: if ( $field->apply('get') ) {
533: $inner[ $field->name() ] = $field->val('get', $row);
534: }
535: }
536:
537: if ( $this->_type === 'object' ) {
538: $join[ $row['dteditor_pkey'] ] = $inner;
539: }
540: else {
541: if ( !isset( $join[ $row['dteditor_pkey'] ] ) ) {
542: $join[ $row['dteditor_pkey'] ] = array();
543: }
544: $join[ $row['dteditor_pkey'] ][] = $inner;
545: }
546: }
547:
548: if ( count($data) > 0 ) {
549: // Check that the joining field is available. The joining key can
550: // come from the Editor instance's primary key, or any other field,
551: // including a nested value (from a left join). If the instance's
552: // pkey, then we've got that in the DT_RowId parameter, so we can
553: // use that. Otherwise, the key must be in the field list.
554: if ( $this->_propExists( $dteTable.'.'.$joinField, $data[0] ) ) {
555: $readField = $dteTable.'.'.$joinField;
556: }
557: else if ( $this->_propExists( $joinField, $data[0] ) ) {
558: $readField = $joinField;
559: }
560: else if ( ! $pkeyIsJoin ) {
561: echo json_encode( array(
562: "sError" => "Join was performed on the field '{$joinField}' which was not "
563: ."included in the Editor field list. The join field must be included "
564: ."as a regular field in the Editor instance."
565: ) );
566: exit(0);
567: }
568:
569: // Loop over the data and do a join based on the data available
570: for ( $i=0 ; $i<count($data) ; $i++ ) {
571: $rowPKey = $pkeyIsJoin ?
572: str_replace( $idPrefix, '', $data[$i]['DT_RowId'] ) :
573: $this->_readProp( $readField, $data[$i] );
574:
575: if ( isset( $join[$rowPKey] ) ) {
576: $data[$i][ $this->_name ] = $join[$rowPKey];
577: }
578: else {
579: $data[$i][ $this->_name ] = ($this->_type === 'object') ?
580: (object)array() : array();
581: }
582: }
583: }
584:
585: // Field options
586: foreach ($this->_fields as $field) {
587: $opts = $field->optionsExec( $db );
588:
589: if ( $opts !== false ) {
590: $name = $this->name().
591: ($this->_type === 'object' ? '.' : '[].').
592: $field->name();
593: $options[ $name ] = $opts;
594: }
595: }
596: }
597:
598:
599: /**
600: * Create a row.
601: * @param Editor $editor Host Editor instance
602: * @param int $parentId Parent row's primary key value
603: * @param string[] $data Data to be set for the join
604: * @internal
605: */
606: public function create ( $editor, $parentId, $data )
607: {
608: // If not settable, or the many count for the join was not submitted
609: // there we do nothing
610: if (
611: ! $this->_set ||
612: ! isset($data[$this->_name]) ||
613: ! isset($data[$this->_name.'-many-count'])
614: ) {
615: return;
616: }
617:
618: $this->_prep( $editor );
619: $db = $editor->db();
620:
621: if ( $this->_type === 'object' ) {
622: $this->_insert( $db, $parentId, $data[$this->_name] );
623: }
624: else {
625: for ( $i=0 ; $i<count($data[$this->_name]) ; $i++ ) {
626: $this->_insert( $db, $parentId, $data[$this->_name][$i] );
627: }
628: }
629: }
630:
631:
632: /**
633: * Update a row.
634: * @param Editor $editor Host Editor instance
635: * @param int $parentId Parent row's primary key value
636: * @param string[] $data Data to be set for the join
637: * @internal
638: */
639: public function update ( $editor, $parentId, $data )
640: {
641: // If not settable, or the many count for the join was not submitted
642: // there we do nothing
643: if ( ! $this->_set || ! isset($data[$this->_name.'-many-count']) ) {
644: return;
645: }
646:
647: $this->_prep( $editor );
648: $db = $editor->db();
649:
650: if ( $this->_type === 'object' ) {
651: // update or insert
652: $this->_update_row( $db, $parentId, $data[$this->_name] );
653: }
654: else {
655: // WARNING - this will remove rows and then readd them. Any
656: // data not in the field list WILL BE LOST
657: // todo - is there a better way of doing this?
658: $this->remove( $editor, array($parentId) );
659: $this->create( $editor, $parentId, $data );
660: }
661: }
662:
663:
664: /**
665: * Delete rows
666: * @param Editor $editor Host Editor instance
667: * @param int[] $ids Parent row IDs to delete
668: * @internal
669: */
670: public function remove ( $editor, $ids )
671: {
672: if ( ! $this->_set ) {
673: return;
674: }
675:
676: $that = $this;
677: $this->_prep( $editor );
678: $db = $editor->db();
679:
680: if ( isset($this->_join['table']) ) {
681: $stmt = $db
682: ->query( 'delete' )
683: ->table( $this->_join['table'] )
684: ->or_where( $this->_join['parent'][1], $ids )
685: ->exec();
686: }
687: else {
688: $stmt = $db
689: ->query( 'delete' )
690: ->table( $this->_table )
691: ->where_group( function ( $q ) use ( $that, $ids ) {
692: $q->or_where( $that->_join['child'], $ids );
693: } );
694:
695: $this->_apply_where( $stmt );
696:
697: $stmt->exec();
698: }
699: }
700:
701:
702: /**
703: * Validate input data
704: *
705: * @param &array $errors Errors array
706: * @param Editor $editor Editor instance
707: * @param string[] $data Data to validate
708: * @internal
709: */
710: public function validate ( &$errors, $editor, $data )
711: {
712: if ( ! $this->_set || ! isset($data[$this->_name]) ) {
713: return;
714: }
715:
716: $this->_prep( $editor );
717:
718: $joinData = $data[$this->_name];
719:
720: if ( $this->_type === 'object' ) {
721: $this->_validateFields( $errors, $editor, $joinData, $this->_name.'.' );
722: }
723: else {
724: for ( $i=0 ; $i<count($joinData) ; $i++ ) {
725: $this->_validateFields( $errors, $editor, $joinData[$i], $this->_name.'[].' );
726: }
727: }
728: }
729:
730:
731:
732: /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
733: * Private methods
734: */
735:
736: /**
737: * Add local WHERE condition to query
738: * @param \DataTables\Database\Query $query Query instance to apply the WHERE conditions to
739: * @private
740: */
741: private function _apply_where ( $query )
742: {
743: for ( $i=0 ; $i<count($this->_where) ; $i++ ) {
744: if ( is_callable( $this->_where[$i] ) ) {
745: $this->_where[$i]( $query );
746: }
747: else {
748: $query->where(
749: $this->_where[$i]['key'],
750: $this->_where[$i]['value'],
751: $this->_where[$i]['op']
752: );
753: }
754: }
755: }
756:
757:
758: /**
759: * Create a row.
760: * @param \DataTables\Database $db Database reference to use
761: * @param int $parentId Parent row's primary key value
762: * @param string[] $data Data to be set for the join
763: * @private
764: */
765: private function _insert( $db, $parentId, $data )
766: {
767: if ( isset($this->_join['table']) ) {
768: // Insert keys into the join table
769: $stmt = $db
770: ->query('insert')
771: ->table( $this->_join['table'] )
772: ->set( $this->_join['parent'][1], $parentId )
773: ->set( $this->_join['child'][1], $data[$this->_join['child'][0]] )
774: ->exec();
775: }
776: else {
777: // Insert values into the target table
778: $stmt = $db
779: ->query('insert')
780: ->table( $this->_table )
781: ->set( $this->_join['child'], $parentId );
782:
783: for ( $i=0 ; $i<count($this->_fields) ; $i++ ) {
784: $field = $this->_fields[$i];
785:
786: if ( $field->apply( 'set', $data ) ) { // TODO should be create or edit
787: $stmt->set( $field->dbField(), $field->val('set', $data) );
788: }
789: }
790:
791: // If the where condition variables should also be added to the database
792: // Note that `whereSet` is now deprecated
793: if ( $this->_whereSet ) {
794: for ( $i=0, $ien=count($this->_where) ; $i<$ien ; $i++ ) {
795: if ( ! is_callable( $this->_where[$i] ) ) {
796: $stmt->set( $this->_where[$i]['key'], $this->_where[$i]['value'] );
797: }
798: }
799: }
800:
801: $stmt->exec();
802: }
803: }
804:
805:
806: /**
807: * Prepare the instance to be run.
808: *
809: * @param Editor $editor Editor instance
810: * @private
811: */
812: private function _prep ( $editor )
813: {
814: $links = $this->_links;
815:
816: // Were links used to configure this instance - if so, we need to
817: // back them onto the join array
818: if ( $this->_join['parent'] === null && count($links) ) {
819: $editorTable = $editor->table();
820: $editorTable = $editorTable[0];
821: $joinTable = $this->table();
822:
823: if ( $this->_aliasParentTable ) {
824: $editorTable = $this->_aliasParentTable;
825: }
826:
827: if ( count( $links ) === 2 ) {
828: // No link table
829: $f1 = explode( '.', $links[0] );
830: $f2 = explode( '.', $links[1] );
831:
832: if ( $f1[0] === $editorTable ) {
833: $this->_join['parent'] = $f1[1];
834: $this->_join['child'] = $f2[1];
835: }
836: else {
837: $this->_join['parent'] = $f2[1];
838: $this->_join['child'] = $f1[1];
839: }
840: }
841: else {
842: // Link table
843: $f1 = explode( '.', $links[0] );
844: $f2 = explode( '.', $links[1] );
845: $f3 = explode( '.', $links[2] );
846: $f4 = explode( '.', $links[3] );
847:
848: // Discover the name of the link table
849: if ( $f1[0] !== $editorTable && $f1[0] !== $joinTable ) {
850: $this->_join['table'] = $f1[0];
851: }
852: else if ( $f2[0] !== $editorTable && $f2[0] !== $joinTable ) {
853: $this->_join['table'] = $f2[0];
854: }
855: else if ( $f3[0] !== $editorTable && $f3[0] !== $joinTable ) {
856: $this->_join['table'] = $f3[0];
857: }
858: else {
859: $this->_join['table'] = $f4[0];
860: }
861:
862: $this->_join['parent'] = array( $f1[1], $f2[1] );
863: $this->_join['child'] = array( $f3[1], $f4[1] );
864: }
865: }
866: }
867:
868:
869: /**
870: * Update a row.
871: * @param \DataTables\Database $db Database reference to use
872: * @param int $parentId Parent row's primary key value
873: * @param string[] $data Data to be set for the join
874: * @private
875: */
876: private function _update_row ( $db, $parentId, $data )
877: {
878: if ( isset($this->_join['table']) ) {
879: // Got a link table, just insert the pkey references
880: $db->push(
881: $this->_join['table'],
882: array(
883: $this->_join['parent'][1] => $parentId,
884: $this->_join['child'][1] => $data[$this->_join['child'][0]]
885: ),
886: array(
887: $this->_join['parent'][1] => $parentId
888: )
889: );
890: }
891: else {
892: // No link table, just a direct reference
893: $set = array(
894: $this->_join['child'] => $parentId
895: );
896:
897: for ( $i=0 ; $i<count($this->_fields) ; $i++ ) {
898: $field = $this->_fields[$i];
899:
900: if ( $field->apply( 'set', $data ) ) {
901: $set[ $field->dbField() ] = $field->val('set', $data);
902: }
903: }
904:
905: // Add WHERE conditions
906: $where = array($this->_join['child'] => $parentId);
907: for ( $i=0, $ien=count($this->_where) ; $i<$ien ; $i++ ) {
908: $where[ $this->_where[$i]['key'] ] = $this->_where[$i]['value'];
909:
910: // Is there any point in this? Is there any harm?
911: // Note that `whereSet` is now deprecated
912: if ( $this->_whereSet ) {
913: if ( ! is_callable( $this->_where[$i] ) ) {
914: $set[ $this->_where[$i]['key'] ] = $this->_where[$i]['value'];
915: }
916: }
917: }
918:
919: $db->push( $this->_table, $set, $where );
920: }
921: }
922:
923:
924: /**
925: * Create an SQL string from the fields that this instance knows about for
926: * using in queries
927: * @param string $direction Direction: 'get' or 'set'.
928: * @returns array Fields to include
929: * @private
930: */
931: private function _fields ( $direction )
932: {
933: $fields = array();
934:
935: for ( $i=0 ; $i<count($this->_fields) ; $i++ ) {
936: $field = $this->_fields[$i];
937:
938: if ( $field->apply( $direction, null ) ) {
939: if ( strpos( $field->dbField() , "." ) === false ) {
940: $fields[] = $this->_table.'.'.$field->dbField() ." as ".$field->dbField();;
941: }
942: else {
943: $fields[] = $field->dbField();// ." as ".$field->dbField();
944: }
945: }
946: }
947:
948: return $fields;
949: }
950:
951:
952: /**
953: * Validate input data
954: *
955: * @param &array $errors Errors array
956: * @param Editor $editor Editor instance
957: * @param string[] $data Data to validate
958: * @param string $prefix Field error prefix for client-side to show the
959: * error message on the appropriate field
960: * @internal
961: */
962: private function _validateFields ( &$errors, $editor, $data, $prefix )
963: {
964: for ( $i=0 ; $i<count($this->_fields) ; $i++ ) {
965: $field = $this->_fields[$i];
966: $validation = $field->validate( $data, $editor );
967:
968: if ( $validation !== true ) {
969: $errors[] = array(
970: "name" => $prefix.$field->name(),
971: "status" => $validation
972: );
973: }
974: }
975: }
976: }
977:
978: