Overview

Namespaces

  • DataTables
    • Database
    • Editor
    • Vendor

Classes

  • DataTables\Database
  • DataTables\Database\Query
  • DataTables\Database\Result
  • DataTables\Editor
  • DataTables\Editor\Field
  • DataTables\Editor\Format
  • DataTables\Editor\Join
  • DataTables\Editor\MJoin
  • DataTables\Editor\Upload
  • DataTables\Editor\Validate
  • DataTables\Ext
  • DataTables\Vendor\Htmlaw
  • DataTables\Vendor\htmLawed
  • Overview
  • Namespace
  • Class
  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: 
447:         $joinField = isset($this->_join['table']) ? $this->_join['parent'][0] : $this->_join['parent'];
448:         $pkeyIsJoin = $pkey === $joinField || $pkey === $dteTable.'.'.$joinField;
449: 
450:         // Sanity check that table selector fields are read only, and have an name without
451:         // a dot (for DataTables mData to be able to read it)
452:         for ( $i=0 ; $i<count($this->_fields) ; $i++ ) {
453:             $field = $this->_fields[$i];
454: 
455:             if ( strpos( $field->dbField() , "." ) !== false ) {
456:                 if ( $field->set() !== Field::SET_NONE && $this->_set ) {
457:                     echo json_encode( array(
458:                         "sError" => "Table selected fields (i.e. '{table}.{column}') in `Join` ".
459:                             "must be read only. Use `set(false)` for the field to disable writing."
460:                     ) );
461:                     exit(0);
462:                 }
463: 
464:                 if ( strpos( $field->name() , "." ) !== false ) {
465:                     echo json_encode( array(
466:                         "sError" => "Table selected fields (i.e. '{table}.{column}') in `Join` ".
467:                             "must have a name alias which does not contain a period ('.'). Use ".
468:                             "name('---') to set a name for the field"
469:                     ) );
470:                     exit(0);
471:                 }
472:             }
473:         }
474: 
475:         // Set up the JOIN query
476:         $stmt = $db
477:             ->query( 'select' )
478:             ->get( $dteTableLocal.'.'.$joinField.' as dteditor_pkey' )
479:             ->get( $this->_fields('get') )
480:             ->table( $dteTable .' as '. $dteTableLocal );
481: 
482:         if ( $this->order() ) {
483:             $stmt->order( $this->order() );
484:         }
485: 
486:         $this->_apply_where( $stmt );
487: 
488:         if ( isset($this->_join['table']) ) {
489:             // Working with a link table
490:             $stmt
491:                 ->join(
492:                     $this->_join['table'],
493:                     $dteTableLocal.'.'.$this->_join['parent'][0] .' = '. $this->_join['table'].'.'.$this->_join['parent'][1]
494:                 )
495:                 ->join(
496:                     $this->_table,
497:                     $this->_table.'.'.$this->_join['child'][0] .' = '. $this->_join['table'].'.'.$this->_join['child'][1]
498:                 );
499:         }
500:         else {
501:             // No link table in the middle
502:             $stmt
503:                 ->join(
504:                     $this->_table,
505:                     $this->_table.'.'.$this->_join['child'] .' = '. $dteTableLocal.'.'.$this->_join['parent']
506:                 );
507:         }
508:         
509:         $res = $stmt->exec();
510:         if ( ! $res ) {
511:             return;
512:         }
513: 
514:         // Map to primary key for fast lookup
515:         $join = array();
516:         while ( $row=$res->fetch() ) {
517:             $inner = array();
518: 
519:             for ( $j=0 ; $j<count($this->_fields) ; $j++ ) {
520:                 $field = $this->_fields[$j];
521:                 if ( $field->apply('get') ) {
522:                     $inner[ $field->name() ] = $field->val('get', $row);
523:                 }
524:             }
525: 
526:             if ( $this->_type === 'object' ) {
527:                 $join[ $row['dteditor_pkey'] ] = $inner;
528:             }
529:             else {
530:                 if ( !isset( $join[ $row['dteditor_pkey'] ] ) ) {
531:                     $join[ $row['dteditor_pkey'] ] = array();
532:                 }
533:                 $join[ $row['dteditor_pkey'] ][] = $inner;
534:             }
535:         }
536: 
537:         // Check that the joining field is available
538:         // The joining key can come from the Editor instance's primary key, or
539:         // any other field. If the instance's pkey, then we've got that in the DT_RowId
540:         // parameter, so we can use that. Otherwise, the key must be in the field list.
541:         if ( !$pkeyIsJoin && count($data) > 0 && !isset($data[0][ $joinField ]) ) {
542:             echo json_encode( array(
543:                 "sError" => "Join was performed on the field '{$joinField}' which was not "
544:                     ."included in the Editor field list. The join field must be included "
545:                     ."as a regular field in the Editor instance."
546:             ) );
547:             exit(0);
548:         }
549: 
550:         // Loop over the data and do a join based on the data available
551:         for ( $i=0 ; $i<count($data) ; $i++ ) {
552:             $rowPKey = $pkeyIsJoin ? 
553:                 str_replace( $idPrefix, '', $data[$i]['DT_RowId'] ) :
554:                 $data[$i][ $joinField ];
555: 
556:             if ( isset( $join[$rowPKey] ) ) {
557:                 $data[$i][ $this->_name ] = $join[$rowPKey];
558:             }
559:             else {
560:                 $data[$i][ $this->_name ] = ($this->_type === 'object') ?
561:                     (object)array() : array();
562:             }
563:         }
564: 
565:         foreach ($this->_fields as $field) {
566:             $opts = $field->optionsExec( $db );
567: 
568:             if ( $opts !== false ) {
569:                 $name = $this->_table.
570:                     ($this->_type === 'object' ? '.' : '[].').
571:                     $field->name();
572:                 $options[ $name ] = $opts;
573:             }
574:         }
575:     }
576: 
577: 
578:     /**
579:      * Create a row.
580:      *  @param Editor $editor Host Editor instance
581:      *  @param int $parentId Parent row's primary key value
582:      *  @param string[] $data Data to be set for the join
583:      *  @internal
584:      */
585:     public function create ( $editor, $parentId, $data )
586:     {
587:         // If not settable, or the many count for the join was not submitted
588:         // there we do nothing
589:         if (
590:             ! $this->_set ||
591:             ! isset($data[$this->_name]) || 
592:             ! isset($data[$this->_name.'-many-count'])
593:         ) {
594:             return;
595:         }
596: 
597:         $this->_prep( $editor );
598:         $db = $editor->db();
599:         
600:         if ( $this->_type === 'object' ) {
601:             $this->_insert( $db, $parentId, $data[$this->_name] );
602:         }
603:         else {
604:             for ( $i=0 ; $i<count($data[$this->_name]) ; $i++ ) {
605:                 $this->_insert( $db, $parentId, $data[$this->_name][$i] );
606:             }
607:         }
608:     }
609: 
610: 
611:     /**
612:      * Update a row.
613:      *  @param Editor $editor Host Editor instance
614:      *  @param int $parentId Parent row's primary key value
615:      *  @param string[] $data Data to be set for the join
616:      *  @internal
617:      */
618:     public function update ( $editor, $parentId, $data )
619:     {
620:         // If not settable, or the many count for the join was not submitted
621:         // there we do nothing
622:         if ( ! $this->_set || ! isset($data[$this->_name.'-many-count']) ) {
623:             return;
624:         }
625: 
626:         $this->_prep( $editor );
627:         $db = $editor->db();
628:         
629:         if ( $this->_type === 'object' ) {
630:             // update or insert
631:             $this->_update_row( $db, $parentId, $data[$this->_name] );
632:         }
633:         else {
634:             // WARNING - this will remove rows and then readd them. Any
635:             // data not in the field list WILL BE LOST
636:             // todo - is there a better way of doing this?
637:             $this->remove( $editor, array($parentId) );
638:             $this->create( $editor, $parentId, $data );
639:         }
640:     }
641: 
642: 
643:     /**
644:      * Delete rows
645:      *  @param Editor $editor Host Editor instance
646:      *  @param int[] $ids Parent row IDs to delete
647:      *  @internal
648:      */
649:     public function remove ( $editor, $ids )
650:     {
651:         if ( ! $this->_set ) {
652:             return;
653:         }
654: 
655:         $this->_prep( $editor );
656:         $db = $editor->db();
657:         
658:         if ( isset($this->_join['table']) ) {
659:             $stmt = $db
660:                 ->query( 'delete' )
661:                 ->table( $this->_join['table'] )
662:                 ->or_where( $this->_join['parent'][1], $ids )
663:                 ->exec();
664:         }
665:         else {
666:             $stmt = $db
667:                 ->query( 'delete' )
668:                 ->table( $this->_table )
669:                 ->where_group( true )
670:                 ->or_where( $this->_join['child'], $ids )
671:                 ->where_group( false );
672: 
673:             $this->_apply_where( $stmt );
674: 
675:             $stmt->exec();
676:         }
677:     }
678: 
679: 
680:     /**
681:      * Validate input data
682:      *
683:      * @param &array $errors Errors array
684:      * @param Editor $editor Editor instance
685:      * @param string[] $data Data to validate
686:      * @internal
687:      */
688:     public function validate ( &$errors, $editor, $data )
689:     {
690:         if ( ! $this->_set || ! isset($data[$this->_name]) ) {
691:             return;
692:         }
693: 
694:         $this->_prep( $editor );
695: 
696:         $joinData = $data[$this->_name];
697: 
698:         if ( $this->_type === 'object' ) {
699:             $this->_validateFields( $errors, $editor, $joinData, $this->_name.'.' );
700:         }
701:         else {
702:             for ( $i=0 ; $i<count($joinData) ; $i++ ) {
703:                 $this->_validateFields( $errors, $editor, $joinData[$i], $this->_name.'[].' );
704:             }
705:         }
706:     }
707: 
708: 
709: 
710:     /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
711:      * Private methods
712:      */
713:     
714:     /**
715:      * Add local WHERE condition to query
716:      *  @param \DataTables\Database\Query $query Query instance to apply the WHERE conditions to
717:      *  @private
718:      */
719:     private function _apply_where ( $query )
720:     {
721:         for ( $i=0 ; $i<count($this->_where) ; $i++ ) {
722:             if ( is_callable( $this->_where[$i] ) ) {
723:                 $this->_where[$i]( $query );
724:             }
725:             else {
726:                 $query->where(
727:                     $this->_where[$i]['key'],
728:                     $this->_where[$i]['value'],
729:                     $this->_where[$i]['op']
730:                 );
731:             }
732:         }
733:     }
734: 
735: 
736:     /**
737:      * Create a row.
738:      *  @param \DataTables\Database $db Database reference to use
739:      *  @param int $parentId Parent row's primary key value
740:      *  @param string[] $data Data to be set for the join
741:      *  @private
742:      */
743:     private function _insert( $db, $parentId, $data )
744:     {
745:         if ( isset($this->_join['table']) ) {
746:             // Insert keys into the join table
747:             $stmt = $db
748:                 ->query('insert')
749:                 ->table( $this->_join['table'] )
750:                 ->set( $this->_join['parent'][1], $parentId )
751:                 ->set( $this->_join['child'][1], $data[$this->_join['child'][0]] )
752:                 ->exec();
753:         }
754:         else {
755:             // Insert values into the target table
756:             $stmt = $db
757:                 ->query('insert')
758:                 ->table( $this->_table )
759:                 ->set( $this->_join['child'], $parentId );
760: 
761:             for ( $i=0 ; $i<count($this->_fields) ; $i++ ) {
762:                 $field = $this->_fields[$i];
763: 
764:                 if ( $field->apply( 'set', $data ) ) {
765:                     $stmt->set( $field->dbField(), $field->val('set', $data) );
766:                 }
767:             }
768: 
769:             // If the where condition variables should also be added to the database
770:             // Note that `whereSet` is now deprecated
771:             if ( $this->_whereSet ) {
772:                 for ( $i=0, $ien=count($this->_where) ; $i<$ien ; $i++ ) {
773:                     if ( ! is_callable( $this->_where[$i] ) ) {
774:                         $stmt->set( $this->_where[$i]['key'], $this->_where[$i]['value'] );
775:                     }
776:                 }
777:             }
778: 
779:             $stmt->exec(); 
780:         }
781:     }
782: 
783: 
784:     /**
785:      * Prepare the instance to be run.
786:      *
787:      * @param  Editor $editor Editor instance
788:      * @private
789:      */
790:     private function _prep ( $editor )
791:     {
792:         $links = $this->_links;
793: 
794:         // Were links used to configure this instance - if so, we need to
795:         // back them onto the join array
796:         if ( $this->_join['parent'] === null && count($links) ) {
797:             $editorTable = $editor->table();
798:             $editorTable = $editorTable[0];
799:             $joinTable = $this->table();
800: 
801:             if ( $this->_aliasParentTable ) {
802:                 $editorTable = $this->_aliasParentTable;
803:             }
804: 
805:             if ( count( $links ) === 2 ) {
806:                 // No link table
807:                 $f1 = explode( '.', $links[0] );
808:                 $f2 = explode( '.', $links[1] );
809: 
810:                 if ( $f1[0] === $editorTable ) {
811:                     $this->_join['parent'] = $f1[1];
812:                     $this->_join['child'] = $f2[1];
813:                 }
814:                 else {
815:                     $this->_join['parent'] = $f2[1];
816:                     $this->_join['child'] = $f1[1];
817:                 }
818:             }
819:             else {
820:                 // Link table
821:                 $f1 = explode( '.', $links[0] );
822:                 $f2 = explode( '.', $links[1] );
823:                 $f3 = explode( '.', $links[2] );
824:                 $f4 = explode( '.', $links[3] );
825: 
826:                 // Discover the name of the link table
827:                 if ( $f1[0] !== $editorTable && $f1[0] !== $joinTable ) {
828:                     $this->_join['table'] = $f1[0];
829:                 }
830:                 else if ( $f2[0] !== $editorTable && $f2[0] !== $joinTable ) {
831:                     $this->_join['table'] = $f2[0];
832:                 }
833:                 else if ( $f3[0] !== $editorTable && $f3[0] !== $joinTable ) {
834:                     $this->_join['table'] = $f3[0];
835:                 }
836:                 else {
837:                     $this->_join['table'] = $f2[0];
838:                 }
839: 
840:                 $this->_join['parent'] = array( $f1[1], $f2[1] );
841:                 $this->_join['child'] = array( $f3[1], $f4[1] );
842:             }
843:         }
844:     }
845: 
846: 
847:     /**
848:      * Update a row.
849:      *  @param \DataTables\Database $db Database reference to use
850:      *  @param int $parentId Parent row's primary key value
851:      *  @param string[] $data Data to be set for the join
852:      *  @private
853:      */
854:     private function _update_row ( $db, $parentId, $data )
855:     {
856:         if ( isset($this->_join['table']) ) {
857:             // Got a link table, just insert the pkey references
858:             $db->push(
859:                 $this->_join['table'],
860:                 array(
861:                     $this->_join['parent'][1] => $parentId,
862:                     $this->_join['child'][1]  => $data[$this->_join['child'][0]]
863:                 ),
864:                 array(
865:                     $this->_join['parent'][1] => $parentId
866:                 )
867:             );
868:         }
869:         else {
870:             // No link table, just a direct reference
871:             $set = array(
872:                 $this->_join['child'] => $parentId
873:             );
874: 
875:             for ( $i=0 ; $i<count($this->_fields) ; $i++ ) {
876:                 $field = $this->_fields[$i];
877: 
878:                 if ( $field->apply( 'set', $data ) ) {
879:                     $set[ $field->dbField() ] = $field->val('set', $data);
880:                 }
881:             }
882: 
883:             // Add WHERE conditions
884:             $where = array($this->_join['child'] => $parentId);
885:             for ( $i=0, $ien=count($this->_where) ; $i<$ien ; $i++ ) {
886:                 $where[ $this->_where[$i]['key'] ] = $this->_where[$i]['value'];
887: 
888:                 // Is there any point in this? Is there any harm?
889:                 // Note that `whereSet` is now deprecated
890:                 if ( $this->_whereSet ) {
891:                     if ( ! is_callable( $this->_where[$i] ) ) {
892:                         $set[ $this->_where[$i]['key'] ] = $this->_where[$i]['value'];
893:                     }
894:                 }
895:             }
896: 
897:             $db->push( $this->_table, $set, $where );
898:         }
899:     }
900: 
901: 
902:     /**
903:      * Create an SQL string from the fields that this instance knows about for
904:      * using in queries
905:      *  @param string $direction Direction: 'get' or 'set'.
906:      *  @returns array Fields to include
907:      *  @private
908:      */
909:     private function _fields ( $direction )
910:     {
911:         $fields = array();
912: 
913:         for ( $i=0 ; $i<count($this->_fields) ; $i++ ) {
914:             $field = $this->_fields[$i];
915: 
916:             if ( $field->apply( $direction, null ) ) {
917:                 if ( strpos( $field->dbField() , "." ) === false ) {
918:                     $fields[] = $this->_table.'.'.$field->dbField() ." as ".$field->dbField();;
919:                 }
920:                 else {
921:                     $fields[] = $field->dbField();// ." as ".$field->dbField();
922:                 }
923:             }
924:         }
925: 
926:         return $fields;
927:     }
928: 
929: 
930:     /**
931:      * Validate input data
932:      *
933:      * @param &array $errors Errors array
934:      * @param Editor $editor Editor instance
935:      * @param string[] $data Data to validate
936:      * @param string $prefix Field error prefix for client-side to show the
937:      *   error message on the appropriate field
938:      * @internal
939:      */
940:     private function _validateFields ( &$errors, $editor, $data, $prefix )
941:     {
942:         for ( $i=0 ; $i<count($this->_fields) ; $i++ ) {
943:             $field = $this->_fields[$i];
944:             $validation = $field->validate( $data, $editor );
945: 
946:             if ( $validation !== true ) {
947:                 $errors[] = array(
948:                     "name" => $prefix.$field->name(),
949:                     "status" => $validation
950:                 );
951:             }
952:         }
953:     }
954: }
955: 
956: 
DataTables Editor 1.5.6 - PHP 5.3+ libraries API documentation generated by ApiGen