@@ -1,6 +1,6 @@ |
||
1 | 1 | <?php |
2 | 2 | |
3 | -declare(strict_types=1); |
|
3 | +declare(strict_types = 1); |
|
4 | 4 | |
5 | 5 | namespace Mouf\Database\TDBM; |
6 | 6 |
@@ -47,236 +47,236 @@ discard block |
||
47 | 47 | */ |
48 | 48 | class TDBMService |
49 | 49 | { |
50 | - const MODE_CURSOR = 1; |
|
51 | - const MODE_ARRAY = 2; |
|
52 | - |
|
53 | - /** |
|
54 | - * The database connection. |
|
55 | - * |
|
56 | - * @var Connection |
|
57 | - */ |
|
58 | - private $connection; |
|
59 | - |
|
60 | - /** |
|
61 | - * @var SchemaAnalyzer |
|
62 | - */ |
|
63 | - private $schemaAnalyzer; |
|
64 | - |
|
65 | - /** |
|
66 | - * @var MagicQuery |
|
67 | - */ |
|
68 | - private $magicQuery; |
|
69 | - |
|
70 | - /** |
|
71 | - * @var TDBMSchemaAnalyzer |
|
72 | - */ |
|
73 | - private $tdbmSchemaAnalyzer; |
|
74 | - |
|
75 | - /** |
|
76 | - * @var string |
|
77 | - */ |
|
78 | - private $cachePrefix; |
|
79 | - |
|
80 | - /** |
|
81 | - * Cache of table of primary keys. |
|
82 | - * Primary keys are stored by tables, as an array of column. |
|
83 | - * For instance $primary_key['my_table'][0] will return the first column of the primary key of table 'my_table'. |
|
84 | - * |
|
85 | - * @var string[] |
|
86 | - */ |
|
87 | - private $primaryKeysColumns; |
|
88 | - |
|
89 | - /** |
|
90 | - * Service storing objects in memory. |
|
91 | - * Access is done by table name and then by primary key. |
|
92 | - * If the primary key is split on several columns, access is done by an array of columns, serialized. |
|
93 | - * |
|
94 | - * @var StandardObjectStorage|WeakrefObjectStorage |
|
95 | - */ |
|
96 | - private $objectStorage; |
|
97 | - |
|
98 | - /** |
|
99 | - * The fetch mode of the result sets returned by `getObjects`. |
|
100 | - * Can be one of: TDBMObjectArray::MODE_CURSOR or TDBMObjectArray::MODE_ARRAY or TDBMObjectArray::MODE_COMPATIBLE_ARRAY. |
|
101 | - * |
|
102 | - * In 'MODE_ARRAY' mode (default), the result is an array. Use this mode by default (unless the list returned is very big). |
|
103 | - * In 'MODE_CURSOR' mode, the result is a Generator which is an iterable collection that can be scanned only once (only one "foreach") on it, |
|
104 | - * and it cannot be accessed via key. Use this mode for large datasets processed by batch. |
|
105 | - * In 'MODE_COMPATIBLE_ARRAY' mode, the result is an old TDBMObjectArray (used up to TDBM 3.2). |
|
106 | - * You can access the array by key, or using foreach, several times. |
|
107 | - * |
|
108 | - * @var int |
|
109 | - */ |
|
110 | - private $mode = self::MODE_ARRAY; |
|
111 | - |
|
112 | - /** |
|
113 | - * Table of new objects not yet inserted in database or objects modified that must be saved. |
|
114 | - * |
|
115 | - * @var \SplObjectStorage of DbRow objects |
|
116 | - */ |
|
117 | - private $toSaveObjects; |
|
118 | - |
|
119 | - /** |
|
120 | - * A cache service to be used. |
|
121 | - * |
|
122 | - * @var Cache|null |
|
123 | - */ |
|
124 | - private $cache; |
|
125 | - |
|
126 | - /** |
|
127 | - * Map associating a table name to a fully qualified Bean class name. |
|
128 | - * |
|
129 | - * @var array |
|
130 | - */ |
|
131 | - private $tableToBeanMap = []; |
|
132 | - |
|
133 | - /** |
|
134 | - * @var \ReflectionClass[] |
|
135 | - */ |
|
136 | - private $reflectionClassCache = array(); |
|
137 | - |
|
138 | - /** |
|
139 | - * @var LoggerInterface |
|
140 | - */ |
|
141 | - private $rootLogger; |
|
142 | - |
|
143 | - /** |
|
144 | - * @var LevelFilter|NullLogger |
|
145 | - */ |
|
146 | - private $logger; |
|
147 | - |
|
148 | - /** |
|
149 | - * @var OrderByAnalyzer |
|
150 | - */ |
|
151 | - private $orderByAnalyzer; |
|
152 | - |
|
153 | - /** |
|
154 | - * @param Connection $connection The DBAL DB connection to use |
|
155 | - * @param Cache|null $cache A cache service to be used |
|
156 | - * @param SchemaAnalyzer $schemaAnalyzer The schema analyzer that will be used to find shortest paths... |
|
157 | - * Will be automatically created if not passed |
|
158 | - */ |
|
159 | - public function __construct(Connection $connection, Cache $cache = null, SchemaAnalyzer $schemaAnalyzer = null, LoggerInterface $logger = null) |
|
160 | - { |
|
161 | - if (extension_loaded('weakref')) { |
|
162 | - $this->objectStorage = new WeakrefObjectStorage(); |
|
163 | - } else { |
|
164 | - $this->objectStorage = new StandardObjectStorage(); |
|
165 | - } |
|
166 | - $this->connection = $connection; |
|
167 | - if ($cache !== null) { |
|
168 | - $this->cache = $cache; |
|
169 | - } else { |
|
170 | - $this->cache = new VoidCache(); |
|
171 | - } |
|
172 | - if ($schemaAnalyzer) { |
|
173 | - $this->schemaAnalyzer = $schemaAnalyzer; |
|
174 | - } else { |
|
175 | - $this->schemaAnalyzer = new SchemaAnalyzer($this->connection->getSchemaManager(), $this->cache, $this->getConnectionUniqueId()); |
|
176 | - } |
|
177 | - |
|
178 | - $this->magicQuery = new MagicQuery($this->connection, $this->cache, $this->schemaAnalyzer); |
|
179 | - |
|
180 | - $this->tdbmSchemaAnalyzer = new TDBMSchemaAnalyzer($connection, $this->cache, $this->schemaAnalyzer); |
|
181 | - $this->cachePrefix = $this->tdbmSchemaAnalyzer->getCachePrefix(); |
|
182 | - |
|
183 | - $this->toSaveObjects = new \SplObjectStorage(); |
|
184 | - if ($logger === null) { |
|
185 | - $this->logger = new NullLogger(); |
|
186 | - $this->rootLogger = new NullLogger(); |
|
187 | - } else { |
|
188 | - $this->rootLogger = $logger; |
|
189 | - $this->setLogLevel(LogLevel::WARNING); |
|
190 | - } |
|
191 | - $this->orderByAnalyzer = new OrderByAnalyzer($this->cache, $this->cachePrefix); |
|
192 | - } |
|
193 | - |
|
194 | - /** |
|
195 | - * Returns the object used to connect to the database. |
|
196 | - * |
|
197 | - * @return Connection |
|
198 | - */ |
|
199 | - public function getConnection() |
|
200 | - { |
|
201 | - return $this->connection; |
|
202 | - } |
|
203 | - |
|
204 | - /** |
|
205 | - * Creates a unique cache key for the current connection. |
|
206 | - * |
|
207 | - * @return string |
|
208 | - */ |
|
209 | - private function getConnectionUniqueId() |
|
210 | - { |
|
211 | - return hash('md4', $this->connection->getHost().'-'.$this->connection->getPort().'-'.$this->connection->getDatabase().'-'.$this->connection->getDriver()->getName()); |
|
212 | - } |
|
213 | - |
|
214 | - /** |
|
215 | - * Sets the default fetch mode of the result sets returned by `findObjects`. |
|
216 | - * Can be one of: TDBMObjectArray::MODE_CURSOR or TDBMObjectArray::MODE_ARRAY. |
|
217 | - * |
|
218 | - * In 'MODE_ARRAY' mode (default), the result is a ResultIterator object that behaves like an array. Use this mode by default (unless the list returned is very big). |
|
219 | - * In 'MODE_CURSOR' mode, the result is a ResultIterator object. If you scan it many times (by calling several time a foreach loop), the query will be run |
|
220 | - * several times. In cursor mode, you cannot access the result set by key. Use this mode for large datasets processed by batch. |
|
221 | - * |
|
222 | - * @param int $mode |
|
223 | - * |
|
224 | - * @return $this |
|
225 | - * |
|
226 | - * @throws TDBMException |
|
227 | - */ |
|
228 | - public function setFetchMode($mode) |
|
229 | - { |
|
230 | - if ($mode !== self::MODE_CURSOR && $mode !== self::MODE_ARRAY) { |
|
231 | - throw new TDBMException("Unknown fetch mode: '".$this->mode."'"); |
|
232 | - } |
|
233 | - $this->mode = $mode; |
|
234 | - |
|
235 | - return $this; |
|
236 | - } |
|
237 | - |
|
238 | - /** |
|
239 | - * Returns a TDBMObject associated from table "$table_name". |
|
240 | - * If the $filters parameter is an int/string, the object returned will be the object whose primary key = $filters. |
|
241 | - * $filters can also be a set of TDBM_Filters (see the findObjects method for more details). |
|
242 | - * |
|
243 | - * For instance, if there is a table 'users', with a primary key on column 'user_id' and a column 'user_name', then |
|
244 | - * $user = $tdbmService->getObject('users',1); |
|
245 | - * echo $user->name; |
|
246 | - * will return the name of the user whose user_id is one. |
|
247 | - * |
|
248 | - * If a table has a primary key over several columns, you should pass to $id an array containing the the value of the various columns. |
|
249 | - * For instance: |
|
250 | - * $group = $tdbmService->getObject('groups',array(1,2)); |
|
251 | - * |
|
252 | - * Note that TDBMObject performs caching for you. If you get twice the same object, the reference of the object you will get |
|
253 | - * will be the same. |
|
254 | - * |
|
255 | - * For instance: |
|
256 | - * $user1 = $tdbmService->getObject('users',1); |
|
257 | - * $user2 = $tdbmService->getObject('users',1); |
|
258 | - * $user1->name = 'John Doe'; |
|
259 | - * echo $user2->name; |
|
260 | - * will return 'John Doe'. |
|
261 | - * |
|
262 | - * You can use filters instead of passing the primary key. For instance: |
|
263 | - * $user = $tdbmService->getObject('users',new EqualFilter('users', 'login', 'jdoe')); |
|
264 | - * This will return the user whose login is 'jdoe'. |
|
265 | - * Please note that if 2 users have the jdoe login in database, the method will throw a TDBM_DuplicateRowException. |
|
266 | - * |
|
267 | - * Also, you can specify the return class for the object (provided the return class extends TDBMObject). |
|
268 | - * For instance: |
|
269 | - * $user = $tdbmService->getObject('users',1,'User'); |
|
270 | - * will return an object from the "User" class. The "User" class must extend the "TDBMObject" class. |
|
271 | - * Please be sure not to override any method or any property unless you perfectly know what you are doing! |
|
272 | - * |
|
273 | - * @param string $table_name The name of the table we retrieve an object from |
|
274 | - * @param mixed $filters If the filter is a string/integer, it will be considered as the id of the object (the value of the primary key). Otherwise, it can be a filter bag (see the filterbag parameter of the findObjects method for more details about filter bags) |
|
275 | - * @param string $className Optional: The name of the class to instanciate. This class must extend the TDBMObject class. If none is specified, a TDBMObject instance will be returned |
|
276 | - * @param bool $lazy_loading If set to true, and if the primary key is passed in parameter of getObject, the object will not be queried in database. It will be queried when you first try to access a column. If at that time the object cannot be found in database, an exception will be thrown |
|
277 | - * |
|
278 | - * @return TDBMObject |
|
279 | - */ |
|
50 | + const MODE_CURSOR = 1; |
|
51 | + const MODE_ARRAY = 2; |
|
52 | + |
|
53 | + /** |
|
54 | + * The database connection. |
|
55 | + * |
|
56 | + * @var Connection |
|
57 | + */ |
|
58 | + private $connection; |
|
59 | + |
|
60 | + /** |
|
61 | + * @var SchemaAnalyzer |
|
62 | + */ |
|
63 | + private $schemaAnalyzer; |
|
64 | + |
|
65 | + /** |
|
66 | + * @var MagicQuery |
|
67 | + */ |
|
68 | + private $magicQuery; |
|
69 | + |
|
70 | + /** |
|
71 | + * @var TDBMSchemaAnalyzer |
|
72 | + */ |
|
73 | + private $tdbmSchemaAnalyzer; |
|
74 | + |
|
75 | + /** |
|
76 | + * @var string |
|
77 | + */ |
|
78 | + private $cachePrefix; |
|
79 | + |
|
80 | + /** |
|
81 | + * Cache of table of primary keys. |
|
82 | + * Primary keys are stored by tables, as an array of column. |
|
83 | + * For instance $primary_key['my_table'][0] will return the first column of the primary key of table 'my_table'. |
|
84 | + * |
|
85 | + * @var string[] |
|
86 | + */ |
|
87 | + private $primaryKeysColumns; |
|
88 | + |
|
89 | + /** |
|
90 | + * Service storing objects in memory. |
|
91 | + * Access is done by table name and then by primary key. |
|
92 | + * If the primary key is split on several columns, access is done by an array of columns, serialized. |
|
93 | + * |
|
94 | + * @var StandardObjectStorage|WeakrefObjectStorage |
|
95 | + */ |
|
96 | + private $objectStorage; |
|
97 | + |
|
98 | + /** |
|
99 | + * The fetch mode of the result sets returned by `getObjects`. |
|
100 | + * Can be one of: TDBMObjectArray::MODE_CURSOR or TDBMObjectArray::MODE_ARRAY or TDBMObjectArray::MODE_COMPATIBLE_ARRAY. |
|
101 | + * |
|
102 | + * In 'MODE_ARRAY' mode (default), the result is an array. Use this mode by default (unless the list returned is very big). |
|
103 | + * In 'MODE_CURSOR' mode, the result is a Generator which is an iterable collection that can be scanned only once (only one "foreach") on it, |
|
104 | + * and it cannot be accessed via key. Use this mode for large datasets processed by batch. |
|
105 | + * In 'MODE_COMPATIBLE_ARRAY' mode, the result is an old TDBMObjectArray (used up to TDBM 3.2). |
|
106 | + * You can access the array by key, or using foreach, several times. |
|
107 | + * |
|
108 | + * @var int |
|
109 | + */ |
|
110 | + private $mode = self::MODE_ARRAY; |
|
111 | + |
|
112 | + /** |
|
113 | + * Table of new objects not yet inserted in database or objects modified that must be saved. |
|
114 | + * |
|
115 | + * @var \SplObjectStorage of DbRow objects |
|
116 | + */ |
|
117 | + private $toSaveObjects; |
|
118 | + |
|
119 | + /** |
|
120 | + * A cache service to be used. |
|
121 | + * |
|
122 | + * @var Cache|null |
|
123 | + */ |
|
124 | + private $cache; |
|
125 | + |
|
126 | + /** |
|
127 | + * Map associating a table name to a fully qualified Bean class name. |
|
128 | + * |
|
129 | + * @var array |
|
130 | + */ |
|
131 | + private $tableToBeanMap = []; |
|
132 | + |
|
133 | + /** |
|
134 | + * @var \ReflectionClass[] |
|
135 | + */ |
|
136 | + private $reflectionClassCache = array(); |
|
137 | + |
|
138 | + /** |
|
139 | + * @var LoggerInterface |
|
140 | + */ |
|
141 | + private $rootLogger; |
|
142 | + |
|
143 | + /** |
|
144 | + * @var LevelFilter|NullLogger |
|
145 | + */ |
|
146 | + private $logger; |
|
147 | + |
|
148 | + /** |
|
149 | + * @var OrderByAnalyzer |
|
150 | + */ |
|
151 | + private $orderByAnalyzer; |
|
152 | + |
|
153 | + /** |
|
154 | + * @param Connection $connection The DBAL DB connection to use |
|
155 | + * @param Cache|null $cache A cache service to be used |
|
156 | + * @param SchemaAnalyzer $schemaAnalyzer The schema analyzer that will be used to find shortest paths... |
|
157 | + * Will be automatically created if not passed |
|
158 | + */ |
|
159 | + public function __construct(Connection $connection, Cache $cache = null, SchemaAnalyzer $schemaAnalyzer = null, LoggerInterface $logger = null) |
|
160 | + { |
|
161 | + if (extension_loaded('weakref')) { |
|
162 | + $this->objectStorage = new WeakrefObjectStorage(); |
|
163 | + } else { |
|
164 | + $this->objectStorage = new StandardObjectStorage(); |
|
165 | + } |
|
166 | + $this->connection = $connection; |
|
167 | + if ($cache !== null) { |
|
168 | + $this->cache = $cache; |
|
169 | + } else { |
|
170 | + $this->cache = new VoidCache(); |
|
171 | + } |
|
172 | + if ($schemaAnalyzer) { |
|
173 | + $this->schemaAnalyzer = $schemaAnalyzer; |
|
174 | + } else { |
|
175 | + $this->schemaAnalyzer = new SchemaAnalyzer($this->connection->getSchemaManager(), $this->cache, $this->getConnectionUniqueId()); |
|
176 | + } |
|
177 | + |
|
178 | + $this->magicQuery = new MagicQuery($this->connection, $this->cache, $this->schemaAnalyzer); |
|
179 | + |
|
180 | + $this->tdbmSchemaAnalyzer = new TDBMSchemaAnalyzer($connection, $this->cache, $this->schemaAnalyzer); |
|
181 | + $this->cachePrefix = $this->tdbmSchemaAnalyzer->getCachePrefix(); |
|
182 | + |
|
183 | + $this->toSaveObjects = new \SplObjectStorage(); |
|
184 | + if ($logger === null) { |
|
185 | + $this->logger = new NullLogger(); |
|
186 | + $this->rootLogger = new NullLogger(); |
|
187 | + } else { |
|
188 | + $this->rootLogger = $logger; |
|
189 | + $this->setLogLevel(LogLevel::WARNING); |
|
190 | + } |
|
191 | + $this->orderByAnalyzer = new OrderByAnalyzer($this->cache, $this->cachePrefix); |
|
192 | + } |
|
193 | + |
|
194 | + /** |
|
195 | + * Returns the object used to connect to the database. |
|
196 | + * |
|
197 | + * @return Connection |
|
198 | + */ |
|
199 | + public function getConnection() |
|
200 | + { |
|
201 | + return $this->connection; |
|
202 | + } |
|
203 | + |
|
204 | + /** |
|
205 | + * Creates a unique cache key for the current connection. |
|
206 | + * |
|
207 | + * @return string |
|
208 | + */ |
|
209 | + private function getConnectionUniqueId() |
|
210 | + { |
|
211 | + return hash('md4', $this->connection->getHost().'-'.$this->connection->getPort().'-'.$this->connection->getDatabase().'-'.$this->connection->getDriver()->getName()); |
|
212 | + } |
|
213 | + |
|
214 | + /** |
|
215 | + * Sets the default fetch mode of the result sets returned by `findObjects`. |
|
216 | + * Can be one of: TDBMObjectArray::MODE_CURSOR or TDBMObjectArray::MODE_ARRAY. |
|
217 | + * |
|
218 | + * In 'MODE_ARRAY' mode (default), the result is a ResultIterator object that behaves like an array. Use this mode by default (unless the list returned is very big). |
|
219 | + * In 'MODE_CURSOR' mode, the result is a ResultIterator object. If you scan it many times (by calling several time a foreach loop), the query will be run |
|
220 | + * several times. In cursor mode, you cannot access the result set by key. Use this mode for large datasets processed by batch. |
|
221 | + * |
|
222 | + * @param int $mode |
|
223 | + * |
|
224 | + * @return $this |
|
225 | + * |
|
226 | + * @throws TDBMException |
|
227 | + */ |
|
228 | + public function setFetchMode($mode) |
|
229 | + { |
|
230 | + if ($mode !== self::MODE_CURSOR && $mode !== self::MODE_ARRAY) { |
|
231 | + throw new TDBMException("Unknown fetch mode: '".$this->mode."'"); |
|
232 | + } |
|
233 | + $this->mode = $mode; |
|
234 | + |
|
235 | + return $this; |
|
236 | + } |
|
237 | + |
|
238 | + /** |
|
239 | + * Returns a TDBMObject associated from table "$table_name". |
|
240 | + * If the $filters parameter is an int/string, the object returned will be the object whose primary key = $filters. |
|
241 | + * $filters can also be a set of TDBM_Filters (see the findObjects method for more details). |
|
242 | + * |
|
243 | + * For instance, if there is a table 'users', with a primary key on column 'user_id' and a column 'user_name', then |
|
244 | + * $user = $tdbmService->getObject('users',1); |
|
245 | + * echo $user->name; |
|
246 | + * will return the name of the user whose user_id is one. |
|
247 | + * |
|
248 | + * If a table has a primary key over several columns, you should pass to $id an array containing the the value of the various columns. |
|
249 | + * For instance: |
|
250 | + * $group = $tdbmService->getObject('groups',array(1,2)); |
|
251 | + * |
|
252 | + * Note that TDBMObject performs caching for you. If you get twice the same object, the reference of the object you will get |
|
253 | + * will be the same. |
|
254 | + * |
|
255 | + * For instance: |
|
256 | + * $user1 = $tdbmService->getObject('users',1); |
|
257 | + * $user2 = $tdbmService->getObject('users',1); |
|
258 | + * $user1->name = 'John Doe'; |
|
259 | + * echo $user2->name; |
|
260 | + * will return 'John Doe'. |
|
261 | + * |
|
262 | + * You can use filters instead of passing the primary key. For instance: |
|
263 | + * $user = $tdbmService->getObject('users',new EqualFilter('users', 'login', 'jdoe')); |
|
264 | + * This will return the user whose login is 'jdoe'. |
|
265 | + * Please note that if 2 users have the jdoe login in database, the method will throw a TDBM_DuplicateRowException. |
|
266 | + * |
|
267 | + * Also, you can specify the return class for the object (provided the return class extends TDBMObject). |
|
268 | + * For instance: |
|
269 | + * $user = $tdbmService->getObject('users',1,'User'); |
|
270 | + * will return an object from the "User" class. The "User" class must extend the "TDBMObject" class. |
|
271 | + * Please be sure not to override any method or any property unless you perfectly know what you are doing! |
|
272 | + * |
|
273 | + * @param string $table_name The name of the table we retrieve an object from |
|
274 | + * @param mixed $filters If the filter is a string/integer, it will be considered as the id of the object (the value of the primary key). Otherwise, it can be a filter bag (see the filterbag parameter of the findObjects method for more details about filter bags) |
|
275 | + * @param string $className Optional: The name of the class to instanciate. This class must extend the TDBMObject class. If none is specified, a TDBMObject instance will be returned |
|
276 | + * @param bool $lazy_loading If set to true, and if the primary key is passed in parameter of getObject, the object will not be queried in database. It will be queried when you first try to access a column. If at that time the object cannot be found in database, an exception will be thrown |
|
277 | + * |
|
278 | + * @return TDBMObject |
|
279 | + */ |
|
280 | 280 | /* public function getObject($table_name, $filters, $className = null, $lazy_loading = false) { |
281 | 281 | |
282 | 282 | if (is_array($filters) || $filters instanceof FilterInterface) { |
@@ -362,199 +362,199 @@ discard block |
||
362 | 362 | return $obj; |
363 | 363 | }*/ |
364 | 364 | |
365 | - /** |
|
366 | - * Removes the given object from database. |
|
367 | - * This cannot be called on an object that is not attached to this TDBMService |
|
368 | - * (will throw a TDBMInvalidOperationException). |
|
369 | - * |
|
370 | - * @param AbstractTDBMObject $object the object to delete |
|
371 | - * |
|
372 | - * @throws TDBMException |
|
373 | - * @throws TDBMInvalidOperationException |
|
374 | - */ |
|
375 | - public function delete(AbstractTDBMObject $object) |
|
376 | - { |
|
377 | - switch ($object->_getStatus()) { |
|
378 | - case TDBMObjectStateEnum::STATE_DELETED: |
|
379 | - // Nothing to do, object already deleted. |
|
380 | - return; |
|
381 | - case TDBMObjectStateEnum::STATE_DETACHED: |
|
382 | - throw new TDBMInvalidOperationException('Cannot delete a detached object'); |
|
383 | - case TDBMObjectStateEnum::STATE_NEW: |
|
384 | - $this->deleteManyToManyRelationships($object); |
|
385 | - foreach ($object->_getDbRows() as $dbRow) { |
|
386 | - $this->removeFromToSaveObjectList($dbRow); |
|
387 | - } |
|
388 | - break; |
|
389 | - case TDBMObjectStateEnum::STATE_DIRTY: |
|
390 | - foreach ($object->_getDbRows() as $dbRow) { |
|
391 | - $this->removeFromToSaveObjectList($dbRow); |
|
392 | - } |
|
393 | - // And continue deleting... |
|
394 | - case TDBMObjectStateEnum::STATE_NOT_LOADED: |
|
395 | - case TDBMObjectStateEnum::STATE_LOADED: |
|
396 | - $this->deleteManyToManyRelationships($object); |
|
397 | - // Let's delete db rows, in reverse order. |
|
398 | - foreach (array_reverse($object->_getDbRows()) as $dbRow) { |
|
399 | - $tableName = $dbRow->_getDbTableName(); |
|
400 | - $primaryKeys = $dbRow->_getPrimaryKeys(); |
|
401 | - $this->connection->delete($tableName, $primaryKeys); |
|
402 | - $this->objectStorage->remove($dbRow->_getDbTableName(), $this->getObjectHash($primaryKeys)); |
|
403 | - } |
|
404 | - break; |
|
405 | - // @codeCoverageIgnoreStart |
|
406 | - default: |
|
407 | - throw new TDBMInvalidOperationException('Unexpected status for bean'); |
|
408 | - // @codeCoverageIgnoreEnd |
|
409 | - } |
|
410 | - |
|
411 | - $object->_setStatus(TDBMObjectStateEnum::STATE_DELETED); |
|
412 | - } |
|
413 | - |
|
414 | - /** |
|
415 | - * Removes all many to many relationships for this object. |
|
416 | - * |
|
417 | - * @param AbstractTDBMObject $object |
|
418 | - */ |
|
419 | - private function deleteManyToManyRelationships(AbstractTDBMObject $object) |
|
420 | - { |
|
421 | - foreach ($object->_getDbRows() as $tableName => $dbRow) { |
|
422 | - $pivotTables = $this->tdbmSchemaAnalyzer->getPivotTableLinkedToTable($tableName); |
|
423 | - foreach ($pivotTables as $pivotTable) { |
|
424 | - $remoteBeans = $object->_getRelationships($pivotTable); |
|
425 | - foreach ($remoteBeans as $remoteBean) { |
|
426 | - $object->_removeRelationship($pivotTable, $remoteBean); |
|
427 | - } |
|
428 | - } |
|
429 | - } |
|
430 | - $this->persistManyToManyRelationships($object); |
|
431 | - } |
|
432 | - |
|
433 | - /** |
|
434 | - * This function removes the given object from the database. It will also remove all objects relied to the one given |
|
435 | - * by parameter before all. |
|
436 | - * |
|
437 | - * Notice: if the object has a multiple primary key, the function will not work. |
|
438 | - * |
|
439 | - * @param AbstractTDBMObject $objToDelete |
|
440 | - */ |
|
441 | - public function deleteCascade(AbstractTDBMObject $objToDelete) |
|
442 | - { |
|
443 | - $this->deleteAllConstraintWithThisObject($objToDelete); |
|
444 | - $this->delete($objToDelete); |
|
445 | - } |
|
446 | - |
|
447 | - /** |
|
448 | - * This function is used only in TDBMService (private function) |
|
449 | - * It will call deleteCascade function foreach object relied with a foreign key to the object given by parameter. |
|
450 | - * |
|
451 | - * @param AbstractTDBMObject $obj |
|
452 | - */ |
|
453 | - private function deleteAllConstraintWithThisObject(AbstractTDBMObject $obj) |
|
454 | - { |
|
455 | - $dbRows = $obj->_getDbRows(); |
|
456 | - foreach ($dbRows as $dbRow) { |
|
457 | - $tableName = $dbRow->_getDbTableName(); |
|
458 | - $pks = array_values($dbRow->_getPrimaryKeys()); |
|
459 | - if (!empty($pks)) { |
|
460 | - $incomingFks = $this->tdbmSchemaAnalyzer->getIncomingForeignKeys($tableName); |
|
461 | - |
|
462 | - foreach ($incomingFks as $incomingFk) { |
|
463 | - $filter = array_combine($incomingFk->getLocalColumns(), $pks); |
|
464 | - |
|
465 | - $results = $this->findObjects($incomingFk->getLocalTableName(), $filter); |
|
466 | - |
|
467 | - foreach ($results as $bean) { |
|
468 | - $this->deleteCascade($bean); |
|
469 | - } |
|
470 | - } |
|
471 | - } |
|
472 | - } |
|
473 | - } |
|
474 | - |
|
475 | - /** |
|
476 | - * This function performs a save() of all the objects that have been modified. |
|
477 | - */ |
|
478 | - public function completeSave() |
|
479 | - { |
|
480 | - foreach ($this->toSaveObjects as $dbRow) { |
|
481 | - $this->save($dbRow->getTDBMObject()); |
|
482 | - } |
|
483 | - } |
|
484 | - |
|
485 | - /** |
|
486 | - * Takes in input a filter_bag (which can be about anything from a string to an array of TDBMObjects... see above from documentation), |
|
487 | - * and gives back a proper Filter object. |
|
488 | - * |
|
489 | - * @param mixed $filter_bag |
|
490 | - * @param int $counter |
|
491 | - * |
|
492 | - * @return array First item: filter string, second item: parameters |
|
493 | - * |
|
494 | - * @throws TDBMException |
|
495 | - */ |
|
496 | - public function buildFilterFromFilterBag($filter_bag, $counter = 1) |
|
497 | - { |
|
498 | - if ($filter_bag === null) { |
|
499 | - return ['', []]; |
|
500 | - } elseif (is_string($filter_bag)) { |
|
501 | - return [$filter_bag, []]; |
|
502 | - } elseif (is_array($filter_bag)) { |
|
503 | - $sqlParts = []; |
|
504 | - $parameters = []; |
|
505 | - foreach ($filter_bag as $column => $value) { |
|
506 | - if (is_int($column)) { |
|
507 | - list($subSqlPart, $subParameters) = $this->buildFilterFromFilterBag($value, $counter); |
|
508 | - $sqlParts[] = $subSqlPart; |
|
509 | - $parameters += $subParameters; |
|
510 | - } else { |
|
511 | - $paramName = 'tdbmparam'.$counter; |
|
512 | - if (is_array($value)) { |
|
513 | - $sqlParts[] = $this->connection->quoteIdentifier($column).' IN :'.$paramName; |
|
514 | - } else { |
|
515 | - $sqlParts[] = $this->connection->quoteIdentifier($column).' = :'.$paramName; |
|
516 | - } |
|
517 | - $parameters[$paramName] = $value; |
|
518 | - ++$counter; |
|
519 | - } |
|
520 | - } |
|
521 | - |
|
522 | - return [implode(' AND ', $sqlParts), $parameters]; |
|
523 | - } elseif ($filter_bag instanceof AbstractTDBMObject) { |
|
524 | - $sqlParts = []; |
|
525 | - $parameters = []; |
|
526 | - $dbRows = $filter_bag->_getDbRows(); |
|
527 | - $dbRow = reset($dbRows); |
|
528 | - $primaryKeys = $dbRow->_getPrimaryKeys(); |
|
529 | - |
|
530 | - foreach ($primaryKeys as $column => $value) { |
|
531 | - $paramName = 'tdbmparam'.$counter; |
|
532 | - $sqlParts[] = $this->connection->quoteIdentifier($dbRow->_getDbTableName()).'.'.$this->connection->quoteIdentifier($column).' = :'.$paramName; |
|
533 | - $parameters[$paramName] = $value; |
|
534 | - ++$counter; |
|
535 | - } |
|
536 | - |
|
537 | - return [implode(' AND ', $sqlParts), $parameters]; |
|
538 | - } elseif ($filter_bag instanceof \Iterator) { |
|
539 | - return $this->buildFilterFromFilterBag(iterator_to_array($filter_bag), $counter); |
|
540 | - } else { |
|
541 | - throw new TDBMException('Error in filter. An object has been passed that is neither a SQL string, nor an array, nor a bean, nor null.'); |
|
542 | - } |
|
543 | - } |
|
544 | - |
|
545 | - /** |
|
546 | - * @param string $table |
|
547 | - * |
|
548 | - * @return string[] |
|
549 | - */ |
|
550 | - public function getPrimaryKeyColumns($table) |
|
551 | - { |
|
552 | - if (!isset($this->primaryKeysColumns[$table])) { |
|
553 | - $this->primaryKeysColumns[$table] = $this->tdbmSchemaAnalyzer->getSchema()->getTable($table)->getPrimaryKeyColumns(); |
|
554 | - |
|
555 | - // TODO TDBM4: See if we need to improve error reporting if table name does not exist. |
|
556 | - |
|
557 | - /*$arr = array(); |
|
365 | + /** |
|
366 | + * Removes the given object from database. |
|
367 | + * This cannot be called on an object that is not attached to this TDBMService |
|
368 | + * (will throw a TDBMInvalidOperationException). |
|
369 | + * |
|
370 | + * @param AbstractTDBMObject $object the object to delete |
|
371 | + * |
|
372 | + * @throws TDBMException |
|
373 | + * @throws TDBMInvalidOperationException |
|
374 | + */ |
|
375 | + public function delete(AbstractTDBMObject $object) |
|
376 | + { |
|
377 | + switch ($object->_getStatus()) { |
|
378 | + case TDBMObjectStateEnum::STATE_DELETED: |
|
379 | + // Nothing to do, object already deleted. |
|
380 | + return; |
|
381 | + case TDBMObjectStateEnum::STATE_DETACHED: |
|
382 | + throw new TDBMInvalidOperationException('Cannot delete a detached object'); |
|
383 | + case TDBMObjectStateEnum::STATE_NEW: |
|
384 | + $this->deleteManyToManyRelationships($object); |
|
385 | + foreach ($object->_getDbRows() as $dbRow) { |
|
386 | + $this->removeFromToSaveObjectList($dbRow); |
|
387 | + } |
|
388 | + break; |
|
389 | + case TDBMObjectStateEnum::STATE_DIRTY: |
|
390 | + foreach ($object->_getDbRows() as $dbRow) { |
|
391 | + $this->removeFromToSaveObjectList($dbRow); |
|
392 | + } |
|
393 | + // And continue deleting... |
|
394 | + case TDBMObjectStateEnum::STATE_NOT_LOADED: |
|
395 | + case TDBMObjectStateEnum::STATE_LOADED: |
|
396 | + $this->deleteManyToManyRelationships($object); |
|
397 | + // Let's delete db rows, in reverse order. |
|
398 | + foreach (array_reverse($object->_getDbRows()) as $dbRow) { |
|
399 | + $tableName = $dbRow->_getDbTableName(); |
|
400 | + $primaryKeys = $dbRow->_getPrimaryKeys(); |
|
401 | + $this->connection->delete($tableName, $primaryKeys); |
|
402 | + $this->objectStorage->remove($dbRow->_getDbTableName(), $this->getObjectHash($primaryKeys)); |
|
403 | + } |
|
404 | + break; |
|
405 | + // @codeCoverageIgnoreStart |
|
406 | + default: |
|
407 | + throw new TDBMInvalidOperationException('Unexpected status for bean'); |
|
408 | + // @codeCoverageIgnoreEnd |
|
409 | + } |
|
410 | + |
|
411 | + $object->_setStatus(TDBMObjectStateEnum::STATE_DELETED); |
|
412 | + } |
|
413 | + |
|
414 | + /** |
|
415 | + * Removes all many to many relationships for this object. |
|
416 | + * |
|
417 | + * @param AbstractTDBMObject $object |
|
418 | + */ |
|
419 | + private function deleteManyToManyRelationships(AbstractTDBMObject $object) |
|
420 | + { |
|
421 | + foreach ($object->_getDbRows() as $tableName => $dbRow) { |
|
422 | + $pivotTables = $this->tdbmSchemaAnalyzer->getPivotTableLinkedToTable($tableName); |
|
423 | + foreach ($pivotTables as $pivotTable) { |
|
424 | + $remoteBeans = $object->_getRelationships($pivotTable); |
|
425 | + foreach ($remoteBeans as $remoteBean) { |
|
426 | + $object->_removeRelationship($pivotTable, $remoteBean); |
|
427 | + } |
|
428 | + } |
|
429 | + } |
|
430 | + $this->persistManyToManyRelationships($object); |
|
431 | + } |
|
432 | + |
|
433 | + /** |
|
434 | + * This function removes the given object from the database. It will also remove all objects relied to the one given |
|
435 | + * by parameter before all. |
|
436 | + * |
|
437 | + * Notice: if the object has a multiple primary key, the function will not work. |
|
438 | + * |
|
439 | + * @param AbstractTDBMObject $objToDelete |
|
440 | + */ |
|
441 | + public function deleteCascade(AbstractTDBMObject $objToDelete) |
|
442 | + { |
|
443 | + $this->deleteAllConstraintWithThisObject($objToDelete); |
|
444 | + $this->delete($objToDelete); |
|
445 | + } |
|
446 | + |
|
447 | + /** |
|
448 | + * This function is used only in TDBMService (private function) |
|
449 | + * It will call deleteCascade function foreach object relied with a foreign key to the object given by parameter. |
|
450 | + * |
|
451 | + * @param AbstractTDBMObject $obj |
|
452 | + */ |
|
453 | + private function deleteAllConstraintWithThisObject(AbstractTDBMObject $obj) |
|
454 | + { |
|
455 | + $dbRows = $obj->_getDbRows(); |
|
456 | + foreach ($dbRows as $dbRow) { |
|
457 | + $tableName = $dbRow->_getDbTableName(); |
|
458 | + $pks = array_values($dbRow->_getPrimaryKeys()); |
|
459 | + if (!empty($pks)) { |
|
460 | + $incomingFks = $this->tdbmSchemaAnalyzer->getIncomingForeignKeys($tableName); |
|
461 | + |
|
462 | + foreach ($incomingFks as $incomingFk) { |
|
463 | + $filter = array_combine($incomingFk->getLocalColumns(), $pks); |
|
464 | + |
|
465 | + $results = $this->findObjects($incomingFk->getLocalTableName(), $filter); |
|
466 | + |
|
467 | + foreach ($results as $bean) { |
|
468 | + $this->deleteCascade($bean); |
|
469 | + } |
|
470 | + } |
|
471 | + } |
|
472 | + } |
|
473 | + } |
|
474 | + |
|
475 | + /** |
|
476 | + * This function performs a save() of all the objects that have been modified. |
|
477 | + */ |
|
478 | + public function completeSave() |
|
479 | + { |
|
480 | + foreach ($this->toSaveObjects as $dbRow) { |
|
481 | + $this->save($dbRow->getTDBMObject()); |
|
482 | + } |
|
483 | + } |
|
484 | + |
|
485 | + /** |
|
486 | + * Takes in input a filter_bag (which can be about anything from a string to an array of TDBMObjects... see above from documentation), |
|
487 | + * and gives back a proper Filter object. |
|
488 | + * |
|
489 | + * @param mixed $filter_bag |
|
490 | + * @param int $counter |
|
491 | + * |
|
492 | + * @return array First item: filter string, second item: parameters |
|
493 | + * |
|
494 | + * @throws TDBMException |
|
495 | + */ |
|
496 | + public function buildFilterFromFilterBag($filter_bag, $counter = 1) |
|
497 | + { |
|
498 | + if ($filter_bag === null) { |
|
499 | + return ['', []]; |
|
500 | + } elseif (is_string($filter_bag)) { |
|
501 | + return [$filter_bag, []]; |
|
502 | + } elseif (is_array($filter_bag)) { |
|
503 | + $sqlParts = []; |
|
504 | + $parameters = []; |
|
505 | + foreach ($filter_bag as $column => $value) { |
|
506 | + if (is_int($column)) { |
|
507 | + list($subSqlPart, $subParameters) = $this->buildFilterFromFilterBag($value, $counter); |
|
508 | + $sqlParts[] = $subSqlPart; |
|
509 | + $parameters += $subParameters; |
|
510 | + } else { |
|
511 | + $paramName = 'tdbmparam'.$counter; |
|
512 | + if (is_array($value)) { |
|
513 | + $sqlParts[] = $this->connection->quoteIdentifier($column).' IN :'.$paramName; |
|
514 | + } else { |
|
515 | + $sqlParts[] = $this->connection->quoteIdentifier($column).' = :'.$paramName; |
|
516 | + } |
|
517 | + $parameters[$paramName] = $value; |
|
518 | + ++$counter; |
|
519 | + } |
|
520 | + } |
|
521 | + |
|
522 | + return [implode(' AND ', $sqlParts), $parameters]; |
|
523 | + } elseif ($filter_bag instanceof AbstractTDBMObject) { |
|
524 | + $sqlParts = []; |
|
525 | + $parameters = []; |
|
526 | + $dbRows = $filter_bag->_getDbRows(); |
|
527 | + $dbRow = reset($dbRows); |
|
528 | + $primaryKeys = $dbRow->_getPrimaryKeys(); |
|
529 | + |
|
530 | + foreach ($primaryKeys as $column => $value) { |
|
531 | + $paramName = 'tdbmparam'.$counter; |
|
532 | + $sqlParts[] = $this->connection->quoteIdentifier($dbRow->_getDbTableName()).'.'.$this->connection->quoteIdentifier($column).' = :'.$paramName; |
|
533 | + $parameters[$paramName] = $value; |
|
534 | + ++$counter; |
|
535 | + } |
|
536 | + |
|
537 | + return [implode(' AND ', $sqlParts), $parameters]; |
|
538 | + } elseif ($filter_bag instanceof \Iterator) { |
|
539 | + return $this->buildFilterFromFilterBag(iterator_to_array($filter_bag), $counter); |
|
540 | + } else { |
|
541 | + throw new TDBMException('Error in filter. An object has been passed that is neither a SQL string, nor an array, nor a bean, nor null.'); |
|
542 | + } |
|
543 | + } |
|
544 | + |
|
545 | + /** |
|
546 | + * @param string $table |
|
547 | + * |
|
548 | + * @return string[] |
|
549 | + */ |
|
550 | + public function getPrimaryKeyColumns($table) |
|
551 | + { |
|
552 | + if (!isset($this->primaryKeysColumns[$table])) { |
|
553 | + $this->primaryKeysColumns[$table] = $this->tdbmSchemaAnalyzer->getSchema()->getTable($table)->getPrimaryKeyColumns(); |
|
554 | + |
|
555 | + // TODO TDBM4: See if we need to improve error reporting if table name does not exist. |
|
556 | + |
|
557 | + /*$arr = array(); |
|
558 | 558 | foreach ($this->connection->getPrimaryKey($table) as $col) { |
559 | 559 | $arr[] = $col->name; |
560 | 560 | } |
@@ -575,158 +575,158 @@ discard block |
||
575 | 575 | throw new TDBMException($str); |
576 | 576 | } |
577 | 577 | }*/ |
578 | - } |
|
579 | - |
|
580 | - return $this->primaryKeysColumns[$table]; |
|
581 | - } |
|
582 | - |
|
583 | - /** |
|
584 | - * This is an internal function, you should not use it in your application. |
|
585 | - * This is used internally by TDBM to add an object to the object cache. |
|
586 | - * |
|
587 | - * @param DbRow $dbRow |
|
588 | - */ |
|
589 | - public function _addToCache(DbRow $dbRow) |
|
590 | - { |
|
591 | - $primaryKey = $this->getPrimaryKeysForObjectFromDbRow($dbRow); |
|
592 | - $hash = $this->getObjectHash($primaryKey); |
|
593 | - $this->objectStorage->set($dbRow->_getDbTableName(), $hash, $dbRow); |
|
594 | - } |
|
595 | - |
|
596 | - /** |
|
597 | - * This is an internal function, you should not use it in your application. |
|
598 | - * This is used internally by TDBM to remove the object from the list of objects that have been |
|
599 | - * created/updated but not saved yet. |
|
600 | - * |
|
601 | - * @param DbRow $myObject |
|
602 | - */ |
|
603 | - private function removeFromToSaveObjectList(DbRow $myObject) |
|
604 | - { |
|
605 | - unset($this->toSaveObjects[$myObject]); |
|
606 | - } |
|
607 | - |
|
608 | - /** |
|
609 | - * This is an internal function, you should not use it in your application. |
|
610 | - * This is used internally by TDBM to add an object to the list of objects that have been |
|
611 | - * created/updated but not saved yet. |
|
612 | - * |
|
613 | - * @param AbstractTDBMObject $myObject |
|
614 | - */ |
|
615 | - public function _addToToSaveObjectList(DbRow $myObject) |
|
616 | - { |
|
617 | - $this->toSaveObjects[$myObject] = true; |
|
618 | - } |
|
619 | - |
|
620 | - /** |
|
621 | - * Generates all the daos and beans. |
|
622 | - * |
|
623 | - * @param string $daoFactoryClassName The classe name of the DAO factory |
|
624 | - * @param string $daonamespace The namespace for the DAOs, without trailing \ |
|
625 | - * @param string $beannamespace The Namespace for the beans, without trailing \ |
|
626 | - * @param bool $storeInUtc If the generated daos should store the date in UTC timezone instead of user's timezone |
|
627 | - * @param string $composerFile If it's set, location of custom Composer file. Relative to project root |
|
628 | - * |
|
629 | - * @return \string[] the list of tables |
|
630 | - */ |
|
631 | - public function generateAllDaosAndBeans($daoFactoryClassName, $daonamespace, $beannamespace, $storeInUtc, $composerFile = null) |
|
632 | - { |
|
633 | - // Purge cache before generating anything. |
|
634 | - $this->cache->deleteAll(); |
|
635 | - |
|
636 | - $tdbmDaoGenerator = new TDBMDaoGenerator($this->schemaAnalyzer, $this->tdbmSchemaAnalyzer->getSchema(), $this->tdbmSchemaAnalyzer); |
|
637 | - if (null !== $composerFile) { |
|
638 | - $tdbmDaoGenerator->setComposerFile(__DIR__.'/../../../../../../../'.$composerFile); |
|
639 | - } |
|
640 | - |
|
641 | - return $tdbmDaoGenerator->generateAllDaosAndBeans($daoFactoryClassName, $daonamespace, $beannamespace, $storeInUtc); |
|
642 | - } |
|
643 | - |
|
644 | - /** |
|
645 | - * @param array<string, string> $tableToBeanMap |
|
646 | - */ |
|
647 | - public function setTableToBeanMap(array $tableToBeanMap) |
|
648 | - { |
|
649 | - $this->tableToBeanMap = $tableToBeanMap; |
|
650 | - } |
|
651 | - |
|
652 | - /** |
|
653 | - * Returns the fully qualified class name of the bean associated with table $tableName. |
|
654 | - * |
|
655 | - * |
|
656 | - * @param string $tableName |
|
657 | - * |
|
658 | - * @return string |
|
659 | - */ |
|
660 | - public function getBeanClassName(string $tableName) : string |
|
661 | - { |
|
662 | - if (isset($this->tableToBeanMap[$tableName])) { |
|
663 | - return $this->tableToBeanMap[$tableName]; |
|
664 | - } else { |
|
665 | - throw new TDBMInvalidArgumentException(sprintf('Could not find a map between table "%s" and any bean. Does table "%s" exists?', $tableName, $tableName)); |
|
666 | - } |
|
667 | - } |
|
668 | - |
|
669 | - /** |
|
670 | - * Saves $object by INSERTing or UPDAT(E)ing it in the database. |
|
671 | - * |
|
672 | - * @param AbstractTDBMObject $object |
|
673 | - * |
|
674 | - * @throws TDBMException |
|
675 | - */ |
|
676 | - public function save(AbstractTDBMObject $object) |
|
677 | - { |
|
678 | - $status = $object->_getStatus(); |
|
679 | - |
|
680 | - if ($status === null) { |
|
681 | - throw new TDBMException(sprintf('Your bean for class %s has no status. It is likely that you overloaded the __construct method and forgot to call parent::__construct.', get_class($object))); |
|
682 | - } |
|
683 | - |
|
684 | - // Let's attach this object if it is in detached state. |
|
685 | - if ($status === TDBMObjectStateEnum::STATE_DETACHED) { |
|
686 | - $object->_attach($this); |
|
687 | - $status = $object->_getStatus(); |
|
688 | - } |
|
689 | - |
|
690 | - if ($status === TDBMObjectStateEnum::STATE_NEW) { |
|
691 | - $dbRows = $object->_getDbRows(); |
|
692 | - |
|
693 | - $unindexedPrimaryKeys = array(); |
|
694 | - |
|
695 | - foreach ($dbRows as $dbRow) { |
|
696 | - $tableName = $dbRow->_getDbTableName(); |
|
697 | - |
|
698 | - $schema = $this->tdbmSchemaAnalyzer->getSchema(); |
|
699 | - $tableDescriptor = $schema->getTable($tableName); |
|
700 | - |
|
701 | - $primaryKeyColumns = $this->getPrimaryKeyColumns($tableName); |
|
702 | - |
|
703 | - if (empty($unindexedPrimaryKeys)) { |
|
704 | - $primaryKeys = $this->getPrimaryKeysForObjectFromDbRow($dbRow); |
|
705 | - } else { |
|
706 | - // First insert, the children must have the same primary key as the parent. |
|
707 | - $primaryKeys = $this->_getPrimaryKeysFromIndexedPrimaryKeys($tableName, $unindexedPrimaryKeys); |
|
708 | - $dbRow->_setPrimaryKeys($primaryKeys); |
|
709 | - } |
|
710 | - |
|
711 | - $references = $dbRow->_getReferences(); |
|
712 | - |
|
713 | - // Let's save all references in NEW or DETACHED state (we need their primary key) |
|
714 | - foreach ($references as $fkName => $reference) { |
|
715 | - if ($reference !== null) { |
|
716 | - $refStatus = $reference->_getStatus(); |
|
717 | - if ($refStatus === TDBMObjectStateEnum::STATE_NEW || $refStatus === TDBMObjectStateEnum::STATE_DETACHED) { |
|
718 | - $this->save($reference); |
|
719 | - } |
|
720 | - } |
|
721 | - } |
|
722 | - |
|
723 | - $dbRowData = $dbRow->_getDbRow(); |
|
724 | - |
|
725 | - // Let's see if the columns for primary key have been set before inserting. |
|
726 | - // We assume that if one of the value of the PK has been set, the PK is set. |
|
727 | - $isPkSet = !empty($primaryKeys); |
|
728 | - |
|
729 | - /*if (!$isPkSet) { |
|
578 | + } |
|
579 | + |
|
580 | + return $this->primaryKeysColumns[$table]; |
|
581 | + } |
|
582 | + |
|
583 | + /** |
|
584 | + * This is an internal function, you should not use it in your application. |
|
585 | + * This is used internally by TDBM to add an object to the object cache. |
|
586 | + * |
|
587 | + * @param DbRow $dbRow |
|
588 | + */ |
|
589 | + public function _addToCache(DbRow $dbRow) |
|
590 | + { |
|
591 | + $primaryKey = $this->getPrimaryKeysForObjectFromDbRow($dbRow); |
|
592 | + $hash = $this->getObjectHash($primaryKey); |
|
593 | + $this->objectStorage->set($dbRow->_getDbTableName(), $hash, $dbRow); |
|
594 | + } |
|
595 | + |
|
596 | + /** |
|
597 | + * This is an internal function, you should not use it in your application. |
|
598 | + * This is used internally by TDBM to remove the object from the list of objects that have been |
|
599 | + * created/updated but not saved yet. |
|
600 | + * |
|
601 | + * @param DbRow $myObject |
|
602 | + */ |
|
603 | + private function removeFromToSaveObjectList(DbRow $myObject) |
|
604 | + { |
|
605 | + unset($this->toSaveObjects[$myObject]); |
|
606 | + } |
|
607 | + |
|
608 | + /** |
|
609 | + * This is an internal function, you should not use it in your application. |
|
610 | + * This is used internally by TDBM to add an object to the list of objects that have been |
|
611 | + * created/updated but not saved yet. |
|
612 | + * |
|
613 | + * @param AbstractTDBMObject $myObject |
|
614 | + */ |
|
615 | + public function _addToToSaveObjectList(DbRow $myObject) |
|
616 | + { |
|
617 | + $this->toSaveObjects[$myObject] = true; |
|
618 | + } |
|
619 | + |
|
620 | + /** |
|
621 | + * Generates all the daos and beans. |
|
622 | + * |
|
623 | + * @param string $daoFactoryClassName The classe name of the DAO factory |
|
624 | + * @param string $daonamespace The namespace for the DAOs, without trailing \ |
|
625 | + * @param string $beannamespace The Namespace for the beans, without trailing \ |
|
626 | + * @param bool $storeInUtc If the generated daos should store the date in UTC timezone instead of user's timezone |
|
627 | + * @param string $composerFile If it's set, location of custom Composer file. Relative to project root |
|
628 | + * |
|
629 | + * @return \string[] the list of tables |
|
630 | + */ |
|
631 | + public function generateAllDaosAndBeans($daoFactoryClassName, $daonamespace, $beannamespace, $storeInUtc, $composerFile = null) |
|
632 | + { |
|
633 | + // Purge cache before generating anything. |
|
634 | + $this->cache->deleteAll(); |
|
635 | + |
|
636 | + $tdbmDaoGenerator = new TDBMDaoGenerator($this->schemaAnalyzer, $this->tdbmSchemaAnalyzer->getSchema(), $this->tdbmSchemaAnalyzer); |
|
637 | + if (null !== $composerFile) { |
|
638 | + $tdbmDaoGenerator->setComposerFile(__DIR__.'/../../../../../../../'.$composerFile); |
|
639 | + } |
|
640 | + |
|
641 | + return $tdbmDaoGenerator->generateAllDaosAndBeans($daoFactoryClassName, $daonamespace, $beannamespace, $storeInUtc); |
|
642 | + } |
|
643 | + |
|
644 | + /** |
|
645 | + * @param array<string, string> $tableToBeanMap |
|
646 | + */ |
|
647 | + public function setTableToBeanMap(array $tableToBeanMap) |
|
648 | + { |
|
649 | + $this->tableToBeanMap = $tableToBeanMap; |
|
650 | + } |
|
651 | + |
|
652 | + /** |
|
653 | + * Returns the fully qualified class name of the bean associated with table $tableName. |
|
654 | + * |
|
655 | + * |
|
656 | + * @param string $tableName |
|
657 | + * |
|
658 | + * @return string |
|
659 | + */ |
|
660 | + public function getBeanClassName(string $tableName) : string |
|
661 | + { |
|
662 | + if (isset($this->tableToBeanMap[$tableName])) { |
|
663 | + return $this->tableToBeanMap[$tableName]; |
|
664 | + } else { |
|
665 | + throw new TDBMInvalidArgumentException(sprintf('Could not find a map between table "%s" and any bean. Does table "%s" exists?', $tableName, $tableName)); |
|
666 | + } |
|
667 | + } |
|
668 | + |
|
669 | + /** |
|
670 | + * Saves $object by INSERTing or UPDAT(E)ing it in the database. |
|
671 | + * |
|
672 | + * @param AbstractTDBMObject $object |
|
673 | + * |
|
674 | + * @throws TDBMException |
|
675 | + */ |
|
676 | + public function save(AbstractTDBMObject $object) |
|
677 | + { |
|
678 | + $status = $object->_getStatus(); |
|
679 | + |
|
680 | + if ($status === null) { |
|
681 | + throw new TDBMException(sprintf('Your bean for class %s has no status. It is likely that you overloaded the __construct method and forgot to call parent::__construct.', get_class($object))); |
|
682 | + } |
|
683 | + |
|
684 | + // Let's attach this object if it is in detached state. |
|
685 | + if ($status === TDBMObjectStateEnum::STATE_DETACHED) { |
|
686 | + $object->_attach($this); |
|
687 | + $status = $object->_getStatus(); |
|
688 | + } |
|
689 | + |
|
690 | + if ($status === TDBMObjectStateEnum::STATE_NEW) { |
|
691 | + $dbRows = $object->_getDbRows(); |
|
692 | + |
|
693 | + $unindexedPrimaryKeys = array(); |
|
694 | + |
|
695 | + foreach ($dbRows as $dbRow) { |
|
696 | + $tableName = $dbRow->_getDbTableName(); |
|
697 | + |
|
698 | + $schema = $this->tdbmSchemaAnalyzer->getSchema(); |
|
699 | + $tableDescriptor = $schema->getTable($tableName); |
|
700 | + |
|
701 | + $primaryKeyColumns = $this->getPrimaryKeyColumns($tableName); |
|
702 | + |
|
703 | + if (empty($unindexedPrimaryKeys)) { |
|
704 | + $primaryKeys = $this->getPrimaryKeysForObjectFromDbRow($dbRow); |
|
705 | + } else { |
|
706 | + // First insert, the children must have the same primary key as the parent. |
|
707 | + $primaryKeys = $this->_getPrimaryKeysFromIndexedPrimaryKeys($tableName, $unindexedPrimaryKeys); |
|
708 | + $dbRow->_setPrimaryKeys($primaryKeys); |
|
709 | + } |
|
710 | + |
|
711 | + $references = $dbRow->_getReferences(); |
|
712 | + |
|
713 | + // Let's save all references in NEW or DETACHED state (we need their primary key) |
|
714 | + foreach ($references as $fkName => $reference) { |
|
715 | + if ($reference !== null) { |
|
716 | + $refStatus = $reference->_getStatus(); |
|
717 | + if ($refStatus === TDBMObjectStateEnum::STATE_NEW || $refStatus === TDBMObjectStateEnum::STATE_DETACHED) { |
|
718 | + $this->save($reference); |
|
719 | + } |
|
720 | + } |
|
721 | + } |
|
722 | + |
|
723 | + $dbRowData = $dbRow->_getDbRow(); |
|
724 | + |
|
725 | + // Let's see if the columns for primary key have been set before inserting. |
|
726 | + // We assume that if one of the value of the PK has been set, the PK is set. |
|
727 | + $isPkSet = !empty($primaryKeys); |
|
728 | + |
|
729 | + /*if (!$isPkSet) { |
|
730 | 730 | // if there is no autoincrement and no pk set, let's go in error. |
731 | 731 | $isAutoIncrement = true; |
732 | 732 | |
@@ -744,27 +744,27 @@ discard block |
||
744 | 744 | |
745 | 745 | }*/ |
746 | 746 | |
747 | - $types = []; |
|
748 | - $escapedDbRowData = []; |
|
747 | + $types = []; |
|
748 | + $escapedDbRowData = []; |
|
749 | 749 | |
750 | - foreach ($dbRowData as $columnName => $value) { |
|
751 | - $columnDescriptor = $tableDescriptor->getColumn($columnName); |
|
752 | - $types[] = $columnDescriptor->getType(); |
|
753 | - $escapedDbRowData[$this->connection->quoteIdentifier($columnName)] = $value; |
|
754 | - } |
|
750 | + foreach ($dbRowData as $columnName => $value) { |
|
751 | + $columnDescriptor = $tableDescriptor->getColumn($columnName); |
|
752 | + $types[] = $columnDescriptor->getType(); |
|
753 | + $escapedDbRowData[$this->connection->quoteIdentifier($columnName)] = $value; |
|
754 | + } |
|
755 | 755 | |
756 | - $this->connection->insert($tableName, $escapedDbRowData, $types); |
|
756 | + $this->connection->insert($tableName, $escapedDbRowData, $types); |
|
757 | 757 | |
758 | - if (!$isPkSet && count($primaryKeyColumns) == 1) { |
|
759 | - $id = $this->connection->lastInsertId(); |
|
760 | - $primaryKeys[$primaryKeyColumns[0]] = $id; |
|
761 | - } |
|
758 | + if (!$isPkSet && count($primaryKeyColumns) == 1) { |
|
759 | + $id = $this->connection->lastInsertId(); |
|
760 | + $primaryKeys[$primaryKeyColumns[0]] = $id; |
|
761 | + } |
|
762 | 762 | |
763 | - // TODO: change this to some private magic accessor in future |
|
764 | - $dbRow->_setPrimaryKeys($primaryKeys); |
|
765 | - $unindexedPrimaryKeys = array_values($primaryKeys); |
|
763 | + // TODO: change this to some private magic accessor in future |
|
764 | + $dbRow->_setPrimaryKeys($primaryKeys); |
|
765 | + $unindexedPrimaryKeys = array_values($primaryKeys); |
|
766 | 766 | |
767 | - /* |
|
767 | + /* |
|
768 | 768 | * When attached, on "save", we check if the column updated is part of a primary key |
769 | 769 | * If this is part of a primary key, we call the _update_id method that updates the id in the list of known objects. |
770 | 770 | * This method should first verify that the id is not already used (and is not auto-incremented) |
@@ -774,7 +774,7 @@ discard block |
||
774 | 774 | * |
775 | 775 | */ |
776 | 776 | |
777 | - /*try { |
|
777 | + /*try { |
|
778 | 778 | $this->db_connection->exec($sql); |
779 | 779 | } catch (TDBMException $e) { |
780 | 780 | $this->db_onerror = true; |
@@ -793,405 +793,405 @@ discard block |
||
793 | 793 | } |
794 | 794 | }*/ |
795 | 795 | |
796 | - // Let's remove this object from the $new_objects static table. |
|
797 | - $this->removeFromToSaveObjectList($dbRow); |
|
798 | - |
|
799 | - // TODO: change this behaviour to something more sensible performance-wise |
|
800 | - // Maybe a setting to trigger this globally? |
|
801 | - //$this->status = TDBMObjectStateEnum::STATE_NOT_LOADED; |
|
802 | - //$this->db_modified_state = false; |
|
803 | - //$dbRow = array(); |
|
804 | - |
|
805 | - // Let's add this object to the list of objects in cache. |
|
806 | - $this->_addToCache($dbRow); |
|
807 | - } |
|
808 | - |
|
809 | - $object->_setStatus(TDBMObjectStateEnum::STATE_LOADED); |
|
810 | - } elseif ($status === TDBMObjectStateEnum::STATE_DIRTY) { |
|
811 | - $dbRows = $object->_getDbRows(); |
|
812 | - |
|
813 | - foreach ($dbRows as $dbRow) { |
|
814 | - $references = $dbRow->_getReferences(); |
|
815 | - |
|
816 | - // Let's save all references in NEW state (we need their primary key) |
|
817 | - foreach ($references as $fkName => $reference) { |
|
818 | - if ($reference !== null && $reference->_getStatus() === TDBMObjectStateEnum::STATE_NEW) { |
|
819 | - $this->save($reference); |
|
820 | - } |
|
821 | - } |
|
822 | - |
|
823 | - // Let's first get the primary keys |
|
824 | - $tableName = $dbRow->_getDbTableName(); |
|
825 | - $dbRowData = $dbRow->_getDbRow(); |
|
826 | - |
|
827 | - $schema = $this->tdbmSchemaAnalyzer->getSchema(); |
|
828 | - $tableDescriptor = $schema->getTable($tableName); |
|
829 | - |
|
830 | - $primaryKeys = $dbRow->_getPrimaryKeys(); |
|
831 | - |
|
832 | - $types = []; |
|
833 | - $escapedDbRowData = []; |
|
834 | - $escapedPrimaryKeys = []; |
|
835 | - |
|
836 | - foreach ($dbRowData as $columnName => $value) { |
|
837 | - $columnDescriptor = $tableDescriptor->getColumn($columnName); |
|
838 | - $types[] = $columnDescriptor->getType(); |
|
839 | - $escapedDbRowData[$this->connection->quoteIdentifier($columnName)] = $value; |
|
840 | - } |
|
841 | - foreach ($primaryKeys as $columnName => $value) { |
|
842 | - $columnDescriptor = $tableDescriptor->getColumn($columnName); |
|
843 | - $types[] = $columnDescriptor->getType(); |
|
844 | - $escapedPrimaryKeys[$this->connection->quoteIdentifier($columnName)] = $value; |
|
845 | - } |
|
846 | - |
|
847 | - $this->connection->update($tableName, $escapedDbRowData, $escapedPrimaryKeys, $types); |
|
848 | - |
|
849 | - // Let's check if the primary key has been updated... |
|
850 | - $needsUpdatePk = false; |
|
851 | - foreach ($primaryKeys as $column => $value) { |
|
852 | - if (!isset($dbRowData[$column]) || $dbRowData[$column] != $value) { |
|
853 | - $needsUpdatePk = true; |
|
854 | - break; |
|
855 | - } |
|
856 | - } |
|
857 | - if ($needsUpdatePk) { |
|
858 | - $this->objectStorage->remove($tableName, $this->getObjectHash($primaryKeys)); |
|
859 | - $newPrimaryKeys = $this->getPrimaryKeysForObjectFromDbRow($dbRow); |
|
860 | - $dbRow->_setPrimaryKeys($newPrimaryKeys); |
|
861 | - $this->objectStorage->set($tableName, $this->getObjectHash($primaryKeys), $dbRow); |
|
862 | - } |
|
863 | - |
|
864 | - // Let's remove this object from the list of objects to save. |
|
865 | - $this->removeFromToSaveObjectList($dbRow); |
|
866 | - } |
|
867 | - |
|
868 | - $object->_setStatus(TDBMObjectStateEnum::STATE_LOADED); |
|
869 | - } elseif ($status === TDBMObjectStateEnum::STATE_DELETED) { |
|
870 | - throw new TDBMInvalidOperationException('This object has been deleted. It cannot be saved.'); |
|
871 | - } |
|
872 | - |
|
873 | - // Finally, let's save all the many to many relationships to this bean. |
|
874 | - $this->persistManyToManyRelationships($object); |
|
875 | - } |
|
876 | - |
|
877 | - private function persistManyToManyRelationships(AbstractTDBMObject $object) |
|
878 | - { |
|
879 | - foreach ($object->_getCachedRelationships() as $pivotTableName => $storage) { |
|
880 | - $tableDescriptor = $this->tdbmSchemaAnalyzer->getSchema()->getTable($pivotTableName); |
|
881 | - list($localFk, $remoteFk) = $this->getPivotTableForeignKeys($pivotTableName, $object); |
|
882 | - |
|
883 | - $toRemoveFromStorage = []; |
|
884 | - |
|
885 | - foreach ($storage as $remoteBean) { |
|
886 | - /* @var $remoteBean AbstractTDBMObject */ |
|
887 | - $statusArr = $storage[$remoteBean]; |
|
888 | - $status = $statusArr['status']; |
|
889 | - $reverse = $statusArr['reverse']; |
|
890 | - if ($reverse) { |
|
891 | - continue; |
|
892 | - } |
|
893 | - |
|
894 | - if ($status === 'new') { |
|
895 | - $remoteBeanStatus = $remoteBean->_getStatus(); |
|
896 | - if ($remoteBeanStatus === TDBMObjectStateEnum::STATE_NEW || $remoteBeanStatus === TDBMObjectStateEnum::STATE_DETACHED) { |
|
897 | - // Let's save remote bean if needed. |
|
898 | - $this->save($remoteBean); |
|
899 | - } |
|
900 | - |
|
901 | - $filters = $this->getPivotFilters($object, $remoteBean, $localFk, $remoteFk); |
|
902 | - |
|
903 | - $types = []; |
|
904 | - $escapedFilters = []; |
|
905 | - |
|
906 | - foreach ($filters as $columnName => $value) { |
|
907 | - $columnDescriptor = $tableDescriptor->getColumn($columnName); |
|
908 | - $types[] = $columnDescriptor->getType(); |
|
909 | - $escapedFilters[$this->connection->quoteIdentifier($columnName)] = $value; |
|
910 | - } |
|
911 | - |
|
912 | - $this->connection->insert($pivotTableName, $escapedFilters, $types); |
|
913 | - |
|
914 | - // Finally, let's mark relationships as saved. |
|
915 | - $statusArr['status'] = 'loaded'; |
|
916 | - $storage[$remoteBean] = $statusArr; |
|
917 | - $remoteStorage = $remoteBean->_getCachedRelationships()[$pivotTableName]; |
|
918 | - $remoteStatusArr = $remoteStorage[$object]; |
|
919 | - $remoteStatusArr['status'] = 'loaded'; |
|
920 | - $remoteStorage[$object] = $remoteStatusArr; |
|
921 | - } elseif ($status === 'delete') { |
|
922 | - $filters = $this->getPivotFilters($object, $remoteBean, $localFk, $remoteFk); |
|
923 | - |
|
924 | - $types = []; |
|
925 | - |
|
926 | - foreach ($filters as $columnName => $value) { |
|
927 | - $columnDescriptor = $tableDescriptor->getColumn($columnName); |
|
928 | - $types[] = $columnDescriptor->getType(); |
|
929 | - } |
|
930 | - |
|
931 | - $this->connection->delete($pivotTableName, $filters, $types); |
|
932 | - |
|
933 | - // Finally, let's remove relationships completely from bean. |
|
934 | - $toRemoveFromStorage[] = $remoteBean; |
|
935 | - |
|
936 | - $remoteBean->_getCachedRelationships()[$pivotTableName]->detach($object); |
|
937 | - } |
|
938 | - } |
|
939 | - |
|
940 | - // Note: due to https://bugs.php.net/bug.php?id=65629, we cannot delete an element inside a foreach loop on a SplStorageObject. |
|
941 | - // Therefore, we cache elements in the $toRemoveFromStorage to remove them at a later stage. |
|
942 | - foreach ($toRemoveFromStorage as $remoteBean) { |
|
943 | - $storage->detach($remoteBean); |
|
944 | - } |
|
945 | - } |
|
946 | - } |
|
947 | - |
|
948 | - private function getPivotFilters(AbstractTDBMObject $localBean, AbstractTDBMObject $remoteBean, ForeignKeyConstraint $localFk, ForeignKeyConstraint $remoteFk) |
|
949 | - { |
|
950 | - $localBeanPk = $this->getPrimaryKeyValues($localBean); |
|
951 | - $remoteBeanPk = $this->getPrimaryKeyValues($remoteBean); |
|
952 | - $localColumns = $localFk->getLocalColumns(); |
|
953 | - $remoteColumns = $remoteFk->getLocalColumns(); |
|
954 | - |
|
955 | - $localFilters = array_combine($localColumns, $localBeanPk); |
|
956 | - $remoteFilters = array_combine($remoteColumns, $remoteBeanPk); |
|
957 | - |
|
958 | - return array_merge($localFilters, $remoteFilters); |
|
959 | - } |
|
960 | - |
|
961 | - /** |
|
962 | - * Returns the "values" of the primary key. |
|
963 | - * This returns the primary key from the $primaryKey attribute, not the one stored in the columns. |
|
964 | - * |
|
965 | - * @param AbstractTDBMObject $bean |
|
966 | - * |
|
967 | - * @return array numerically indexed array of values |
|
968 | - */ |
|
969 | - private function getPrimaryKeyValues(AbstractTDBMObject $bean) |
|
970 | - { |
|
971 | - $dbRows = $bean->_getDbRows(); |
|
972 | - $dbRow = reset($dbRows); |
|
973 | - |
|
974 | - return array_values($dbRow->_getPrimaryKeys()); |
|
975 | - } |
|
976 | - |
|
977 | - /** |
|
978 | - * Returns a unique hash used to store the object based on its primary key. |
|
979 | - * If the array contains only one value, then the value is returned. |
|
980 | - * Otherwise, a hash representing the array is returned. |
|
981 | - * |
|
982 | - * @param array $primaryKeys An array of columns => values forming the primary key |
|
983 | - * |
|
984 | - * @return string |
|
985 | - */ |
|
986 | - public function getObjectHash(array $primaryKeys) |
|
987 | - { |
|
988 | - if (count($primaryKeys) === 1) { |
|
989 | - return reset($primaryKeys); |
|
990 | - } else { |
|
991 | - ksort($primaryKeys); |
|
992 | - |
|
993 | - return md5(json_encode($primaryKeys)); |
|
994 | - } |
|
995 | - } |
|
996 | - |
|
997 | - /** |
|
998 | - * Returns an array of primary keys from the object. |
|
999 | - * The primary keys are extracted from the object columns and not from the primary keys stored in the |
|
1000 | - * $primaryKeys variable of the object. |
|
1001 | - * |
|
1002 | - * @param DbRow $dbRow |
|
1003 | - * |
|
1004 | - * @return array Returns an array of column => value |
|
1005 | - */ |
|
1006 | - public function getPrimaryKeysForObjectFromDbRow(DbRow $dbRow) |
|
1007 | - { |
|
1008 | - $table = $dbRow->_getDbTableName(); |
|
1009 | - $dbRowData = $dbRow->_getDbRow(); |
|
1010 | - |
|
1011 | - return $this->_getPrimaryKeysFromObjectData($table, $dbRowData); |
|
1012 | - } |
|
1013 | - |
|
1014 | - /** |
|
1015 | - * Returns an array of primary keys for the given row. |
|
1016 | - * The primary keys are extracted from the object columns. |
|
1017 | - * |
|
1018 | - * @param $table |
|
1019 | - * @param array $columns |
|
1020 | - * |
|
1021 | - * @return array |
|
1022 | - */ |
|
1023 | - public function _getPrimaryKeysFromObjectData($table, array $columns) |
|
1024 | - { |
|
1025 | - $primaryKeyColumns = $this->getPrimaryKeyColumns($table); |
|
1026 | - $values = array(); |
|
1027 | - foreach ($primaryKeyColumns as $column) { |
|
1028 | - if (isset($columns[$column])) { |
|
1029 | - $values[$column] = $columns[$column]; |
|
1030 | - } |
|
1031 | - } |
|
1032 | - |
|
1033 | - return $values; |
|
1034 | - } |
|
1035 | - |
|
1036 | - /** |
|
1037 | - * Attaches $object to this TDBMService. |
|
1038 | - * The $object must be in DETACHED state and will pass in NEW state. |
|
1039 | - * |
|
1040 | - * @param AbstractTDBMObject $object |
|
1041 | - * |
|
1042 | - * @throws TDBMInvalidOperationException |
|
1043 | - */ |
|
1044 | - public function attach(AbstractTDBMObject $object) |
|
1045 | - { |
|
1046 | - $object->_attach($this); |
|
1047 | - } |
|
1048 | - |
|
1049 | - /** |
|
1050 | - * Returns an associative array (column => value) for the primary keys from the table name and an |
|
1051 | - * indexed array of primary key values. |
|
1052 | - * |
|
1053 | - * @param string $tableName |
|
1054 | - * @param array $indexedPrimaryKeys |
|
1055 | - */ |
|
1056 | - public function _getPrimaryKeysFromIndexedPrimaryKeys($tableName, array $indexedPrimaryKeys) |
|
1057 | - { |
|
1058 | - $primaryKeyColumns = $this->tdbmSchemaAnalyzer->getSchema()->getTable($tableName)->getPrimaryKeyColumns(); |
|
1059 | - |
|
1060 | - if (count($primaryKeyColumns) !== count($indexedPrimaryKeys)) { |
|
1061 | - throw new TDBMException(sprintf('Wrong number of columns passed for primary key. Expected %s columns for table "%s", |
|
796 | + // Let's remove this object from the $new_objects static table. |
|
797 | + $this->removeFromToSaveObjectList($dbRow); |
|
798 | + |
|
799 | + // TODO: change this behaviour to something more sensible performance-wise |
|
800 | + // Maybe a setting to trigger this globally? |
|
801 | + //$this->status = TDBMObjectStateEnum::STATE_NOT_LOADED; |
|
802 | + //$this->db_modified_state = false; |
|
803 | + //$dbRow = array(); |
|
804 | + |
|
805 | + // Let's add this object to the list of objects in cache. |
|
806 | + $this->_addToCache($dbRow); |
|
807 | + } |
|
808 | + |
|
809 | + $object->_setStatus(TDBMObjectStateEnum::STATE_LOADED); |
|
810 | + } elseif ($status === TDBMObjectStateEnum::STATE_DIRTY) { |
|
811 | + $dbRows = $object->_getDbRows(); |
|
812 | + |
|
813 | + foreach ($dbRows as $dbRow) { |
|
814 | + $references = $dbRow->_getReferences(); |
|
815 | + |
|
816 | + // Let's save all references in NEW state (we need their primary key) |
|
817 | + foreach ($references as $fkName => $reference) { |
|
818 | + if ($reference !== null && $reference->_getStatus() === TDBMObjectStateEnum::STATE_NEW) { |
|
819 | + $this->save($reference); |
|
820 | + } |
|
821 | + } |
|
822 | + |
|
823 | + // Let's first get the primary keys |
|
824 | + $tableName = $dbRow->_getDbTableName(); |
|
825 | + $dbRowData = $dbRow->_getDbRow(); |
|
826 | + |
|
827 | + $schema = $this->tdbmSchemaAnalyzer->getSchema(); |
|
828 | + $tableDescriptor = $schema->getTable($tableName); |
|
829 | + |
|
830 | + $primaryKeys = $dbRow->_getPrimaryKeys(); |
|
831 | + |
|
832 | + $types = []; |
|
833 | + $escapedDbRowData = []; |
|
834 | + $escapedPrimaryKeys = []; |
|
835 | + |
|
836 | + foreach ($dbRowData as $columnName => $value) { |
|
837 | + $columnDescriptor = $tableDescriptor->getColumn($columnName); |
|
838 | + $types[] = $columnDescriptor->getType(); |
|
839 | + $escapedDbRowData[$this->connection->quoteIdentifier($columnName)] = $value; |
|
840 | + } |
|
841 | + foreach ($primaryKeys as $columnName => $value) { |
|
842 | + $columnDescriptor = $tableDescriptor->getColumn($columnName); |
|
843 | + $types[] = $columnDescriptor->getType(); |
|
844 | + $escapedPrimaryKeys[$this->connection->quoteIdentifier($columnName)] = $value; |
|
845 | + } |
|
846 | + |
|
847 | + $this->connection->update($tableName, $escapedDbRowData, $escapedPrimaryKeys, $types); |
|
848 | + |
|
849 | + // Let's check if the primary key has been updated... |
|
850 | + $needsUpdatePk = false; |
|
851 | + foreach ($primaryKeys as $column => $value) { |
|
852 | + if (!isset($dbRowData[$column]) || $dbRowData[$column] != $value) { |
|
853 | + $needsUpdatePk = true; |
|
854 | + break; |
|
855 | + } |
|
856 | + } |
|
857 | + if ($needsUpdatePk) { |
|
858 | + $this->objectStorage->remove($tableName, $this->getObjectHash($primaryKeys)); |
|
859 | + $newPrimaryKeys = $this->getPrimaryKeysForObjectFromDbRow($dbRow); |
|
860 | + $dbRow->_setPrimaryKeys($newPrimaryKeys); |
|
861 | + $this->objectStorage->set($tableName, $this->getObjectHash($primaryKeys), $dbRow); |
|
862 | + } |
|
863 | + |
|
864 | + // Let's remove this object from the list of objects to save. |
|
865 | + $this->removeFromToSaveObjectList($dbRow); |
|
866 | + } |
|
867 | + |
|
868 | + $object->_setStatus(TDBMObjectStateEnum::STATE_LOADED); |
|
869 | + } elseif ($status === TDBMObjectStateEnum::STATE_DELETED) { |
|
870 | + throw new TDBMInvalidOperationException('This object has been deleted. It cannot be saved.'); |
|
871 | + } |
|
872 | + |
|
873 | + // Finally, let's save all the many to many relationships to this bean. |
|
874 | + $this->persistManyToManyRelationships($object); |
|
875 | + } |
|
876 | + |
|
877 | + private function persistManyToManyRelationships(AbstractTDBMObject $object) |
|
878 | + { |
|
879 | + foreach ($object->_getCachedRelationships() as $pivotTableName => $storage) { |
|
880 | + $tableDescriptor = $this->tdbmSchemaAnalyzer->getSchema()->getTable($pivotTableName); |
|
881 | + list($localFk, $remoteFk) = $this->getPivotTableForeignKeys($pivotTableName, $object); |
|
882 | + |
|
883 | + $toRemoveFromStorage = []; |
|
884 | + |
|
885 | + foreach ($storage as $remoteBean) { |
|
886 | + /* @var $remoteBean AbstractTDBMObject */ |
|
887 | + $statusArr = $storage[$remoteBean]; |
|
888 | + $status = $statusArr['status']; |
|
889 | + $reverse = $statusArr['reverse']; |
|
890 | + if ($reverse) { |
|
891 | + continue; |
|
892 | + } |
|
893 | + |
|
894 | + if ($status === 'new') { |
|
895 | + $remoteBeanStatus = $remoteBean->_getStatus(); |
|
896 | + if ($remoteBeanStatus === TDBMObjectStateEnum::STATE_NEW || $remoteBeanStatus === TDBMObjectStateEnum::STATE_DETACHED) { |
|
897 | + // Let's save remote bean if needed. |
|
898 | + $this->save($remoteBean); |
|
899 | + } |
|
900 | + |
|
901 | + $filters = $this->getPivotFilters($object, $remoteBean, $localFk, $remoteFk); |
|
902 | + |
|
903 | + $types = []; |
|
904 | + $escapedFilters = []; |
|
905 | + |
|
906 | + foreach ($filters as $columnName => $value) { |
|
907 | + $columnDescriptor = $tableDescriptor->getColumn($columnName); |
|
908 | + $types[] = $columnDescriptor->getType(); |
|
909 | + $escapedFilters[$this->connection->quoteIdentifier($columnName)] = $value; |
|
910 | + } |
|
911 | + |
|
912 | + $this->connection->insert($pivotTableName, $escapedFilters, $types); |
|
913 | + |
|
914 | + // Finally, let's mark relationships as saved. |
|
915 | + $statusArr['status'] = 'loaded'; |
|
916 | + $storage[$remoteBean] = $statusArr; |
|
917 | + $remoteStorage = $remoteBean->_getCachedRelationships()[$pivotTableName]; |
|
918 | + $remoteStatusArr = $remoteStorage[$object]; |
|
919 | + $remoteStatusArr['status'] = 'loaded'; |
|
920 | + $remoteStorage[$object] = $remoteStatusArr; |
|
921 | + } elseif ($status === 'delete') { |
|
922 | + $filters = $this->getPivotFilters($object, $remoteBean, $localFk, $remoteFk); |
|
923 | + |
|
924 | + $types = []; |
|
925 | + |
|
926 | + foreach ($filters as $columnName => $value) { |
|
927 | + $columnDescriptor = $tableDescriptor->getColumn($columnName); |
|
928 | + $types[] = $columnDescriptor->getType(); |
|
929 | + } |
|
930 | + |
|
931 | + $this->connection->delete($pivotTableName, $filters, $types); |
|
932 | + |
|
933 | + // Finally, let's remove relationships completely from bean. |
|
934 | + $toRemoveFromStorage[] = $remoteBean; |
|
935 | + |
|
936 | + $remoteBean->_getCachedRelationships()[$pivotTableName]->detach($object); |
|
937 | + } |
|
938 | + } |
|
939 | + |
|
940 | + // Note: due to https://bugs.php.net/bug.php?id=65629, we cannot delete an element inside a foreach loop on a SplStorageObject. |
|
941 | + // Therefore, we cache elements in the $toRemoveFromStorage to remove them at a later stage. |
|
942 | + foreach ($toRemoveFromStorage as $remoteBean) { |
|
943 | + $storage->detach($remoteBean); |
|
944 | + } |
|
945 | + } |
|
946 | + } |
|
947 | + |
|
948 | + private function getPivotFilters(AbstractTDBMObject $localBean, AbstractTDBMObject $remoteBean, ForeignKeyConstraint $localFk, ForeignKeyConstraint $remoteFk) |
|
949 | + { |
|
950 | + $localBeanPk = $this->getPrimaryKeyValues($localBean); |
|
951 | + $remoteBeanPk = $this->getPrimaryKeyValues($remoteBean); |
|
952 | + $localColumns = $localFk->getLocalColumns(); |
|
953 | + $remoteColumns = $remoteFk->getLocalColumns(); |
|
954 | + |
|
955 | + $localFilters = array_combine($localColumns, $localBeanPk); |
|
956 | + $remoteFilters = array_combine($remoteColumns, $remoteBeanPk); |
|
957 | + |
|
958 | + return array_merge($localFilters, $remoteFilters); |
|
959 | + } |
|
960 | + |
|
961 | + /** |
|
962 | + * Returns the "values" of the primary key. |
|
963 | + * This returns the primary key from the $primaryKey attribute, not the one stored in the columns. |
|
964 | + * |
|
965 | + * @param AbstractTDBMObject $bean |
|
966 | + * |
|
967 | + * @return array numerically indexed array of values |
|
968 | + */ |
|
969 | + private function getPrimaryKeyValues(AbstractTDBMObject $bean) |
|
970 | + { |
|
971 | + $dbRows = $bean->_getDbRows(); |
|
972 | + $dbRow = reset($dbRows); |
|
973 | + |
|
974 | + return array_values($dbRow->_getPrimaryKeys()); |
|
975 | + } |
|
976 | + |
|
977 | + /** |
|
978 | + * Returns a unique hash used to store the object based on its primary key. |
|
979 | + * If the array contains only one value, then the value is returned. |
|
980 | + * Otherwise, a hash representing the array is returned. |
|
981 | + * |
|
982 | + * @param array $primaryKeys An array of columns => values forming the primary key |
|
983 | + * |
|
984 | + * @return string |
|
985 | + */ |
|
986 | + public function getObjectHash(array $primaryKeys) |
|
987 | + { |
|
988 | + if (count($primaryKeys) === 1) { |
|
989 | + return reset($primaryKeys); |
|
990 | + } else { |
|
991 | + ksort($primaryKeys); |
|
992 | + |
|
993 | + return md5(json_encode($primaryKeys)); |
|
994 | + } |
|
995 | + } |
|
996 | + |
|
997 | + /** |
|
998 | + * Returns an array of primary keys from the object. |
|
999 | + * The primary keys are extracted from the object columns and not from the primary keys stored in the |
|
1000 | + * $primaryKeys variable of the object. |
|
1001 | + * |
|
1002 | + * @param DbRow $dbRow |
|
1003 | + * |
|
1004 | + * @return array Returns an array of column => value |
|
1005 | + */ |
|
1006 | + public function getPrimaryKeysForObjectFromDbRow(DbRow $dbRow) |
|
1007 | + { |
|
1008 | + $table = $dbRow->_getDbTableName(); |
|
1009 | + $dbRowData = $dbRow->_getDbRow(); |
|
1010 | + |
|
1011 | + return $this->_getPrimaryKeysFromObjectData($table, $dbRowData); |
|
1012 | + } |
|
1013 | + |
|
1014 | + /** |
|
1015 | + * Returns an array of primary keys for the given row. |
|
1016 | + * The primary keys are extracted from the object columns. |
|
1017 | + * |
|
1018 | + * @param $table |
|
1019 | + * @param array $columns |
|
1020 | + * |
|
1021 | + * @return array |
|
1022 | + */ |
|
1023 | + public function _getPrimaryKeysFromObjectData($table, array $columns) |
|
1024 | + { |
|
1025 | + $primaryKeyColumns = $this->getPrimaryKeyColumns($table); |
|
1026 | + $values = array(); |
|
1027 | + foreach ($primaryKeyColumns as $column) { |
|
1028 | + if (isset($columns[$column])) { |
|
1029 | + $values[$column] = $columns[$column]; |
|
1030 | + } |
|
1031 | + } |
|
1032 | + |
|
1033 | + return $values; |
|
1034 | + } |
|
1035 | + |
|
1036 | + /** |
|
1037 | + * Attaches $object to this TDBMService. |
|
1038 | + * The $object must be in DETACHED state and will pass in NEW state. |
|
1039 | + * |
|
1040 | + * @param AbstractTDBMObject $object |
|
1041 | + * |
|
1042 | + * @throws TDBMInvalidOperationException |
|
1043 | + */ |
|
1044 | + public function attach(AbstractTDBMObject $object) |
|
1045 | + { |
|
1046 | + $object->_attach($this); |
|
1047 | + } |
|
1048 | + |
|
1049 | + /** |
|
1050 | + * Returns an associative array (column => value) for the primary keys from the table name and an |
|
1051 | + * indexed array of primary key values. |
|
1052 | + * |
|
1053 | + * @param string $tableName |
|
1054 | + * @param array $indexedPrimaryKeys |
|
1055 | + */ |
|
1056 | + public function _getPrimaryKeysFromIndexedPrimaryKeys($tableName, array $indexedPrimaryKeys) |
|
1057 | + { |
|
1058 | + $primaryKeyColumns = $this->tdbmSchemaAnalyzer->getSchema()->getTable($tableName)->getPrimaryKeyColumns(); |
|
1059 | + |
|
1060 | + if (count($primaryKeyColumns) !== count($indexedPrimaryKeys)) { |
|
1061 | + throw new TDBMException(sprintf('Wrong number of columns passed for primary key. Expected %s columns for table "%s", |
|
1062 | 1062 | got %s instead.', count($primaryKeyColumns), $tableName, count($indexedPrimaryKeys))); |
1063 | - } |
|
1064 | - |
|
1065 | - return array_combine($primaryKeyColumns, $indexedPrimaryKeys); |
|
1066 | - } |
|
1067 | - |
|
1068 | - /** |
|
1069 | - * Return the list of tables (from child to parent) joining the tables passed in parameter. |
|
1070 | - * Tables must be in a single line of inheritance. The method will find missing tables. |
|
1071 | - * |
|
1072 | - * Algorithm: one of those tables is the ultimate child. From this child, by recursively getting the parent, |
|
1073 | - * we must be able to find all other tables. |
|
1074 | - * |
|
1075 | - * @param string[] $tables |
|
1076 | - * |
|
1077 | - * @return string[] |
|
1078 | - */ |
|
1079 | - public function _getLinkBetweenInheritedTables(array $tables) |
|
1080 | - { |
|
1081 | - sort($tables); |
|
1082 | - |
|
1083 | - return $this->fromCache($this->cachePrefix.'_linkbetweeninheritedtables_'.implode('__split__', $tables), |
|
1084 | - function () use ($tables) { |
|
1085 | - return $this->_getLinkBetweenInheritedTablesWithoutCache($tables); |
|
1086 | - }); |
|
1087 | - } |
|
1088 | - |
|
1089 | - /** |
|
1090 | - * Return the list of tables (from child to parent) joining the tables passed in parameter. |
|
1091 | - * Tables must be in a single line of inheritance. The method will find missing tables. |
|
1092 | - * |
|
1093 | - * Algorithm: one of those tables is the ultimate child. From this child, by recursively getting the parent, |
|
1094 | - * we must be able to find all other tables. |
|
1095 | - * |
|
1096 | - * @param string[] $tables |
|
1097 | - * |
|
1098 | - * @return string[] |
|
1099 | - */ |
|
1100 | - private function _getLinkBetweenInheritedTablesWithoutCache(array $tables) |
|
1101 | - { |
|
1102 | - $schemaAnalyzer = $this->schemaAnalyzer; |
|
1103 | - |
|
1104 | - foreach ($tables as $currentTable) { |
|
1105 | - $allParents = [$currentTable]; |
|
1106 | - while ($currentFk = $schemaAnalyzer->getParentRelationship($currentTable)) { |
|
1107 | - $currentTable = $currentFk->getForeignTableName(); |
|
1108 | - $allParents[] = $currentTable; |
|
1109 | - } |
|
1110 | - |
|
1111 | - // Now, does the $allParents contain all the tables we want? |
|
1112 | - $notFoundTables = array_diff($tables, $allParents); |
|
1113 | - if (empty($notFoundTables)) { |
|
1114 | - // We have a winner! |
|
1115 | - return $allParents; |
|
1116 | - } |
|
1117 | - } |
|
1118 | - |
|
1119 | - throw TDBMInheritanceException::create($tables); |
|
1120 | - } |
|
1121 | - |
|
1122 | - /** |
|
1123 | - * Returns the list of tables related to this table (via a parent or child inheritance relationship). |
|
1124 | - * |
|
1125 | - * @param string $table |
|
1126 | - * |
|
1127 | - * @return string[] |
|
1128 | - */ |
|
1129 | - public function _getRelatedTablesByInheritance($table) |
|
1130 | - { |
|
1131 | - return $this->fromCache($this->cachePrefix.'_relatedtables_'.$table, function () use ($table) { |
|
1132 | - return $this->_getRelatedTablesByInheritanceWithoutCache($table); |
|
1133 | - }); |
|
1134 | - } |
|
1135 | - |
|
1136 | - /** |
|
1137 | - * Returns the list of tables related to this table (via a parent or child inheritance relationship). |
|
1138 | - * |
|
1139 | - * @param string $table |
|
1140 | - * |
|
1141 | - * @return string[] |
|
1142 | - */ |
|
1143 | - private function _getRelatedTablesByInheritanceWithoutCache($table) |
|
1144 | - { |
|
1145 | - $schemaAnalyzer = $this->schemaAnalyzer; |
|
1146 | - |
|
1147 | - // Let's scan the parent tables |
|
1148 | - $currentTable = $table; |
|
1149 | - |
|
1150 | - $parentTables = []; |
|
1151 | - |
|
1152 | - // Get parent relationship |
|
1153 | - while ($currentFk = $schemaAnalyzer->getParentRelationship($currentTable)) { |
|
1154 | - $currentTable = $currentFk->getForeignTableName(); |
|
1155 | - $parentTables[] = $currentTable; |
|
1156 | - } |
|
1157 | - |
|
1158 | - // Let's recurse in children |
|
1159 | - $childrenTables = $this->exploreChildrenTablesRelationships($schemaAnalyzer, $table); |
|
1160 | - |
|
1161 | - return array_merge(array_reverse($parentTables), $childrenTables); |
|
1162 | - } |
|
1163 | - |
|
1164 | - /** |
|
1165 | - * Explore all the children and descendant of $table and returns ForeignKeyConstraints on those. |
|
1166 | - * |
|
1167 | - * @param string $table |
|
1168 | - * |
|
1169 | - * @return string[] |
|
1170 | - */ |
|
1171 | - private function exploreChildrenTablesRelationships(SchemaAnalyzer $schemaAnalyzer, $table) |
|
1172 | - { |
|
1173 | - $tables = [$table]; |
|
1174 | - $keys = $schemaAnalyzer->getChildrenRelationships($table); |
|
1175 | - |
|
1176 | - foreach ($keys as $key) { |
|
1177 | - $tables = array_merge($tables, $this->exploreChildrenTablesRelationships($schemaAnalyzer, $key->getLocalTableName())); |
|
1178 | - } |
|
1179 | - |
|
1180 | - return $tables; |
|
1181 | - } |
|
1182 | - |
|
1183 | - /** |
|
1184 | - * Casts a foreign key into SQL, assuming table name is used with no alias. |
|
1185 | - * The returned value does contain only one table. For instance:. |
|
1186 | - * |
|
1187 | - * " LEFT JOIN table2 ON table1.id = table2.table1_id" |
|
1188 | - * |
|
1189 | - * @param ForeignKeyConstraint $fk |
|
1190 | - * @param bool $leftTableIsLocal |
|
1191 | - * |
|
1192 | - * @return string |
|
1193 | - */ |
|
1194 | - /*private function foreignKeyToSql(ForeignKeyConstraint $fk, $leftTableIsLocal) { |
|
1063 | + } |
|
1064 | + |
|
1065 | + return array_combine($primaryKeyColumns, $indexedPrimaryKeys); |
|
1066 | + } |
|
1067 | + |
|
1068 | + /** |
|
1069 | + * Return the list of tables (from child to parent) joining the tables passed in parameter. |
|
1070 | + * Tables must be in a single line of inheritance. The method will find missing tables. |
|
1071 | + * |
|
1072 | + * Algorithm: one of those tables is the ultimate child. From this child, by recursively getting the parent, |
|
1073 | + * we must be able to find all other tables. |
|
1074 | + * |
|
1075 | + * @param string[] $tables |
|
1076 | + * |
|
1077 | + * @return string[] |
|
1078 | + */ |
|
1079 | + public function _getLinkBetweenInheritedTables(array $tables) |
|
1080 | + { |
|
1081 | + sort($tables); |
|
1082 | + |
|
1083 | + return $this->fromCache($this->cachePrefix.'_linkbetweeninheritedtables_'.implode('__split__', $tables), |
|
1084 | + function () use ($tables) { |
|
1085 | + return $this->_getLinkBetweenInheritedTablesWithoutCache($tables); |
|
1086 | + }); |
|
1087 | + } |
|
1088 | + |
|
1089 | + /** |
|
1090 | + * Return the list of tables (from child to parent) joining the tables passed in parameter. |
|
1091 | + * Tables must be in a single line of inheritance. The method will find missing tables. |
|
1092 | + * |
|
1093 | + * Algorithm: one of those tables is the ultimate child. From this child, by recursively getting the parent, |
|
1094 | + * we must be able to find all other tables. |
|
1095 | + * |
|
1096 | + * @param string[] $tables |
|
1097 | + * |
|
1098 | + * @return string[] |
|
1099 | + */ |
|
1100 | + private function _getLinkBetweenInheritedTablesWithoutCache(array $tables) |
|
1101 | + { |
|
1102 | + $schemaAnalyzer = $this->schemaAnalyzer; |
|
1103 | + |
|
1104 | + foreach ($tables as $currentTable) { |
|
1105 | + $allParents = [$currentTable]; |
|
1106 | + while ($currentFk = $schemaAnalyzer->getParentRelationship($currentTable)) { |
|
1107 | + $currentTable = $currentFk->getForeignTableName(); |
|
1108 | + $allParents[] = $currentTable; |
|
1109 | + } |
|
1110 | + |
|
1111 | + // Now, does the $allParents contain all the tables we want? |
|
1112 | + $notFoundTables = array_diff($tables, $allParents); |
|
1113 | + if (empty($notFoundTables)) { |
|
1114 | + // We have a winner! |
|
1115 | + return $allParents; |
|
1116 | + } |
|
1117 | + } |
|
1118 | + |
|
1119 | + throw TDBMInheritanceException::create($tables); |
|
1120 | + } |
|
1121 | + |
|
1122 | + /** |
|
1123 | + * Returns the list of tables related to this table (via a parent or child inheritance relationship). |
|
1124 | + * |
|
1125 | + * @param string $table |
|
1126 | + * |
|
1127 | + * @return string[] |
|
1128 | + */ |
|
1129 | + public function _getRelatedTablesByInheritance($table) |
|
1130 | + { |
|
1131 | + return $this->fromCache($this->cachePrefix.'_relatedtables_'.$table, function () use ($table) { |
|
1132 | + return $this->_getRelatedTablesByInheritanceWithoutCache($table); |
|
1133 | + }); |
|
1134 | + } |
|
1135 | + |
|
1136 | + /** |
|
1137 | + * Returns the list of tables related to this table (via a parent or child inheritance relationship). |
|
1138 | + * |
|
1139 | + * @param string $table |
|
1140 | + * |
|
1141 | + * @return string[] |
|
1142 | + */ |
|
1143 | + private function _getRelatedTablesByInheritanceWithoutCache($table) |
|
1144 | + { |
|
1145 | + $schemaAnalyzer = $this->schemaAnalyzer; |
|
1146 | + |
|
1147 | + // Let's scan the parent tables |
|
1148 | + $currentTable = $table; |
|
1149 | + |
|
1150 | + $parentTables = []; |
|
1151 | + |
|
1152 | + // Get parent relationship |
|
1153 | + while ($currentFk = $schemaAnalyzer->getParentRelationship($currentTable)) { |
|
1154 | + $currentTable = $currentFk->getForeignTableName(); |
|
1155 | + $parentTables[] = $currentTable; |
|
1156 | + } |
|
1157 | + |
|
1158 | + // Let's recurse in children |
|
1159 | + $childrenTables = $this->exploreChildrenTablesRelationships($schemaAnalyzer, $table); |
|
1160 | + |
|
1161 | + return array_merge(array_reverse($parentTables), $childrenTables); |
|
1162 | + } |
|
1163 | + |
|
1164 | + /** |
|
1165 | + * Explore all the children and descendant of $table and returns ForeignKeyConstraints on those. |
|
1166 | + * |
|
1167 | + * @param string $table |
|
1168 | + * |
|
1169 | + * @return string[] |
|
1170 | + */ |
|
1171 | + private function exploreChildrenTablesRelationships(SchemaAnalyzer $schemaAnalyzer, $table) |
|
1172 | + { |
|
1173 | + $tables = [$table]; |
|
1174 | + $keys = $schemaAnalyzer->getChildrenRelationships($table); |
|
1175 | + |
|
1176 | + foreach ($keys as $key) { |
|
1177 | + $tables = array_merge($tables, $this->exploreChildrenTablesRelationships($schemaAnalyzer, $key->getLocalTableName())); |
|
1178 | + } |
|
1179 | + |
|
1180 | + return $tables; |
|
1181 | + } |
|
1182 | + |
|
1183 | + /** |
|
1184 | + * Casts a foreign key into SQL, assuming table name is used with no alias. |
|
1185 | + * The returned value does contain only one table. For instance:. |
|
1186 | + * |
|
1187 | + * " LEFT JOIN table2 ON table1.id = table2.table1_id" |
|
1188 | + * |
|
1189 | + * @param ForeignKeyConstraint $fk |
|
1190 | + * @param bool $leftTableIsLocal |
|
1191 | + * |
|
1192 | + * @return string |
|
1193 | + */ |
|
1194 | + /*private function foreignKeyToSql(ForeignKeyConstraint $fk, $leftTableIsLocal) { |
|
1195 | 1195 | $onClauses = []; |
1196 | 1196 | $foreignTableName = $this->connection->quoteIdentifier($fk->getForeignTableName()); |
1197 | 1197 | $foreignColumns = $fk->getForeignColumns(); |
@@ -1217,409 +1217,409 @@ discard block |
||
1217 | 1217 | } |
1218 | 1218 | }*/ |
1219 | 1219 | |
1220 | - /** |
|
1221 | - * Returns a `ResultIterator` object representing filtered records of "$mainTable" . |
|
1222 | - * |
|
1223 | - * The findObjects method should be the most used query method in TDBM if you want to query the database for objects. |
|
1224 | - * (Note: if you want to query the database for an object by its primary key, use the findObjectByPk method). |
|
1225 | - * |
|
1226 | - * The findObjects method takes in parameter: |
|
1227 | - * - mainTable: the kind of bean you want to retrieve. In TDBM, a bean matches a database row, so the |
|
1228 | - * `$mainTable` parameter should be the name of an existing table in database. |
|
1229 | - * - filter: The filter is a filter bag. It is what you use to filter your request (the WHERE part in SQL). |
|
1230 | - * It can be a string (SQL Where clause), or even a bean or an associative array (key = column to filter, value = value to find) |
|
1231 | - * - parameters: The parameters used in the filter. If you pass a SQL string as a filter, be sure to avoid |
|
1232 | - * concatenating parameters in the string (this leads to SQL injection and also to poor caching performance). |
|
1233 | - * Instead, please consider passing parameters (see documentation for more details). |
|
1234 | - * - additionalTablesFetch: An array of SQL tables names. The beans related to those tables will be fetched along |
|
1235 | - * the main table. This is useful to avoid hitting the database with numerous subqueries. |
|
1236 | - * - mode: The fetch mode of the result. See `setFetchMode()` method for more details. |
|
1237 | - * |
|
1238 | - * The `findObjects` method will return a `ResultIterator`. A `ResultIterator` is an object that behaves as an array |
|
1239 | - * (in ARRAY mode) at least. It can be iterated using a `foreach` loop. |
|
1240 | - * |
|
1241 | - * Finally, if filter_bag is null, the whole table is returned. |
|
1242 | - * |
|
1243 | - * @param string $mainTable The name of the table queried |
|
1244 | - * @param string|array|null $filter The SQL filters to apply to the query (the WHERE part). Columns from tables different from $mainTable must be prefixed by the table name (in the form: table.column) |
|
1245 | - * @param array $parameters |
|
1246 | - * @param string|UncheckedOrderBy|null $orderString The ORDER BY part of the query. Columns from tables different from $mainTable must be prefixed by the table name (in the form: table.column) |
|
1247 | - * @param array $additionalTablesFetch |
|
1248 | - * @param int $mode |
|
1249 | - * @param string $className Optional: The name of the class to instantiate. This class must extend the TDBMObject class. If none is specified, a TDBMObject instance will be returned |
|
1250 | - * |
|
1251 | - * @return ResultIterator An object representing an array of results |
|
1252 | - * |
|
1253 | - * @throws TDBMException |
|
1254 | - */ |
|
1255 | - public function findObjects(string $mainTable, $filter = null, array $parameters = array(), $orderString = null, array $additionalTablesFetch = array(), $mode = null, string $className = null) |
|
1256 | - { |
|
1257 | - // $mainTable is not secured in MagicJoin, let's add a bit of security to avoid SQL injection. |
|
1258 | - if (!preg_match('/^[a-zA-Z_][a-zA-Z0-9_]*$/', $mainTable)) { |
|
1259 | - throw new TDBMException(sprintf("Invalid table name: '%s'", $mainTable)); |
|
1260 | - } |
|
1261 | - |
|
1262 | - $mode = $mode ?: $this->mode; |
|
1263 | - |
|
1264 | - list($filterString, $additionalParameters) = $this->buildFilterFromFilterBag($filter); |
|
1265 | - |
|
1266 | - $parameters = array_merge($parameters, $additionalParameters); |
|
1267 | - |
|
1268 | - $queryFactory = new FindObjectsQueryFactory($mainTable, $additionalTablesFetch, $filterString, $orderString, $this, $this->tdbmSchemaAnalyzer->getSchema(), $this->orderByAnalyzer); |
|
1269 | - |
|
1270 | - return new ResultIterator($queryFactory, $parameters, $this->objectStorage, $className, $this, $this->magicQuery, $mode, $this->logger); |
|
1271 | - } |
|
1272 | - |
|
1273 | - /** |
|
1274 | - * @param string $mainTable The name of the table queried |
|
1275 | - * @param string $from The from sql statement |
|
1276 | - * @param string|array|null $filter The SQL filters to apply to the query (the WHERE part). All columns must be prefixed by the table name (in the form: table.column) |
|
1277 | - * @param array $parameters |
|
1278 | - * @param string|UncheckedOrderBy|null $orderString The ORDER BY part of the query. All columns must be prefixed by the table name (in the form: table.column) |
|
1279 | - * @param int $mode |
|
1280 | - * @param string $className Optional: The name of the class to instantiate. This class must extend the TDBMObject class. If none is specified, a TDBMObject instance will be returned |
|
1281 | - * |
|
1282 | - * @return ResultIterator An object representing an array of results |
|
1283 | - * |
|
1284 | - * @throws TDBMException |
|
1285 | - */ |
|
1286 | - public function findObjectsFromSql(string $mainTable, string $from, $filter = null, array $parameters = array(), $orderString = null, $mode = null, string $className = null) |
|
1287 | - { |
|
1288 | - // $mainTable is not secured in MagicJoin, let's add a bit of security to avoid SQL injection. |
|
1289 | - if (!preg_match('/^[a-zA-Z_][a-zA-Z0-9_]*$/', $mainTable)) { |
|
1290 | - throw new TDBMException(sprintf("Invalid table name: '%s'", $mainTable)); |
|
1291 | - } |
|
1292 | - |
|
1293 | - $mode = $mode ?: $this->mode; |
|
1294 | - |
|
1295 | - list($filterString, $additionalParameters) = $this->buildFilterFromFilterBag($filter); |
|
1296 | - |
|
1297 | - $parameters = array_merge($parameters, $additionalParameters); |
|
1298 | - |
|
1299 | - $queryFactory = new FindObjectsFromSqlQueryFactory($mainTable, $from, $filterString, $orderString, $this, $this->tdbmSchemaAnalyzer->getSchema(), $this->orderByAnalyzer, $this->schemaAnalyzer, $this->cache, $this->cachePrefix); |
|
1300 | - |
|
1301 | - return new ResultIterator($queryFactory, $parameters, $this->objectStorage, $className, $this, $this->magicQuery, $mode, $this->logger); |
|
1302 | - } |
|
1303 | - |
|
1304 | - /** |
|
1305 | - * @param $table |
|
1306 | - * @param array $primaryKeys |
|
1307 | - * @param array $additionalTablesFetch |
|
1308 | - * @param bool $lazy Whether to perform lazy loading on this object or not |
|
1309 | - * @param string $className |
|
1310 | - * |
|
1311 | - * @return AbstractTDBMObject |
|
1312 | - * |
|
1313 | - * @throws TDBMException |
|
1314 | - */ |
|
1315 | - public function findObjectByPk(string $table, array $primaryKeys, array $additionalTablesFetch = array(), bool $lazy = false, string $className = null) |
|
1316 | - { |
|
1317 | - $primaryKeys = $this->_getPrimaryKeysFromObjectData($table, $primaryKeys); |
|
1318 | - $hash = $this->getObjectHash($primaryKeys); |
|
1319 | - |
|
1320 | - if ($this->objectStorage->has($table, $hash)) { |
|
1321 | - $dbRow = $this->objectStorage->get($table, $hash); |
|
1322 | - $bean = $dbRow->getTDBMObject(); |
|
1323 | - if ($className !== null && !is_a($bean, $className)) { |
|
1324 | - throw new TDBMException("TDBM cannot create a bean of class '".$className."'. The requested object was already loaded and its class is '".get_class($bean)."'"); |
|
1325 | - } |
|
1326 | - |
|
1327 | - return $bean; |
|
1328 | - } |
|
1329 | - |
|
1330 | - // Are we performing lazy fetching? |
|
1331 | - if ($lazy === true) { |
|
1332 | - // Can we perform lazy fetching? |
|
1333 | - $tables = $this->_getRelatedTablesByInheritance($table); |
|
1334 | - // Only allowed if no inheritance. |
|
1335 | - if (count($tables) === 1) { |
|
1336 | - if ($className === null) { |
|
1337 | - $className = isset($this->tableToBeanMap[$table]) ? $this->tableToBeanMap[$table] : 'Mouf\\Database\\TDBM\\TDBMObject'; |
|
1338 | - } |
|
1339 | - |
|
1340 | - // Let's construct the bean |
|
1341 | - if (!isset($this->reflectionClassCache[$className])) { |
|
1342 | - $this->reflectionClassCache[$className] = new \ReflectionClass($className); |
|
1343 | - } |
|
1344 | - // Let's bypass the constructor when creating the bean! |
|
1345 | - $bean = $this->reflectionClassCache[$className]->newInstanceWithoutConstructor(); |
|
1346 | - /* @var $bean AbstractTDBMObject */ |
|
1347 | - $bean->_constructLazy($table, $primaryKeys, $this); |
|
1348 | - |
|
1349 | - return $bean; |
|
1350 | - } |
|
1351 | - } |
|
1352 | - |
|
1353 | - // Did not find the object in cache? Let's query it! |
|
1354 | - return $this->findObjectOrFail($table, $primaryKeys, [], $additionalTablesFetch, $className); |
|
1355 | - } |
|
1356 | - |
|
1357 | - /** |
|
1358 | - * Returns a unique bean (or null) according to the filters passed in parameter. |
|
1359 | - * |
|
1360 | - * @param string $mainTable The name of the table queried |
|
1361 | - * @param string|array|null $filter The SQL filters to apply to the query (the WHERE part). All columns must be prefixed by the table name (in the form: table.column) |
|
1362 | - * @param array $parameters |
|
1363 | - * @param array $additionalTablesFetch |
|
1364 | - * @param string $className Optional: The name of the class to instantiate. This class must extend the TDBMObject class. If none is specified, a TDBMObject instance will be returned |
|
1365 | - * |
|
1366 | - * @return AbstractTDBMObject|null The object we want, or null if no object matches the filters |
|
1367 | - * |
|
1368 | - * @throws TDBMException |
|
1369 | - */ |
|
1370 | - public function findObject(string $mainTable, $filter = null, array $parameters = array(), array $additionalTablesFetch = array(), string $className = null) |
|
1371 | - { |
|
1372 | - $objects = $this->findObjects($mainTable, $filter, $parameters, null, $additionalTablesFetch, self::MODE_ARRAY, $className); |
|
1373 | - $page = $objects->take(0, 2); |
|
1374 | - $count = $page->count(); |
|
1375 | - if ($count > 1) { |
|
1376 | - throw new DuplicateRowException("Error while querying an object for table '$mainTable': More than 1 row have been returned, but we should have received at most one."); |
|
1377 | - } elseif ($count === 0) { |
|
1378 | - return; |
|
1379 | - } |
|
1380 | - |
|
1381 | - return $page[0]; |
|
1382 | - } |
|
1383 | - |
|
1384 | - /** |
|
1385 | - * Returns a unique bean (or null) according to the filters passed in parameter. |
|
1386 | - * |
|
1387 | - * @param string $mainTable The name of the table queried |
|
1388 | - * @param string $from The from sql statement |
|
1389 | - * @param string|array|null $filter The SQL filters to apply to the query (the WHERE part). All columns must be prefixed by the table name (in the form: table.column) |
|
1390 | - * @param array $parameters |
|
1391 | - * @param string $className Optional: The name of the class to instantiate. This class must extend the TDBMObject class. If none is specified, a TDBMObject instance will be returned |
|
1392 | - * |
|
1393 | - * @return AbstractTDBMObject|null The object we want, or null if no object matches the filters |
|
1394 | - * |
|
1395 | - * @throws TDBMException |
|
1396 | - */ |
|
1397 | - public function findObjectFromSql($mainTable, $from, $filter = null, array $parameters = array(), $className = null) |
|
1398 | - { |
|
1399 | - $objects = $this->findObjectsFromSql($mainTable, $from, $filter, $parameters, null, self::MODE_ARRAY, $className); |
|
1400 | - $page = $objects->take(0, 2); |
|
1401 | - $count = $page->count(); |
|
1402 | - if ($count > 1) { |
|
1403 | - throw new DuplicateRowException("Error while querying an object for table '$mainTable': More than 1 row have been returned, but we should have received at most one."); |
|
1404 | - } elseif ($count === 0) { |
|
1405 | - return; |
|
1406 | - } |
|
1407 | - |
|
1408 | - return $page[0]; |
|
1409 | - } |
|
1410 | - |
|
1411 | - /** |
|
1412 | - * Returns a unique bean according to the filters passed in parameter. |
|
1413 | - * Throws a NoBeanFoundException if no bean was found for the filter passed in parameter. |
|
1414 | - * |
|
1415 | - * @param string $mainTable The name of the table queried |
|
1416 | - * @param string|array|null $filter The SQL filters to apply to the query (the WHERE part). All columns must be prefixed by the table name (in the form: table.column) |
|
1417 | - * @param array $parameters |
|
1418 | - * @param array $additionalTablesFetch |
|
1419 | - * @param string $className Optional: The name of the class to instantiate. This class must extend the TDBMObject class. If none is specified, a TDBMObject instance will be returned |
|
1420 | - * |
|
1421 | - * @return AbstractTDBMObject The object we want |
|
1422 | - * |
|
1423 | - * @throws TDBMException |
|
1424 | - */ |
|
1425 | - public function findObjectOrFail(string $mainTable, $filter = null, array $parameters = array(), array $additionalTablesFetch = array(), string $className = null) |
|
1426 | - { |
|
1427 | - $bean = $this->findObject($mainTable, $filter, $parameters, $additionalTablesFetch, $className); |
|
1428 | - if ($bean === null) { |
|
1429 | - throw new NoBeanFoundException("No result found for query on table '".$mainTable."'"); |
|
1430 | - } |
|
1431 | - |
|
1432 | - return $bean; |
|
1433 | - } |
|
1434 | - |
|
1435 | - /** |
|
1436 | - * @param array $beanData An array of data: array<table, array<column, value>> |
|
1437 | - * |
|
1438 | - * @return array an array with first item = class name, second item = table name and third item = list of tables needed |
|
1439 | - */ |
|
1440 | - public function _getClassNameFromBeanData(array $beanData) |
|
1441 | - { |
|
1442 | - if (count($beanData) === 1) { |
|
1443 | - $tableName = array_keys($beanData)[0]; |
|
1444 | - $allTables = [$tableName]; |
|
1445 | - } else { |
|
1446 | - $tables = []; |
|
1447 | - foreach ($beanData as $table => $row) { |
|
1448 | - $primaryKeyColumns = $this->getPrimaryKeyColumns($table); |
|
1449 | - $pkSet = false; |
|
1450 | - foreach ($primaryKeyColumns as $columnName) { |
|
1451 | - if ($row[$columnName] !== null) { |
|
1452 | - $pkSet = true; |
|
1453 | - break; |
|
1454 | - } |
|
1455 | - } |
|
1456 | - if ($pkSet) { |
|
1457 | - $tables[] = $table; |
|
1458 | - } |
|
1459 | - } |
|
1460 | - |
|
1461 | - // $tables contains the tables for this bean. Let's view the top most part of the hierarchy |
|
1462 | - try { |
|
1463 | - $allTables = $this->_getLinkBetweenInheritedTables($tables); |
|
1464 | - } catch (TDBMInheritanceException $e) { |
|
1465 | - throw TDBMInheritanceException::extendException($e, $this, $beanData); |
|
1466 | - } |
|
1467 | - $tableName = $allTables[0]; |
|
1468 | - } |
|
1469 | - |
|
1470 | - // Only one table in this bean. Life is sweat, let's look at its type: |
|
1471 | - if (isset($this->tableToBeanMap[$tableName])) { |
|
1472 | - return [$this->tableToBeanMap[$tableName], $tableName, $allTables]; |
|
1473 | - } else { |
|
1474 | - return ['Mouf\\Database\\TDBM\\TDBMObject', $tableName, $allTables]; |
|
1475 | - } |
|
1476 | - } |
|
1477 | - |
|
1478 | - /** |
|
1479 | - * Returns an item from cache or computes it using $closure and puts it in cache. |
|
1480 | - * |
|
1481 | - * @param string $key |
|
1482 | - * @param callable $closure |
|
1483 | - * |
|
1484 | - * @return mixed |
|
1485 | - */ |
|
1486 | - private function fromCache(string $key, callable $closure) |
|
1487 | - { |
|
1488 | - $item = $this->cache->fetch($key); |
|
1489 | - if ($item === false) { |
|
1490 | - $item = $closure(); |
|
1491 | - $this->cache->save($key, $item); |
|
1492 | - } |
|
1493 | - |
|
1494 | - return $item; |
|
1495 | - } |
|
1496 | - |
|
1497 | - /** |
|
1498 | - * Returns the foreign key object. |
|
1499 | - * |
|
1500 | - * @param string $table |
|
1501 | - * @param string $fkName |
|
1502 | - * |
|
1503 | - * @return ForeignKeyConstraint |
|
1504 | - */ |
|
1505 | - public function _getForeignKeyByName(string $table, string $fkName) |
|
1506 | - { |
|
1507 | - return $this->tdbmSchemaAnalyzer->getSchema()->getTable($table)->getForeignKey($fkName); |
|
1508 | - } |
|
1509 | - |
|
1510 | - /** |
|
1511 | - * @param $pivotTableName |
|
1512 | - * @param AbstractTDBMObject $bean |
|
1513 | - * |
|
1514 | - * @return AbstractTDBMObject[] |
|
1515 | - */ |
|
1516 | - public function _getRelatedBeans(string $pivotTableName, AbstractTDBMObject $bean) |
|
1517 | - { |
|
1518 | - list($localFk, $remoteFk) = $this->getPivotTableForeignKeys($pivotTableName, $bean); |
|
1519 | - /* @var $localFk ForeignKeyConstraint */ |
|
1520 | - /* @var $remoteFk ForeignKeyConstraint */ |
|
1521 | - $remoteTable = $remoteFk->getForeignTableName(); |
|
1522 | - |
|
1523 | - $primaryKeys = $this->getPrimaryKeyValues($bean); |
|
1524 | - $columnNames = array_map(function ($name) use ($pivotTableName) { |
|
1525 | - return $pivotTableName.'.'.$name; |
|
1526 | - }, $localFk->getLocalColumns()); |
|
1527 | - |
|
1528 | - $filter = array_combine($columnNames, $primaryKeys); |
|
1529 | - |
|
1530 | - return $this->findObjects($remoteTable, $filter); |
|
1531 | - } |
|
1532 | - |
|
1533 | - /** |
|
1534 | - * @param $pivotTableName |
|
1535 | - * @param AbstractTDBMObject $bean The LOCAL bean |
|
1536 | - * |
|
1537 | - * @return ForeignKeyConstraint[] First item: the LOCAL bean, second item: the REMOTE bean |
|
1538 | - * |
|
1539 | - * @throws TDBMException |
|
1540 | - */ |
|
1541 | - private function getPivotTableForeignKeys(string $pivotTableName, AbstractTDBMObject $bean) |
|
1542 | - { |
|
1543 | - $fks = array_values($this->tdbmSchemaAnalyzer->getSchema()->getTable($pivotTableName)->getForeignKeys()); |
|
1544 | - $table1 = $fks[0]->getForeignTableName(); |
|
1545 | - $table2 = $fks[1]->getForeignTableName(); |
|
1546 | - |
|
1547 | - $beanTables = array_map(function (DbRow $dbRow) { |
|
1548 | - return $dbRow->_getDbTableName(); |
|
1549 | - }, $bean->_getDbRows()); |
|
1550 | - |
|
1551 | - if (in_array($table1, $beanTables)) { |
|
1552 | - return [$fks[0], $fks[1]]; |
|
1553 | - } elseif (in_array($table2, $beanTables)) { |
|
1554 | - return [$fks[1], $fks[0]]; |
|
1555 | - } else { |
|
1556 | - throw new TDBMException("Unexpected bean type in getPivotTableForeignKeys. Awaiting beans from table {$table1} and {$table2} for pivot table {$pivotTableName}"); |
|
1557 | - } |
|
1558 | - } |
|
1559 | - |
|
1560 | - /** |
|
1561 | - * Returns a list of pivot tables linked to $bean. |
|
1562 | - * |
|
1563 | - * @param AbstractTDBMObject $bean |
|
1564 | - * |
|
1565 | - * @return string[] |
|
1566 | - */ |
|
1567 | - public function _getPivotTablesLinkedToBean(AbstractTDBMObject $bean) |
|
1568 | - { |
|
1569 | - $junctionTables = []; |
|
1570 | - $allJunctionTables = $this->schemaAnalyzer->detectJunctionTables(true); |
|
1571 | - foreach ($bean->_getDbRows() as $dbRow) { |
|
1572 | - foreach ($allJunctionTables as $table) { |
|
1573 | - // There are exactly 2 FKs since this is a pivot table. |
|
1574 | - $fks = array_values($table->getForeignKeys()); |
|
1575 | - |
|
1576 | - if ($fks[0]->getForeignTableName() === $dbRow->_getDbTableName() || $fks[1]->getForeignTableName() === $dbRow->_getDbTableName()) { |
|
1577 | - $junctionTables[] = $table->getName(); |
|
1578 | - } |
|
1579 | - } |
|
1580 | - } |
|
1581 | - |
|
1582 | - return $junctionTables; |
|
1583 | - } |
|
1584 | - |
|
1585 | - /** |
|
1586 | - * Array of types for tables. |
|
1587 | - * Key: table name |
|
1588 | - * Value: array of types indexed by column. |
|
1589 | - * |
|
1590 | - * @var array[] |
|
1591 | - */ |
|
1592 | - private $typesForTable = []; |
|
1593 | - |
|
1594 | - /** |
|
1595 | - * @internal |
|
1596 | - * |
|
1597 | - * @param string $tableName |
|
1598 | - * |
|
1599 | - * @return Type[] |
|
1600 | - */ |
|
1601 | - public function _getColumnTypesForTable(string $tableName) |
|
1602 | - { |
|
1603 | - if (!isset($typesForTable[$tableName])) { |
|
1604 | - $columns = $this->tdbmSchemaAnalyzer->getSchema()->getTable($tableName)->getColumns(); |
|
1605 | - $typesForTable[$tableName] = array_map(function (Column $column) { |
|
1606 | - return $column->getType(); |
|
1607 | - }, $columns); |
|
1608 | - } |
|
1609 | - |
|
1610 | - return $typesForTable[$tableName]; |
|
1611 | - } |
|
1612 | - |
|
1613 | - /** |
|
1614 | - * Sets the minimum log level. |
|
1615 | - * $level must be one of Psr\Log\LogLevel::xxx. |
|
1616 | - * |
|
1617 | - * Defaults to LogLevel::WARNING |
|
1618 | - * |
|
1619 | - * @param string $level |
|
1620 | - */ |
|
1621 | - public function setLogLevel(string $level) |
|
1622 | - { |
|
1623 | - $this->logger = new LevelFilter($this->rootLogger, $level); |
|
1624 | - } |
|
1220 | + /** |
|
1221 | + * Returns a `ResultIterator` object representing filtered records of "$mainTable" . |
|
1222 | + * |
|
1223 | + * The findObjects method should be the most used query method in TDBM if you want to query the database for objects. |
|
1224 | + * (Note: if you want to query the database for an object by its primary key, use the findObjectByPk method). |
|
1225 | + * |
|
1226 | + * The findObjects method takes in parameter: |
|
1227 | + * - mainTable: the kind of bean you want to retrieve. In TDBM, a bean matches a database row, so the |
|
1228 | + * `$mainTable` parameter should be the name of an existing table in database. |
|
1229 | + * - filter: The filter is a filter bag. It is what you use to filter your request (the WHERE part in SQL). |
|
1230 | + * It can be a string (SQL Where clause), or even a bean or an associative array (key = column to filter, value = value to find) |
|
1231 | + * - parameters: The parameters used in the filter. If you pass a SQL string as a filter, be sure to avoid |
|
1232 | + * concatenating parameters in the string (this leads to SQL injection and also to poor caching performance). |
|
1233 | + * Instead, please consider passing parameters (see documentation for more details). |
|
1234 | + * - additionalTablesFetch: An array of SQL tables names. The beans related to those tables will be fetched along |
|
1235 | + * the main table. This is useful to avoid hitting the database with numerous subqueries. |
|
1236 | + * - mode: The fetch mode of the result. See `setFetchMode()` method for more details. |
|
1237 | + * |
|
1238 | + * The `findObjects` method will return a `ResultIterator`. A `ResultIterator` is an object that behaves as an array |
|
1239 | + * (in ARRAY mode) at least. It can be iterated using a `foreach` loop. |
|
1240 | + * |
|
1241 | + * Finally, if filter_bag is null, the whole table is returned. |
|
1242 | + * |
|
1243 | + * @param string $mainTable The name of the table queried |
|
1244 | + * @param string|array|null $filter The SQL filters to apply to the query (the WHERE part). Columns from tables different from $mainTable must be prefixed by the table name (in the form: table.column) |
|
1245 | + * @param array $parameters |
|
1246 | + * @param string|UncheckedOrderBy|null $orderString The ORDER BY part of the query. Columns from tables different from $mainTable must be prefixed by the table name (in the form: table.column) |
|
1247 | + * @param array $additionalTablesFetch |
|
1248 | + * @param int $mode |
|
1249 | + * @param string $className Optional: The name of the class to instantiate. This class must extend the TDBMObject class. If none is specified, a TDBMObject instance will be returned |
|
1250 | + * |
|
1251 | + * @return ResultIterator An object representing an array of results |
|
1252 | + * |
|
1253 | + * @throws TDBMException |
|
1254 | + */ |
|
1255 | + public function findObjects(string $mainTable, $filter = null, array $parameters = array(), $orderString = null, array $additionalTablesFetch = array(), $mode = null, string $className = null) |
|
1256 | + { |
|
1257 | + // $mainTable is not secured in MagicJoin, let's add a bit of security to avoid SQL injection. |
|
1258 | + if (!preg_match('/^[a-zA-Z_][a-zA-Z0-9_]*$/', $mainTable)) { |
|
1259 | + throw new TDBMException(sprintf("Invalid table name: '%s'", $mainTable)); |
|
1260 | + } |
|
1261 | + |
|
1262 | + $mode = $mode ?: $this->mode; |
|
1263 | + |
|
1264 | + list($filterString, $additionalParameters) = $this->buildFilterFromFilterBag($filter); |
|
1265 | + |
|
1266 | + $parameters = array_merge($parameters, $additionalParameters); |
|
1267 | + |
|
1268 | + $queryFactory = new FindObjectsQueryFactory($mainTable, $additionalTablesFetch, $filterString, $orderString, $this, $this->tdbmSchemaAnalyzer->getSchema(), $this->orderByAnalyzer); |
|
1269 | + |
|
1270 | + return new ResultIterator($queryFactory, $parameters, $this->objectStorage, $className, $this, $this->magicQuery, $mode, $this->logger); |
|
1271 | + } |
|
1272 | + |
|
1273 | + /** |
|
1274 | + * @param string $mainTable The name of the table queried |
|
1275 | + * @param string $from The from sql statement |
|
1276 | + * @param string|array|null $filter The SQL filters to apply to the query (the WHERE part). All columns must be prefixed by the table name (in the form: table.column) |
|
1277 | + * @param array $parameters |
|
1278 | + * @param string|UncheckedOrderBy|null $orderString The ORDER BY part of the query. All columns must be prefixed by the table name (in the form: table.column) |
|
1279 | + * @param int $mode |
|
1280 | + * @param string $className Optional: The name of the class to instantiate. This class must extend the TDBMObject class. If none is specified, a TDBMObject instance will be returned |
|
1281 | + * |
|
1282 | + * @return ResultIterator An object representing an array of results |
|
1283 | + * |
|
1284 | + * @throws TDBMException |
|
1285 | + */ |
|
1286 | + public function findObjectsFromSql(string $mainTable, string $from, $filter = null, array $parameters = array(), $orderString = null, $mode = null, string $className = null) |
|
1287 | + { |
|
1288 | + // $mainTable is not secured in MagicJoin, let's add a bit of security to avoid SQL injection. |
|
1289 | + if (!preg_match('/^[a-zA-Z_][a-zA-Z0-9_]*$/', $mainTable)) { |
|
1290 | + throw new TDBMException(sprintf("Invalid table name: '%s'", $mainTable)); |
|
1291 | + } |
|
1292 | + |
|
1293 | + $mode = $mode ?: $this->mode; |
|
1294 | + |
|
1295 | + list($filterString, $additionalParameters) = $this->buildFilterFromFilterBag($filter); |
|
1296 | + |
|
1297 | + $parameters = array_merge($parameters, $additionalParameters); |
|
1298 | + |
|
1299 | + $queryFactory = new FindObjectsFromSqlQueryFactory($mainTable, $from, $filterString, $orderString, $this, $this->tdbmSchemaAnalyzer->getSchema(), $this->orderByAnalyzer, $this->schemaAnalyzer, $this->cache, $this->cachePrefix); |
|
1300 | + |
|
1301 | + return new ResultIterator($queryFactory, $parameters, $this->objectStorage, $className, $this, $this->magicQuery, $mode, $this->logger); |
|
1302 | + } |
|
1303 | + |
|
1304 | + /** |
|
1305 | + * @param $table |
|
1306 | + * @param array $primaryKeys |
|
1307 | + * @param array $additionalTablesFetch |
|
1308 | + * @param bool $lazy Whether to perform lazy loading on this object or not |
|
1309 | + * @param string $className |
|
1310 | + * |
|
1311 | + * @return AbstractTDBMObject |
|
1312 | + * |
|
1313 | + * @throws TDBMException |
|
1314 | + */ |
|
1315 | + public function findObjectByPk(string $table, array $primaryKeys, array $additionalTablesFetch = array(), bool $lazy = false, string $className = null) |
|
1316 | + { |
|
1317 | + $primaryKeys = $this->_getPrimaryKeysFromObjectData($table, $primaryKeys); |
|
1318 | + $hash = $this->getObjectHash($primaryKeys); |
|
1319 | + |
|
1320 | + if ($this->objectStorage->has($table, $hash)) { |
|
1321 | + $dbRow = $this->objectStorage->get($table, $hash); |
|
1322 | + $bean = $dbRow->getTDBMObject(); |
|
1323 | + if ($className !== null && !is_a($bean, $className)) { |
|
1324 | + throw new TDBMException("TDBM cannot create a bean of class '".$className."'. The requested object was already loaded and its class is '".get_class($bean)."'"); |
|
1325 | + } |
|
1326 | + |
|
1327 | + return $bean; |
|
1328 | + } |
|
1329 | + |
|
1330 | + // Are we performing lazy fetching? |
|
1331 | + if ($lazy === true) { |
|
1332 | + // Can we perform lazy fetching? |
|
1333 | + $tables = $this->_getRelatedTablesByInheritance($table); |
|
1334 | + // Only allowed if no inheritance. |
|
1335 | + if (count($tables) === 1) { |
|
1336 | + if ($className === null) { |
|
1337 | + $className = isset($this->tableToBeanMap[$table]) ? $this->tableToBeanMap[$table] : 'Mouf\\Database\\TDBM\\TDBMObject'; |
|
1338 | + } |
|
1339 | + |
|
1340 | + // Let's construct the bean |
|
1341 | + if (!isset($this->reflectionClassCache[$className])) { |
|
1342 | + $this->reflectionClassCache[$className] = new \ReflectionClass($className); |
|
1343 | + } |
|
1344 | + // Let's bypass the constructor when creating the bean! |
|
1345 | + $bean = $this->reflectionClassCache[$className]->newInstanceWithoutConstructor(); |
|
1346 | + /* @var $bean AbstractTDBMObject */ |
|
1347 | + $bean->_constructLazy($table, $primaryKeys, $this); |
|
1348 | + |
|
1349 | + return $bean; |
|
1350 | + } |
|
1351 | + } |
|
1352 | + |
|
1353 | + // Did not find the object in cache? Let's query it! |
|
1354 | + return $this->findObjectOrFail($table, $primaryKeys, [], $additionalTablesFetch, $className); |
|
1355 | + } |
|
1356 | + |
|
1357 | + /** |
|
1358 | + * Returns a unique bean (or null) according to the filters passed in parameter. |
|
1359 | + * |
|
1360 | + * @param string $mainTable The name of the table queried |
|
1361 | + * @param string|array|null $filter The SQL filters to apply to the query (the WHERE part). All columns must be prefixed by the table name (in the form: table.column) |
|
1362 | + * @param array $parameters |
|
1363 | + * @param array $additionalTablesFetch |
|
1364 | + * @param string $className Optional: The name of the class to instantiate. This class must extend the TDBMObject class. If none is specified, a TDBMObject instance will be returned |
|
1365 | + * |
|
1366 | + * @return AbstractTDBMObject|null The object we want, or null if no object matches the filters |
|
1367 | + * |
|
1368 | + * @throws TDBMException |
|
1369 | + */ |
|
1370 | + public function findObject(string $mainTable, $filter = null, array $parameters = array(), array $additionalTablesFetch = array(), string $className = null) |
|
1371 | + { |
|
1372 | + $objects = $this->findObjects($mainTable, $filter, $parameters, null, $additionalTablesFetch, self::MODE_ARRAY, $className); |
|
1373 | + $page = $objects->take(0, 2); |
|
1374 | + $count = $page->count(); |
|
1375 | + if ($count > 1) { |
|
1376 | + throw new DuplicateRowException("Error while querying an object for table '$mainTable': More than 1 row have been returned, but we should have received at most one."); |
|
1377 | + } elseif ($count === 0) { |
|
1378 | + return; |
|
1379 | + } |
|
1380 | + |
|
1381 | + return $page[0]; |
|
1382 | + } |
|
1383 | + |
|
1384 | + /** |
|
1385 | + * Returns a unique bean (or null) according to the filters passed in parameter. |
|
1386 | + * |
|
1387 | + * @param string $mainTable The name of the table queried |
|
1388 | + * @param string $from The from sql statement |
|
1389 | + * @param string|array|null $filter The SQL filters to apply to the query (the WHERE part). All columns must be prefixed by the table name (in the form: table.column) |
|
1390 | + * @param array $parameters |
|
1391 | + * @param string $className Optional: The name of the class to instantiate. This class must extend the TDBMObject class. If none is specified, a TDBMObject instance will be returned |
|
1392 | + * |
|
1393 | + * @return AbstractTDBMObject|null The object we want, or null if no object matches the filters |
|
1394 | + * |
|
1395 | + * @throws TDBMException |
|
1396 | + */ |
|
1397 | + public function findObjectFromSql($mainTable, $from, $filter = null, array $parameters = array(), $className = null) |
|
1398 | + { |
|
1399 | + $objects = $this->findObjectsFromSql($mainTable, $from, $filter, $parameters, null, self::MODE_ARRAY, $className); |
|
1400 | + $page = $objects->take(0, 2); |
|
1401 | + $count = $page->count(); |
|
1402 | + if ($count > 1) { |
|
1403 | + throw new DuplicateRowException("Error while querying an object for table '$mainTable': More than 1 row have been returned, but we should have received at most one."); |
|
1404 | + } elseif ($count === 0) { |
|
1405 | + return; |
|
1406 | + } |
|
1407 | + |
|
1408 | + return $page[0]; |
|
1409 | + } |
|
1410 | + |
|
1411 | + /** |
|
1412 | + * Returns a unique bean according to the filters passed in parameter. |
|
1413 | + * Throws a NoBeanFoundException if no bean was found for the filter passed in parameter. |
|
1414 | + * |
|
1415 | + * @param string $mainTable The name of the table queried |
|
1416 | + * @param string|array|null $filter The SQL filters to apply to the query (the WHERE part). All columns must be prefixed by the table name (in the form: table.column) |
|
1417 | + * @param array $parameters |
|
1418 | + * @param array $additionalTablesFetch |
|
1419 | + * @param string $className Optional: The name of the class to instantiate. This class must extend the TDBMObject class. If none is specified, a TDBMObject instance will be returned |
|
1420 | + * |
|
1421 | + * @return AbstractTDBMObject The object we want |
|
1422 | + * |
|
1423 | + * @throws TDBMException |
|
1424 | + */ |
|
1425 | + public function findObjectOrFail(string $mainTable, $filter = null, array $parameters = array(), array $additionalTablesFetch = array(), string $className = null) |
|
1426 | + { |
|
1427 | + $bean = $this->findObject($mainTable, $filter, $parameters, $additionalTablesFetch, $className); |
|
1428 | + if ($bean === null) { |
|
1429 | + throw new NoBeanFoundException("No result found for query on table '".$mainTable."'"); |
|
1430 | + } |
|
1431 | + |
|
1432 | + return $bean; |
|
1433 | + } |
|
1434 | + |
|
1435 | + /** |
|
1436 | + * @param array $beanData An array of data: array<table, array<column, value>> |
|
1437 | + * |
|
1438 | + * @return array an array with first item = class name, second item = table name and third item = list of tables needed |
|
1439 | + */ |
|
1440 | + public function _getClassNameFromBeanData(array $beanData) |
|
1441 | + { |
|
1442 | + if (count($beanData) === 1) { |
|
1443 | + $tableName = array_keys($beanData)[0]; |
|
1444 | + $allTables = [$tableName]; |
|
1445 | + } else { |
|
1446 | + $tables = []; |
|
1447 | + foreach ($beanData as $table => $row) { |
|
1448 | + $primaryKeyColumns = $this->getPrimaryKeyColumns($table); |
|
1449 | + $pkSet = false; |
|
1450 | + foreach ($primaryKeyColumns as $columnName) { |
|
1451 | + if ($row[$columnName] !== null) { |
|
1452 | + $pkSet = true; |
|
1453 | + break; |
|
1454 | + } |
|
1455 | + } |
|
1456 | + if ($pkSet) { |
|
1457 | + $tables[] = $table; |
|
1458 | + } |
|
1459 | + } |
|
1460 | + |
|
1461 | + // $tables contains the tables for this bean. Let's view the top most part of the hierarchy |
|
1462 | + try { |
|
1463 | + $allTables = $this->_getLinkBetweenInheritedTables($tables); |
|
1464 | + } catch (TDBMInheritanceException $e) { |
|
1465 | + throw TDBMInheritanceException::extendException($e, $this, $beanData); |
|
1466 | + } |
|
1467 | + $tableName = $allTables[0]; |
|
1468 | + } |
|
1469 | + |
|
1470 | + // Only one table in this bean. Life is sweat, let's look at its type: |
|
1471 | + if (isset($this->tableToBeanMap[$tableName])) { |
|
1472 | + return [$this->tableToBeanMap[$tableName], $tableName, $allTables]; |
|
1473 | + } else { |
|
1474 | + return ['Mouf\\Database\\TDBM\\TDBMObject', $tableName, $allTables]; |
|
1475 | + } |
|
1476 | + } |
|
1477 | + |
|
1478 | + /** |
|
1479 | + * Returns an item from cache or computes it using $closure and puts it in cache. |
|
1480 | + * |
|
1481 | + * @param string $key |
|
1482 | + * @param callable $closure |
|
1483 | + * |
|
1484 | + * @return mixed |
|
1485 | + */ |
|
1486 | + private function fromCache(string $key, callable $closure) |
|
1487 | + { |
|
1488 | + $item = $this->cache->fetch($key); |
|
1489 | + if ($item === false) { |
|
1490 | + $item = $closure(); |
|
1491 | + $this->cache->save($key, $item); |
|
1492 | + } |
|
1493 | + |
|
1494 | + return $item; |
|
1495 | + } |
|
1496 | + |
|
1497 | + /** |
|
1498 | + * Returns the foreign key object. |
|
1499 | + * |
|
1500 | + * @param string $table |
|
1501 | + * @param string $fkName |
|
1502 | + * |
|
1503 | + * @return ForeignKeyConstraint |
|
1504 | + */ |
|
1505 | + public function _getForeignKeyByName(string $table, string $fkName) |
|
1506 | + { |
|
1507 | + return $this->tdbmSchemaAnalyzer->getSchema()->getTable($table)->getForeignKey($fkName); |
|
1508 | + } |
|
1509 | + |
|
1510 | + /** |
|
1511 | + * @param $pivotTableName |
|
1512 | + * @param AbstractTDBMObject $bean |
|
1513 | + * |
|
1514 | + * @return AbstractTDBMObject[] |
|
1515 | + */ |
|
1516 | + public function _getRelatedBeans(string $pivotTableName, AbstractTDBMObject $bean) |
|
1517 | + { |
|
1518 | + list($localFk, $remoteFk) = $this->getPivotTableForeignKeys($pivotTableName, $bean); |
|
1519 | + /* @var $localFk ForeignKeyConstraint */ |
|
1520 | + /* @var $remoteFk ForeignKeyConstraint */ |
|
1521 | + $remoteTable = $remoteFk->getForeignTableName(); |
|
1522 | + |
|
1523 | + $primaryKeys = $this->getPrimaryKeyValues($bean); |
|
1524 | + $columnNames = array_map(function ($name) use ($pivotTableName) { |
|
1525 | + return $pivotTableName.'.'.$name; |
|
1526 | + }, $localFk->getLocalColumns()); |
|
1527 | + |
|
1528 | + $filter = array_combine($columnNames, $primaryKeys); |
|
1529 | + |
|
1530 | + return $this->findObjects($remoteTable, $filter); |
|
1531 | + } |
|
1532 | + |
|
1533 | + /** |
|
1534 | + * @param $pivotTableName |
|
1535 | + * @param AbstractTDBMObject $bean The LOCAL bean |
|
1536 | + * |
|
1537 | + * @return ForeignKeyConstraint[] First item: the LOCAL bean, second item: the REMOTE bean |
|
1538 | + * |
|
1539 | + * @throws TDBMException |
|
1540 | + */ |
|
1541 | + private function getPivotTableForeignKeys(string $pivotTableName, AbstractTDBMObject $bean) |
|
1542 | + { |
|
1543 | + $fks = array_values($this->tdbmSchemaAnalyzer->getSchema()->getTable($pivotTableName)->getForeignKeys()); |
|
1544 | + $table1 = $fks[0]->getForeignTableName(); |
|
1545 | + $table2 = $fks[1]->getForeignTableName(); |
|
1546 | + |
|
1547 | + $beanTables = array_map(function (DbRow $dbRow) { |
|
1548 | + return $dbRow->_getDbTableName(); |
|
1549 | + }, $bean->_getDbRows()); |
|
1550 | + |
|
1551 | + if (in_array($table1, $beanTables)) { |
|
1552 | + return [$fks[0], $fks[1]]; |
|
1553 | + } elseif (in_array($table2, $beanTables)) { |
|
1554 | + return [$fks[1], $fks[0]]; |
|
1555 | + } else { |
|
1556 | + throw new TDBMException("Unexpected bean type in getPivotTableForeignKeys. Awaiting beans from table {$table1} and {$table2} for pivot table {$pivotTableName}"); |
|
1557 | + } |
|
1558 | + } |
|
1559 | + |
|
1560 | + /** |
|
1561 | + * Returns a list of pivot tables linked to $bean. |
|
1562 | + * |
|
1563 | + * @param AbstractTDBMObject $bean |
|
1564 | + * |
|
1565 | + * @return string[] |
|
1566 | + */ |
|
1567 | + public function _getPivotTablesLinkedToBean(AbstractTDBMObject $bean) |
|
1568 | + { |
|
1569 | + $junctionTables = []; |
|
1570 | + $allJunctionTables = $this->schemaAnalyzer->detectJunctionTables(true); |
|
1571 | + foreach ($bean->_getDbRows() as $dbRow) { |
|
1572 | + foreach ($allJunctionTables as $table) { |
|
1573 | + // There are exactly 2 FKs since this is a pivot table. |
|
1574 | + $fks = array_values($table->getForeignKeys()); |
|
1575 | + |
|
1576 | + if ($fks[0]->getForeignTableName() === $dbRow->_getDbTableName() || $fks[1]->getForeignTableName() === $dbRow->_getDbTableName()) { |
|
1577 | + $junctionTables[] = $table->getName(); |
|
1578 | + } |
|
1579 | + } |
|
1580 | + } |
|
1581 | + |
|
1582 | + return $junctionTables; |
|
1583 | + } |
|
1584 | + |
|
1585 | + /** |
|
1586 | + * Array of types for tables. |
|
1587 | + * Key: table name |
|
1588 | + * Value: array of types indexed by column. |
|
1589 | + * |
|
1590 | + * @var array[] |
|
1591 | + */ |
|
1592 | + private $typesForTable = []; |
|
1593 | + |
|
1594 | + /** |
|
1595 | + * @internal |
|
1596 | + * |
|
1597 | + * @param string $tableName |
|
1598 | + * |
|
1599 | + * @return Type[] |
|
1600 | + */ |
|
1601 | + public function _getColumnTypesForTable(string $tableName) |
|
1602 | + { |
|
1603 | + if (!isset($typesForTable[$tableName])) { |
|
1604 | + $columns = $this->tdbmSchemaAnalyzer->getSchema()->getTable($tableName)->getColumns(); |
|
1605 | + $typesForTable[$tableName] = array_map(function (Column $column) { |
|
1606 | + return $column->getType(); |
|
1607 | + }, $columns); |
|
1608 | + } |
|
1609 | + |
|
1610 | + return $typesForTable[$tableName]; |
|
1611 | + } |
|
1612 | + |
|
1613 | + /** |
|
1614 | + * Sets the minimum log level. |
|
1615 | + * $level must be one of Psr\Log\LogLevel::xxx. |
|
1616 | + * |
|
1617 | + * Defaults to LogLevel::WARNING |
|
1618 | + * |
|
1619 | + * @param string $level |
|
1620 | + */ |
|
1621 | + public function setLogLevel(string $level) |
|
1622 | + { |
|
1623 | + $this->logger = new LevelFilter($this->rootLogger, $level); |
|
1624 | + } |
|
1625 | 1625 | } |
@@ -7,23 +7,23 @@ |
||
7 | 7 | */ |
8 | 8 | class TDBMInheritanceException extends TDBMException |
9 | 9 | { |
10 | - public static function create(array $tables) : TDBMInheritanceException |
|
11 | - { |
|
12 | - return new self(sprintf('The tables (%s) cannot be linked by an inheritance relationship. Does your data set contains multiple children for one parent row? (multiple inheritance is not supported by TDBM)', implode(', ', $tables))); |
|
13 | - } |
|
10 | + public static function create(array $tables) : TDBMInheritanceException |
|
11 | + { |
|
12 | + return new self(sprintf('The tables (%s) cannot be linked by an inheritance relationship. Does your data set contains multiple children for one parent row? (multiple inheritance is not supported by TDBM)', implode(', ', $tables))); |
|
13 | + } |
|
14 | 14 | |
15 | - public static function extendException(TDBMInheritanceException $e, TDBMService $tdbmService, array $beanData) |
|
16 | - { |
|
17 | - $pks = []; |
|
18 | - foreach ($beanData as $table => $row) { |
|
19 | - $primaryKeyColumns = $tdbmService->getPrimaryKeyColumns($table); |
|
20 | - foreach ($primaryKeyColumns as $columnName) { |
|
21 | - if ($row[$columnName] !== null) { |
|
22 | - $pks[] = $table.'.'.$columnName.' => '.var_export($row[$columnName], true); |
|
23 | - } |
|
24 | - } |
|
25 | - } |
|
15 | + public static function extendException(TDBMInheritanceException $e, TDBMService $tdbmService, array $beanData) |
|
16 | + { |
|
17 | + $pks = []; |
|
18 | + foreach ($beanData as $table => $row) { |
|
19 | + $primaryKeyColumns = $tdbmService->getPrimaryKeyColumns($table); |
|
20 | + foreach ($primaryKeyColumns as $columnName) { |
|
21 | + if ($row[$columnName] !== null) { |
|
22 | + $pks[] = $table.'.'.$columnName.' => '.var_export($row[$columnName], true); |
|
23 | + } |
|
24 | + } |
|
25 | + } |
|
26 | 26 | |
27 | - throw new self($e->getMessage().' (row in error: '.implode(', ', $pks).')', 0, $e); |
|
28 | - } |
|
27 | + throw new self($e->getMessage().' (row in error: '.implode(', ', $pks).')', 0, $e); |
|
28 | + } |
|
29 | 29 | } |
@@ -12,65 +12,65 @@ discard block |
||
12 | 12 | */ |
13 | 13 | class DirectForeignKeyMethodDescriptor implements MethodDescriptorInterface |
14 | 14 | { |
15 | - /** |
|
16 | - * @var ForeignKeyConstraint |
|
17 | - */ |
|
18 | - private $fk; |
|
19 | - |
|
20 | - private $useAlternateName = false; |
|
21 | - /** |
|
22 | - * @var Table |
|
23 | - */ |
|
24 | - private $mainTable; |
|
25 | - |
|
26 | - /** |
|
27 | - * @param ForeignKeyConstraint $fk The foreign key pointing to our bean |
|
28 | - * @param Table $mainTable The main table that is pointed to |
|
29 | - */ |
|
30 | - public function __construct(ForeignKeyConstraint $fk, Table $mainTable) |
|
31 | - { |
|
32 | - $this->fk = $fk; |
|
33 | - $this->mainTable = $mainTable; |
|
34 | - } |
|
35 | - |
|
36 | - /** |
|
37 | - * Returns the name of the method to be generated. |
|
38 | - * |
|
39 | - * @return string |
|
40 | - */ |
|
41 | - public function getName() : string |
|
42 | - { |
|
43 | - if (!$this->useAlternateName) { |
|
44 | - return 'get'.TDBMDaoGenerator::toCamelCase($this->fk->getLocalTableName()); |
|
45 | - } else { |
|
46 | - $methodName = 'get'.TDBMDaoGenerator::toCamelCase($this->fk->getLocalTableName()).'By'; |
|
47 | - |
|
48 | - $camelizedColumns = array_map([TDBMDaoGenerator::class, 'toCamelCase'], $this->fk->getLocalColumns()); |
|
49 | - |
|
50 | - $methodName .= implode('And', $camelizedColumns); |
|
51 | - |
|
52 | - return $methodName; |
|
53 | - } |
|
54 | - } |
|
55 | - |
|
56 | - /** |
|
57 | - * Requests the use of an alternative name for this method. |
|
58 | - */ |
|
59 | - public function useAlternativeName() |
|
60 | - { |
|
61 | - $this->useAlternateName = true; |
|
62 | - } |
|
63 | - |
|
64 | - /** |
|
65 | - * Returns the code of the method. |
|
66 | - * |
|
67 | - * @return string |
|
68 | - */ |
|
69 | - public function getCode() : string |
|
70 | - { |
|
71 | - $code = ''; |
|
72 | - |
|
73 | - $getterCode = ' /** |
|
15 | + /** |
|
16 | + * @var ForeignKeyConstraint |
|
17 | + */ |
|
18 | + private $fk; |
|
19 | + |
|
20 | + private $useAlternateName = false; |
|
21 | + /** |
|
22 | + * @var Table |
|
23 | + */ |
|
24 | + private $mainTable; |
|
25 | + |
|
26 | + /** |
|
27 | + * @param ForeignKeyConstraint $fk The foreign key pointing to our bean |
|
28 | + * @param Table $mainTable The main table that is pointed to |
|
29 | + */ |
|
30 | + public function __construct(ForeignKeyConstraint $fk, Table $mainTable) |
|
31 | + { |
|
32 | + $this->fk = $fk; |
|
33 | + $this->mainTable = $mainTable; |
|
34 | + } |
|
35 | + |
|
36 | + /** |
|
37 | + * Returns the name of the method to be generated. |
|
38 | + * |
|
39 | + * @return string |
|
40 | + */ |
|
41 | + public function getName() : string |
|
42 | + { |
|
43 | + if (!$this->useAlternateName) { |
|
44 | + return 'get'.TDBMDaoGenerator::toCamelCase($this->fk->getLocalTableName()); |
|
45 | + } else { |
|
46 | + $methodName = 'get'.TDBMDaoGenerator::toCamelCase($this->fk->getLocalTableName()).'By'; |
|
47 | + |
|
48 | + $camelizedColumns = array_map([TDBMDaoGenerator::class, 'toCamelCase'], $this->fk->getLocalColumns()); |
|
49 | + |
|
50 | + $methodName .= implode('And', $camelizedColumns); |
|
51 | + |
|
52 | + return $methodName; |
|
53 | + } |
|
54 | + } |
|
55 | + |
|
56 | + /** |
|
57 | + * Requests the use of an alternative name for this method. |
|
58 | + */ |
|
59 | + public function useAlternativeName() |
|
60 | + { |
|
61 | + $this->useAlternateName = true; |
|
62 | + } |
|
63 | + |
|
64 | + /** |
|
65 | + * Returns the code of the method. |
|
66 | + * |
|
67 | + * @return string |
|
68 | + */ |
|
69 | + public function getCode() : string |
|
70 | + { |
|
71 | + $code = ''; |
|
72 | + |
|
73 | + $getterCode = ' /** |
|
74 | 74 | * Returns the list of %s pointing to this bean via the %s column. |
75 | 75 | * |
76 | 76 | * @return %s[]|AlterableResultIterator |
@@ -82,55 +82,55 @@ discard block |
||
82 | 82 | |
83 | 83 | '; |
84 | 84 | |
85 | - $beanClass = TDBMDaoGenerator::getBeanNameFromTableName($this->fk->getLocalTableName()); |
|
86 | - $code .= sprintf($getterCode, |
|
87 | - $beanClass, |
|
88 | - implode(', ', $this->fk->getColumns()), |
|
89 | - $beanClass, |
|
90 | - $this->getName(), |
|
91 | - var_export($this->fk->getLocalTableName(), true), |
|
92 | - var_export($this->fk->getName(), true), |
|
93 | - var_export($this->fk->getLocalTableName(), true), |
|
94 | - $this->getFilters($this->fk) |
|
95 | - ); |
|
96 | - |
|
97 | - return $code; |
|
98 | - } |
|
99 | - |
|
100 | - private function getFilters(ForeignKeyConstraint $fk) : string |
|
101 | - { |
|
102 | - $counter = 0; |
|
103 | - $parameters = []; |
|
104 | - |
|
105 | - $pkColumns = $this->mainTable->getPrimaryKeyColumns(); |
|
106 | - |
|
107 | - foreach ($fk->getLocalColumns() as $columnName) { |
|
108 | - $pkColumn = $pkColumns[$counter]; |
|
109 | - $parameters[] = sprintf('%s => $this->get(%s, %s)', var_export($fk->getLocalTableName().'.'.$columnName, true), var_export($pkColumn, true), var_export($this->fk->getForeignTableName(), true)); |
|
110 | - ++$counter; |
|
111 | - } |
|
112 | - $parametersCode = '['.implode(', ', $parameters).']'; |
|
113 | - |
|
114 | - return $parametersCode; |
|
115 | - } |
|
116 | - |
|
117 | - /** |
|
118 | - * Returns an array of classes that needs a "use" for this method. |
|
119 | - * |
|
120 | - * @return string[] |
|
121 | - */ |
|
122 | - public function getUsedClasses() : array |
|
123 | - { |
|
124 | - return [TDBMDaoGenerator::getBeanNameFromTableName($this->fk->getForeignTableName())]; |
|
125 | - } |
|
126 | - |
|
127 | - /** |
|
128 | - * Returns the code to past in jsonSerialize. |
|
129 | - * |
|
130 | - * @return string |
|
131 | - */ |
|
132 | - public function getJsonSerializeCode() : string |
|
133 | - { |
|
134 | - return ''; |
|
135 | - } |
|
85 | + $beanClass = TDBMDaoGenerator::getBeanNameFromTableName($this->fk->getLocalTableName()); |
|
86 | + $code .= sprintf($getterCode, |
|
87 | + $beanClass, |
|
88 | + implode(', ', $this->fk->getColumns()), |
|
89 | + $beanClass, |
|
90 | + $this->getName(), |
|
91 | + var_export($this->fk->getLocalTableName(), true), |
|
92 | + var_export($this->fk->getName(), true), |
|
93 | + var_export($this->fk->getLocalTableName(), true), |
|
94 | + $this->getFilters($this->fk) |
|
95 | + ); |
|
96 | + |
|
97 | + return $code; |
|
98 | + } |
|
99 | + |
|
100 | + private function getFilters(ForeignKeyConstraint $fk) : string |
|
101 | + { |
|
102 | + $counter = 0; |
|
103 | + $parameters = []; |
|
104 | + |
|
105 | + $pkColumns = $this->mainTable->getPrimaryKeyColumns(); |
|
106 | + |
|
107 | + foreach ($fk->getLocalColumns() as $columnName) { |
|
108 | + $pkColumn = $pkColumns[$counter]; |
|
109 | + $parameters[] = sprintf('%s => $this->get(%s, %s)', var_export($fk->getLocalTableName().'.'.$columnName, true), var_export($pkColumn, true), var_export($this->fk->getForeignTableName(), true)); |
|
110 | + ++$counter; |
|
111 | + } |
|
112 | + $parametersCode = '['.implode(', ', $parameters).']'; |
|
113 | + |
|
114 | + return $parametersCode; |
|
115 | + } |
|
116 | + |
|
117 | + /** |
|
118 | + * Returns an array of classes that needs a "use" for this method. |
|
119 | + * |
|
120 | + * @return string[] |
|
121 | + */ |
|
122 | + public function getUsedClasses() : array |
|
123 | + { |
|
124 | + return [TDBMDaoGenerator::getBeanNameFromTableName($this->fk->getForeignTableName())]; |
|
125 | + } |
|
126 | + |
|
127 | + /** |
|
128 | + * Returns the code to past in jsonSerialize. |
|
129 | + * |
|
130 | + * @return string |
|
131 | + */ |
|
132 | + public function getJsonSerializeCode() : string |
|
133 | + { |
|
134 | + return ''; |
|
135 | + } |
|
136 | 136 | } |
@@ -1,6 +1,6 @@ |
||
1 | 1 | <?php |
2 | 2 | |
3 | -declare(strict_types=1); |
|
3 | +declare(strict_types = 1); |
|
4 | 4 | |
5 | 5 | namespace Mouf\Database\TDBM; |
6 | 6 |
@@ -7,99 +7,99 @@ discard block |
||
7 | 7 | |
8 | 8 | class PivotTableMethodsDescriptor implements MethodDescriptorInterface |
9 | 9 | { |
10 | - /** |
|
11 | - * @var Table |
|
12 | - */ |
|
13 | - private $pivotTable; |
|
14 | - |
|
15 | - private $useAlternateName = false; |
|
16 | - |
|
17 | - /** |
|
18 | - * @var ForeignKeyConstraint |
|
19 | - */ |
|
20 | - private $localFk; |
|
21 | - |
|
22 | - /** |
|
23 | - * @var ForeignKeyConstraint |
|
24 | - */ |
|
25 | - private $remoteFk; |
|
26 | - |
|
27 | - /** |
|
28 | - * @param Table $pivotTable The pivot table |
|
29 | - * @param ForeignKeyConstraint $localFk |
|
30 | - * @param ForeignKeyConstraint $remoteFk |
|
31 | - */ |
|
32 | - public function __construct(Table $pivotTable, ForeignKeyConstraint $localFk, ForeignKeyConstraint $remoteFk) |
|
33 | - { |
|
34 | - $this->pivotTable = $pivotTable; |
|
35 | - $this->localFk = $localFk; |
|
36 | - $this->remoteFk = $remoteFk; |
|
37 | - } |
|
38 | - |
|
39 | - /** |
|
40 | - * Requests the use of an alternative name for this method. |
|
41 | - */ |
|
42 | - public function useAlternativeName() |
|
43 | - { |
|
44 | - $this->useAlternateName = true; |
|
45 | - } |
|
46 | - |
|
47 | - /** |
|
48 | - * Returns the name of the method to be generated. |
|
49 | - * |
|
50 | - * @return string |
|
51 | - */ |
|
52 | - public function getName() : string |
|
53 | - { |
|
54 | - if (!$this->useAlternateName) { |
|
55 | - return 'get'.TDBMDaoGenerator::toCamelCase($this->remoteFk->getForeignTableName()); |
|
56 | - } else { |
|
57 | - return 'get'.TDBMDaoGenerator::toCamelCase($this->remoteFk->getForeignTableName()).'By'.TDBMDaoGenerator::toCamelCase($this->pivotTable->getName()); |
|
58 | - } |
|
59 | - } |
|
60 | - |
|
61 | - /** |
|
62 | - * Returns the plural name. |
|
63 | - * |
|
64 | - * @return string |
|
65 | - */ |
|
66 | - private function getPluralName() : string |
|
67 | - { |
|
68 | - if (!$this->useAlternateName) { |
|
69 | - return TDBMDaoGenerator::toCamelCase($this->remoteFk->getForeignTableName()); |
|
70 | - } else { |
|
71 | - return TDBMDaoGenerator::toCamelCase($this->remoteFk->getForeignTableName()).'By'.TDBMDaoGenerator::toCamelCase($this->pivotTable->getName()); |
|
72 | - } |
|
73 | - } |
|
74 | - |
|
75 | - /** |
|
76 | - * Returns the singular name. |
|
77 | - * |
|
78 | - * @return string |
|
79 | - */ |
|
80 | - private function getSingularName() : string |
|
81 | - { |
|
82 | - if (!$this->useAlternateName) { |
|
83 | - return TDBMDaoGenerator::toCamelCase(TDBMDaoGenerator::toSingular($this->remoteFk->getForeignTableName())); |
|
84 | - } else { |
|
85 | - return TDBMDaoGenerator::toCamelCase(TDBMDaoGenerator::toSingular($this->remoteFk->getForeignTableName())).'By'.TDBMDaoGenerator::toCamelCase($this->pivotTable->getName()); |
|
86 | - } |
|
87 | - } |
|
88 | - |
|
89 | - /** |
|
90 | - * Returns the code of the method. |
|
91 | - * |
|
92 | - * @return string |
|
93 | - */ |
|
94 | - public function getCode() : string |
|
95 | - { |
|
96 | - $singularName = $this->getSingularName(); |
|
97 | - $pluralName = $this->getPluralName(); |
|
98 | - $remoteBeanName = TDBMDaoGenerator::getBeanNameFromTableName($this->remoteFk->getForeignTableName()); |
|
99 | - $variableName = '$'.TDBMDaoGenerator::toVariableName($remoteBeanName); |
|
100 | - $pluralVariableName = $variableName.'s'; |
|
101 | - |
|
102 | - $str = ' /** |
|
10 | + /** |
|
11 | + * @var Table |
|
12 | + */ |
|
13 | + private $pivotTable; |
|
14 | + |
|
15 | + private $useAlternateName = false; |
|
16 | + |
|
17 | + /** |
|
18 | + * @var ForeignKeyConstraint |
|
19 | + */ |
|
20 | + private $localFk; |
|
21 | + |
|
22 | + /** |
|
23 | + * @var ForeignKeyConstraint |
|
24 | + */ |
|
25 | + private $remoteFk; |
|
26 | + |
|
27 | + /** |
|
28 | + * @param Table $pivotTable The pivot table |
|
29 | + * @param ForeignKeyConstraint $localFk |
|
30 | + * @param ForeignKeyConstraint $remoteFk |
|
31 | + */ |
|
32 | + public function __construct(Table $pivotTable, ForeignKeyConstraint $localFk, ForeignKeyConstraint $remoteFk) |
|
33 | + { |
|
34 | + $this->pivotTable = $pivotTable; |
|
35 | + $this->localFk = $localFk; |
|
36 | + $this->remoteFk = $remoteFk; |
|
37 | + } |
|
38 | + |
|
39 | + /** |
|
40 | + * Requests the use of an alternative name for this method. |
|
41 | + */ |
|
42 | + public function useAlternativeName() |
|
43 | + { |
|
44 | + $this->useAlternateName = true; |
|
45 | + } |
|
46 | + |
|
47 | + /** |
|
48 | + * Returns the name of the method to be generated. |
|
49 | + * |
|
50 | + * @return string |
|
51 | + */ |
|
52 | + public function getName() : string |
|
53 | + { |
|
54 | + if (!$this->useAlternateName) { |
|
55 | + return 'get'.TDBMDaoGenerator::toCamelCase($this->remoteFk->getForeignTableName()); |
|
56 | + } else { |
|
57 | + return 'get'.TDBMDaoGenerator::toCamelCase($this->remoteFk->getForeignTableName()).'By'.TDBMDaoGenerator::toCamelCase($this->pivotTable->getName()); |
|
58 | + } |
|
59 | + } |
|
60 | + |
|
61 | + /** |
|
62 | + * Returns the plural name. |
|
63 | + * |
|
64 | + * @return string |
|
65 | + */ |
|
66 | + private function getPluralName() : string |
|
67 | + { |
|
68 | + if (!$this->useAlternateName) { |
|
69 | + return TDBMDaoGenerator::toCamelCase($this->remoteFk->getForeignTableName()); |
|
70 | + } else { |
|
71 | + return TDBMDaoGenerator::toCamelCase($this->remoteFk->getForeignTableName()).'By'.TDBMDaoGenerator::toCamelCase($this->pivotTable->getName()); |
|
72 | + } |
|
73 | + } |
|
74 | + |
|
75 | + /** |
|
76 | + * Returns the singular name. |
|
77 | + * |
|
78 | + * @return string |
|
79 | + */ |
|
80 | + private function getSingularName() : string |
|
81 | + { |
|
82 | + if (!$this->useAlternateName) { |
|
83 | + return TDBMDaoGenerator::toCamelCase(TDBMDaoGenerator::toSingular($this->remoteFk->getForeignTableName())); |
|
84 | + } else { |
|
85 | + return TDBMDaoGenerator::toCamelCase(TDBMDaoGenerator::toSingular($this->remoteFk->getForeignTableName())).'By'.TDBMDaoGenerator::toCamelCase($this->pivotTable->getName()); |
|
86 | + } |
|
87 | + } |
|
88 | + |
|
89 | + /** |
|
90 | + * Returns the code of the method. |
|
91 | + * |
|
92 | + * @return string |
|
93 | + */ |
|
94 | + public function getCode() : string |
|
95 | + { |
|
96 | + $singularName = $this->getSingularName(); |
|
97 | + $pluralName = $this->getPluralName(); |
|
98 | + $remoteBeanName = TDBMDaoGenerator::getBeanNameFromTableName($this->remoteFk->getForeignTableName()); |
|
99 | + $variableName = '$'.TDBMDaoGenerator::toVariableName($remoteBeanName); |
|
100 | + $pluralVariableName = $variableName.'s'; |
|
101 | + |
|
102 | + $str = ' /** |
|
103 | 103 | * Returns the list of %s associated to this bean via the %s pivot table. |
104 | 104 | * |
105 | 105 | * @return %s[] |
@@ -110,9 +110,9 @@ discard block |
||
110 | 110 | } |
111 | 111 | '; |
112 | 112 | |
113 | - $getterCode = sprintf($str, $remoteBeanName, $this->pivotTable->getName(), $remoteBeanName, $pluralName, var_export($this->remoteFk->getLocalTableName(), true)); |
|
113 | + $getterCode = sprintf($str, $remoteBeanName, $this->pivotTable->getName(), $remoteBeanName, $pluralName, var_export($this->remoteFk->getLocalTableName(), true)); |
|
114 | 114 | |
115 | - $str = ' /** |
|
115 | + $str = ' /** |
|
116 | 116 | * Adds a relationship with %s associated to this bean via the %s pivot table. |
117 | 117 | * |
118 | 118 | * @param %s %s |
@@ -123,9 +123,9 @@ discard block |
||
123 | 123 | } |
124 | 124 | '; |
125 | 125 | |
126 | - $adderCode = sprintf($str, $remoteBeanName, $this->pivotTable->getName(), $remoteBeanName, $variableName, $singularName, $remoteBeanName, $variableName, var_export($this->remoteFk->getLocalTableName(), true), $variableName); |
|
126 | + $adderCode = sprintf($str, $remoteBeanName, $this->pivotTable->getName(), $remoteBeanName, $variableName, $singularName, $remoteBeanName, $variableName, var_export($this->remoteFk->getLocalTableName(), true), $variableName); |
|
127 | 127 | |
128 | - $str = ' /** |
|
128 | + $str = ' /** |
|
129 | 129 | * Deletes the relationship with %s associated to this bean via the %s pivot table. |
130 | 130 | * |
131 | 131 | * @param %s %s |
@@ -136,9 +136,9 @@ discard block |
||
136 | 136 | } |
137 | 137 | '; |
138 | 138 | |
139 | - $removerCode = sprintf($str, $remoteBeanName, $this->pivotTable->getName(), $remoteBeanName, $variableName, $singularName, $remoteBeanName, $variableName, var_export($this->remoteFk->getLocalTableName(), true), $variableName); |
|
139 | + $removerCode = sprintf($str, $remoteBeanName, $this->pivotTable->getName(), $remoteBeanName, $variableName, $singularName, $remoteBeanName, $variableName, var_export($this->remoteFk->getLocalTableName(), true), $variableName); |
|
140 | 140 | |
141 | - $str = ' /** |
|
141 | + $str = ' /** |
|
142 | 142 | * Returns whether this bean is associated with %s via the %s pivot table. |
143 | 143 | * |
144 | 144 | * @param %s %s |
@@ -150,9 +150,9 @@ discard block |
||
150 | 150 | } |
151 | 151 | '; |
152 | 152 | |
153 | - $hasCode = sprintf($str, $remoteBeanName, $this->pivotTable->getName(), $remoteBeanName, $variableName, $singularName, $remoteBeanName, $variableName, var_export($this->remoteFk->getLocalTableName(), true), $variableName); |
|
153 | + $hasCode = sprintf($str, $remoteBeanName, $this->pivotTable->getName(), $remoteBeanName, $variableName, $singularName, $remoteBeanName, $variableName, var_export($this->remoteFk->getLocalTableName(), true), $variableName); |
|
154 | 154 | |
155 | - $str = ' /** |
|
155 | + $str = ' /** |
|
156 | 156 | * Sets all relationships with %s associated to this bean via the %s pivot table. |
157 | 157 | * Exiting relationships will be removed and replaced by the provided relationships. |
158 | 158 | * |
@@ -164,38 +164,38 @@ discard block |
||
164 | 164 | } |
165 | 165 | '; |
166 | 166 | |
167 | - $setterCode = sprintf($str, $remoteBeanName, $this->pivotTable->getName(), $remoteBeanName, $pluralVariableName, $pluralName, $pluralVariableName, var_export($this->remoteFk->getLocalTableName(), true), $pluralVariableName); |
|
168 | - |
|
169 | - $code = $getterCode.$adderCode.$removerCode.$hasCode.$setterCode; |
|
170 | - |
|
171 | - return $code; |
|
172 | - } |
|
173 | - |
|
174 | - /** |
|
175 | - * Returns an array of classes that needs a "use" for this method. |
|
176 | - * |
|
177 | - * @return string[] |
|
178 | - */ |
|
179 | - public function getUsedClasses() : array |
|
180 | - { |
|
181 | - return [TDBMDaoGenerator::getBeanNameFromTableName($this->remoteFk->getForeignTableName())]; |
|
182 | - } |
|
183 | - |
|
184 | - /** |
|
185 | - * Returns the code to past in jsonSerialize. |
|
186 | - * |
|
187 | - * @return string |
|
188 | - */ |
|
189 | - public function getJsonSerializeCode() : string |
|
190 | - { |
|
191 | - $remoteBeanName = TDBMDaoGenerator::getBeanNameFromTableName($this->remoteFk->getForeignTableName()); |
|
192 | - $variableName = '$'.TDBMDaoGenerator::toVariableName($remoteBeanName); |
|
193 | - |
|
194 | - return ' if (!$stopRecursion) { |
|
167 | + $setterCode = sprintf($str, $remoteBeanName, $this->pivotTable->getName(), $remoteBeanName, $pluralVariableName, $pluralName, $pluralVariableName, var_export($this->remoteFk->getLocalTableName(), true), $pluralVariableName); |
|
168 | + |
|
169 | + $code = $getterCode.$adderCode.$removerCode.$hasCode.$setterCode; |
|
170 | + |
|
171 | + return $code; |
|
172 | + } |
|
173 | + |
|
174 | + /** |
|
175 | + * Returns an array of classes that needs a "use" for this method. |
|
176 | + * |
|
177 | + * @return string[] |
|
178 | + */ |
|
179 | + public function getUsedClasses() : array |
|
180 | + { |
|
181 | + return [TDBMDaoGenerator::getBeanNameFromTableName($this->remoteFk->getForeignTableName())]; |
|
182 | + } |
|
183 | + |
|
184 | + /** |
|
185 | + * Returns the code to past in jsonSerialize. |
|
186 | + * |
|
187 | + * @return string |
|
188 | + */ |
|
189 | + public function getJsonSerializeCode() : string |
|
190 | + { |
|
191 | + $remoteBeanName = TDBMDaoGenerator::getBeanNameFromTableName($this->remoteFk->getForeignTableName()); |
|
192 | + $variableName = '$'.TDBMDaoGenerator::toVariableName($remoteBeanName); |
|
193 | + |
|
194 | + return ' if (!$stopRecursion) { |
|
195 | 195 | $array[\''.lcfirst($this->getPluralName()).'\'] = array_map(function ('.$remoteBeanName.' '.$variableName.') { |
196 | 196 | return '.$variableName.'->jsonSerialize(true); |
197 | 197 | }, $this->'.$this->getName().'()); |
198 | 198 | } |
199 | 199 | '; |
200 | - } |
|
200 | + } |
|
201 | 201 | } |
@@ -14,274 +14,274 @@ |
||
14 | 14 | */ |
15 | 15 | class AlterableResultIterator implements Result, \ArrayAccess, \JsonSerializable |
16 | 16 | { |
17 | - /** |
|
18 | - * @var \Iterator|null |
|
19 | - */ |
|
20 | - private $resultIterator; |
|
17 | + /** |
|
18 | + * @var \Iterator|null |
|
19 | + */ |
|
20 | + private $resultIterator; |
|
21 | 21 | |
22 | - /** |
|
23 | - * Key: the object to alter in the result set. |
|
24 | - * Value: "add" => the object will be added to the resultset (if it is not found in it) |
|
25 | - * "delete" => the object will be removed from the resultset (if found). |
|
26 | - * |
|
27 | - * @var \SplObjectStorage |
|
28 | - */ |
|
29 | - private $alterations; |
|
22 | + /** |
|
23 | + * Key: the object to alter in the result set. |
|
24 | + * Value: "add" => the object will be added to the resultset (if it is not found in it) |
|
25 | + * "delete" => the object will be removed from the resultset (if found). |
|
26 | + * |
|
27 | + * @var \SplObjectStorage |
|
28 | + */ |
|
29 | + private $alterations; |
|
30 | 30 | |
31 | - /** |
|
32 | - * The result array from the result set. |
|
33 | - * |
|
34 | - * @var array|null |
|
35 | - */ |
|
36 | - private $resultArray; |
|
31 | + /** |
|
32 | + * The result array from the result set. |
|
33 | + * |
|
34 | + * @var array|null |
|
35 | + */ |
|
36 | + private $resultArray; |
|
37 | 37 | |
38 | - /** |
|
39 | - * @param \Iterator|null $resultIterator |
|
40 | - */ |
|
41 | - public function __construct(\Iterator $resultIterator = null) |
|
42 | - { |
|
43 | - $this->resultIterator = $resultIterator; |
|
44 | - $this->alterations = new \SplObjectStorage(); |
|
45 | - } |
|
38 | + /** |
|
39 | + * @param \Iterator|null $resultIterator |
|
40 | + */ |
|
41 | + public function __construct(\Iterator $resultIterator = null) |
|
42 | + { |
|
43 | + $this->resultIterator = $resultIterator; |
|
44 | + $this->alterations = new \SplObjectStorage(); |
|
45 | + } |
|
46 | 46 | |
47 | - /** |
|
48 | - * Sets a new iterator as the base iterator to be altered. |
|
49 | - * |
|
50 | - * @param \Iterator $resultIterator |
|
51 | - */ |
|
52 | - public function setResultIterator(\Iterator $resultIterator) |
|
53 | - { |
|
54 | - $this->resultIterator = $resultIterator; |
|
55 | - $this->resultArray = null; |
|
56 | - } |
|
47 | + /** |
|
48 | + * Sets a new iterator as the base iterator to be altered. |
|
49 | + * |
|
50 | + * @param \Iterator $resultIterator |
|
51 | + */ |
|
52 | + public function setResultIterator(\Iterator $resultIterator) |
|
53 | + { |
|
54 | + $this->resultIterator = $resultIterator; |
|
55 | + $this->resultArray = null; |
|
56 | + } |
|
57 | 57 | |
58 | - /** |
|
59 | - * Returns the non altered result iterator (or null if none exist). |
|
60 | - * |
|
61 | - * @return \Iterator|null |
|
62 | - */ |
|
63 | - public function getUnderlyingResultIterator() |
|
64 | - { |
|
65 | - return $this->resultIterator; |
|
66 | - } |
|
58 | + /** |
|
59 | + * Returns the non altered result iterator (or null if none exist). |
|
60 | + * |
|
61 | + * @return \Iterator|null |
|
62 | + */ |
|
63 | + public function getUnderlyingResultIterator() |
|
64 | + { |
|
65 | + return $this->resultIterator; |
|
66 | + } |
|
67 | 67 | |
68 | - /** |
|
69 | - * Adds an additional object to the result set (if not already available). |
|
70 | - * |
|
71 | - * @param $object |
|
72 | - */ |
|
73 | - public function add($object) |
|
74 | - { |
|
75 | - $this->alterations->attach($object, 'add'); |
|
68 | + /** |
|
69 | + * Adds an additional object to the result set (if not already available). |
|
70 | + * |
|
71 | + * @param $object |
|
72 | + */ |
|
73 | + public function add($object) |
|
74 | + { |
|
75 | + $this->alterations->attach($object, 'add'); |
|
76 | 76 | |
77 | - if ($this->resultArray !== null) { |
|
78 | - $foundKey = array_search($object, $this->resultArray, true); |
|
79 | - if ($foundKey === false) { |
|
80 | - $this->resultArray[] = $object; |
|
81 | - } |
|
82 | - } |
|
83 | - } |
|
77 | + if ($this->resultArray !== null) { |
|
78 | + $foundKey = array_search($object, $this->resultArray, true); |
|
79 | + if ($foundKey === false) { |
|
80 | + $this->resultArray[] = $object; |
|
81 | + } |
|
82 | + } |
|
83 | + } |
|
84 | 84 | |
85 | - /** |
|
86 | - * Removes an object from the result set. |
|
87 | - * |
|
88 | - * @param $object |
|
89 | - */ |
|
90 | - public function remove($object) |
|
91 | - { |
|
92 | - $this->alterations->attach($object, 'delete'); |
|
85 | + /** |
|
86 | + * Removes an object from the result set. |
|
87 | + * |
|
88 | + * @param $object |
|
89 | + */ |
|
90 | + public function remove($object) |
|
91 | + { |
|
92 | + $this->alterations->attach($object, 'delete'); |
|
93 | 93 | |
94 | - if ($this->resultArray !== null) { |
|
95 | - $foundKey = array_search($object, $this->resultArray, true); |
|
96 | - if ($foundKey !== false) { |
|
97 | - unset($this->resultArray[$foundKey]); |
|
98 | - } |
|
99 | - } |
|
100 | - } |
|
94 | + if ($this->resultArray !== null) { |
|
95 | + $foundKey = array_search($object, $this->resultArray, true); |
|
96 | + if ($foundKey !== false) { |
|
97 | + unset($this->resultArray[$foundKey]); |
|
98 | + } |
|
99 | + } |
|
100 | + } |
|
101 | 101 | |
102 | - /** |
|
103 | - * Casts the result set to a PHP array. |
|
104 | - * |
|
105 | - * @return array |
|
106 | - */ |
|
107 | - public function toArray() |
|
108 | - { |
|
109 | - if ($this->resultArray === null) { |
|
110 | - if ($this->resultIterator !== null) { |
|
111 | - $this->resultArray = iterator_to_array($this->resultIterator); |
|
112 | - } else { |
|
113 | - $this->resultArray = []; |
|
114 | - } |
|
102 | + /** |
|
103 | + * Casts the result set to a PHP array. |
|
104 | + * |
|
105 | + * @return array |
|
106 | + */ |
|
107 | + public function toArray() |
|
108 | + { |
|
109 | + if ($this->resultArray === null) { |
|
110 | + if ($this->resultIterator !== null) { |
|
111 | + $this->resultArray = iterator_to_array($this->resultIterator); |
|
112 | + } else { |
|
113 | + $this->resultArray = []; |
|
114 | + } |
|
115 | 115 | |
116 | - foreach ($this->alterations as $obj) { |
|
117 | - $action = $this->alterations->getInfo(); // return, if exists, associated with cur. obj. data; else NULL |
|
116 | + foreach ($this->alterations as $obj) { |
|
117 | + $action = $this->alterations->getInfo(); // return, if exists, associated with cur. obj. data; else NULL |
|
118 | 118 | |
119 | - $foundKey = array_search($obj, $this->resultArray, true); |
|
119 | + $foundKey = array_search($obj, $this->resultArray, true); |
|
120 | 120 | |
121 | - if ($action === 'add' && $foundKey === false) { |
|
122 | - $this->resultArray[] = $obj; |
|
123 | - } elseif ($action === 'delete' && $foundKey !== false) { |
|
124 | - unset($this->resultArray[$foundKey]); |
|
125 | - } |
|
126 | - } |
|
127 | - } |
|
121 | + if ($action === 'add' && $foundKey === false) { |
|
122 | + $this->resultArray[] = $obj; |
|
123 | + } elseif ($action === 'delete' && $foundKey !== false) { |
|
124 | + unset($this->resultArray[$foundKey]); |
|
125 | + } |
|
126 | + } |
|
127 | + } |
|
128 | 128 | |
129 | - return array_values($this->resultArray); |
|
130 | - } |
|
129 | + return array_values($this->resultArray); |
|
130 | + } |
|
131 | 131 | |
132 | - /** |
|
133 | - * Whether a offset exists. |
|
134 | - * |
|
135 | - * @link http://php.net/manual/en/arrayaccess.offsetexists.php |
|
136 | - * |
|
137 | - * @param mixed $offset <p> |
|
138 | - * An offset to check for. |
|
139 | - * </p> |
|
140 | - * |
|
141 | - * @return bool true on success or false on failure. |
|
142 | - * </p> |
|
143 | - * <p> |
|
144 | - * The return value will be casted to boolean if non-boolean was returned |
|
145 | - * |
|
146 | - * @since 5.0.0 |
|
147 | - */ |
|
148 | - public function offsetExists($offset) |
|
149 | - { |
|
150 | - return isset($this->toArray()[$offset]); |
|
151 | - } |
|
132 | + /** |
|
133 | + * Whether a offset exists. |
|
134 | + * |
|
135 | + * @link http://php.net/manual/en/arrayaccess.offsetexists.php |
|
136 | + * |
|
137 | + * @param mixed $offset <p> |
|
138 | + * An offset to check for. |
|
139 | + * </p> |
|
140 | + * |
|
141 | + * @return bool true on success or false on failure. |
|
142 | + * </p> |
|
143 | + * <p> |
|
144 | + * The return value will be casted to boolean if non-boolean was returned |
|
145 | + * |
|
146 | + * @since 5.0.0 |
|
147 | + */ |
|
148 | + public function offsetExists($offset) |
|
149 | + { |
|
150 | + return isset($this->toArray()[$offset]); |
|
151 | + } |
|
152 | 152 | |
153 | - /** |
|
154 | - * Offset to retrieve. |
|
155 | - * |
|
156 | - * @link http://php.net/manual/en/arrayaccess.offsetget.php |
|
157 | - * |
|
158 | - * @param mixed $offset <p> |
|
159 | - * The offset to retrieve. |
|
160 | - * </p> |
|
161 | - * |
|
162 | - * @return mixed Can return all value types |
|
163 | - * |
|
164 | - * @since 5.0.0 |
|
165 | - */ |
|
166 | - public function offsetGet($offset) |
|
167 | - { |
|
168 | - return $this->toArray()[$offset]; |
|
169 | - } |
|
153 | + /** |
|
154 | + * Offset to retrieve. |
|
155 | + * |
|
156 | + * @link http://php.net/manual/en/arrayaccess.offsetget.php |
|
157 | + * |
|
158 | + * @param mixed $offset <p> |
|
159 | + * The offset to retrieve. |
|
160 | + * </p> |
|
161 | + * |
|
162 | + * @return mixed Can return all value types |
|
163 | + * |
|
164 | + * @since 5.0.0 |
|
165 | + */ |
|
166 | + public function offsetGet($offset) |
|
167 | + { |
|
168 | + return $this->toArray()[$offset]; |
|
169 | + } |
|
170 | 170 | |
171 | - /** |
|
172 | - * Offset to set. |
|
173 | - * |
|
174 | - * @link http://php.net/manual/en/arrayaccess.offsetset.php |
|
175 | - * |
|
176 | - * @param mixed $offset <p> |
|
177 | - * The offset to assign the value to. |
|
178 | - * </p> |
|
179 | - * @param mixed $value <p> |
|
180 | - * The value to set. |
|
181 | - * </p> |
|
182 | - * |
|
183 | - * @since 5.0.0 |
|
184 | - */ |
|
185 | - public function offsetSet($offset, $value) |
|
186 | - { |
|
187 | - throw new TDBMInvalidOperationException('You can set values in a TDBM result set, even in an alterable one. Use the add method instead.'); |
|
188 | - } |
|
171 | + /** |
|
172 | + * Offset to set. |
|
173 | + * |
|
174 | + * @link http://php.net/manual/en/arrayaccess.offsetset.php |
|
175 | + * |
|
176 | + * @param mixed $offset <p> |
|
177 | + * The offset to assign the value to. |
|
178 | + * </p> |
|
179 | + * @param mixed $value <p> |
|
180 | + * The value to set. |
|
181 | + * </p> |
|
182 | + * |
|
183 | + * @since 5.0.0 |
|
184 | + */ |
|
185 | + public function offsetSet($offset, $value) |
|
186 | + { |
|
187 | + throw new TDBMInvalidOperationException('You can set values in a TDBM result set, even in an alterable one. Use the add method instead.'); |
|
188 | + } |
|
189 | 189 | |
190 | - /** |
|
191 | - * Offset to unset. |
|
192 | - * |
|
193 | - * @link http://php.net/manual/en/arrayaccess.offsetunset.php |
|
194 | - * |
|
195 | - * @param mixed $offset <p> |
|
196 | - * The offset to unset. |
|
197 | - * </p> |
|
198 | - * |
|
199 | - * @since 5.0.0 |
|
200 | - */ |
|
201 | - public function offsetUnset($offset) |
|
202 | - { |
|
203 | - throw new TDBMInvalidOperationException('You can unset values in a TDBM result set, even in an alterable one. Use the delete method instead.'); |
|
204 | - } |
|
190 | + /** |
|
191 | + * Offset to unset. |
|
192 | + * |
|
193 | + * @link http://php.net/manual/en/arrayaccess.offsetunset.php |
|
194 | + * |
|
195 | + * @param mixed $offset <p> |
|
196 | + * The offset to unset. |
|
197 | + * </p> |
|
198 | + * |
|
199 | + * @since 5.0.0 |
|
200 | + */ |
|
201 | + public function offsetUnset($offset) |
|
202 | + { |
|
203 | + throw new TDBMInvalidOperationException('You can unset values in a TDBM result set, even in an alterable one. Use the delete method instead.'); |
|
204 | + } |
|
205 | 205 | |
206 | - /** |
|
207 | - * @param int $offset |
|
208 | - * |
|
209 | - * @return \Porpaginas\Page |
|
210 | - */ |
|
211 | - public function take($offset, $limit) |
|
212 | - { |
|
213 | - // TODO: replace this with a class implementing the map method. |
|
214 | - return new ArrayPage(array_slice($this->toArray(), $offset, $limit), $offset, $limit, count($this->toArray())); |
|
215 | - } |
|
206 | + /** |
|
207 | + * @param int $offset |
|
208 | + * |
|
209 | + * @return \Porpaginas\Page |
|
210 | + */ |
|
211 | + public function take($offset, $limit) |
|
212 | + { |
|
213 | + // TODO: replace this with a class implementing the map method. |
|
214 | + return new ArrayPage(array_slice($this->toArray(), $offset, $limit), $offset, $limit, count($this->toArray())); |
|
215 | + } |
|
216 | 216 | |
217 | - /** |
|
218 | - * Return the number of all results in the paginatable. |
|
219 | - * |
|
220 | - * @return int |
|
221 | - */ |
|
222 | - public function count() |
|
223 | - { |
|
224 | - return count($this->toArray()); |
|
225 | - } |
|
217 | + /** |
|
218 | + * Return the number of all results in the paginatable. |
|
219 | + * |
|
220 | + * @return int |
|
221 | + */ |
|
222 | + public function count() |
|
223 | + { |
|
224 | + return count($this->toArray()); |
|
225 | + } |
|
226 | 226 | |
227 | - /** |
|
228 | - * Return an iterator over all results of the paginatable. |
|
229 | - * |
|
230 | - * @return Iterator |
|
231 | - */ |
|
232 | - public function getIterator() |
|
233 | - { |
|
234 | - if ($this->alterations->count() === 0) { |
|
235 | - if ($this->resultIterator !== null) { |
|
236 | - return $this->resultIterator; |
|
237 | - } else { |
|
238 | - return new \ArrayIterator([]); |
|
239 | - } |
|
240 | - } else { |
|
241 | - return new \ArrayIterator($this->toArray()); |
|
242 | - } |
|
243 | - } |
|
227 | + /** |
|
228 | + * Return an iterator over all results of the paginatable. |
|
229 | + * |
|
230 | + * @return Iterator |
|
231 | + */ |
|
232 | + public function getIterator() |
|
233 | + { |
|
234 | + if ($this->alterations->count() === 0) { |
|
235 | + if ($this->resultIterator !== null) { |
|
236 | + return $this->resultIterator; |
|
237 | + } else { |
|
238 | + return new \ArrayIterator([]); |
|
239 | + } |
|
240 | + } else { |
|
241 | + return new \ArrayIterator($this->toArray()); |
|
242 | + } |
|
243 | + } |
|
244 | 244 | |
245 | - /** |
|
246 | - * Specify data which should be serialized to JSON. |
|
247 | - * |
|
248 | - * @link http://php.net/manual/en/jsonserializable.jsonserialize.php |
|
249 | - * |
|
250 | - * @return mixed data which can be serialized by <b>json_encode</b>, |
|
251 | - * which is a value of any type other than a resource |
|
252 | - * |
|
253 | - * @since 5.4.0 |
|
254 | - */ |
|
255 | - public function jsonSerialize() |
|
256 | - { |
|
257 | - return $this->toArray(); |
|
258 | - } |
|
245 | + /** |
|
246 | + * Specify data which should be serialized to JSON. |
|
247 | + * |
|
248 | + * @link http://php.net/manual/en/jsonserializable.jsonserialize.php |
|
249 | + * |
|
250 | + * @return mixed data which can be serialized by <b>json_encode</b>, |
|
251 | + * which is a value of any type other than a resource |
|
252 | + * |
|
253 | + * @since 5.4.0 |
|
254 | + */ |
|
255 | + public function jsonSerialize() |
|
256 | + { |
|
257 | + return $this->toArray(); |
|
258 | + } |
|
259 | 259 | |
260 | - /** |
|
261 | - * Returns only one value (the first) of the result set. |
|
262 | - * Returns null if no value exists. |
|
263 | - * |
|
264 | - * @return mixed|null |
|
265 | - */ |
|
266 | - public function first() |
|
267 | - { |
|
268 | - $page = $this->take(0, 1); |
|
269 | - foreach ($page as $bean) { |
|
270 | - return $bean; |
|
271 | - } |
|
260 | + /** |
|
261 | + * Returns only one value (the first) of the result set. |
|
262 | + * Returns null if no value exists. |
|
263 | + * |
|
264 | + * @return mixed|null |
|
265 | + */ |
|
266 | + public function first() |
|
267 | + { |
|
268 | + $page = $this->take(0, 1); |
|
269 | + foreach ($page as $bean) { |
|
270 | + return $bean; |
|
271 | + } |
|
272 | 272 | |
273 | - return; |
|
274 | - } |
|
273 | + return; |
|
274 | + } |
|
275 | 275 | |
276 | - /** |
|
277 | - * Returns a new iterator mapping any call using the $callable function. |
|
278 | - * |
|
279 | - * @param callable $callable |
|
280 | - * |
|
281 | - * @return MapIterator |
|
282 | - */ |
|
283 | - public function map(callable $callable) |
|
284 | - { |
|
285 | - return new MapIterator($this->getIterator(), $callable); |
|
286 | - } |
|
276 | + /** |
|
277 | + * Returns a new iterator mapping any call using the $callable function. |
|
278 | + * |
|
279 | + * @param callable $callable |
|
280 | + * |
|
281 | + * @return MapIterator |
|
282 | + */ |
|
283 | + public function map(callable $callable) |
|
284 | + { |
|
285 | + return new MapIterator($this->getIterator(), $callable); |
|
286 | + } |
|
287 | 287 | } |