-
Notifications
You must be signed in to change notification settings - Fork 18
/
Copy pathTable.php
3102 lines (2831 loc) · 107 KB
/
Table.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php
declare(strict_types=1);
/**
* CakePHP(tm) : Rapid Development Framework (https://cakephp.org)
* Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
*
* Licensed under The MIT License
* For full copyright and license information, please see the LICENSE.txt
* Redistributions of files must retain the above copyright notice.
*
* @copyright Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
* @link https://cakephp.org CakePHP(tm) Project
* @since 3.0.0
* @license https://opensource.org/licenses/mit-license.php MIT License
*/
namespace Cake\ORM;
use ArrayObject;
use BadMethodCallException;
use Cake\Core\App;
use Cake\Core\Configure;
use Cake\Database\Connection;
use Cake\Database\Schema\TableSchemaInterface;
use Cake\Database\TypeFactory;
use Cake\Datasource\ConnectionManager;
use Cake\Datasource\EntityInterface;
use Cake\Datasource\Exception\InvalidPrimaryKeyException;
use Cake\Datasource\RepositoryInterface;
use Cake\Datasource\RulesAwareTrait;
use Cake\Event\EventDispatcherInterface;
use Cake\Event\EventDispatcherTrait;
use Cake\Event\EventListenerInterface;
use Cake\Event\EventManager;
use Cake\ORM\Association\BelongsTo;
use Cake\ORM\Association\BelongsToMany;
use Cake\ORM\Association\HasMany;
use Cake\ORM\Association\HasOne;
use Cake\ORM\Exception\MissingEntityException;
use Cake\ORM\Exception\PersistenceFailedException;
use Cake\ORM\Exception\RolledbackTransactionException;
use Cake\ORM\Rule\IsUnique;
use Cake\Utility\Inflector;
use Cake\Validation\ValidatorAwareInterface;
use Cake\Validation\ValidatorAwareTrait;
use Exception;
use InvalidArgumentException;
use RuntimeException;
/**
* Represents a single database table.
*
* Exposes methods for retrieving data out of it, and manages the associations
* this table has to other tables. Multiple instances of this class can be created
* for the same database table with different aliases, this allows you to address
* your database structure in a richer and more expressive way.
*
* ### Retrieving data
*
* The primary way to retrieve data is using Table::find(). See that method
* for more information.
*
* ### Dynamic finders
*
* In addition to the standard find($type) finder methods, CakePHP provides dynamic
* finder methods. These methods allow you to easily set basic conditions up. For example
* to filter users by username you would call
*
* ```
* $query = $users->findByUsername('mark');
* ```
*
* You can also combine conditions on multiple fields using either `Or` or `And`:
*
* ```
* $query = $users->findByUsernameOrEmail('mark', '[email protected]');
* ```
*
* ### Bulk updates/deletes
*
* You can use Table::updateAll() and Table::deleteAll() to do bulk updates/deletes.
* You should be aware that events will *not* be fired for bulk updates/deletes.
*
* ### Events
*
* Table objects emit several events during as life-cycle hooks during find, delete and save
* operations. All events use the CakePHP event package:
*
* - `Model.beforeFind` Fired before each find operation. By stopping the event and
* supplying a return value you can bypass the find operation entirely. Any
* changes done to the $query instance will be retained for the rest of the find. The
* `$primary` parameter indicates whether or not this is the root query, or an
* associated query.
*
* - `Model.buildValidator` Allows listeners to modify validation rules
* for the provided named validator.
*
* - `Model.buildRules` Allows listeners to modify the rules checker by adding more rules.
*
* - `Model.beforeRules` Fired before an entity is validated using the rules checker.
* By stopping this event, you can return the final value of the rules checking operation.
*
* - `Model.afterRules` Fired after the rules have been checked on the entity. By
* stopping this event, you can return the final value of the rules checking operation.
*
* - `Model.beforeSave` Fired before each entity is saved. Stopping this event will
* abort the save operation. When the event is stopped the result of the event will be returned.
*
* - `Model.afterSave` Fired after an entity is saved.
*
* - `Model.afterSaveCommit` Fired after the transaction in which the save operation is
* wrapped has been committed. It’s also triggered for non atomic saves where database
* operations are implicitly committed. The event is triggered only for the primary
* table on which save() is directly called. The event is not triggered if a
* transaction is started before calling save.
*
* - `Model.beforeDelete` Fired before an entity is deleted. By stopping this
* event you will abort the delete operation.
*
* - `Model.afterDelete` Fired after an entity has been deleted.
*
* ### Callbacks
*
* You can subscribe to the events listed above in your table classes by implementing the
* lifecycle methods below:
*
* - `beforeFind(EventInterface $event, Query $query, ArrayObject $options, boolean $primary)`
* - `beforeMarshal(EventInterface $event, ArrayObject $data, ArrayObject $options)`
* - `afterMarshal(EventInterface $event, EntityInterface $entity, ArrayObject $options)`
* - `buildValidator(EventInterface $event, Validator $validator, string $name)`
* - `buildRules(RulesChecker $rules)`
* - `beforeRules(EventInterface $event, EntityInterface $entity, ArrayObject $options, string $operation)`
* - `afterRules(EventInterface $event, EntityInterface $entity, ArrayObject $options, bool $result, string $operation)`
* - `beforeSave(EventInterface $event, EntityInterface $entity, ArrayObject $options)`
* - `afterSave(EventInterface $event, EntityInterface $entity, ArrayObject $options)`
* - `afterSaveCommit(EventInterface $event, EntityInterface $entity, ArrayObject $options)`
* - `beforeDelete(EventInterface $event, EntityInterface $entity, ArrayObject $options)`
* - `afterDelete(EventInterface $event, EntityInterface $entity, ArrayObject $options)`
* - `afterDeleteCommit(EventInterface $event, EntityInterface $entity, ArrayObject $options)`
*
* @see \Cake\Event\EventManager for reference on the events system.
* @link https://book.cakephp.org/4/en/orm/table-objects.html#event-list
*/
class Table implements RepositoryInterface, EventListenerInterface, EventDispatcherInterface, ValidatorAwareInterface
{
use EventDispatcherTrait;
use RulesAwareTrait;
use ValidatorAwareTrait;
/**
* Name of default validation set.
*
* @var string
*/
public const DEFAULT_VALIDATOR = 'default';
/**
* The alias this object is assigned to validators as.
*
* @var string
*/
public const VALIDATOR_PROVIDER_NAME = 'table';
/**
* The name of the event dispatched when a validator has been built.
*
* @var string
*/
public const BUILD_VALIDATOR_EVENT = 'Model.buildValidator';
/**
* The rules class name that is used.
*
* @var string
*/
public const RULES_CLASS = RulesChecker::class;
/**
* The IsUnique class name that is used.
*
* @var string
*/
public const IS_UNIQUE_CLASS = IsUnique::class;
/**
* Name of the table as it can be found in the database
*
* @var string|null
*/
protected $_table;
/**
* Human name giving to this particular instance. Multiple objects representing
* the same database table can exist by using different aliases.
*
* @var string|null
*/
protected $_alias;
/**
* Connection instance
*
* @var \Cake\Database\Connection|null
*/
protected $_connection;
/**
* The schema object containing a description of this table fields
*
* @var \Cake\Database\Schema\TableSchemaInterface|null
*/
protected $_schema;
/**
* The name of the field that represents the primary key in the table
*
* @var string|string[]|null
*/
protected $_primaryKey;
/**
* The name of the field that represents a human readable representation of a row
*
* @var string|string[]|null
*/
protected $_displayField;
/**
* The associations container for this Table.
*
* @var \Cake\ORM\AssociationCollection
*/
protected $_associations;
/**
* BehaviorRegistry for this table
*
* @var \Cake\ORM\BehaviorRegistry
*/
protected $_behaviors;
/**
* The name of the class that represent a single row for this table
*
* @var string
* @psalm-var class-string<\Cake\Datasource\EntityInterface>
*/
protected $_entityClass;
/**
* Registry key used to create this table object
*
* @var string|null
*/
protected $_registryAlias;
/**
* Initializes a new instance
*
* The $config array understands the following keys:
*
* - table: Name of the database table to represent
* - alias: Alias to be assigned to this table (default to table name)
* - connection: The connection instance to use
* - entityClass: The fully namespaced class name of the entity class that will
* represent rows in this table.
* - schema: A \Cake\Database\Schema\TableSchemaInterface object or an array that can be
* passed to it.
* - eventManager: An instance of an event manager to use for internal events
* - behaviors: A BehaviorRegistry. Generally not used outside of tests.
* - associations: An AssociationCollection instance.
* - validator: A Validator instance which is assigned as the "default"
* validation set, or an associative array, where key is the name of the
* validation set and value the Validator instance.
*
* @param array $config List of options for this table
*/
public function __construct(array $config = [])
{
if (!empty($config['registryAlias'])) {
$this->setRegistryAlias($config['registryAlias']);
}
if (!empty($config['table'])) {
$this->setTable($config['table']);
}
if (!empty($config['alias'])) {
$this->setAlias($config['alias']);
}
if (!empty($config['connection'])) {
$this->setConnection($config['connection']);
}
if (!empty($config['schema'])) {
$this->setSchema($config['schema']);
}
if (!empty($config['entityClass'])) {
$this->setEntityClass($config['entityClass']);
}
$eventManager = $behaviors = $associations = null;
if (!empty($config['eventManager'])) {
$eventManager = $config['eventManager'];
}
if (!empty($config['behaviors'])) {
$behaviors = $config['behaviors'];
}
if (!empty($config['associations'])) {
$associations = $config['associations'];
}
if (!empty($config['validator'])) {
if (!is_array($config['validator'])) {
$this->setValidator(static::DEFAULT_VALIDATOR, $config['validator']);
} else {
foreach ($config['validator'] as $name => $validator) {
$this->setValidator($name, $validator);
}
}
}
$this->_eventManager = $eventManager ?: new EventManager();
$this->_behaviors = $behaviors ?: new BehaviorRegistry();
$this->_behaviors->setTable($this);
$this->_associations = $associations ?: new AssociationCollection();
$this->initialize($config);
$this->_eventManager->on($this);
$this->dispatchEvent('Model.initialize');
}
/**
* Get the default connection name.
*
* This method is used to get the fallback connection name if an
* instance is created through the TableLocator without a connection.
*
* @return string
* @see \Cake\ORM\Locator\TableLocator::get()
*/
public static function defaultConnectionName(): string
{
return 'default';
}
/**
* Initialize a table instance. Called after the constructor.
*
* You can use this method to define associations, attach behaviors
* define validation and do any other initialization logic you need.
*
* ```
* public function initialize(array $config)
* {
* $this->belongsTo('Users');
* $this->belongsToMany('Tagging.Tags');
* $this->setPrimaryKey('something_else');
* }
* ```
*
* @param array $config Configuration options passed to the constructor
* @return void
*/
public function initialize(array $config): void
{
}
/**
* Sets the database table name.
*
* This can include the database schema name in the form 'schema.table'.
* If the name must be quoted, enable automatic identifier quoting.
*
* @param string $table Table name.
* @return $this
*/
public function setTable(string $table)
{
$this->_table = $table;
return $this;
}
/**
* Returns the database table name.
*
* This can include the database schema name if set using `setTable()`.
*
* @return string
*/
public function getTable(): string
{
if ($this->_table === null) {
$table = namespaceSplit(static::class);
$table = substr(end($table), 0, -5);
if (!$table) {
$table = $this->getAlias();
}
$this->_table = Inflector::underscore($table);
}
return $this->_table;
}
/**
* Sets the table alias.
*
* @param string $alias Table alias
* @return $this
*/
public function setAlias(string $alias)
{
$this->_alias = $alias;
return $this;
}
/**
* Returns the table alias.
*
* @return string
*/
public function getAlias(): string
{
if ($this->_alias === null) {
$alias = namespaceSplit(static::class);
$alias = substr(end($alias), 0, -5) ?: $this->getTable();
$this->_alias = $alias;
}
return $this->_alias;
}
/**
* Alias a field with the table's current alias.
*
* If field is already aliased it will result in no-op.
*
* @param string $field The field to alias.
* @return string The field prefixed with the table alias.
*/
public function aliasField(string $field): string
{
if (strpos($field, '.') !== false) {
return $field;
}
return $this->getAlias() . '.' . $field;
}
/**
* Sets the table registry key used to create this table instance.
*
* @param string $registryAlias The key used to access this object.
* @return $this
*/
public function setRegistryAlias(string $registryAlias)
{
$this->_registryAlias = $registryAlias;
return $this;
}
/**
* Returns the table registry key used to create this table instance.
*
* @return string
*/
public function getRegistryAlias(): string
{
if ($this->_registryAlias === null) {
$this->_registryAlias = $this->getAlias();
}
return $this->_registryAlias;
}
/**
* Sets the connection instance.
*
* @param \Cake\Database\Connection $connection The connection instance
* @return $this
*/
public function setConnection(Connection $connection)
{
$this->_connection = $connection;
return $this;
}
/**
* Returns the connection instance.
*
* @return \Cake\Database\Connection
*/
public function getConnection(): Connection
{
if (!$this->_connection) {
/** @var \Cake\Database\Connection $connection */
$connection = ConnectionManager::get(static::defaultConnectionName());
$this->_connection = $connection;
}
return $this->_connection;
}
/**
* Returns the schema table object describing this table's properties.
*
* @return \Cake\Database\Schema\TableSchemaInterface
*/
public function getSchema(): TableSchemaInterface
{
if ($this->_schema === null) {
$this->_schema = $this->_initializeSchema(
$this->getConnection()
->getSchemaCollection()
->describe($this->getTable())
);
if (Configure::read('debug')) {
$this->checkAliasLengths();
}
}
return $this->_schema;
}
/**
* Sets the schema table object describing this table's properties.
*
* If an array is passed, a new TableSchemaInterface will be constructed
* out of it and used as the schema for this table.
*
* @param array|\Cake\Database\Schema\TableSchemaInterface $schema Schema to be used for this table
* @return $this
*/
public function setSchema($schema)
{
if (is_array($schema)) {
$constraints = [];
if (isset($schema['_constraints'])) {
$constraints = $schema['_constraints'];
unset($schema['_constraints']);
}
$schema = $this->getConnection()->getDriver()->newTableSchema($this->getTable(), $schema);
foreach ($constraints as $name => $value) {
$schema->addConstraint($name, $value);
}
}
$this->_schema = $schema;
if (Configure::read('debug')) {
$this->checkAliasLengths();
}
return $this;
}
/**
* Checks if all table name + column name combinations used for
* queries fit into the max length allowed by database driver.
*
* @return void
* @throws \RuntimeException When an alias combination is too long
*/
protected function checkAliasLengths(): void
{
if ($this->_schema === null) {
throw new RuntimeException("Unable to check max alias lengths for `{$this->getAlias()}` without schema.");
}
$maxLength = null;
if (method_exists($this->getConnection()->getDriver(), 'getMaxAliasLength')) {
$maxLength = $this->getConnection()->getDriver()->getMaxAliasLength();
}
if ($maxLength === null) {
return;
}
$table = $this->getAlias();
foreach ($this->_schema->columns() as $name) {
if (strlen($table . '__' . $name) > $maxLength) {
$nameLength = $maxLength - 2;
throw new RuntimeException(
'ORM queries generate field aliases using the table name/alias and column name. ' .
"The table alias `{$table}` and column `{$name}` create an alias longer than ({$nameLength}). " .
'You must change the table schema in the database and shorten either the table or column ' .
'identifier so they fit within the database alias limits.'
);
}
}
}
/**
* Override this function in order to alter the schema used by this table.
* This function is only called after fetching the schema out of the database.
* If you wish to provide your own schema to this table without touching the
* database, you can override schema() or inject the definitions though that
* method.
*
* ### Example:
*
* ```
* protected function _initializeSchema(\Cake\Database\Schema\TableSchemaInterface $schema) {
* $schema->setColumnType('preferences', 'json');
* return $schema;
* }
* ```
*
* @param \Cake\Database\Schema\TableSchemaInterface $schema The table definition fetched from database.
* @return \Cake\Database\Schema\TableSchemaInterface the altered schema
*/
protected function _initializeSchema(TableSchemaInterface $schema): TableSchemaInterface
{
return $schema;
}
/**
* Test to see if a Table has a specific field/column.
*
* Delegates to the schema object and checks for column presence
* using the Schema\Table instance.
*
* @param string $field The field to check for.
* @return bool True if the field exists, false if it does not.
*/
public function hasField(string $field): bool
{
$schema = $this->getSchema();
return $schema->getColumn($field) !== null;
}
/**
* Sets the primary key field name.
*
* @param string|string[] $key Sets a new name to be used as primary key
* @return $this
*/
public function setPrimaryKey($key)
{
$this->_primaryKey = $key;
return $this;
}
/**
* Returns the primary key field name.
*
* @return string|string[]
*/
public function getPrimaryKey()
{
if ($this->_primaryKey === null) {
$key = $this->getSchema()->getPrimaryKey();
if (count($key) === 1) {
$key = $key[0];
}
$this->_primaryKey = $key;
}
return $this->_primaryKey;
}
/**
* Sets the display field.
*
* @param string|string[] $field Name to be used as display field.
* @return $this
*/
public function setDisplayField($field)
{
$this->_displayField = $field;
return $this;
}
/**
* Returns the display field.
*
* @return string|string[]|null
*/
public function getDisplayField()
{
if ($this->_displayField === null) {
$schema = $this->getSchema();
$primary = (array)$this->getPrimaryKey();
$this->_displayField = array_shift($primary);
if ($schema->getColumn('title')) {
$this->_displayField = 'title';
}
if ($schema->getColumn('name')) {
$this->_displayField = 'name';
}
}
return $this->_displayField;
}
/**
* Returns the class used to hydrate rows for this table.
*
* @return string
* @psalm-return class-string<\Cake\Datasource\EntityInterface>
*/
public function getEntityClass(): string
{
if (!$this->_entityClass) {
$default = Entity::class;
$self = static::class;
$parts = explode('\\', $self);
if ($self === self::class || count($parts) < 3) {
return $this->_entityClass = $default;
}
$alias = Inflector::classify(Inflector::underscore(substr(array_pop($parts), 0, -5)));
$name = implode('\\', array_slice($parts, 0, -1)) . '\\Entity\\' . $alias;
if (!class_exists($name)) {
return $this->_entityClass = $default;
}
/** @var class-string<\Cake\Datasource\EntityInterface>|null $class */
$class = App::className($name, 'Model/Entity');
if (!$class) {
throw new MissingEntityException([$name]);
}
$this->_entityClass = $class;
}
return $this->_entityClass;
}
/**
* Sets the class used to hydrate rows for this table.
*
* @param string $name The name of the class to use
* @throws \Cake\ORM\Exception\MissingEntityException when the entity class cannot be found
* @return $this
*/
public function setEntityClass(string $name)
{
/** @psalm-var class-string<\Cake\Datasource\EntityInterface>|null */
$class = App::className($name, 'Model/Entity');
if ($class === null) {
throw new MissingEntityException([$name]);
}
$this->_entityClass = $class;
return $this;
}
/**
* Add a behavior.
*
* Adds a behavior to this table's behavior collection. Behaviors
* provide an easy way to create horizontally re-usable features
* that can provide trait like functionality, and allow for events
* to be listened to.
*
* Example:
*
* Load a behavior, with some settings.
*
* ```
* $this->addBehavior('Tree', ['parent' => 'parentId']);
* ```
*
* Behaviors are generally loaded during Table::initialize().
*
* @param string $name The name of the behavior. Can be a short class reference.
* @param array $options The options for the behavior to use.
* @return $this
* @throws \RuntimeException If a behavior is being reloaded.
* @see \Cake\ORM\Behavior
*/
public function addBehavior(string $name, array $options = [])
{
$this->_behaviors->load($name, $options);
return $this;
}
/**
* Adds an array of behaviors to the table's behavior collection.
*
* Example:
*
* ```
* $this->addBehaviors([
* 'Timestamp',
* 'Tree' => ['level' => 'level'],
* ]);
* ```
*
* @param array $behaviors All of the behaviors to load.
* @return $this
* @throws \RuntimeException If a behavior is being reloaded.
*/
public function addBehaviors(array $behaviors)
{
foreach ($behaviors as $name => $options) {
if (is_int($name)) {
$name = $options;
$options = [];
}
$this->addBehavior($name, $options);
}
return $this;
}
/**
* Removes a behavior from this table's behavior registry.
*
* Example:
*
* Remove a behavior from this table.
*
* ```
* $this->removeBehavior('Tree');
* ```
*
* @param string $name The alias that the behavior was added with.
* @return $this
* @see \Cake\ORM\Behavior
*/
public function removeBehavior(string $name)
{
$this->_behaviors->unload($name);
return $this;
}
/**
* Returns the behavior registry for this table.
*
* @return \Cake\ORM\BehaviorRegistry The BehaviorRegistry instance.
*/
public function behaviors(): BehaviorRegistry
{
return $this->_behaviors;
}
/**
* Get a behavior from the registry.
*
* @param string $name The behavior alias to get from the registry.
* @return \Cake\ORM\Behavior
* @throws \InvalidArgumentException If the behavior does not exist.
*/
public function getBehavior(string $name): Behavior
{
if (!$this->_behaviors->has($name)) {
throw new InvalidArgumentException(sprintf(
'The %s behavior is not defined on %s.',
$name,
static::class
));
}
$behavior = $this->_behaviors->get($name);
return $behavior;
}
/**
* Check if a behavior with the given alias has been loaded.
*
* @param string $name The behavior alias to check.
* @return bool Whether or not the behavior exists.
*/
public function hasBehavior(string $name): bool
{
return $this->_behaviors->has($name);
}
/**
* Returns an association object configured for the specified alias.
*
* The name argument also supports dot syntax to access deeper associations.
*
* ```
* $users = $this->getAssociation('Articles.Comments.Users');
* ```
*
* Note that this method requires the association to be present or otherwise
* throws an exception.
* If you are not sure, use hasAssociation() before calling this method.
*
* @param string $name The alias used for the association.
* @return \Cake\ORM\Association The association.
* @throws \InvalidArgumentException
*/
public function getAssociation(string $name): Association
{
$association = $this->findAssociation($name);
if (!$association) {
$assocations = $this->associations()->keys();
$message = "The `{$name}` association is not defined on `{$this->getAlias()}`.";
if ($assocations) {
$message .= "\nValid associations are: " . implode(', ', $assocations);
}
throw new InvalidArgumentException($message);
}
return $association;
}
/**
* Checks whether a specific association exists on this Table instance.
*
* The name argument also supports dot syntax to access deeper associations.
*
* ```
* $hasUsers = $this->hasAssociation('Articles.Comments.Users');
* ```
*
* @param string $name The alias used for the association.
* @return bool
*/
public function hasAssociation(string $name): bool
{
return $this->findAssociation($name) !== null;
}
/**
* Returns an association object configured for the specified alias if any.
*
* The name argument also supports dot syntax to access deeper associations.
*
* ```
* $users = $this->getAssociation('Articles.Comments.Users');
* ```
*
* @param string $name The alias used for the association.
* @return \Cake\ORM\Association|null Either the association or null.
*/
protected function findAssociation(string $name): ?Association
{
if (strpos($name, '.') === false) {
return $this->_associations->get($name);
}
$result = null;
[$name, $next] = array_pad(explode('.', $name, 2), 2, null);
if ($name !== null) {
$result = $this->_associations->get($name);
}
if ($result !== null && $next !== null) {
$result = $result->getTarget()->getAssociation($next);
}
return $result;
}
/**
* Get the associations collection for this table.
*
* @return \Cake\ORM\AssociationCollection The collection of association objects.
*/
public function associations(): AssociationCollection
{
return $this->_associations;
}
/**
* Setup multiple associations.
*
* It takes an array containing set of table names indexed by association type
* as argument:
*
* ```
* $this->Posts->addAssociations([
* 'belongsTo' => [
* 'Users' => ['className' => 'App\Model\Table\UsersTable']
* ],
* 'hasMany' => ['Comments'],
* 'belongsToMany' => ['Tags']
* ]);
* ```
*
* Each association type accepts multiple associations where the keys
* are the aliases, and the values are association config data. If numeric
* keys are used the values will be treated as association aliases.
*
* @param array $params Set of associations to bind (indexed by association type)
* @return $this
* @see \Cake\ORM\Table::belongsTo()
* @see \Cake\ORM\Table::hasOne()
* @see \Cake\ORM\Table::hasMany()
* @see \Cake\ORM\Table::belongsToMany()
*/
public function addAssociations(array $params)
{
foreach ($params as $assocType => $tables) {
foreach ($tables as $associated => $options) {