-
Notifications
You must be signed in to change notification settings - Fork 3.4k
/
TableLocator.php
383 lines (338 loc) · 11.9 KB
/
TableLocator.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
<?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.1.0
* @license https://opensource.org/licenses/mit-license.php MIT License
*/
namespace Cake\ORM\Locator;
use Cake\Core\App;
use Cake\Database\Exception\DatabaseException;
use Cake\Datasource\ConnectionManager;
use Cake\Datasource\Locator\AbstractLocator;
use Cake\Datasource\RepositoryInterface;
use Cake\ORM\AssociationCollection;
use Cake\ORM\Exception\MissingTableClassException;
use Cake\ORM\Query\QueryFactory;
use Cake\ORM\Table;
use Cake\Utility\Inflector;
use function Cake\Core\pluginSplit;
/**
* Provides a default registry/factory for Table objects.
*/
class TableLocator extends AbstractLocator implements LocatorInterface
{
/**
* Contains a list of locations where table classes should be looked for.
*
* @var array<string>
*/
protected array $locations = [];
/**
* Configuration for aliases.
*
* @var array<string, array|null>
*/
protected array $_config = [];
/**
* Instances that belong to the registry.
*
* @var array<string, \Cake\ORM\Table>
* @psalm-suppress NonInvariantDocblockPropertyType
*/
protected array $instances = [];
/**
* Contains a list of Table objects that were created out of the
* built-in Table class. The list is indexed by table alias
*
* @var array<\Cake\ORM\Table>
*/
protected array $_fallbacked = [];
/**
* Fallback class to use
*
* @var string
* @psalm-var class-string<\Cake\ORM\Table>
*/
protected string $fallbackClassName = Table::class;
/**
* Whether fallback class should be used if a table class could not be found.
*
* @var bool
*/
protected bool $allowFallbackClass = true;
protected QueryFactory $queryFactory;
/**
* Constructor.
*
* @param array<string>|null $locations Locations where tables should be looked for.
* If none provided, the default `Model\Table` under your app's namespace is used.
*/
public function __construct(?array $locations = null, ?QueryFactory $queryFactory = null)
{
if ($locations === null) {
$locations = [
'Model/Table',
];
}
foreach ($locations as $location) {
$this->addLocation($location);
}
$this->queryFactory = $queryFactory ?: new QueryFactory();
}
/**
* Set if fallback class should be used.
*
* Controls whether a fallback class should be used to create a table
* instance if a concrete class for alias used in `get()` could not be found.
*
* @param bool $allow Flag to enable or disable fallback
* @return $this
*/
public function allowFallbackClass(bool $allow)
{
$this->allowFallbackClass = $allow;
return $this;
}
/**
* Set fallback class name.
*
* The class that should be used to create a table instance if a concrete
* class for alias used in `get()` could not be found. Defaults to
* `Cake\ORM\Table`.
*
* @param string $className Fallback class name
* @return $this
* @psalm-param class-string<\Cake\ORM\Table> $className
*/
public function setFallbackClassName(string $className)
{
$this->fallbackClassName = $className;
return $this;
}
/**
* @inheritDoc
*/
public function setConfig(array|string $alias, ?array $options = null)
{
if (!is_string($alias)) {
$this->_config = $alias;
return $this;
}
if (isset($this->instances[$alias])) {
throw new DatabaseException(sprintf(
'You cannot configure `%s`, it has already been constructed.',
$alias
));
}
$this->_config[$alias] = $options;
return $this;
}
/**
* @inheritDoc
*/
public function getConfig(?string $alias = null): array
{
if ($alias === null) {
return $this->_config;
}
return $this->_config[$alias] ?? [];
}
/**
* Get a table instance from the registry.
*
* Tables are only created once until the registry is flushed.
* This means that aliases must be unique across your application.
* This is important because table associations are resolved at runtime
* and cyclic references need to be handled correctly.
*
* The options that can be passed are the same as in {@link \Cake\ORM\Table::__construct()}, but the
* `className` key is also recognized.
*
* ### Options
*
* - `className` Define the specific class name to use. If undefined, CakePHP will generate the
* class name based on the alias. For example 'Users' would result in
* `App\Model\Table\UsersTable` being used. If this class does not exist,
* then the default `Cake\ORM\Table` class will be used. By setting the `className`
* option you can define the specific class to use. The className option supports
* plugin short class references {@link \Cake\Core\App::shortName()}.
* - `table` Define the table name to use. If undefined, this option will default to the underscored
* version of the alias name.
* - `connection` Inject the specific connection object to use. If this option and `connectionName` are undefined,
* The table class' `defaultConnectionName()` method will be invoked to fetch the connection name.
* - `connectionName` Define the connection name to use. The named connection will be fetched from
* {@link \Cake\Datasource\ConnectionManager}.
*
* *Note* If your `$alias` uses plugin syntax only the name part will be used as
* key in the registry. This means that if two plugins, or a plugin and app provide
* the same alias, the registry will only store the first instance.
*
* @param string $alias The alias name you want to get. Should be in CamelCase format.
* @param array<string, mixed> $options The options you want to build the table with.
* If a table has already been loaded the options will be ignored.
* @return \Cake\ORM\Table
* @throws \RuntimeException When you try to configure an alias that already exists.
*/
public function get(string $alias, array $options = []): Table
{
/** @var \Cake\ORM\Table */
return parent::get($alias, $options);
}
/**
* @inheritDoc
*/
protected function createInstance(string $alias, array $options): Table
{
if (!str_contains($alias, '\\')) {
[, $classAlias] = pluginSplit($alias);
$options = ['alias' => $classAlias] + $options;
} elseif (!isset($options['alias'])) {
$options['className'] = $alias;
}
if (isset($this->_config[$alias])) {
$options += $this->_config[$alias];
}
$allowFallbackClass = $options['allowFallbackClass'] ?? $this->allowFallbackClass;
$className = $this->_getClassName($alias, $options);
if ($className) {
$options['className'] = $className;
} elseif ($allowFallbackClass) {
if (empty($options['className'])) {
$options['className'] = $alias;
}
if (!isset($options['table']) && !str_contains($options['className'], '\\')) {
[, $table] = pluginSplit($options['className']);
$options['table'] = Inflector::underscore($table);
}
$options['className'] = $this->fallbackClassName;
} else {
$message = $options['className'] ?? $alias;
$message = '`' . $message . '`';
if (!str_contains($message, '\\')) {
$message = 'for alias ' . $message;
}
throw new MissingTableClassException([$message]);
}
if (empty($options['connection'])) {
if (!empty($options['connectionName'])) {
$connectionName = $options['connectionName'];
} else {
/** @var \Cake\ORM\Table $className */
$className = $options['className'];
$connectionName = $className::defaultConnectionName();
}
$options['connection'] = ConnectionManager::get($connectionName);
}
if (empty($options['associations'])) {
$associations = new AssociationCollection($this);
$options['associations'] = $associations;
}
if (empty($options['queryFactory'])) {
$options['queryFactory'] = $this->queryFactory;
}
$options['registryAlias'] = $alias;
$instance = $this->_create($options);
if ($options['className'] === $this->fallbackClassName) {
$this->_fallbacked[$alias] = $instance;
}
return $instance;
}
/**
* Gets the table class name.
*
* @param string $alias The alias name you want to get. Should be in CamelCase format.
* @param array<string, mixed> $options Table options array.
* @return string|null
*/
protected function _getClassName(string $alias, array $options = []): ?string
{
if (empty($options['className'])) {
$options['className'] = $alias;
}
if (str_contains($options['className'], '\\') && class_exists($options['className'])) {
return $options['className'];
}
foreach ($this->locations as $location) {
$class = App::className($options['className'], $location, 'Table');
if ($class !== null) {
return $class;
}
}
return null;
}
/**
* Wrapper for creating table instances
*
* @param array<string, mixed> $options The alias to check for.
* @return \Cake\ORM\Table
*/
protected function _create(array $options): Table
{
/** @var class-string<\Cake\ORM\Table> $class */
$class = $options['className'];
return new $class($options);
}
/**
* Set a Table instance.
*
* @param string $alias The alias to set.
* @param \Cake\ORM\Table $repository The Table to set.
* @return \Cake\ORM\Table
* @psalm-suppress MoreSpecificImplementedParamType
*/
public function set(string $alias, RepositoryInterface $repository): Table
{
return $this->instances[$alias] = $repository;
}
/**
* @inheritDoc
*/
public function clear(): void
{
parent::clear();
$this->_fallbacked = [];
$this->_config = [];
}
/**
* Returns the list of tables that were created by this registry that could
* not be instantiated from a specific subclass. This method is useful for
* debugging common mistakes when setting up associations or created new table
* classes.
*
* @return array<\Cake\ORM\Table>
*/
public function genericInstances(): array
{
return $this->_fallbacked;
}
/**
* @inheritDoc
*/
public function remove(string $alias): void
{
parent::remove($alias);
unset($this->_fallbacked[$alias]);
}
/**
* Adds a location where tables should be looked for.
*
* @param string $location Location to add.
* @return $this
* @since 3.8.0
*/
public function addLocation(string $location)
{
$location = str_replace('\\', '/', $location);
$this->locations[] = trim($location, '/');
return $this;
}
}