1 <?php
2
3 /*
4 * This file is part of the ICanBoogie package.
5 *
6 * (c) Olivier Laviale <olivier.laviale@gmail.com>
7 *
8 * For the full copyright and license information, please view the LICENSE
9 * file that was distributed with this source code.
10 */
11
12 namespace ICanBoogie;
13
14 use ICanBoogie\ActiveRecord\Connections;
15
16 /**
17 * Models manager.
18 *
19 * Extends the ActiveRecord manager to handle module defined models.
20 */
21 class Models extends \ICanBoogie\ActiveRecord\Models
22 {
23 /**
24 * The modules accessor.
25 *
26 * @var Modules
27 */
28 protected $modules;
29
30 /**
31 * Initializes the {@link $modules} property.
32 *
33 * @param Connections $connections Connections manager.
34 * @param array $definitions Model definitions.
35 * @param Modules $modules Modules manager.
36 */
37 public function __construct(Connections $connections, array $definitions, Modules $modules)
38 {
39 $this->modules = $modules;
40
41 parent::__construct($connections, $definitions);
42 }
43
44 /**
45 * Checks if a model exists by first checking if the module it belongs to is enabled and that
46 * it actually defines the model.
47 *
48 * @param mixed $id
49 *
50 * @return bool
51 */
52 public function offsetExists($id)
53 {
54 list($module_id, $model_id) = explode('/', $id) + [ 1 => 'primary' ];
55
56 if (!isset($this->modules[$module_id]))
57 {
58 return parent::offsetExists($id);
59 }
60
61 $descriptor = $this->modules->descriptors[$module_id];
62
63 return isset($descriptor[Module::T_MODELS][$model_id]);
64 }
65
66 /**
67 * Gets the specified model of the specified module.
68 *
69 * The pattern used to request a model is `<module_id>[/<model_id>]` where `<module_id>` is
70 * the identifier of the module and `<model_id>` is the identifier of the module's model. The
71 * `<model_id>` part is optional and defaults to `primary`.
72 *
73 * @param mixed $id Identifier of the model.
74 *
75 * @return ActiveRecord\Model
76 */
77 public function offsetGet($id)
78 {
79 if (isset($this->instances[$id]))
80 {
81 return $this->instances[$id];
82 }
83
84 list($module_id, $model_id) = explode('/', $id) + [ 1 => 'primary' ];
85
86 if (!isset($this->modules[$module_id]))
87 {
88 return parent::offsetGet($id);
89 }
90
91 return $this->instances[$id] = $this->modules[$module_id]->model($model_id);
92 }
93 }