@@ -144,9 +144,7 @@ discard block |
||
144 | 144 | * |
145 | 145 | * @param string $daonamespace |
146 | 146 | * @param string $beannamespace |
147 | - * @param int $keepSupport |
|
148 | 147 | * @param int $storeInUtc |
149 | - * @param int $castDatesToDateTime |
|
150 | 148 | * @param string $selfedit |
151 | 149 | * |
152 | 150 | * @throws \Mouf\MoufException |
@@ -183,6 +181,9 @@ discard block |
||
183 | 181 | |
184 | 182 | protected $errorMsg; |
185 | 183 | |
184 | + /** |
|
185 | + * @param string $msg |
|
186 | + */ |
|
186 | 187 | private function displayErrorMsg($msg) |
187 | 188 | { |
188 | 189 | $this->errorMsg = $msg; |
@@ -15,178 +15,178 @@ |
||
15 | 15 | */ |
16 | 16 | class TdbmInstallController extends Controller |
17 | 17 | { |
18 | - /** |
|
19 | - * @var HtmlBlock |
|
20 | - */ |
|
21 | - public $content; |
|
22 | - |
|
23 | - public $selfedit; |
|
24 | - |
|
25 | - /** |
|
26 | - * The active MoufManager to be edited/viewed. |
|
27 | - * |
|
28 | - * @var MoufManager |
|
29 | - */ |
|
30 | - public $moufManager; |
|
31 | - |
|
32 | - /** |
|
33 | - * The template used by the main page for mouf. |
|
34 | - * |
|
35 | - * @Property |
|
36 | - * @Compulsory |
|
37 | - * |
|
38 | - * @var TemplateInterface |
|
39 | - */ |
|
40 | - public $template; |
|
41 | - |
|
42 | - /** |
|
43 | - * Displays the first install screen. |
|
44 | - * |
|
45 | - * @Action |
|
46 | - * @Logged |
|
47 | - * |
|
48 | - * @param string $selfedit If true, the name of the component must be a component from the Mouf framework itself (internal use only) |
|
49 | - */ |
|
50 | - public function defaultAction($selfedit = 'false') |
|
51 | - { |
|
52 | - $this->selfedit = $selfedit; |
|
53 | - |
|
54 | - if ($selfedit == 'true') { |
|
55 | - $this->moufManager = MoufManager::getMoufManager(); |
|
56 | - } else { |
|
57 | - $this->moufManager = MoufManager::getMoufManagerHiddenInstance(); |
|
58 | - } |
|
59 | - |
|
60 | - $this->content->addFile(dirname(__FILE__).'/../../../../views/installStep1.php', $this); |
|
61 | - $this->template->toHtml(); |
|
62 | - } |
|
63 | - |
|
64 | - /** |
|
65 | - * Skips the install process. |
|
66 | - * |
|
67 | - * @Action |
|
68 | - * @Logged |
|
69 | - * |
|
70 | - * @param string $selfedit If true, the name of the component must be a component from the Mouf framework itself (internal use only) |
|
71 | - */ |
|
72 | - public function skip($selfedit = 'false') |
|
73 | - { |
|
74 | - InstallUtils::continueInstall($selfedit == 'true'); |
|
75 | - } |
|
76 | - |
|
77 | - protected $daoNamespace; |
|
78 | - protected $beanNamespace; |
|
79 | - protected $autoloadDetected; |
|
80 | - protected $storeInUtc; |
|
81 | - |
|
82 | - /** |
|
83 | - * Displays the second install screen. |
|
84 | - * |
|
85 | - * @Action |
|
86 | - * @Logged |
|
87 | - * |
|
88 | - * @param string $selfedit If true, the name of the component must be a component from the Mouf framework itself (internal use only) |
|
89 | - */ |
|
90 | - public function configure($selfedit = 'false') |
|
91 | - { |
|
92 | - $this->selfedit = $selfedit; |
|
93 | - |
|
94 | - if ($selfedit == 'true') { |
|
95 | - $this->moufManager = MoufManager::getMoufManager(); |
|
96 | - } else { |
|
97 | - $this->moufManager = MoufManager::getMoufManagerHiddenInstance(); |
|
98 | - } |
|
99 | - |
|
100 | - // Let's start by performing basic checks about the instances we assume to exist. |
|
101 | - if (!$this->moufManager->instanceExists('dbalConnection')) { |
|
102 | - $this->displayErrorMsg("The TDBM install process assumes your database connection instance is already created, and that the name of this instance is 'dbalConnection'. Could not find the 'dbalConnection' instance."); |
|
103 | - |
|
104 | - return; |
|
105 | - } |
|
106 | - |
|
107 | - if (!$this->moufManager->instanceExists('noCacheService')) { |
|
108 | - $this->displayErrorMsg("The TDBM install process assumes that a cache instance named 'noCacheService' exists. Could not find the 'noCacheService' instance."); |
|
109 | - |
|
110 | - return; |
|
111 | - } |
|
112 | - |
|
113 | - $this->daoNamespace = $this->moufManager->getVariable('tdbmDefaultDaoNamespace_tdbmService'); |
|
114 | - $this->beanNamespace = $this->moufManager->getVariable('tdbmDefaultBeanNamespace_tdbmService'); |
|
115 | - |
|
116 | - if ($this->daoNamespace == null && $this->beanNamespace == null) { |
|
117 | - $classNameMapper = ClassNameMapper::createFromComposerFile(__DIR__.'/../../../../../../../../composer.json'); |
|
118 | - |
|
119 | - $autoloadNamespaces = $classNameMapper->getManagedNamespaces(); |
|
120 | - if ($autoloadNamespaces) { |
|
121 | - $this->autoloadDetected = true; |
|
122 | - $rootNamespace = $autoloadNamespaces[0]; |
|
123 | - $this->daoNamespace = $rootNamespace.'Dao'; |
|
124 | - $this->beanNamespace = $rootNamespace.'Dao\\Bean'; |
|
125 | - } else { |
|
126 | - $this->autoloadDetected = false; |
|
127 | - $this->daoNamespace = 'YourApplication\\Dao'; |
|
128 | - $this->beanNamespace = 'YourApplication\\Dao\\Bean'; |
|
129 | - } |
|
130 | - } else { |
|
131 | - $this->autoloadDetected = true; |
|
132 | - } |
|
133 | - |
|
134 | - $this->castDatesToDateTime = true; |
|
135 | - |
|
136 | - $this->content->addFile(dirname(__FILE__).'/../../../../views/installStep2.php', $this); |
|
137 | - $this->template->toHtml(); |
|
138 | - } |
|
139 | - |
|
140 | - /** |
|
141 | - * This action generates the TDBM instance, then the DAOs and Beans. |
|
142 | - * |
|
143 | - * @Action |
|
144 | - * |
|
145 | - * @param string $daonamespace |
|
146 | - * @param string $beannamespace |
|
147 | - * @param int $keepSupport |
|
148 | - * @param int $storeInUtc |
|
149 | - * @param int $castDatesToDateTime |
|
150 | - * @param string $selfedit |
|
151 | - * |
|
152 | - * @throws \Mouf\MoufException |
|
153 | - */ |
|
154 | - public function generate($daonamespace, $beannamespace, $storeInUtc = 0, $selfedit = 'false') |
|
155 | - { |
|
156 | - $this->selfedit = $selfedit; |
|
157 | - |
|
158 | - if ($selfedit == 'true') { |
|
159 | - $this->moufManager = MoufManager::getMoufManager(); |
|
160 | - } else { |
|
161 | - $this->moufManager = MoufManager::getMoufManagerHiddenInstance(); |
|
162 | - } |
|
163 | - |
|
164 | - if (!$this->moufManager->instanceExists('doctrineApcCache')) { |
|
165 | - $doctrineApcCache = $this->moufManager->createInstance('Doctrine\\Common\\Cache\\ApcCache')->setName('doctrineApcCache'); |
|
166 | - // TODO: set namespace |
|
167 | - } else { |
|
168 | - $doctrineApcCache = $this->moufManager->getInstanceDescriptor('doctrineApcCache'); |
|
169 | - } |
|
170 | - |
|
171 | - if (!$this->moufManager->instanceExists('tdbmService')) { |
|
172 | - $tdbmService = $this->moufManager->createInstance('Mouf\\Database\\TDBM\\TDBMService')->setName('tdbmService'); |
|
173 | - $tdbmService->getConstructorArgumentProperty('connection')->setValue($this->moufManager->getInstanceDescriptor('dbalConnection')); |
|
174 | - $tdbmService->getConstructorArgumentProperty('cache')->setValue($doctrineApcCache); |
|
175 | - } |
|
176 | - |
|
177 | - $this->moufManager->rewriteMouf(); |
|
178 | - |
|
179 | - TdbmController::generateDaos($this->moufManager, 'tdbmService', $daonamespace, $beannamespace, 'DaoFactory', 'daoFactory', $selfedit, $storeInUtc); |
|
180 | - |
|
181 | - InstallUtils::continueInstall($selfedit == 'true'); |
|
182 | - } |
|
183 | - |
|
184 | - protected $errorMsg; |
|
185 | - |
|
186 | - private function displayErrorMsg($msg) |
|
187 | - { |
|
188 | - $this->errorMsg = $msg; |
|
189 | - $this->content->addFile(dirname(__FILE__).'/../../../../views/installError.php', $this); |
|
190 | - $this->template->toHtml(); |
|
191 | - } |
|
18 | + /** |
|
19 | + * @var HtmlBlock |
|
20 | + */ |
|
21 | + public $content; |
|
22 | + |
|
23 | + public $selfedit; |
|
24 | + |
|
25 | + /** |
|
26 | + * The active MoufManager to be edited/viewed. |
|
27 | + * |
|
28 | + * @var MoufManager |
|
29 | + */ |
|
30 | + public $moufManager; |
|
31 | + |
|
32 | + /** |
|
33 | + * The template used by the main page for mouf. |
|
34 | + * |
|
35 | + * @Property |
|
36 | + * @Compulsory |
|
37 | + * |
|
38 | + * @var TemplateInterface |
|
39 | + */ |
|
40 | + public $template; |
|
41 | + |
|
42 | + /** |
|
43 | + * Displays the first install screen. |
|
44 | + * |
|
45 | + * @Action |
|
46 | + * @Logged |
|
47 | + * |
|
48 | + * @param string $selfedit If true, the name of the component must be a component from the Mouf framework itself (internal use only) |
|
49 | + */ |
|
50 | + public function defaultAction($selfedit = 'false') |
|
51 | + { |
|
52 | + $this->selfedit = $selfedit; |
|
53 | + |
|
54 | + if ($selfedit == 'true') { |
|
55 | + $this->moufManager = MoufManager::getMoufManager(); |
|
56 | + } else { |
|
57 | + $this->moufManager = MoufManager::getMoufManagerHiddenInstance(); |
|
58 | + } |
|
59 | + |
|
60 | + $this->content->addFile(dirname(__FILE__).'/../../../../views/installStep1.php', $this); |
|
61 | + $this->template->toHtml(); |
|
62 | + } |
|
63 | + |
|
64 | + /** |
|
65 | + * Skips the install process. |
|
66 | + * |
|
67 | + * @Action |
|
68 | + * @Logged |
|
69 | + * |
|
70 | + * @param string $selfedit If true, the name of the component must be a component from the Mouf framework itself (internal use only) |
|
71 | + */ |
|
72 | + public function skip($selfedit = 'false') |
|
73 | + { |
|
74 | + InstallUtils::continueInstall($selfedit == 'true'); |
|
75 | + } |
|
76 | + |
|
77 | + protected $daoNamespace; |
|
78 | + protected $beanNamespace; |
|
79 | + protected $autoloadDetected; |
|
80 | + protected $storeInUtc; |
|
81 | + |
|
82 | + /** |
|
83 | + * Displays the second install screen. |
|
84 | + * |
|
85 | + * @Action |
|
86 | + * @Logged |
|
87 | + * |
|
88 | + * @param string $selfedit If true, the name of the component must be a component from the Mouf framework itself (internal use only) |
|
89 | + */ |
|
90 | + public function configure($selfedit = 'false') |
|
91 | + { |
|
92 | + $this->selfedit = $selfedit; |
|
93 | + |
|
94 | + if ($selfedit == 'true') { |
|
95 | + $this->moufManager = MoufManager::getMoufManager(); |
|
96 | + } else { |
|
97 | + $this->moufManager = MoufManager::getMoufManagerHiddenInstance(); |
|
98 | + } |
|
99 | + |
|
100 | + // Let's start by performing basic checks about the instances we assume to exist. |
|
101 | + if (!$this->moufManager->instanceExists('dbalConnection')) { |
|
102 | + $this->displayErrorMsg("The TDBM install process assumes your database connection instance is already created, and that the name of this instance is 'dbalConnection'. Could not find the 'dbalConnection' instance."); |
|
103 | + |
|
104 | + return; |
|
105 | + } |
|
106 | + |
|
107 | + if (!$this->moufManager->instanceExists('noCacheService')) { |
|
108 | + $this->displayErrorMsg("The TDBM install process assumes that a cache instance named 'noCacheService' exists. Could not find the 'noCacheService' instance."); |
|
109 | + |
|
110 | + return; |
|
111 | + } |
|
112 | + |
|
113 | + $this->daoNamespace = $this->moufManager->getVariable('tdbmDefaultDaoNamespace_tdbmService'); |
|
114 | + $this->beanNamespace = $this->moufManager->getVariable('tdbmDefaultBeanNamespace_tdbmService'); |
|
115 | + |
|
116 | + if ($this->daoNamespace == null && $this->beanNamespace == null) { |
|
117 | + $classNameMapper = ClassNameMapper::createFromComposerFile(__DIR__.'/../../../../../../../../composer.json'); |
|
118 | + |
|
119 | + $autoloadNamespaces = $classNameMapper->getManagedNamespaces(); |
|
120 | + if ($autoloadNamespaces) { |
|
121 | + $this->autoloadDetected = true; |
|
122 | + $rootNamespace = $autoloadNamespaces[0]; |
|
123 | + $this->daoNamespace = $rootNamespace.'Dao'; |
|
124 | + $this->beanNamespace = $rootNamespace.'Dao\\Bean'; |
|
125 | + } else { |
|
126 | + $this->autoloadDetected = false; |
|
127 | + $this->daoNamespace = 'YourApplication\\Dao'; |
|
128 | + $this->beanNamespace = 'YourApplication\\Dao\\Bean'; |
|
129 | + } |
|
130 | + } else { |
|
131 | + $this->autoloadDetected = true; |
|
132 | + } |
|
133 | + |
|
134 | + $this->castDatesToDateTime = true; |
|
135 | + |
|
136 | + $this->content->addFile(dirname(__FILE__).'/../../../../views/installStep2.php', $this); |
|
137 | + $this->template->toHtml(); |
|
138 | + } |
|
139 | + |
|
140 | + /** |
|
141 | + * This action generates the TDBM instance, then the DAOs and Beans. |
|
142 | + * |
|
143 | + * @Action |
|
144 | + * |
|
145 | + * @param string $daonamespace |
|
146 | + * @param string $beannamespace |
|
147 | + * @param int $keepSupport |
|
148 | + * @param int $storeInUtc |
|
149 | + * @param int $castDatesToDateTime |
|
150 | + * @param string $selfedit |
|
151 | + * |
|
152 | + * @throws \Mouf\MoufException |
|
153 | + */ |
|
154 | + public function generate($daonamespace, $beannamespace, $storeInUtc = 0, $selfedit = 'false') |
|
155 | + { |
|
156 | + $this->selfedit = $selfedit; |
|
157 | + |
|
158 | + if ($selfedit == 'true') { |
|
159 | + $this->moufManager = MoufManager::getMoufManager(); |
|
160 | + } else { |
|
161 | + $this->moufManager = MoufManager::getMoufManagerHiddenInstance(); |
|
162 | + } |
|
163 | + |
|
164 | + if (!$this->moufManager->instanceExists('doctrineApcCache')) { |
|
165 | + $doctrineApcCache = $this->moufManager->createInstance('Doctrine\\Common\\Cache\\ApcCache')->setName('doctrineApcCache'); |
|
166 | + // TODO: set namespace |
|
167 | + } else { |
|
168 | + $doctrineApcCache = $this->moufManager->getInstanceDescriptor('doctrineApcCache'); |
|
169 | + } |
|
170 | + |
|
171 | + if (!$this->moufManager->instanceExists('tdbmService')) { |
|
172 | + $tdbmService = $this->moufManager->createInstance('Mouf\\Database\\TDBM\\TDBMService')->setName('tdbmService'); |
|
173 | + $tdbmService->getConstructorArgumentProperty('connection')->setValue($this->moufManager->getInstanceDescriptor('dbalConnection')); |
|
174 | + $tdbmService->getConstructorArgumentProperty('cache')->setValue($doctrineApcCache); |
|
175 | + } |
|
176 | + |
|
177 | + $this->moufManager->rewriteMouf(); |
|
178 | + |
|
179 | + TdbmController::generateDaos($this->moufManager, 'tdbmService', $daonamespace, $beannamespace, 'DaoFactory', 'daoFactory', $selfedit, $storeInUtc); |
|
180 | + |
|
181 | + InstallUtils::continueInstall($selfedit == 'true'); |
|
182 | + } |
|
183 | + |
|
184 | + protected $errorMsg; |
|
185 | + |
|
186 | + private function displayErrorMsg($msg) |
|
187 | + { |
|
188 | + $this->errorMsg = $msg; |
|
189 | + $this->content->addFile(dirname(__FILE__).'/../../../../views/installError.php', $this); |
|
190 | + $this->template->toHtml(); |
|
191 | + } |
|
192 | 192 | } |
@@ -60,6 +60,9 @@ discard block |
||
60 | 60 | |
61 | 61 | private $innerResultIterator; |
62 | 62 | |
63 | + /** |
|
64 | + * @param integer $offset |
|
65 | + */ |
|
63 | 66 | public function __construct(ResultIterator $parentResult, $magicSql, array $parameters, $limit, $offset, array $columnDescriptors, $objectStorage, $className, TDBMService $tdbmService, MagicQuery $magicQuery, $mode) |
64 | 67 | { |
65 | 68 | $this->parentResult = $parentResult; |
@@ -108,7 +111,7 @@ discard block |
||
108 | 111 | } |
109 | 112 | |
110 | 113 | /** |
111 | - * @return int |
|
114 | + * @return double |
|
112 | 115 | */ |
113 | 116 | public function getCurrentPage() |
114 | 117 | { |
@@ -29,230 +29,230 @@ |
||
29 | 29 | */ |
30 | 30 | class PageIterator implements Page, \ArrayAccess, \JsonSerializable |
31 | 31 | { |
32 | - /** |
|
33 | - * @var Statement |
|
34 | - */ |
|
35 | - protected $statement; |
|
32 | + /** |
|
33 | + * @var Statement |
|
34 | + */ |
|
35 | + protected $statement; |
|
36 | 36 | |
37 | - protected $fetchStarted = false; |
|
38 | - private $objectStorage; |
|
39 | - private $className; |
|
37 | + protected $fetchStarted = false; |
|
38 | + private $objectStorage; |
|
39 | + private $className; |
|
40 | 40 | |
41 | - private $parentResult; |
|
42 | - private $tdbmService; |
|
43 | - private $magicSql; |
|
44 | - private $parameters; |
|
45 | - private $limit; |
|
46 | - private $offset; |
|
47 | - private $columnDescriptors; |
|
48 | - private $magicQuery; |
|
41 | + private $parentResult; |
|
42 | + private $tdbmService; |
|
43 | + private $magicSql; |
|
44 | + private $parameters; |
|
45 | + private $limit; |
|
46 | + private $offset; |
|
47 | + private $columnDescriptors; |
|
48 | + private $magicQuery; |
|
49 | 49 | |
50 | - /** |
|
51 | - * The key of the current retrieved object. |
|
52 | - * |
|
53 | - * @var int |
|
54 | - */ |
|
55 | - protected $key = -1; |
|
50 | + /** |
|
51 | + * The key of the current retrieved object. |
|
52 | + * |
|
53 | + * @var int |
|
54 | + */ |
|
55 | + protected $key = -1; |
|
56 | 56 | |
57 | - protected $current = null; |
|
57 | + protected $current = null; |
|
58 | 58 | |
59 | - private $databasePlatform; |
|
59 | + private $databasePlatform; |
|
60 | 60 | |
61 | - private $innerResultIterator; |
|
61 | + private $innerResultIterator; |
|
62 | 62 | |
63 | - public function __construct(ResultIterator $parentResult, $magicSql, array $parameters, $limit, $offset, array $columnDescriptors, $objectStorage, $className, TDBMService $tdbmService, MagicQuery $magicQuery, $mode) |
|
64 | - { |
|
65 | - $this->parentResult = $parentResult; |
|
66 | - $this->magicSql = $magicSql; |
|
67 | - $this->objectStorage = $objectStorage; |
|
68 | - $this->className = $className; |
|
69 | - $this->tdbmService = $tdbmService; |
|
70 | - $this->parameters = $parameters; |
|
71 | - $this->limit = $limit; |
|
72 | - $this->offset = $offset; |
|
73 | - $this->columnDescriptors = $columnDescriptors; |
|
74 | - $this->magicQuery = $magicQuery; |
|
75 | - $this->databasePlatform = $this->tdbmService->getConnection()->getDatabasePlatform(); |
|
76 | - $this->mode = $mode; |
|
77 | - } |
|
63 | + public function __construct(ResultIterator $parentResult, $magicSql, array $parameters, $limit, $offset, array $columnDescriptors, $objectStorage, $className, TDBMService $tdbmService, MagicQuery $magicQuery, $mode) |
|
64 | + { |
|
65 | + $this->parentResult = $parentResult; |
|
66 | + $this->magicSql = $magicSql; |
|
67 | + $this->objectStorage = $objectStorage; |
|
68 | + $this->className = $className; |
|
69 | + $this->tdbmService = $tdbmService; |
|
70 | + $this->parameters = $parameters; |
|
71 | + $this->limit = $limit; |
|
72 | + $this->offset = $offset; |
|
73 | + $this->columnDescriptors = $columnDescriptors; |
|
74 | + $this->magicQuery = $magicQuery; |
|
75 | + $this->databasePlatform = $this->tdbmService->getConnection()->getDatabasePlatform(); |
|
76 | + $this->mode = $mode; |
|
77 | + } |
|
78 | 78 | |
79 | - /** |
|
80 | - * Retrieve an external iterator. |
|
81 | - * |
|
82 | - * @link http://php.net/manual/en/iteratoraggregate.getiterator.php |
|
83 | - * |
|
84 | - * @return InnerResultIterator An instance of an object implementing <b>Iterator</b> or |
|
85 | - * <b>Traversable</b> |
|
86 | - * |
|
87 | - * @since 5.0.0 |
|
88 | - */ |
|
89 | - public function getIterator() |
|
90 | - { |
|
91 | - if ($this->innerResultIterator === null) { |
|
92 | - if ($this->mode === TDBMService::MODE_CURSOR) { |
|
93 | - $this->innerResultIterator = new InnerResultIterator($this->magicSql, $this->parameters, $this->limit, $this->offset, $this->columnDescriptors, $this->objectStorage, $this->className, $this->tdbmService, $this->magicQuery); |
|
94 | - } else { |
|
95 | - $this->innerResultIterator = new InnerResultArray($this->magicSql, $this->parameters, $this->limit, $this->offset, $this->columnDescriptors, $this->objectStorage, $this->className, $this->tdbmService, $this->magicQuery); |
|
96 | - } |
|
97 | - } |
|
79 | + /** |
|
80 | + * Retrieve an external iterator. |
|
81 | + * |
|
82 | + * @link http://php.net/manual/en/iteratoraggregate.getiterator.php |
|
83 | + * |
|
84 | + * @return InnerResultIterator An instance of an object implementing <b>Iterator</b> or |
|
85 | + * <b>Traversable</b> |
|
86 | + * |
|
87 | + * @since 5.0.0 |
|
88 | + */ |
|
89 | + public function getIterator() |
|
90 | + { |
|
91 | + if ($this->innerResultIterator === null) { |
|
92 | + if ($this->mode === TDBMService::MODE_CURSOR) { |
|
93 | + $this->innerResultIterator = new InnerResultIterator($this->magicSql, $this->parameters, $this->limit, $this->offset, $this->columnDescriptors, $this->objectStorage, $this->className, $this->tdbmService, $this->magicQuery); |
|
94 | + } else { |
|
95 | + $this->innerResultIterator = new InnerResultArray($this->magicSql, $this->parameters, $this->limit, $this->offset, $this->columnDescriptors, $this->objectStorage, $this->className, $this->tdbmService, $this->magicQuery); |
|
96 | + } |
|
97 | + } |
|
98 | 98 | |
99 | - return $this->innerResultIterator; |
|
100 | - } |
|
99 | + return $this->innerResultIterator; |
|
100 | + } |
|
101 | 101 | |
102 | - /** |
|
103 | - * @return int |
|
104 | - */ |
|
105 | - public function getCurrentOffset() |
|
106 | - { |
|
107 | - return $this->offset; |
|
108 | - } |
|
102 | + /** |
|
103 | + * @return int |
|
104 | + */ |
|
105 | + public function getCurrentOffset() |
|
106 | + { |
|
107 | + return $this->offset; |
|
108 | + } |
|
109 | 109 | |
110 | - /** |
|
111 | - * @return int |
|
112 | - */ |
|
113 | - public function getCurrentPage() |
|
114 | - { |
|
115 | - return floor($this->offset / $this->limit) + 1; |
|
116 | - } |
|
110 | + /** |
|
111 | + * @return int |
|
112 | + */ |
|
113 | + public function getCurrentPage() |
|
114 | + { |
|
115 | + return floor($this->offset / $this->limit) + 1; |
|
116 | + } |
|
117 | 117 | |
118 | - /** |
|
119 | - * @return int |
|
120 | - */ |
|
121 | - public function getCurrentLimit() |
|
122 | - { |
|
123 | - return $this->limit; |
|
124 | - } |
|
118 | + /** |
|
119 | + * @return int |
|
120 | + */ |
|
121 | + public function getCurrentLimit() |
|
122 | + { |
|
123 | + return $this->limit; |
|
124 | + } |
|
125 | 125 | |
126 | - /** |
|
127 | - * Return the number of results on the current page of the {@link Result}. |
|
128 | - * |
|
129 | - * @return int |
|
130 | - */ |
|
131 | - public function count() |
|
132 | - { |
|
133 | - return $this->getIterator()->count(); |
|
134 | - } |
|
126 | + /** |
|
127 | + * Return the number of results on the current page of the {@link Result}. |
|
128 | + * |
|
129 | + * @return int |
|
130 | + */ |
|
131 | + public function count() |
|
132 | + { |
|
133 | + return $this->getIterator()->count(); |
|
134 | + } |
|
135 | 135 | |
136 | - /** |
|
137 | - * Return the number of ALL results in the paginatable of {@link Result}. |
|
138 | - * |
|
139 | - * @return int |
|
140 | - */ |
|
141 | - public function totalCount() |
|
142 | - { |
|
143 | - return $this->parentResult->count(); |
|
144 | - } |
|
136 | + /** |
|
137 | + * Return the number of ALL results in the paginatable of {@link Result}. |
|
138 | + * |
|
139 | + * @return int |
|
140 | + */ |
|
141 | + public function totalCount() |
|
142 | + { |
|
143 | + return $this->parentResult->count(); |
|
144 | + } |
|
145 | 145 | |
146 | - /** |
|
147 | - * Casts the result set to a PHP array. |
|
148 | - * |
|
149 | - * @return array |
|
150 | - */ |
|
151 | - public function toArray() |
|
152 | - { |
|
153 | - return iterator_to_array($this->getIterator()); |
|
154 | - } |
|
146 | + /** |
|
147 | + * Casts the result set to a PHP array. |
|
148 | + * |
|
149 | + * @return array |
|
150 | + */ |
|
151 | + public function toArray() |
|
152 | + { |
|
153 | + return iterator_to_array($this->getIterator()); |
|
154 | + } |
|
155 | 155 | |
156 | - /** |
|
157 | - * Returns a new iterator mapping any call using the $callable function. |
|
158 | - * |
|
159 | - * @param callable $callable |
|
160 | - * |
|
161 | - * @return MapIterator |
|
162 | - */ |
|
163 | - public function map(callable $callable) |
|
164 | - { |
|
165 | - return new MapIterator($this->getIterator(), $callable); |
|
166 | - } |
|
156 | + /** |
|
157 | + * Returns a new iterator mapping any call using the $callable function. |
|
158 | + * |
|
159 | + * @param callable $callable |
|
160 | + * |
|
161 | + * @return MapIterator |
|
162 | + */ |
|
163 | + public function map(callable $callable) |
|
164 | + { |
|
165 | + return new MapIterator($this->getIterator(), $callable); |
|
166 | + } |
|
167 | 167 | |
168 | - /** |
|
169 | - * Whether a offset exists. |
|
170 | - * |
|
171 | - * @link http://php.net/manual/en/arrayaccess.offsetexists.php |
|
172 | - * |
|
173 | - * @param mixed $offset <p> |
|
174 | - * An offset to check for. |
|
175 | - * </p> |
|
176 | - * |
|
177 | - * @return bool true on success or false on failure. |
|
178 | - * </p> |
|
179 | - * <p> |
|
180 | - * The return value will be casted to boolean if non-boolean was returned. |
|
181 | - * |
|
182 | - * @since 5.0.0 |
|
183 | - */ |
|
184 | - public function offsetExists($offset) |
|
185 | - { |
|
186 | - return $this->getIterator()->offsetExists($offset); |
|
187 | - } |
|
168 | + /** |
|
169 | + * Whether a offset exists. |
|
170 | + * |
|
171 | + * @link http://php.net/manual/en/arrayaccess.offsetexists.php |
|
172 | + * |
|
173 | + * @param mixed $offset <p> |
|
174 | + * An offset to check for. |
|
175 | + * </p> |
|
176 | + * |
|
177 | + * @return bool true on success or false on failure. |
|
178 | + * </p> |
|
179 | + * <p> |
|
180 | + * The return value will be casted to boolean if non-boolean was returned. |
|
181 | + * |
|
182 | + * @since 5.0.0 |
|
183 | + */ |
|
184 | + public function offsetExists($offset) |
|
185 | + { |
|
186 | + return $this->getIterator()->offsetExists($offset); |
|
187 | + } |
|
188 | 188 | |
189 | - /** |
|
190 | - * Offset to retrieve. |
|
191 | - * |
|
192 | - * @link http://php.net/manual/en/arrayaccess.offsetget.php |
|
193 | - * |
|
194 | - * @param mixed $offset <p> |
|
195 | - * The offset to retrieve. |
|
196 | - * </p> |
|
197 | - * |
|
198 | - * @return mixed Can return all value types. |
|
199 | - * |
|
200 | - * @since 5.0.0 |
|
201 | - */ |
|
202 | - public function offsetGet($offset) |
|
203 | - { |
|
204 | - return $this->getIterator()->offsetGet($offset); |
|
205 | - } |
|
189 | + /** |
|
190 | + * Offset to retrieve. |
|
191 | + * |
|
192 | + * @link http://php.net/manual/en/arrayaccess.offsetget.php |
|
193 | + * |
|
194 | + * @param mixed $offset <p> |
|
195 | + * The offset to retrieve. |
|
196 | + * </p> |
|
197 | + * |
|
198 | + * @return mixed Can return all value types. |
|
199 | + * |
|
200 | + * @since 5.0.0 |
|
201 | + */ |
|
202 | + public function offsetGet($offset) |
|
203 | + { |
|
204 | + return $this->getIterator()->offsetGet($offset); |
|
205 | + } |
|
206 | 206 | |
207 | - /** |
|
208 | - * Offset to set. |
|
209 | - * |
|
210 | - * @link http://php.net/manual/en/arrayaccess.offsetset.php |
|
211 | - * |
|
212 | - * @param mixed $offset <p> |
|
213 | - * The offset to assign the value to. |
|
214 | - * </p> |
|
215 | - * @param mixed $value <p> |
|
216 | - * The value to set. |
|
217 | - * </p> |
|
218 | - * |
|
219 | - * @since 5.0.0 |
|
220 | - */ |
|
221 | - public function offsetSet($offset, $value) |
|
222 | - { |
|
223 | - return $this->getIterator()->offsetSet($offset, $value); |
|
224 | - } |
|
207 | + /** |
|
208 | + * Offset to set. |
|
209 | + * |
|
210 | + * @link http://php.net/manual/en/arrayaccess.offsetset.php |
|
211 | + * |
|
212 | + * @param mixed $offset <p> |
|
213 | + * The offset to assign the value to. |
|
214 | + * </p> |
|
215 | + * @param mixed $value <p> |
|
216 | + * The value to set. |
|
217 | + * </p> |
|
218 | + * |
|
219 | + * @since 5.0.0 |
|
220 | + */ |
|
221 | + public function offsetSet($offset, $value) |
|
222 | + { |
|
223 | + return $this->getIterator()->offsetSet($offset, $value); |
|
224 | + } |
|
225 | 225 | |
226 | - /** |
|
227 | - * Offset to unset. |
|
228 | - * |
|
229 | - * @link http://php.net/manual/en/arrayaccess.offsetunset.php |
|
230 | - * |
|
231 | - * @param mixed $offset <p> |
|
232 | - * The offset to unset. |
|
233 | - * </p> |
|
234 | - * |
|
235 | - * @since 5.0.0 |
|
236 | - */ |
|
237 | - public function offsetUnset($offset) |
|
238 | - { |
|
239 | - return $this->getIterator()->offsetUnset($offset); |
|
240 | - } |
|
226 | + /** |
|
227 | + * Offset to unset. |
|
228 | + * |
|
229 | + * @link http://php.net/manual/en/arrayaccess.offsetunset.php |
|
230 | + * |
|
231 | + * @param mixed $offset <p> |
|
232 | + * The offset to unset. |
|
233 | + * </p> |
|
234 | + * |
|
235 | + * @since 5.0.0 |
|
236 | + */ |
|
237 | + public function offsetUnset($offset) |
|
238 | + { |
|
239 | + return $this->getIterator()->offsetUnset($offset); |
|
240 | + } |
|
241 | 241 | |
242 | - /** |
|
243 | - * Specify data which should be serialized to JSON. |
|
244 | - * |
|
245 | - * @link http://php.net/manual/en/jsonserializable.jsonserialize.php |
|
246 | - * |
|
247 | - * @return mixed data which can be serialized by <b>json_encode</b>, |
|
248 | - * which is a value of any type other than a resource. |
|
249 | - * |
|
250 | - * @since 5.4.0 |
|
251 | - */ |
|
252 | - public function jsonSerialize() |
|
253 | - { |
|
254 | - return array_map(function (AbstractTDBMObject $item) { |
|
255 | - return $item->jsonSerialize(); |
|
256 | - }, $this->toArray()); |
|
257 | - } |
|
242 | + /** |
|
243 | + * Specify data which should be serialized to JSON. |
|
244 | + * |
|
245 | + * @link http://php.net/manual/en/jsonserializable.jsonserialize.php |
|
246 | + * |
|
247 | + * @return mixed data which can be serialized by <b>json_encode</b>, |
|
248 | + * which is a value of any type other than a resource. |
|
249 | + * |
|
250 | + * @since 5.4.0 |
|
251 | + */ |
|
252 | + public function jsonSerialize() |
|
253 | + { |
|
254 | + return array_map(function (AbstractTDBMObject $item) { |
|
255 | + return $item->jsonSerialize(); |
|
256 | + }, $this->toArray()); |
|
257 | + } |
|
258 | 258 | } |
@@ -112,7 +112,7 @@ discard block |
||
112 | 112 | */ |
113 | 113 | public function getCurrentPage() |
114 | 114 | { |
115 | - return floor($this->offset / $this->limit) + 1; |
|
115 | + return floor($this->offset/$this->limit)+1; |
|
116 | 116 | } |
117 | 117 | |
118 | 118 | /** |
@@ -251,7 +251,7 @@ discard block |
||
251 | 251 | */ |
252 | 252 | public function jsonSerialize() |
253 | 253 | { |
254 | - return array_map(function (AbstractTDBMObject $item) { |
|
254 | + return array_map(function(AbstractTDBMObject $item) { |
|
255 | 255 | return $item->jsonSerialize(); |
256 | 256 | }, $this->toArray()); |
257 | 257 | } |
@@ -66,6 +66,13 @@ discard block |
||
66 | 66 | |
67 | 67 | private $mode; |
68 | 68 | |
69 | + /** |
|
70 | + * @param string $magicSql |
|
71 | + * @param string $magicSqlCount |
|
72 | + * @param WeakrefObjectStorage $objectStorage |
|
73 | + * @param string|null $className |
|
74 | + * @param integer $mode |
|
75 | + */ |
|
69 | 76 | public function __construct($magicSql, $magicSqlCount, array $parameters, array $columnDescriptors, $objectStorage, $className, TDBMService $tdbmService, MagicQuery $magicQuery, $mode) |
70 | 77 | { |
71 | 78 | $this->magicSql = $magicSql; |
@@ -147,6 +154,7 @@ discard block |
||
147 | 154 | |
148 | 155 | /** |
149 | 156 | * @param int $offset |
157 | + * @param integer $limit |
|
150 | 158 | * |
151 | 159 | * @return PageIterator |
152 | 160 | */ |
@@ -30,219 +30,219 @@ |
||
30 | 30 | */ |
31 | 31 | class ResultIterator implements Result, \ArrayAccess, \JsonSerializable |
32 | 32 | { |
33 | - /** |
|
34 | - * @var Statement |
|
35 | - */ |
|
36 | - protected $statement; |
|
37 | - |
|
38 | - protected $fetchStarted = false; |
|
39 | - private $objectStorage; |
|
40 | - private $className; |
|
41 | - |
|
42 | - private $tdbmService; |
|
43 | - private $magicSql; |
|
44 | - private $magicSqlCount; |
|
45 | - private $parameters; |
|
46 | - private $columnDescriptors; |
|
47 | - private $magicQuery; |
|
48 | - |
|
49 | - /** |
|
50 | - * @var InnerResultIterator |
|
51 | - */ |
|
52 | - private $innerResultIterator; |
|
53 | - |
|
54 | - /** |
|
55 | - * The key of the current retrieved object. |
|
56 | - * |
|
57 | - * @var int |
|
58 | - */ |
|
59 | - protected $key = -1; |
|
60 | - |
|
61 | - protected $current = null; |
|
62 | - |
|
63 | - private $databasePlatform; |
|
64 | - |
|
65 | - private $totalCount; |
|
66 | - |
|
67 | - private $mode; |
|
68 | - |
|
69 | - public function __construct($magicSql, $magicSqlCount, array $parameters, array $columnDescriptors, $objectStorage, $className, TDBMService $tdbmService, MagicQuery $magicQuery, $mode) |
|
70 | - { |
|
71 | - $this->magicSql = $magicSql; |
|
72 | - $this->magicSqlCount = $magicSqlCount; |
|
73 | - $this->objectStorage = $objectStorage; |
|
74 | - $this->className = $className; |
|
75 | - $this->tdbmService = $tdbmService; |
|
76 | - $this->parameters = $parameters; |
|
77 | - $this->columnDescriptors = $columnDescriptors; |
|
78 | - $this->magicQuery = $magicQuery; |
|
79 | - $this->databasePlatform = $this->tdbmService->getConnection()->getDatabasePlatform(); |
|
80 | - $this->mode = $mode; |
|
81 | - } |
|
82 | - |
|
83 | - protected function executeCountQuery() |
|
84 | - { |
|
85 | - $sql = $this->magicQuery->build($this->magicSqlCount, $this->parameters); |
|
86 | - $this->totalCount = $this->tdbmService->getConnection()->fetchColumn($sql, $this->parameters); |
|
87 | - } |
|
88 | - |
|
89 | - /** |
|
90 | - * Counts found records (this is the number of records fetched, taking into account the LIMIT and OFFSET settings). |
|
91 | - * |
|
92 | - * @return int |
|
93 | - */ |
|
94 | - public function count() |
|
95 | - { |
|
96 | - if ($this->totalCount === null) { |
|
97 | - $this->executeCountQuery(); |
|
98 | - } |
|
99 | - |
|
100 | - return $this->totalCount; |
|
101 | - } |
|
102 | - |
|
103 | - /** |
|
104 | - * Casts the result set to a PHP array. |
|
105 | - * |
|
106 | - * @return array |
|
107 | - */ |
|
108 | - public function toArray() |
|
109 | - { |
|
110 | - return iterator_to_array($this->getIterator()); |
|
111 | - } |
|
112 | - |
|
113 | - /** |
|
114 | - * Returns a new iterator mapping any call using the $callable function. |
|
115 | - * |
|
116 | - * @param callable $callable |
|
117 | - * |
|
118 | - * @return MapIterator |
|
119 | - */ |
|
120 | - public function map(callable $callable) |
|
121 | - { |
|
122 | - return new MapIterator($this->getIterator(), $callable); |
|
123 | - } |
|
124 | - |
|
125 | - /** |
|
126 | - * Retrieve an external iterator. |
|
127 | - * |
|
128 | - * @link http://php.net/manual/en/iteratoraggregate.getiterator.php |
|
129 | - * |
|
130 | - * @return InnerResultIterator An instance of an object implementing <b>Iterator</b> or |
|
131 | - * <b>Traversable</b> |
|
132 | - * |
|
133 | - * @since 5.0.0 |
|
134 | - */ |
|
135 | - public function getIterator() |
|
136 | - { |
|
137 | - if ($this->innerResultIterator === null) { |
|
138 | - if ($this->mode === TDBMService::MODE_CURSOR) { |
|
139 | - $this->innerResultIterator = new InnerResultIterator($this->magicSql, $this->parameters, null, null, $this->columnDescriptors, $this->objectStorage, $this->className, $this->tdbmService, $this->magicQuery); |
|
140 | - } else { |
|
141 | - $this->innerResultIterator = new InnerResultArray($this->magicSql, $this->parameters, null, null, $this->columnDescriptors, $this->objectStorage, $this->className, $this->tdbmService, $this->magicQuery); |
|
142 | - } |
|
143 | - } |
|
144 | - |
|
145 | - return $this->innerResultIterator; |
|
146 | - } |
|
147 | - |
|
148 | - /** |
|
149 | - * @param int $offset |
|
150 | - * |
|
151 | - * @return PageIterator |
|
152 | - */ |
|
153 | - public function take($offset, $limit) |
|
154 | - { |
|
155 | - return new PageIterator($this, $this->magicSql, $this->parameters, $limit, $offset, $this->columnDescriptors, $this->objectStorage, $this->className, $this->tdbmService, $this->magicQuery, $this->mode); |
|
156 | - } |
|
157 | - |
|
158 | - /** |
|
159 | - * Whether a offset exists. |
|
160 | - * |
|
161 | - * @link http://php.net/manual/en/arrayaccess.offsetexists.php |
|
162 | - * |
|
163 | - * @param mixed $offset <p> |
|
164 | - * An offset to check for. |
|
165 | - * </p> |
|
166 | - * |
|
167 | - * @return bool true on success or false on failure. |
|
168 | - * </p> |
|
169 | - * <p> |
|
170 | - * The return value will be casted to boolean if non-boolean was returned. |
|
171 | - * |
|
172 | - * @since 5.0.0 |
|
173 | - */ |
|
174 | - public function offsetExists($offset) |
|
175 | - { |
|
176 | - return $this->getIterator()->offsetExists($offset); |
|
177 | - } |
|
178 | - |
|
179 | - /** |
|
180 | - * Offset to retrieve. |
|
181 | - * |
|
182 | - * @link http://php.net/manual/en/arrayaccess.offsetget.php |
|
183 | - * |
|
184 | - * @param mixed $offset <p> |
|
185 | - * The offset to retrieve. |
|
186 | - * </p> |
|
187 | - * |
|
188 | - * @return mixed Can return all value types. |
|
189 | - * |
|
190 | - * @since 5.0.0 |
|
191 | - */ |
|
192 | - public function offsetGet($offset) |
|
193 | - { |
|
194 | - return $this->getIterator()->offsetGet($offset); |
|
195 | - } |
|
196 | - |
|
197 | - /** |
|
198 | - * Offset to set. |
|
199 | - * |
|
200 | - * @link http://php.net/manual/en/arrayaccess.offsetset.php |
|
201 | - * |
|
202 | - * @param mixed $offset <p> |
|
203 | - * The offset to assign the value to. |
|
204 | - * </p> |
|
205 | - * @param mixed $value <p> |
|
206 | - * The value to set. |
|
207 | - * </p> |
|
208 | - * |
|
209 | - * @since 5.0.0 |
|
210 | - */ |
|
211 | - public function offsetSet($offset, $value) |
|
212 | - { |
|
213 | - return $this->getIterator()->offsetSet($offset, $value); |
|
214 | - } |
|
215 | - |
|
216 | - /** |
|
217 | - * Offset to unset. |
|
218 | - * |
|
219 | - * @link http://php.net/manual/en/arrayaccess.offsetunset.php |
|
220 | - * |
|
221 | - * @param mixed $offset <p> |
|
222 | - * The offset to unset. |
|
223 | - * </p> |
|
224 | - * |
|
225 | - * @since 5.0.0 |
|
226 | - */ |
|
227 | - public function offsetUnset($offset) |
|
228 | - { |
|
229 | - return $this->getIterator()->offsetUnset($offset); |
|
230 | - } |
|
231 | - |
|
232 | - /** |
|
233 | - * Specify data which should be serialized to JSON. |
|
234 | - * |
|
235 | - * @link http://php.net/manual/en/jsonserializable.jsonserialize.php |
|
236 | - * |
|
237 | - * @return mixed data which can be serialized by <b>json_encode</b>, |
|
238 | - * which is a value of any type other than a resource. |
|
239 | - * |
|
240 | - * @since 5.4.0 |
|
241 | - */ |
|
242 | - public function jsonSerialize() |
|
243 | - { |
|
244 | - return array_map(function (AbstractTDBMObject $item) { |
|
245 | - return $item->jsonSerialize(); |
|
246 | - }, $this->toArray()); |
|
247 | - } |
|
33 | + /** |
|
34 | + * @var Statement |
|
35 | + */ |
|
36 | + protected $statement; |
|
37 | + |
|
38 | + protected $fetchStarted = false; |
|
39 | + private $objectStorage; |
|
40 | + private $className; |
|
41 | + |
|
42 | + private $tdbmService; |
|
43 | + private $magicSql; |
|
44 | + private $magicSqlCount; |
|
45 | + private $parameters; |
|
46 | + private $columnDescriptors; |
|
47 | + private $magicQuery; |
|
48 | + |
|
49 | + /** |
|
50 | + * @var InnerResultIterator |
|
51 | + */ |
|
52 | + private $innerResultIterator; |
|
53 | + |
|
54 | + /** |
|
55 | + * The key of the current retrieved object. |
|
56 | + * |
|
57 | + * @var int |
|
58 | + */ |
|
59 | + protected $key = -1; |
|
60 | + |
|
61 | + protected $current = null; |
|
62 | + |
|
63 | + private $databasePlatform; |
|
64 | + |
|
65 | + private $totalCount; |
|
66 | + |
|
67 | + private $mode; |
|
68 | + |
|
69 | + public function __construct($magicSql, $magicSqlCount, array $parameters, array $columnDescriptors, $objectStorage, $className, TDBMService $tdbmService, MagicQuery $magicQuery, $mode) |
|
70 | + { |
|
71 | + $this->magicSql = $magicSql; |
|
72 | + $this->magicSqlCount = $magicSqlCount; |
|
73 | + $this->objectStorage = $objectStorage; |
|
74 | + $this->className = $className; |
|
75 | + $this->tdbmService = $tdbmService; |
|
76 | + $this->parameters = $parameters; |
|
77 | + $this->columnDescriptors = $columnDescriptors; |
|
78 | + $this->magicQuery = $magicQuery; |
|
79 | + $this->databasePlatform = $this->tdbmService->getConnection()->getDatabasePlatform(); |
|
80 | + $this->mode = $mode; |
|
81 | + } |
|
82 | + |
|
83 | + protected function executeCountQuery() |
|
84 | + { |
|
85 | + $sql = $this->magicQuery->build($this->magicSqlCount, $this->parameters); |
|
86 | + $this->totalCount = $this->tdbmService->getConnection()->fetchColumn($sql, $this->parameters); |
|
87 | + } |
|
88 | + |
|
89 | + /** |
|
90 | + * Counts found records (this is the number of records fetched, taking into account the LIMIT and OFFSET settings). |
|
91 | + * |
|
92 | + * @return int |
|
93 | + */ |
|
94 | + public function count() |
|
95 | + { |
|
96 | + if ($this->totalCount === null) { |
|
97 | + $this->executeCountQuery(); |
|
98 | + } |
|
99 | + |
|
100 | + return $this->totalCount; |
|
101 | + } |
|
102 | + |
|
103 | + /** |
|
104 | + * Casts the result set to a PHP array. |
|
105 | + * |
|
106 | + * @return array |
|
107 | + */ |
|
108 | + public function toArray() |
|
109 | + { |
|
110 | + return iterator_to_array($this->getIterator()); |
|
111 | + } |
|
112 | + |
|
113 | + /** |
|
114 | + * Returns a new iterator mapping any call using the $callable function. |
|
115 | + * |
|
116 | + * @param callable $callable |
|
117 | + * |
|
118 | + * @return MapIterator |
|
119 | + */ |
|
120 | + public function map(callable $callable) |
|
121 | + { |
|
122 | + return new MapIterator($this->getIterator(), $callable); |
|
123 | + } |
|
124 | + |
|
125 | + /** |
|
126 | + * Retrieve an external iterator. |
|
127 | + * |
|
128 | + * @link http://php.net/manual/en/iteratoraggregate.getiterator.php |
|
129 | + * |
|
130 | + * @return InnerResultIterator An instance of an object implementing <b>Iterator</b> or |
|
131 | + * <b>Traversable</b> |
|
132 | + * |
|
133 | + * @since 5.0.0 |
|
134 | + */ |
|
135 | + public function getIterator() |
|
136 | + { |
|
137 | + if ($this->innerResultIterator === null) { |
|
138 | + if ($this->mode === TDBMService::MODE_CURSOR) { |
|
139 | + $this->innerResultIterator = new InnerResultIterator($this->magicSql, $this->parameters, null, null, $this->columnDescriptors, $this->objectStorage, $this->className, $this->tdbmService, $this->magicQuery); |
|
140 | + } else { |
|
141 | + $this->innerResultIterator = new InnerResultArray($this->magicSql, $this->parameters, null, null, $this->columnDescriptors, $this->objectStorage, $this->className, $this->tdbmService, $this->magicQuery); |
|
142 | + } |
|
143 | + } |
|
144 | + |
|
145 | + return $this->innerResultIterator; |
|
146 | + } |
|
147 | + |
|
148 | + /** |
|
149 | + * @param int $offset |
|
150 | + * |
|
151 | + * @return PageIterator |
|
152 | + */ |
|
153 | + public function take($offset, $limit) |
|
154 | + { |
|
155 | + return new PageIterator($this, $this->magicSql, $this->parameters, $limit, $offset, $this->columnDescriptors, $this->objectStorage, $this->className, $this->tdbmService, $this->magicQuery, $this->mode); |
|
156 | + } |
|
157 | + |
|
158 | + /** |
|
159 | + * Whether a offset exists. |
|
160 | + * |
|
161 | + * @link http://php.net/manual/en/arrayaccess.offsetexists.php |
|
162 | + * |
|
163 | + * @param mixed $offset <p> |
|
164 | + * An offset to check for. |
|
165 | + * </p> |
|
166 | + * |
|
167 | + * @return bool true on success or false on failure. |
|
168 | + * </p> |
|
169 | + * <p> |
|
170 | + * The return value will be casted to boolean if non-boolean was returned. |
|
171 | + * |
|
172 | + * @since 5.0.0 |
|
173 | + */ |
|
174 | + public function offsetExists($offset) |
|
175 | + { |
|
176 | + return $this->getIterator()->offsetExists($offset); |
|
177 | + } |
|
178 | + |
|
179 | + /** |
|
180 | + * Offset to retrieve. |
|
181 | + * |
|
182 | + * @link http://php.net/manual/en/arrayaccess.offsetget.php |
|
183 | + * |
|
184 | + * @param mixed $offset <p> |
|
185 | + * The offset to retrieve. |
|
186 | + * </p> |
|
187 | + * |
|
188 | + * @return mixed Can return all value types. |
|
189 | + * |
|
190 | + * @since 5.0.0 |
|
191 | + */ |
|
192 | + public function offsetGet($offset) |
|
193 | + { |
|
194 | + return $this->getIterator()->offsetGet($offset); |
|
195 | + } |
|
196 | + |
|
197 | + /** |
|
198 | + * Offset to set. |
|
199 | + * |
|
200 | + * @link http://php.net/manual/en/arrayaccess.offsetset.php |
|
201 | + * |
|
202 | + * @param mixed $offset <p> |
|
203 | + * The offset to assign the value to. |
|
204 | + * </p> |
|
205 | + * @param mixed $value <p> |
|
206 | + * The value to set. |
|
207 | + * </p> |
|
208 | + * |
|
209 | + * @since 5.0.0 |
|
210 | + */ |
|
211 | + public function offsetSet($offset, $value) |
|
212 | + { |
|
213 | + return $this->getIterator()->offsetSet($offset, $value); |
|
214 | + } |
|
215 | + |
|
216 | + /** |
|
217 | + * Offset to unset. |
|
218 | + * |
|
219 | + * @link http://php.net/manual/en/arrayaccess.offsetunset.php |
|
220 | + * |
|
221 | + * @param mixed $offset <p> |
|
222 | + * The offset to unset. |
|
223 | + * </p> |
|
224 | + * |
|
225 | + * @since 5.0.0 |
|
226 | + */ |
|
227 | + public function offsetUnset($offset) |
|
228 | + { |
|
229 | + return $this->getIterator()->offsetUnset($offset); |
|
230 | + } |
|
231 | + |
|
232 | + /** |
|
233 | + * Specify data which should be serialized to JSON. |
|
234 | + * |
|
235 | + * @link http://php.net/manual/en/jsonserializable.jsonserialize.php |
|
236 | + * |
|
237 | + * @return mixed data which can be serialized by <b>json_encode</b>, |
|
238 | + * which is a value of any type other than a resource. |
|
239 | + * |
|
240 | + * @since 5.4.0 |
|
241 | + */ |
|
242 | + public function jsonSerialize() |
|
243 | + { |
|
244 | + return array_map(function (AbstractTDBMObject $item) { |
|
245 | + return $item->jsonSerialize(); |
|
246 | + }, $this->toArray()); |
|
247 | + } |
|
248 | 248 | } |
@@ -241,7 +241,7 @@ |
||
241 | 241 | */ |
242 | 242 | public function jsonSerialize() |
243 | 243 | { |
244 | - return array_map(function (AbstractTDBMObject $item) { |
|
244 | + return array_map(function(AbstractTDBMObject $item) { |
|
245 | 245 | return $item->jsonSerialize(); |
246 | 246 | }, $this->toArray()); |
247 | 247 | } |
@@ -777,7 +777,7 @@ discard block |
||
777 | 777 | * This is used internally by TDBM to add an object to the list of objects that have been |
778 | 778 | * created/updated but not saved yet. |
779 | 779 | * |
780 | - * @param AbstractTDBMObject $myObject |
|
780 | + * @param DbRow $myObject |
|
781 | 781 | */ |
782 | 782 | public function _addToToSaveObjectList(DbRow $myObject) |
783 | 783 | { |
@@ -1441,7 +1441,7 @@ discard block |
||
1441 | 1441 | } |
1442 | 1442 | |
1443 | 1443 | /** |
1444 | - * @param $table |
|
1444 | + * @param string $table |
|
1445 | 1445 | * @param array $primaryKeys |
1446 | 1446 | * @param array $additionalTablesFetch |
1447 | 1447 | * @param bool $lazy Whether to perform lazy loading on this object or not. |
@@ -1616,7 +1616,7 @@ discard block |
||
1616 | 1616 | * @param $pivotTableName |
1617 | 1617 | * @param AbstractTDBMObject $bean |
1618 | 1618 | * |
1619 | - * @return AbstractTDBMObject[] |
|
1619 | + * @return ResultIterator |
|
1620 | 1620 | */ |
1621 | 1621 | public function _getRelatedBeans($pivotTableName, AbstractTDBMObject $bean) |
1622 | 1622 | { |
@@ -23,9 +23,7 @@ |
||
23 | 23 | use Doctrine\Common\Cache\Cache; |
24 | 24 | use Doctrine\Common\Cache\VoidCache; |
25 | 25 | use Doctrine\DBAL\Connection; |
26 | -use Doctrine\DBAL\Schema\Column; |
|
27 | 26 | use Doctrine\DBAL\Schema\ForeignKeyConstraint; |
28 | -use Doctrine\DBAL\Schema\Schema; |
|
29 | 27 | use Doctrine\DBAL\Schema\Table; |
30 | 28 | use Mouf\Database\MagicQuery; |
31 | 29 | use Mouf\Database\SchemaAnalyzer\SchemaAnalyzer; |
@@ -41,231 +41,231 @@ discard block |
||
41 | 41 | */ |
42 | 42 | class TDBMService |
43 | 43 | { |
44 | - const MODE_CURSOR = 1; |
|
45 | - const MODE_ARRAY = 2; |
|
46 | - |
|
47 | - /** |
|
48 | - * The database connection. |
|
49 | - * |
|
50 | - * @var Connection |
|
51 | - */ |
|
52 | - private $connection; |
|
53 | - |
|
54 | - /** |
|
55 | - * @var SchemaAnalyzer |
|
56 | - */ |
|
57 | - private $schemaAnalyzer; |
|
58 | - |
|
59 | - /** |
|
60 | - * @var MagicQuery |
|
61 | - */ |
|
62 | - private $magicQuery; |
|
63 | - |
|
64 | - /** |
|
65 | - * @var TDBMSchemaAnalyzer |
|
66 | - */ |
|
67 | - private $tdbmSchemaAnalyzer; |
|
68 | - |
|
69 | - /** |
|
70 | - * @var string |
|
71 | - */ |
|
72 | - private $cachePrefix; |
|
73 | - |
|
74 | - /** |
|
75 | - * The default autosave mode for the objects |
|
76 | - * True to automatically save the object. |
|
77 | - * If false, the user must explicitly call the save() method to save the object. |
|
78 | - * |
|
79 | - * @var bool |
|
80 | - */ |
|
81 | - //private $autosave_default = false; |
|
82 | - |
|
83 | - /** |
|
84 | - * Cache of table of primary keys. |
|
85 | - * Primary keys are stored by tables, as an array of column. |
|
86 | - * For instance $primary_key['my_table'][0] will return the first column of the primary key of table 'my_table'. |
|
87 | - * |
|
88 | - * @var string[] |
|
89 | - */ |
|
90 | - private $primaryKeysColumns; |
|
91 | - |
|
92 | - /** |
|
93 | - * Service storing objects in memory. |
|
94 | - * Access is done by table name and then by primary key. |
|
95 | - * If the primary key is split on several columns, access is done by an array of columns, serialized. |
|
96 | - * |
|
97 | - * @var StandardObjectStorage|WeakrefObjectStorage |
|
98 | - */ |
|
99 | - private $objectStorage; |
|
100 | - |
|
101 | - /** |
|
102 | - * The fetch mode of the result sets returned by `getObjects`. |
|
103 | - * Can be one of: TDBMObjectArray::MODE_CURSOR or TDBMObjectArray::MODE_ARRAY or TDBMObjectArray::MODE_COMPATIBLE_ARRAY. |
|
104 | - * |
|
105 | - * In 'MODE_ARRAY' mode (default), the result is an array. Use this mode by default (unless the list returned is very big). |
|
106 | - * 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, |
|
107 | - * and it cannot be accessed via key. Use this mode for large datasets processed by batch. |
|
108 | - * In 'MODE_COMPATIBLE_ARRAY' mode, the result is an old TDBMObjectArray (used up to TDBM 3.2). |
|
109 | - * You can access the array by key, or using foreach, several times. |
|
110 | - * |
|
111 | - * @var int |
|
112 | - */ |
|
113 | - private $mode = self::MODE_ARRAY; |
|
114 | - |
|
115 | - /** |
|
116 | - * Table of new objects not yet inserted in database or objects modified that must be saved. |
|
117 | - * |
|
118 | - * @var \SplObjectStorage of DbRow objects |
|
119 | - */ |
|
120 | - private $toSaveObjects; |
|
121 | - |
|
122 | - /// The timestamp of the script startup. Useful to stop execution before time limit is reached and display useful error message. |
|
123 | - public static $script_start_up_time; |
|
124 | - |
|
125 | - /** |
|
126 | - * The content of the cache variable. |
|
127 | - * |
|
128 | - * @var array<string, mixed> |
|
129 | - */ |
|
130 | - private $cache; |
|
131 | - |
|
132 | - private $cacheKey = '__TDBM_Cache__'; |
|
133 | - |
|
134 | - /** |
|
135 | - * Map associating a table name to a fully qualified Bean class name. |
|
136 | - * |
|
137 | - * @var array |
|
138 | - */ |
|
139 | - private $tableToBeanMap = []; |
|
140 | - |
|
141 | - /** |
|
142 | - * @var \ReflectionClass[] |
|
143 | - */ |
|
144 | - private $reflectionClassCache; |
|
145 | - |
|
146 | - /** |
|
147 | - * @param Connection $connection The DBAL DB connection to use |
|
148 | - * @param Cache|null $cache A cache service to be used |
|
149 | - * @param SchemaAnalyzer $schemaAnalyzer The schema analyzer that will be used to find shortest paths... |
|
150 | - * Will be automatically created if not passed. |
|
151 | - */ |
|
152 | - public function __construct(Connection $connection, Cache $cache = null, SchemaAnalyzer $schemaAnalyzer = null) |
|
153 | - { |
|
154 | - //register_shutdown_function(array($this,"completeSaveOnExit")); |
|
155 | - if (extension_loaded('weakref')) { |
|
156 | - $this->objectStorage = new WeakrefObjectStorage(); |
|
157 | - } else { |
|
158 | - $this->objectStorage = new StandardObjectStorage(); |
|
159 | - } |
|
160 | - $this->connection = $connection; |
|
161 | - if ($cache !== null) { |
|
162 | - $this->cache = $cache; |
|
163 | - } else { |
|
164 | - $this->cache = new VoidCache(); |
|
165 | - } |
|
166 | - if ($schemaAnalyzer) { |
|
167 | - $this->schemaAnalyzer = $schemaAnalyzer; |
|
168 | - } else { |
|
169 | - $this->schemaAnalyzer = new SchemaAnalyzer($this->connection->getSchemaManager(), $this->cache, $this->getConnectionUniqueId()); |
|
170 | - } |
|
171 | - |
|
172 | - $this->magicQuery = new MagicQuery($this->connection, $this->cache, $this->schemaAnalyzer); |
|
173 | - |
|
174 | - $this->tdbmSchemaAnalyzer = new TDBMSchemaAnalyzer($connection, $this->cache, $this->schemaAnalyzer); |
|
175 | - $this->cachePrefix = $this->tdbmSchemaAnalyzer->getCachePrefix(); |
|
176 | - |
|
177 | - if (self::$script_start_up_time === null) { |
|
178 | - self::$script_start_up_time = microtime(true); |
|
179 | - } |
|
180 | - $this->toSaveObjects = new \SplObjectStorage(); |
|
181 | - } |
|
182 | - |
|
183 | - /** |
|
184 | - * Returns the object used to connect to the database. |
|
185 | - * |
|
186 | - * @return Connection |
|
187 | - */ |
|
188 | - public function getConnection() |
|
189 | - { |
|
190 | - return $this->connection; |
|
191 | - } |
|
192 | - |
|
193 | - /** |
|
194 | - * Creates a unique cache key for the current connection. |
|
195 | - * |
|
196 | - * @return string |
|
197 | - */ |
|
198 | - private function getConnectionUniqueId() |
|
199 | - { |
|
200 | - return hash('md4', $this->connection->getHost().'-'.$this->connection->getPort().'-'.$this->connection->getDatabase().'-'.$this->connection->getDriver()->getName()); |
|
201 | - } |
|
202 | - |
|
203 | - /** |
|
204 | - * Sets the default fetch mode of the result sets returned by `getObjects`. |
|
205 | - * Can be one of: TDBMObjectArray::MODE_CURSOR or TDBMObjectArray::MODE_ARRAY. |
|
206 | - * |
|
207 | - * 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). |
|
208 | - * 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 |
|
209 | - * several times. In cursor mode, you cannot access the result set by key. Use this mode for large datasets processed by batch. |
|
210 | - * |
|
211 | - * @param int $mode |
|
212 | - * |
|
213 | - * @return $this |
|
214 | - * |
|
215 | - * @throws TDBMException |
|
216 | - */ |
|
217 | - public function setFetchMode($mode) |
|
218 | - { |
|
219 | - if ($mode !== self::MODE_CURSOR && $mode !== self::MODE_ARRAY) { |
|
220 | - throw new TDBMException("Unknown fetch mode: '".$this->mode."'"); |
|
221 | - } |
|
222 | - $this->mode = $mode; |
|
223 | - |
|
224 | - return $this; |
|
225 | - } |
|
226 | - |
|
227 | - /** |
|
228 | - * Returns a TDBMObject associated from table "$table_name". |
|
229 | - * If the $filters parameter is an int/string, the object returned will be the object whose primary key = $filters. |
|
230 | - * $filters can also be a set of TDBM_Filters (see the getObjects method for more details). |
|
231 | - * |
|
232 | - * For instance, if there is a table 'users', with a primary key on column 'user_id' and a column 'user_name', then |
|
233 | - * $user = $tdbmService->getObject('users',1); |
|
234 | - * echo $user->name; |
|
235 | - * will return the name of the user whose user_id is one. |
|
236 | - * |
|
237 | - * 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. |
|
238 | - * For instance: |
|
239 | - * $group = $tdbmService->getObject('groups',array(1,2)); |
|
240 | - * |
|
241 | - * Note that TDBMObject performs caching for you. If you get twice the same object, the reference of the object you will get |
|
242 | - * will be the same. |
|
243 | - * |
|
244 | - * For instance: |
|
245 | - * $user1 = $tdbmService->getObject('users',1); |
|
246 | - * $user2 = $tdbmService->getObject('users',1); |
|
247 | - * $user1->name = 'John Doe'; |
|
248 | - * echo $user2->name; |
|
249 | - * will return 'John Doe'. |
|
250 | - * |
|
251 | - * You can use filters instead of passing the primary key. For instance: |
|
252 | - * $user = $tdbmService->getObject('users',new EqualFilter('users', 'login', 'jdoe')); |
|
253 | - * This will return the user whose login is 'jdoe'. |
|
254 | - * Please note that if 2 users have the jdoe login in database, the method will throw a TDBM_DuplicateRowException. |
|
255 | - * |
|
256 | - * Also, you can specify the return class for the object (provided the return class extends TDBMObject). |
|
257 | - * For instance: |
|
258 | - * $user = $tdbmService->getObject('users',1,'User'); |
|
259 | - * will return an object from the "User" class. The "User" class must extend the "TDBMObject" class. |
|
260 | - * Please be sure not to override any method or any property unless you perfectly know what you are doing! |
|
261 | - * |
|
262 | - * @param string $table_name The name of the table we retrieve an object from. |
|
263 | - * @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 getObjects method for more details about filter bags) |
|
264 | - * @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. |
|
265 | - * @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. |
|
266 | - * |
|
267 | - * @return TDBMObject |
|
268 | - */ |
|
44 | + const MODE_CURSOR = 1; |
|
45 | + const MODE_ARRAY = 2; |
|
46 | + |
|
47 | + /** |
|
48 | + * The database connection. |
|
49 | + * |
|
50 | + * @var Connection |
|
51 | + */ |
|
52 | + private $connection; |
|
53 | + |
|
54 | + /** |
|
55 | + * @var SchemaAnalyzer |
|
56 | + */ |
|
57 | + private $schemaAnalyzer; |
|
58 | + |
|
59 | + /** |
|
60 | + * @var MagicQuery |
|
61 | + */ |
|
62 | + private $magicQuery; |
|
63 | + |
|
64 | + /** |
|
65 | + * @var TDBMSchemaAnalyzer |
|
66 | + */ |
|
67 | + private $tdbmSchemaAnalyzer; |
|
68 | + |
|
69 | + /** |
|
70 | + * @var string |
|
71 | + */ |
|
72 | + private $cachePrefix; |
|
73 | + |
|
74 | + /** |
|
75 | + * The default autosave mode for the objects |
|
76 | + * True to automatically save the object. |
|
77 | + * If false, the user must explicitly call the save() method to save the object. |
|
78 | + * |
|
79 | + * @var bool |
|
80 | + */ |
|
81 | + //private $autosave_default = false; |
|
82 | + |
|
83 | + /** |
|
84 | + * Cache of table of primary keys. |
|
85 | + * Primary keys are stored by tables, as an array of column. |
|
86 | + * For instance $primary_key['my_table'][0] will return the first column of the primary key of table 'my_table'. |
|
87 | + * |
|
88 | + * @var string[] |
|
89 | + */ |
|
90 | + private $primaryKeysColumns; |
|
91 | + |
|
92 | + /** |
|
93 | + * Service storing objects in memory. |
|
94 | + * Access is done by table name and then by primary key. |
|
95 | + * If the primary key is split on several columns, access is done by an array of columns, serialized. |
|
96 | + * |
|
97 | + * @var StandardObjectStorage|WeakrefObjectStorage |
|
98 | + */ |
|
99 | + private $objectStorage; |
|
100 | + |
|
101 | + /** |
|
102 | + * The fetch mode of the result sets returned by `getObjects`. |
|
103 | + * Can be one of: TDBMObjectArray::MODE_CURSOR or TDBMObjectArray::MODE_ARRAY or TDBMObjectArray::MODE_COMPATIBLE_ARRAY. |
|
104 | + * |
|
105 | + * In 'MODE_ARRAY' mode (default), the result is an array. Use this mode by default (unless the list returned is very big). |
|
106 | + * 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, |
|
107 | + * and it cannot be accessed via key. Use this mode for large datasets processed by batch. |
|
108 | + * In 'MODE_COMPATIBLE_ARRAY' mode, the result is an old TDBMObjectArray (used up to TDBM 3.2). |
|
109 | + * You can access the array by key, or using foreach, several times. |
|
110 | + * |
|
111 | + * @var int |
|
112 | + */ |
|
113 | + private $mode = self::MODE_ARRAY; |
|
114 | + |
|
115 | + /** |
|
116 | + * Table of new objects not yet inserted in database or objects modified that must be saved. |
|
117 | + * |
|
118 | + * @var \SplObjectStorage of DbRow objects |
|
119 | + */ |
|
120 | + private $toSaveObjects; |
|
121 | + |
|
122 | + /// The timestamp of the script startup. Useful to stop execution before time limit is reached and display useful error message. |
|
123 | + public static $script_start_up_time; |
|
124 | + |
|
125 | + /** |
|
126 | + * The content of the cache variable. |
|
127 | + * |
|
128 | + * @var array<string, mixed> |
|
129 | + */ |
|
130 | + private $cache; |
|
131 | + |
|
132 | + private $cacheKey = '__TDBM_Cache__'; |
|
133 | + |
|
134 | + /** |
|
135 | + * Map associating a table name to a fully qualified Bean class name. |
|
136 | + * |
|
137 | + * @var array |
|
138 | + */ |
|
139 | + private $tableToBeanMap = []; |
|
140 | + |
|
141 | + /** |
|
142 | + * @var \ReflectionClass[] |
|
143 | + */ |
|
144 | + private $reflectionClassCache; |
|
145 | + |
|
146 | + /** |
|
147 | + * @param Connection $connection The DBAL DB connection to use |
|
148 | + * @param Cache|null $cache A cache service to be used |
|
149 | + * @param SchemaAnalyzer $schemaAnalyzer The schema analyzer that will be used to find shortest paths... |
|
150 | + * Will be automatically created if not passed. |
|
151 | + */ |
|
152 | + public function __construct(Connection $connection, Cache $cache = null, SchemaAnalyzer $schemaAnalyzer = null) |
|
153 | + { |
|
154 | + //register_shutdown_function(array($this,"completeSaveOnExit")); |
|
155 | + if (extension_loaded('weakref')) { |
|
156 | + $this->objectStorage = new WeakrefObjectStorage(); |
|
157 | + } else { |
|
158 | + $this->objectStorage = new StandardObjectStorage(); |
|
159 | + } |
|
160 | + $this->connection = $connection; |
|
161 | + if ($cache !== null) { |
|
162 | + $this->cache = $cache; |
|
163 | + } else { |
|
164 | + $this->cache = new VoidCache(); |
|
165 | + } |
|
166 | + if ($schemaAnalyzer) { |
|
167 | + $this->schemaAnalyzer = $schemaAnalyzer; |
|
168 | + } else { |
|
169 | + $this->schemaAnalyzer = new SchemaAnalyzer($this->connection->getSchemaManager(), $this->cache, $this->getConnectionUniqueId()); |
|
170 | + } |
|
171 | + |
|
172 | + $this->magicQuery = new MagicQuery($this->connection, $this->cache, $this->schemaAnalyzer); |
|
173 | + |
|
174 | + $this->tdbmSchemaAnalyzer = new TDBMSchemaAnalyzer($connection, $this->cache, $this->schemaAnalyzer); |
|
175 | + $this->cachePrefix = $this->tdbmSchemaAnalyzer->getCachePrefix(); |
|
176 | + |
|
177 | + if (self::$script_start_up_time === null) { |
|
178 | + self::$script_start_up_time = microtime(true); |
|
179 | + } |
|
180 | + $this->toSaveObjects = new \SplObjectStorage(); |
|
181 | + } |
|
182 | + |
|
183 | + /** |
|
184 | + * Returns the object used to connect to the database. |
|
185 | + * |
|
186 | + * @return Connection |
|
187 | + */ |
|
188 | + public function getConnection() |
|
189 | + { |
|
190 | + return $this->connection; |
|
191 | + } |
|
192 | + |
|
193 | + /** |
|
194 | + * Creates a unique cache key for the current connection. |
|
195 | + * |
|
196 | + * @return string |
|
197 | + */ |
|
198 | + private function getConnectionUniqueId() |
|
199 | + { |
|
200 | + return hash('md4', $this->connection->getHost().'-'.$this->connection->getPort().'-'.$this->connection->getDatabase().'-'.$this->connection->getDriver()->getName()); |
|
201 | + } |
|
202 | + |
|
203 | + /** |
|
204 | + * Sets the default fetch mode of the result sets returned by `getObjects`. |
|
205 | + * Can be one of: TDBMObjectArray::MODE_CURSOR or TDBMObjectArray::MODE_ARRAY. |
|
206 | + * |
|
207 | + * 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). |
|
208 | + * 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 |
|
209 | + * several times. In cursor mode, you cannot access the result set by key. Use this mode for large datasets processed by batch. |
|
210 | + * |
|
211 | + * @param int $mode |
|
212 | + * |
|
213 | + * @return $this |
|
214 | + * |
|
215 | + * @throws TDBMException |
|
216 | + */ |
|
217 | + public function setFetchMode($mode) |
|
218 | + { |
|
219 | + if ($mode !== self::MODE_CURSOR && $mode !== self::MODE_ARRAY) { |
|
220 | + throw new TDBMException("Unknown fetch mode: '".$this->mode."'"); |
|
221 | + } |
|
222 | + $this->mode = $mode; |
|
223 | + |
|
224 | + return $this; |
|
225 | + } |
|
226 | + |
|
227 | + /** |
|
228 | + * Returns a TDBMObject associated from table "$table_name". |
|
229 | + * If the $filters parameter is an int/string, the object returned will be the object whose primary key = $filters. |
|
230 | + * $filters can also be a set of TDBM_Filters (see the getObjects method for more details). |
|
231 | + * |
|
232 | + * For instance, if there is a table 'users', with a primary key on column 'user_id' and a column 'user_name', then |
|
233 | + * $user = $tdbmService->getObject('users',1); |
|
234 | + * echo $user->name; |
|
235 | + * will return the name of the user whose user_id is one. |
|
236 | + * |
|
237 | + * 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. |
|
238 | + * For instance: |
|
239 | + * $group = $tdbmService->getObject('groups',array(1,2)); |
|
240 | + * |
|
241 | + * Note that TDBMObject performs caching for you. If you get twice the same object, the reference of the object you will get |
|
242 | + * will be the same. |
|
243 | + * |
|
244 | + * For instance: |
|
245 | + * $user1 = $tdbmService->getObject('users',1); |
|
246 | + * $user2 = $tdbmService->getObject('users',1); |
|
247 | + * $user1->name = 'John Doe'; |
|
248 | + * echo $user2->name; |
|
249 | + * will return 'John Doe'. |
|
250 | + * |
|
251 | + * You can use filters instead of passing the primary key. For instance: |
|
252 | + * $user = $tdbmService->getObject('users',new EqualFilter('users', 'login', 'jdoe')); |
|
253 | + * This will return the user whose login is 'jdoe'. |
|
254 | + * Please note that if 2 users have the jdoe login in database, the method will throw a TDBM_DuplicateRowException. |
|
255 | + * |
|
256 | + * Also, you can specify the return class for the object (provided the return class extends TDBMObject). |
|
257 | + * For instance: |
|
258 | + * $user = $tdbmService->getObject('users',1,'User'); |
|
259 | + * will return an object from the "User" class. The "User" class must extend the "TDBMObject" class. |
|
260 | + * Please be sure not to override any method or any property unless you perfectly know what you are doing! |
|
261 | + * |
|
262 | + * @param string $table_name The name of the table we retrieve an object from. |
|
263 | + * @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 getObjects method for more details about filter bags) |
|
264 | + * @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. |
|
265 | + * @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. |
|
266 | + * |
|
267 | + * @return TDBMObject |
|
268 | + */ |
|
269 | 269 | /* public function getObject($table_name, $filters, $className = null, $lazy_loading = false) { |
270 | 270 | |
271 | 271 | if (is_array($filters) || $filters instanceof FilterInterface) { |
@@ -351,215 +351,215 @@ discard block |
||
351 | 351 | return $obj; |
352 | 352 | }*/ |
353 | 353 | |
354 | - /** |
|
355 | - * Removes the given object from database. |
|
356 | - * This cannot be called on an object that is not attached to this TDBMService |
|
357 | - * (will throw a TDBMInvalidOperationException). |
|
358 | - * |
|
359 | - * @param AbstractTDBMObject $object the object to delete. |
|
360 | - * |
|
361 | - * @throws TDBMException |
|
362 | - * @throws TDBMInvalidOperationException |
|
363 | - */ |
|
364 | - public function delete(AbstractTDBMObject $object) |
|
365 | - { |
|
366 | - switch ($object->_getStatus()) { |
|
367 | - case TDBMObjectStateEnum::STATE_DELETED: |
|
368 | - // Nothing to do, object already deleted. |
|
369 | - return; |
|
370 | - case TDBMObjectStateEnum::STATE_DETACHED: |
|
371 | - throw new TDBMInvalidOperationException('Cannot delete a detached object'); |
|
372 | - case TDBMObjectStateEnum::STATE_NEW: |
|
373 | - $this->deleteManyToManyRelationships($object); |
|
374 | - foreach ($object->_getDbRows() as $dbRow) { |
|
375 | - $this->removeFromToSaveObjectList($dbRow); |
|
376 | - } |
|
377 | - break; |
|
378 | - case TDBMObjectStateEnum::STATE_DIRTY: |
|
379 | - foreach ($object->_getDbRows() as $dbRow) { |
|
380 | - $this->removeFromToSaveObjectList($dbRow); |
|
381 | - } |
|
382 | - case TDBMObjectStateEnum::STATE_NOT_LOADED: |
|
383 | - case TDBMObjectStateEnum::STATE_LOADED: |
|
384 | - $this->deleteManyToManyRelationships($object); |
|
385 | - // Let's delete db rows, in reverse order. |
|
386 | - foreach (array_reverse($object->_getDbRows()) as $dbRow) { |
|
387 | - $tableName = $dbRow->_getDbTableName(); |
|
388 | - $primaryKeys = $dbRow->_getPrimaryKeys(); |
|
389 | - $this->connection->delete($tableName, $primaryKeys); |
|
390 | - $this->objectStorage->remove($dbRow->_getDbTableName(), $this->getObjectHash($primaryKeys)); |
|
391 | - } |
|
392 | - break; |
|
393 | - // @codeCoverageIgnoreStart |
|
394 | - default: |
|
395 | - throw new TDBMInvalidOperationException('Unexpected status for bean'); |
|
396 | - // @codeCoverageIgnoreEnd |
|
397 | - } |
|
398 | - |
|
399 | - $object->_setStatus(TDBMObjectStateEnum::STATE_DELETED); |
|
400 | - } |
|
401 | - |
|
402 | - /** |
|
403 | - * Removes all many to many relationships for this object. |
|
404 | - * |
|
405 | - * @param AbstractTDBMObject $object |
|
406 | - */ |
|
407 | - private function deleteManyToManyRelationships(AbstractTDBMObject $object) |
|
408 | - { |
|
409 | - foreach ($object->_getDbRows() as $tableName => $dbRow) { |
|
410 | - $pivotTables = $this->tdbmSchemaAnalyzer->getPivotTableLinkedToTable($tableName); |
|
411 | - foreach ($pivotTables as $pivotTable) { |
|
412 | - $remoteBeans = $object->_getRelationships($pivotTable); |
|
413 | - foreach ($remoteBeans as $remoteBean) { |
|
414 | - $object->_removeRelationship($pivotTable, $remoteBean); |
|
415 | - } |
|
416 | - } |
|
417 | - } |
|
418 | - $this->persistManyToManyRelationships($object); |
|
419 | - } |
|
420 | - |
|
421 | - /** |
|
422 | - * This function removes the given object from the database. It will also remove all objects relied to the one given |
|
423 | - * by parameter before all. |
|
424 | - * |
|
425 | - * Notice: if the object has a multiple primary key, the function will not work. |
|
426 | - * |
|
427 | - * @param AbstractTDBMObject $objToDelete |
|
428 | - */ |
|
429 | - public function deleteCascade(AbstractTDBMObject $objToDelete) |
|
430 | - { |
|
431 | - $this->deleteAllConstraintWithThisObject($objToDelete); |
|
432 | - $this->delete($objToDelete); |
|
433 | - } |
|
434 | - |
|
435 | - /** |
|
436 | - * This function is used only in TDBMService (private function) |
|
437 | - * It will call deleteCascade function foreach object relied with a foreign key to the object given by parameter. |
|
438 | - * |
|
439 | - * @param AbstractTDBMObject $obj |
|
440 | - */ |
|
441 | - private function deleteAllConstraintWithThisObject(AbstractTDBMObject $obj) |
|
442 | - { |
|
443 | - $dbRows = $obj->_getDbRows(); |
|
444 | - foreach ($dbRows as $dbRow) { |
|
445 | - $tableName = $dbRow->_getDbTableName(); |
|
446 | - $pks = array_values($dbRow->_getPrimaryKeys()); |
|
447 | - if (!empty($pks)) { |
|
448 | - $incomingFks = $this->tdbmSchemaAnalyzer->getIncomingForeignKeys($tableName); |
|
449 | - |
|
450 | - foreach ($incomingFks as $incomingFk) { |
|
451 | - $filter = array_combine($incomingFk->getLocalColumns(), $pks); |
|
452 | - |
|
453 | - $results = $this->findObjects($incomingFk->getLocalTableName(), $filter); |
|
454 | - |
|
455 | - foreach ($results as $bean) { |
|
456 | - $this->deleteCascade($bean); |
|
457 | - } |
|
458 | - } |
|
459 | - } |
|
460 | - } |
|
461 | - } |
|
462 | - |
|
463 | - /** |
|
464 | - * This function performs a save() of all the objects that have been modified. |
|
465 | - */ |
|
466 | - public function completeSave() |
|
467 | - { |
|
468 | - foreach ($this->toSaveObjects as $dbRow) { |
|
469 | - $this->save($dbRow->getTDBMObject()); |
|
470 | - } |
|
471 | - } |
|
472 | - |
|
473 | - /** |
|
474 | - * Returns an array of objects of "table_name" kind filtered from the filter bag. |
|
475 | - * |
|
476 | - * The getObjects method should be the most used query method in TDBM if you want to query the database for objects. |
|
477 | - * (Note: if you want to query the database for an object by its primary key, use the getObject method). |
|
478 | - * |
|
479 | - * The getObjects method takes in parameter: |
|
480 | - * - table_name: the kinf of TDBMObject you want to retrieve. In TDBM, a TDBMObject matches a database row, so the |
|
481 | - * $table_name parameter should be the name of an existing table in database. |
|
482 | - * - filter_bag: The filter bag is anything that you can use to filter your request. It can be a SQL Where clause, |
|
483 | - * a series of TDBM_Filter objects, or even TDBMObjects or TDBMObjectArrays that you will use as filters. |
|
484 | - * - order_bag: The order bag is anything that will be used to order the data that is passed back to you. |
|
485 | - * A SQL Order by clause can be used as an order bag for instance, or a OrderByColumn object |
|
486 | - * - from (optionnal): The offset from which the query should be performed. For instance, if $from=5, the getObjects method |
|
487 | - * will return objects from the 6th rows. |
|
488 | - * - limit (optionnal): The maximum number of objects to return. Used together with $from, you can implement |
|
489 | - * paging mechanisms. |
|
490 | - * - hint_path (optionnal): EXPERTS ONLY! The path the request should use if not the most obvious one. This parameter |
|
491 | - * should be used only if you perfectly know what you are doing. |
|
492 | - * |
|
493 | - * The getObjects method will return a TDBMObjectArray. A TDBMObjectArray is an array of TDBMObjects that does behave as |
|
494 | - * a single TDBMObject if the array has only one member. Refer to the documentation of TDBMObjectArray and TDBMObject |
|
495 | - * to learn more. |
|
496 | - * |
|
497 | - * More about the filter bag: |
|
498 | - * A filter is anything that can change the set of objects returned by getObjects. |
|
499 | - * There are many kind of filters in TDBM: |
|
500 | - * A filter can be: |
|
501 | - * - A SQL WHERE clause: |
|
502 | - * The clause is specified without the "WHERE" keyword. For instance: |
|
503 | - * $filter = "users.first_name LIKE 'J%'"; |
|
504 | - * is a valid filter. |
|
505 | - * The only difference with SQL is that when you specify a column name, it should always be fully qualified with |
|
506 | - * the table name: "country_name='France'" is not valid, while "countries.country_name='France'" is valid (if |
|
507 | - * "countries" is a table and "country_name" a column in that table, sure. |
|
508 | - * For instance, |
|
509 | - * $french_users = TDBMObject::getObjects("users", "countries.country_name='France'"); |
|
510 | - * will return all the users that are French (based on trhe assumption that TDBM can find a way to connect the users |
|
511 | - * table to the country table using foreign keys, see the manual for that point). |
|
512 | - * - A TDBMObject: |
|
513 | - * An object can be used as a filter. For instance, we could get the France object and then find any users related to |
|
514 | - * that object using: |
|
515 | - * $france = TDBMObject::getObjects("country", "countries.country_name='France'"); |
|
516 | - * $french_users = TDBMObject::getObjects("users", $france); |
|
517 | - * - A TDBMObjectArray can be used as a filter too. |
|
518 | - * For instance: |
|
519 | - * $french_groups = TDBMObject::getObjects("groups", $french_users); |
|
520 | - * might return all the groups in which french users can be found. |
|
521 | - * - Finally, TDBM_xxxFilter instances can be used. |
|
522 | - * TDBM provides the developer a set of TDBM_xxxFilters that can be used to model a SQL Where query. |
|
523 | - * Using the appropriate filter object, you can model the operations =,<,<=,>,>=,IN,LIKE,AND,OR, IS NULL and NOT |
|
524 | - * For instance: |
|
525 | - * $french_users = TDBMObject::getObjects("users", new EqualFilter('countries','country_name','France'); |
|
526 | - * Refer to the documentation of the appropriate filters for more information. |
|
527 | - * |
|
528 | - * The nice thing about a filter bag is that it can be any filter, or any array of filters. In that case, filters are |
|
529 | - * 'ANDed' together. |
|
530 | - * So a request like this is valid: |
|
531 | - * $france = TDBMObject::getObjects("country", "countries.country_name='France'"); |
|
532 | - * $french_administrators = TDBMObject::getObjects("users", array($france,"role.role_name='Administrators'"); |
|
533 | - * This requests would return the users that are both French and administrators. |
|
534 | - * |
|
535 | - * Finally, if filter_bag is null, the whole table is returned. |
|
536 | - * |
|
537 | - * More about the order bag: |
|
538 | - * The order bag contains anything that can be used to order the data that is passed back to you. |
|
539 | - * The order bag can contain two kinds of objects: |
|
540 | - * - A SQL ORDER BY clause: |
|
541 | - * The clause is specified without the "ORDER BY" keyword. For instance: |
|
542 | - * $orderby = "users.last_name ASC, users.first_name ASC"; |
|
543 | - * is a valid order bag. |
|
544 | - * The only difference with SQL is that when you specify a column name, it should always be fully qualified with |
|
545 | - * the table name: "country_name ASC" is not valid, while "countries.country_name ASC" is valid (if |
|
546 | - * "countries" is a table and "country_name" a column in that table, sure. |
|
547 | - * For instance, |
|
548 | - * $french_users = TDBMObject::getObjects("users", null, "countries.country_name ASC"); |
|
549 | - * will return all the users sorted by country. |
|
550 | - * - A OrderByColumn object |
|
551 | - * This object models a single column in a database. |
|
552 | - * |
|
553 | - * @param string $table_name The name of the table queried |
|
554 | - * @param mixed $filter_bag The filter bag (see above for complete description) |
|
555 | - * @param mixed $orderby_bag The order bag (see above for complete description) |
|
556 | - * @param int $from The offset |
|
557 | - * @param int $limit The maximum number of rows returned |
|
558 | - * @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. |
|
559 | - * @param unknown_type $hint_path Hints to get the path for the query (expert parameter, you should leave it to null). |
|
560 | - * |
|
561 | - * @return TDBMObjectArray A TDBMObjectArray containing the resulting objects of the query. |
|
562 | - */ |
|
354 | + /** |
|
355 | + * Removes the given object from database. |
|
356 | + * This cannot be called on an object that is not attached to this TDBMService |
|
357 | + * (will throw a TDBMInvalidOperationException). |
|
358 | + * |
|
359 | + * @param AbstractTDBMObject $object the object to delete. |
|
360 | + * |
|
361 | + * @throws TDBMException |
|
362 | + * @throws TDBMInvalidOperationException |
|
363 | + */ |
|
364 | + public function delete(AbstractTDBMObject $object) |
|
365 | + { |
|
366 | + switch ($object->_getStatus()) { |
|
367 | + case TDBMObjectStateEnum::STATE_DELETED: |
|
368 | + // Nothing to do, object already deleted. |
|
369 | + return; |
|
370 | + case TDBMObjectStateEnum::STATE_DETACHED: |
|
371 | + throw new TDBMInvalidOperationException('Cannot delete a detached object'); |
|
372 | + case TDBMObjectStateEnum::STATE_NEW: |
|
373 | + $this->deleteManyToManyRelationships($object); |
|
374 | + foreach ($object->_getDbRows() as $dbRow) { |
|
375 | + $this->removeFromToSaveObjectList($dbRow); |
|
376 | + } |
|
377 | + break; |
|
378 | + case TDBMObjectStateEnum::STATE_DIRTY: |
|
379 | + foreach ($object->_getDbRows() as $dbRow) { |
|
380 | + $this->removeFromToSaveObjectList($dbRow); |
|
381 | + } |
|
382 | + case TDBMObjectStateEnum::STATE_NOT_LOADED: |
|
383 | + case TDBMObjectStateEnum::STATE_LOADED: |
|
384 | + $this->deleteManyToManyRelationships($object); |
|
385 | + // Let's delete db rows, in reverse order. |
|
386 | + foreach (array_reverse($object->_getDbRows()) as $dbRow) { |
|
387 | + $tableName = $dbRow->_getDbTableName(); |
|
388 | + $primaryKeys = $dbRow->_getPrimaryKeys(); |
|
389 | + $this->connection->delete($tableName, $primaryKeys); |
|
390 | + $this->objectStorage->remove($dbRow->_getDbTableName(), $this->getObjectHash($primaryKeys)); |
|
391 | + } |
|
392 | + break; |
|
393 | + // @codeCoverageIgnoreStart |
|
394 | + default: |
|
395 | + throw new TDBMInvalidOperationException('Unexpected status for bean'); |
|
396 | + // @codeCoverageIgnoreEnd |
|
397 | + } |
|
398 | + |
|
399 | + $object->_setStatus(TDBMObjectStateEnum::STATE_DELETED); |
|
400 | + } |
|
401 | + |
|
402 | + /** |
|
403 | + * Removes all many to many relationships for this object. |
|
404 | + * |
|
405 | + * @param AbstractTDBMObject $object |
|
406 | + */ |
|
407 | + private function deleteManyToManyRelationships(AbstractTDBMObject $object) |
|
408 | + { |
|
409 | + foreach ($object->_getDbRows() as $tableName => $dbRow) { |
|
410 | + $pivotTables = $this->tdbmSchemaAnalyzer->getPivotTableLinkedToTable($tableName); |
|
411 | + foreach ($pivotTables as $pivotTable) { |
|
412 | + $remoteBeans = $object->_getRelationships($pivotTable); |
|
413 | + foreach ($remoteBeans as $remoteBean) { |
|
414 | + $object->_removeRelationship($pivotTable, $remoteBean); |
|
415 | + } |
|
416 | + } |
|
417 | + } |
|
418 | + $this->persistManyToManyRelationships($object); |
|
419 | + } |
|
420 | + |
|
421 | + /** |
|
422 | + * This function removes the given object from the database. It will also remove all objects relied to the one given |
|
423 | + * by parameter before all. |
|
424 | + * |
|
425 | + * Notice: if the object has a multiple primary key, the function will not work. |
|
426 | + * |
|
427 | + * @param AbstractTDBMObject $objToDelete |
|
428 | + */ |
|
429 | + public function deleteCascade(AbstractTDBMObject $objToDelete) |
|
430 | + { |
|
431 | + $this->deleteAllConstraintWithThisObject($objToDelete); |
|
432 | + $this->delete($objToDelete); |
|
433 | + } |
|
434 | + |
|
435 | + /** |
|
436 | + * This function is used only in TDBMService (private function) |
|
437 | + * It will call deleteCascade function foreach object relied with a foreign key to the object given by parameter. |
|
438 | + * |
|
439 | + * @param AbstractTDBMObject $obj |
|
440 | + */ |
|
441 | + private function deleteAllConstraintWithThisObject(AbstractTDBMObject $obj) |
|
442 | + { |
|
443 | + $dbRows = $obj->_getDbRows(); |
|
444 | + foreach ($dbRows as $dbRow) { |
|
445 | + $tableName = $dbRow->_getDbTableName(); |
|
446 | + $pks = array_values($dbRow->_getPrimaryKeys()); |
|
447 | + if (!empty($pks)) { |
|
448 | + $incomingFks = $this->tdbmSchemaAnalyzer->getIncomingForeignKeys($tableName); |
|
449 | + |
|
450 | + foreach ($incomingFks as $incomingFk) { |
|
451 | + $filter = array_combine($incomingFk->getLocalColumns(), $pks); |
|
452 | + |
|
453 | + $results = $this->findObjects($incomingFk->getLocalTableName(), $filter); |
|
454 | + |
|
455 | + foreach ($results as $bean) { |
|
456 | + $this->deleteCascade($bean); |
|
457 | + } |
|
458 | + } |
|
459 | + } |
|
460 | + } |
|
461 | + } |
|
462 | + |
|
463 | + /** |
|
464 | + * This function performs a save() of all the objects that have been modified. |
|
465 | + */ |
|
466 | + public function completeSave() |
|
467 | + { |
|
468 | + foreach ($this->toSaveObjects as $dbRow) { |
|
469 | + $this->save($dbRow->getTDBMObject()); |
|
470 | + } |
|
471 | + } |
|
472 | + |
|
473 | + /** |
|
474 | + * Returns an array of objects of "table_name" kind filtered from the filter bag. |
|
475 | + * |
|
476 | + * The getObjects method should be the most used query method in TDBM if you want to query the database for objects. |
|
477 | + * (Note: if you want to query the database for an object by its primary key, use the getObject method). |
|
478 | + * |
|
479 | + * The getObjects method takes in parameter: |
|
480 | + * - table_name: the kinf of TDBMObject you want to retrieve. In TDBM, a TDBMObject matches a database row, so the |
|
481 | + * $table_name parameter should be the name of an existing table in database. |
|
482 | + * - filter_bag: The filter bag is anything that you can use to filter your request. It can be a SQL Where clause, |
|
483 | + * a series of TDBM_Filter objects, or even TDBMObjects or TDBMObjectArrays that you will use as filters. |
|
484 | + * - order_bag: The order bag is anything that will be used to order the data that is passed back to you. |
|
485 | + * A SQL Order by clause can be used as an order bag for instance, or a OrderByColumn object |
|
486 | + * - from (optionnal): The offset from which the query should be performed. For instance, if $from=5, the getObjects method |
|
487 | + * will return objects from the 6th rows. |
|
488 | + * - limit (optionnal): The maximum number of objects to return. Used together with $from, you can implement |
|
489 | + * paging mechanisms. |
|
490 | + * - hint_path (optionnal): EXPERTS ONLY! The path the request should use if not the most obvious one. This parameter |
|
491 | + * should be used only if you perfectly know what you are doing. |
|
492 | + * |
|
493 | + * The getObjects method will return a TDBMObjectArray. A TDBMObjectArray is an array of TDBMObjects that does behave as |
|
494 | + * a single TDBMObject if the array has only one member. Refer to the documentation of TDBMObjectArray and TDBMObject |
|
495 | + * to learn more. |
|
496 | + * |
|
497 | + * More about the filter bag: |
|
498 | + * A filter is anything that can change the set of objects returned by getObjects. |
|
499 | + * There are many kind of filters in TDBM: |
|
500 | + * A filter can be: |
|
501 | + * - A SQL WHERE clause: |
|
502 | + * The clause is specified without the "WHERE" keyword. For instance: |
|
503 | + * $filter = "users.first_name LIKE 'J%'"; |
|
504 | + * is a valid filter. |
|
505 | + * The only difference with SQL is that when you specify a column name, it should always be fully qualified with |
|
506 | + * the table name: "country_name='France'" is not valid, while "countries.country_name='France'" is valid (if |
|
507 | + * "countries" is a table and "country_name" a column in that table, sure. |
|
508 | + * For instance, |
|
509 | + * $french_users = TDBMObject::getObjects("users", "countries.country_name='France'"); |
|
510 | + * will return all the users that are French (based on trhe assumption that TDBM can find a way to connect the users |
|
511 | + * table to the country table using foreign keys, see the manual for that point). |
|
512 | + * - A TDBMObject: |
|
513 | + * An object can be used as a filter. For instance, we could get the France object and then find any users related to |
|
514 | + * that object using: |
|
515 | + * $france = TDBMObject::getObjects("country", "countries.country_name='France'"); |
|
516 | + * $french_users = TDBMObject::getObjects("users", $france); |
|
517 | + * - A TDBMObjectArray can be used as a filter too. |
|
518 | + * For instance: |
|
519 | + * $french_groups = TDBMObject::getObjects("groups", $french_users); |
|
520 | + * might return all the groups in which french users can be found. |
|
521 | + * - Finally, TDBM_xxxFilter instances can be used. |
|
522 | + * TDBM provides the developer a set of TDBM_xxxFilters that can be used to model a SQL Where query. |
|
523 | + * Using the appropriate filter object, you can model the operations =,<,<=,>,>=,IN,LIKE,AND,OR, IS NULL and NOT |
|
524 | + * For instance: |
|
525 | + * $french_users = TDBMObject::getObjects("users", new EqualFilter('countries','country_name','France'); |
|
526 | + * Refer to the documentation of the appropriate filters for more information. |
|
527 | + * |
|
528 | + * The nice thing about a filter bag is that it can be any filter, or any array of filters. In that case, filters are |
|
529 | + * 'ANDed' together. |
|
530 | + * So a request like this is valid: |
|
531 | + * $france = TDBMObject::getObjects("country", "countries.country_name='France'"); |
|
532 | + * $french_administrators = TDBMObject::getObjects("users", array($france,"role.role_name='Administrators'"); |
|
533 | + * This requests would return the users that are both French and administrators. |
|
534 | + * |
|
535 | + * Finally, if filter_bag is null, the whole table is returned. |
|
536 | + * |
|
537 | + * More about the order bag: |
|
538 | + * The order bag contains anything that can be used to order the data that is passed back to you. |
|
539 | + * The order bag can contain two kinds of objects: |
|
540 | + * - A SQL ORDER BY clause: |
|
541 | + * The clause is specified without the "ORDER BY" keyword. For instance: |
|
542 | + * $orderby = "users.last_name ASC, users.first_name ASC"; |
|
543 | + * is a valid order bag. |
|
544 | + * The only difference with SQL is that when you specify a column name, it should always be fully qualified with |
|
545 | + * the table name: "country_name ASC" is not valid, while "countries.country_name ASC" is valid (if |
|
546 | + * "countries" is a table and "country_name" a column in that table, sure. |
|
547 | + * For instance, |
|
548 | + * $french_users = TDBMObject::getObjects("users", null, "countries.country_name ASC"); |
|
549 | + * will return all the users sorted by country. |
|
550 | + * - A OrderByColumn object |
|
551 | + * This object models a single column in a database. |
|
552 | + * |
|
553 | + * @param string $table_name The name of the table queried |
|
554 | + * @param mixed $filter_bag The filter bag (see above for complete description) |
|
555 | + * @param mixed $orderby_bag The order bag (see above for complete description) |
|
556 | + * @param int $from The offset |
|
557 | + * @param int $limit The maximum number of rows returned |
|
558 | + * @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. |
|
559 | + * @param unknown_type $hint_path Hints to get the path for the query (expert parameter, you should leave it to null). |
|
560 | + * |
|
561 | + * @return TDBMObjectArray A TDBMObjectArray containing the resulting objects of the query. |
|
562 | + */ |
|
563 | 563 | /* public function getObjects($table_name, $filter_bag=null, $orderby_bag=null, $from=null, $limit=null, $className=null, $hint_path=null) { |
564 | 564 | if ($this->connection == null) { |
565 | 565 | throw new TDBMException("Error while calling TDBMObject::getObject(): No connection has been established on the database!"); |
@@ -567,56 +567,56 @@ discard block |
||
567 | 567 | return $this->getObjectsByMode('getObjects', $table_name, $filter_bag, $orderby_bag, $from, $limit, $className, $hint_path); |
568 | 568 | }*/ |
569 | 569 | |
570 | - /** |
|
571 | - * Takes in input a filter_bag (which can be about anything from a string to an array of TDBMObjects... see above from documentation), |
|
572 | - * and gives back a proper Filter object. |
|
573 | - * |
|
574 | - * @param mixed $filter_bag |
|
575 | - * |
|
576 | - * @return array First item: filter string, second item: parameters. |
|
577 | - * |
|
578 | - * @throws TDBMException |
|
579 | - */ |
|
580 | - public function buildFilterFromFilterBag($filter_bag) |
|
581 | - { |
|
582 | - $counter = 1; |
|
583 | - if ($filter_bag === null) { |
|
584 | - return ['', []]; |
|
585 | - } elseif (is_string($filter_bag)) { |
|
586 | - return [$filter_bag, []]; |
|
587 | - } elseif (is_array($filter_bag)) { |
|
588 | - $sqlParts = []; |
|
589 | - $parameters = []; |
|
590 | - foreach ($filter_bag as $column => $value) { |
|
591 | - $paramName = 'tdbmparam'.$counter; |
|
592 | - if (is_array($value)) { |
|
593 | - $sqlParts[] = $this->connection->quoteIdentifier($column).' IN :'.$paramName; |
|
594 | - } else { |
|
595 | - $sqlParts[] = $this->connection->quoteIdentifier($column).' = :'.$paramName; |
|
596 | - } |
|
597 | - $parameters[$paramName] = $value; |
|
598 | - ++$counter; |
|
599 | - } |
|
600 | - |
|
601 | - return [implode(' AND ', $sqlParts), $parameters]; |
|
602 | - } elseif ($filter_bag instanceof AbstractTDBMObject) { |
|
603 | - $dbRows = $filter_bag->_getDbRows(); |
|
604 | - $dbRow = reset($dbRows); |
|
605 | - $primaryKeys = $dbRow->_getPrimaryKeys(); |
|
606 | - |
|
607 | - foreach ($primaryKeys as $column => $value) { |
|
608 | - $paramName = 'tdbmparam'.$counter; |
|
609 | - $sqlParts[] = $this->connection->quoteIdentifier($dbRow->_getDbTableName()).'.'.$this->connection->quoteIdentifier($column).' = :'.$paramName; |
|
610 | - $parameters[$paramName] = $value; |
|
611 | - ++$counter; |
|
612 | - } |
|
613 | - |
|
614 | - return [implode(' AND ', $sqlParts), $parameters]; |
|
615 | - } elseif ($filter_bag instanceof \Iterator) { |
|
616 | - return $this->buildFilterFromFilterBag(iterator_to_array($filter_bag)); |
|
617 | - } else { |
|
618 | - 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.'); |
|
619 | - } |
|
570 | + /** |
|
571 | + * Takes in input a filter_bag (which can be about anything from a string to an array of TDBMObjects... see above from documentation), |
|
572 | + * and gives back a proper Filter object. |
|
573 | + * |
|
574 | + * @param mixed $filter_bag |
|
575 | + * |
|
576 | + * @return array First item: filter string, second item: parameters. |
|
577 | + * |
|
578 | + * @throws TDBMException |
|
579 | + */ |
|
580 | + public function buildFilterFromFilterBag($filter_bag) |
|
581 | + { |
|
582 | + $counter = 1; |
|
583 | + if ($filter_bag === null) { |
|
584 | + return ['', []]; |
|
585 | + } elseif (is_string($filter_bag)) { |
|
586 | + return [$filter_bag, []]; |
|
587 | + } elseif (is_array($filter_bag)) { |
|
588 | + $sqlParts = []; |
|
589 | + $parameters = []; |
|
590 | + foreach ($filter_bag as $column => $value) { |
|
591 | + $paramName = 'tdbmparam'.$counter; |
|
592 | + if (is_array($value)) { |
|
593 | + $sqlParts[] = $this->connection->quoteIdentifier($column).' IN :'.$paramName; |
|
594 | + } else { |
|
595 | + $sqlParts[] = $this->connection->quoteIdentifier($column).' = :'.$paramName; |
|
596 | + } |
|
597 | + $parameters[$paramName] = $value; |
|
598 | + ++$counter; |
|
599 | + } |
|
600 | + |
|
601 | + return [implode(' AND ', $sqlParts), $parameters]; |
|
602 | + } elseif ($filter_bag instanceof AbstractTDBMObject) { |
|
603 | + $dbRows = $filter_bag->_getDbRows(); |
|
604 | + $dbRow = reset($dbRows); |
|
605 | + $primaryKeys = $dbRow->_getPrimaryKeys(); |
|
606 | + |
|
607 | + foreach ($primaryKeys as $column => $value) { |
|
608 | + $paramName = 'tdbmparam'.$counter; |
|
609 | + $sqlParts[] = $this->connection->quoteIdentifier($dbRow->_getDbTableName()).'.'.$this->connection->quoteIdentifier($column).' = :'.$paramName; |
|
610 | + $parameters[$paramName] = $value; |
|
611 | + ++$counter; |
|
612 | + } |
|
613 | + |
|
614 | + return [implode(' AND ', $sqlParts), $parameters]; |
|
615 | + } elseif ($filter_bag instanceof \Iterator) { |
|
616 | + return $this->buildFilterFromFilterBag(iterator_to_array($filter_bag)); |
|
617 | + } else { |
|
618 | + 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.'); |
|
619 | + } |
|
620 | 620 | |
621 | 621 | // // First filter_bag should be an array, if it is a singleton, let's put it in an array. |
622 | 622 | // if ($filter_bag === null) { |
@@ -673,55 +673,55 @@ discard block |
||
673 | 673 | // $filter = new AndFilter($filter_bag2); |
674 | 674 | // |
675 | 675 | // return $filter; |
676 | - } |
|
677 | - |
|
678 | - /** |
|
679 | - * Takes in input an order_bag (which can be about anything from a string to an array of OrderByColumn objects... see above from documentation), |
|
680 | - * and gives back an array of OrderByColumn / OrderBySQLString objects. |
|
681 | - * |
|
682 | - * @param unknown_type $orderby_bag |
|
683 | - * |
|
684 | - * @return array |
|
685 | - */ |
|
686 | - public function buildOrderArrayFromOrderBag($orderby_bag) |
|
687 | - { |
|
688 | - // Fourth, let's apply the same steps to the orderby_bag |
|
689 | - // 4-1 orderby_bag should be an array, if it is a singleton, let's put it in an array. |
|
690 | - |
|
691 | - if (!is_array($orderby_bag)) { |
|
692 | - $orderby_bag = array($orderby_bag); |
|
693 | - } |
|
694 | - |
|
695 | - // 4-2, let's take all the objects out of the orderby bag, and let's make objects from them |
|
696 | - $orderby_bag2 = array(); |
|
697 | - foreach ($orderby_bag as $thing) { |
|
698 | - if (is_a($thing, 'Mouf\\Database\\TDBM\\Filters\\OrderBySQLString')) { |
|
699 | - $orderby_bag2[] = $thing; |
|
700 | - } elseif (is_a($thing, 'Mouf\\Database\\TDBM\\Filters\\OrderByColumn')) { |
|
701 | - $orderby_bag2[] = $thing; |
|
702 | - } elseif (is_string($thing)) { |
|
703 | - $orderby_bag2[] = new OrderBySQLString($thing); |
|
704 | - } elseif ($thing !== null) { |
|
705 | - throw new TDBMException('Error in orderby bag in getObjectsByFilter. An object has been passed that is neither a OrderBySQLString, nor a OrderByColumn, nor a string, nor null.'); |
|
706 | - } |
|
707 | - } |
|
708 | - |
|
709 | - return $orderby_bag2; |
|
710 | - } |
|
711 | - |
|
712 | - /** |
|
713 | - * @param string $table |
|
714 | - * |
|
715 | - * @return string[] |
|
716 | - */ |
|
717 | - public function getPrimaryKeyColumns($table) |
|
718 | - { |
|
719 | - if (!isset($this->primaryKeysColumns[$table])) { |
|
720 | - $this->primaryKeysColumns[$table] = $this->tdbmSchemaAnalyzer->getSchema()->getTable($table)->getPrimaryKeyColumns(); |
|
721 | - |
|
722 | - // TODO TDBM4: See if we need to improve error reporting if table name does not exist. |
|
723 | - |
|
724 | - /*$arr = array(); |
|
676 | + } |
|
677 | + |
|
678 | + /** |
|
679 | + * Takes in input an order_bag (which can be about anything from a string to an array of OrderByColumn objects... see above from documentation), |
|
680 | + * and gives back an array of OrderByColumn / OrderBySQLString objects. |
|
681 | + * |
|
682 | + * @param unknown_type $orderby_bag |
|
683 | + * |
|
684 | + * @return array |
|
685 | + */ |
|
686 | + public function buildOrderArrayFromOrderBag($orderby_bag) |
|
687 | + { |
|
688 | + // Fourth, let's apply the same steps to the orderby_bag |
|
689 | + // 4-1 orderby_bag should be an array, if it is a singleton, let's put it in an array. |
|
690 | + |
|
691 | + if (!is_array($orderby_bag)) { |
|
692 | + $orderby_bag = array($orderby_bag); |
|
693 | + } |
|
694 | + |
|
695 | + // 4-2, let's take all the objects out of the orderby bag, and let's make objects from them |
|
696 | + $orderby_bag2 = array(); |
|
697 | + foreach ($orderby_bag as $thing) { |
|
698 | + if (is_a($thing, 'Mouf\\Database\\TDBM\\Filters\\OrderBySQLString')) { |
|
699 | + $orderby_bag2[] = $thing; |
|
700 | + } elseif (is_a($thing, 'Mouf\\Database\\TDBM\\Filters\\OrderByColumn')) { |
|
701 | + $orderby_bag2[] = $thing; |
|
702 | + } elseif (is_string($thing)) { |
|
703 | + $orderby_bag2[] = new OrderBySQLString($thing); |
|
704 | + } elseif ($thing !== null) { |
|
705 | + throw new TDBMException('Error in orderby bag in getObjectsByFilter. An object has been passed that is neither a OrderBySQLString, nor a OrderByColumn, nor a string, nor null.'); |
|
706 | + } |
|
707 | + } |
|
708 | + |
|
709 | + return $orderby_bag2; |
|
710 | + } |
|
711 | + |
|
712 | + /** |
|
713 | + * @param string $table |
|
714 | + * |
|
715 | + * @return string[] |
|
716 | + */ |
|
717 | + public function getPrimaryKeyColumns($table) |
|
718 | + { |
|
719 | + if (!isset($this->primaryKeysColumns[$table])) { |
|
720 | + $this->primaryKeysColumns[$table] = $this->tdbmSchemaAnalyzer->getSchema()->getTable($table)->getPrimaryKeyColumns(); |
|
721 | + |
|
722 | + // TODO TDBM4: See if we need to improve error reporting if table name does not exist. |
|
723 | + |
|
724 | + /*$arr = array(); |
|
725 | 725 | foreach ($this->connection->getPrimaryKey($table) as $col) { |
726 | 726 | $arr[] = $col->name; |
727 | 727 | } |
@@ -742,128 +742,128 @@ discard block |
||
742 | 742 | throw new TDBMException($str); |
743 | 743 | } |
744 | 744 | }*/ |
745 | - } |
|
746 | - |
|
747 | - return $this->primaryKeysColumns[$table]; |
|
748 | - } |
|
749 | - |
|
750 | - /** |
|
751 | - * This is an internal function, you should not use it in your application. |
|
752 | - * This is used internally by TDBM to add an object to the object cache. |
|
753 | - * |
|
754 | - * @param DbRow $dbRow |
|
755 | - */ |
|
756 | - public function _addToCache(DbRow $dbRow) |
|
757 | - { |
|
758 | - $primaryKey = $this->getPrimaryKeysForObjectFromDbRow($dbRow); |
|
759 | - $hash = $this->getObjectHash($primaryKey); |
|
760 | - $this->objectStorage->set($dbRow->_getDbTableName(), $hash, $dbRow); |
|
761 | - } |
|
762 | - |
|
763 | - /** |
|
764 | - * This is an internal function, you should not use it in your application. |
|
765 | - * This is used internally by TDBM to remove the object from the list of objects that have been |
|
766 | - * created/updated but not saved yet. |
|
767 | - * |
|
768 | - * @param DbRow $myObject |
|
769 | - */ |
|
770 | - private function removeFromToSaveObjectList(DbRow $myObject) |
|
771 | - { |
|
772 | - unset($this->toSaveObjects[$myObject]); |
|
773 | - } |
|
774 | - |
|
775 | - /** |
|
776 | - * This is an internal function, you should not use it in your application. |
|
777 | - * This is used internally by TDBM to add an object to the list of objects that have been |
|
778 | - * created/updated but not saved yet. |
|
779 | - * |
|
780 | - * @param AbstractTDBMObject $myObject |
|
781 | - */ |
|
782 | - public function _addToToSaveObjectList(DbRow $myObject) |
|
783 | - { |
|
784 | - $this->toSaveObjects[$myObject] = true; |
|
785 | - } |
|
786 | - |
|
787 | - /** |
|
788 | - * Generates all the daos and beans. |
|
789 | - * |
|
790 | - * @param string $daoFactoryClassName The classe name of the DAO factory |
|
791 | - * @param string $daonamespace The namespace for the DAOs, without trailing \ |
|
792 | - * @param string $beannamespace The Namespace for the beans, without trailing \ |
|
793 | - * @param bool $storeInUtc If the generated daos should store the date in UTC timezone instead of user's timezone. |
|
794 | - * |
|
795 | - * @return \string[] the list of tables |
|
796 | - */ |
|
797 | - public function generateAllDaosAndBeans($daoFactoryClassName, $daonamespace, $beannamespace, $storeInUtc) |
|
798 | - { |
|
799 | - $tdbmDaoGenerator = new TDBMDaoGenerator($this->schemaAnalyzer, $this->tdbmSchemaAnalyzer->getSchema(), $this->tdbmSchemaAnalyzer); |
|
800 | - |
|
801 | - return $tdbmDaoGenerator->generateAllDaosAndBeans($daoFactoryClassName, $daonamespace, $beannamespace, $storeInUtc); |
|
802 | - } |
|
803 | - |
|
804 | - /** |
|
805 | - * @param array<string, string> $tableToBeanMap |
|
806 | - */ |
|
807 | - public function setTableToBeanMap(array $tableToBeanMap) |
|
808 | - { |
|
809 | - $this->tableToBeanMap = $tableToBeanMap; |
|
810 | - } |
|
811 | - |
|
812 | - /** |
|
813 | - * Saves $object by INSERTing or UPDAT(E)ing it in the database. |
|
814 | - * |
|
815 | - * @param AbstractTDBMObject $object |
|
816 | - * |
|
817 | - * @throws TDBMException |
|
818 | - */ |
|
819 | - public function save(AbstractTDBMObject $object) |
|
820 | - { |
|
821 | - $status = $object->_getStatus(); |
|
822 | - |
|
823 | - // Let's attach this object if it is in detached state. |
|
824 | - if ($status === TDBMObjectStateEnum::STATE_DETACHED) { |
|
825 | - $object->_attach($this); |
|
826 | - $status = $object->_getStatus(); |
|
827 | - } |
|
828 | - |
|
829 | - if ($status === TDBMObjectStateEnum::STATE_NEW) { |
|
830 | - $dbRows = $object->_getDbRows(); |
|
831 | - |
|
832 | - $unindexedPrimaryKeys = array(); |
|
833 | - |
|
834 | - foreach ($dbRows as $dbRow) { |
|
835 | - $tableName = $dbRow->_getDbTableName(); |
|
836 | - |
|
837 | - $schema = $this->tdbmSchemaAnalyzer->getSchema(); |
|
838 | - $tableDescriptor = $schema->getTable($tableName); |
|
839 | - |
|
840 | - $primaryKeyColumns = $this->getPrimaryKeyColumns($tableName); |
|
841 | - |
|
842 | - if (empty($unindexedPrimaryKeys)) { |
|
843 | - $primaryKeys = $this->getPrimaryKeysForObjectFromDbRow($dbRow); |
|
844 | - } else { |
|
845 | - // First insert, the children must have the same primary key as the parent. |
|
846 | - $primaryKeys = $this->_getPrimaryKeysFromIndexedPrimaryKeys($tableName, $unindexedPrimaryKeys); |
|
847 | - $dbRow->_setPrimaryKeys($primaryKeys); |
|
848 | - } |
|
849 | - |
|
850 | - $references = $dbRow->_getReferences(); |
|
851 | - |
|
852 | - // Let's save all references in NEW or DETACHED state (we need their primary key) |
|
853 | - foreach ($references as $fkName => $reference) { |
|
854 | - $refStatus = $reference->_getStatus(); |
|
855 | - if ($refStatus === TDBMObjectStateEnum::STATE_NEW || $refStatus === TDBMObjectStateEnum::STATE_DETACHED) { |
|
856 | - $this->save($reference); |
|
857 | - } |
|
858 | - } |
|
859 | - |
|
860 | - $dbRowData = $dbRow->_getDbRow(); |
|
861 | - |
|
862 | - // Let's see if the columns for primary key have been set before inserting. |
|
863 | - // We assume that if one of the value of the PK has been set, the PK is set. |
|
864 | - $isPkSet = !empty($primaryKeys); |
|
865 | - |
|
866 | - /*if (!$isPkSet) { |
|
745 | + } |
|
746 | + |
|
747 | + return $this->primaryKeysColumns[$table]; |
|
748 | + } |
|
749 | + |
|
750 | + /** |
|
751 | + * This is an internal function, you should not use it in your application. |
|
752 | + * This is used internally by TDBM to add an object to the object cache. |
|
753 | + * |
|
754 | + * @param DbRow $dbRow |
|
755 | + */ |
|
756 | + public function _addToCache(DbRow $dbRow) |
|
757 | + { |
|
758 | + $primaryKey = $this->getPrimaryKeysForObjectFromDbRow($dbRow); |
|
759 | + $hash = $this->getObjectHash($primaryKey); |
|
760 | + $this->objectStorage->set($dbRow->_getDbTableName(), $hash, $dbRow); |
|
761 | + } |
|
762 | + |
|
763 | + /** |
|
764 | + * This is an internal function, you should not use it in your application. |
|
765 | + * This is used internally by TDBM to remove the object from the list of objects that have been |
|
766 | + * created/updated but not saved yet. |
|
767 | + * |
|
768 | + * @param DbRow $myObject |
|
769 | + */ |
|
770 | + private function removeFromToSaveObjectList(DbRow $myObject) |
|
771 | + { |
|
772 | + unset($this->toSaveObjects[$myObject]); |
|
773 | + } |
|
774 | + |
|
775 | + /** |
|
776 | + * This is an internal function, you should not use it in your application. |
|
777 | + * This is used internally by TDBM to add an object to the list of objects that have been |
|
778 | + * created/updated but not saved yet. |
|
779 | + * |
|
780 | + * @param AbstractTDBMObject $myObject |
|
781 | + */ |
|
782 | + public function _addToToSaveObjectList(DbRow $myObject) |
|
783 | + { |
|
784 | + $this->toSaveObjects[$myObject] = true; |
|
785 | + } |
|
786 | + |
|
787 | + /** |
|
788 | + * Generates all the daos and beans. |
|
789 | + * |
|
790 | + * @param string $daoFactoryClassName The classe name of the DAO factory |
|
791 | + * @param string $daonamespace The namespace for the DAOs, without trailing \ |
|
792 | + * @param string $beannamespace The Namespace for the beans, without trailing \ |
|
793 | + * @param bool $storeInUtc If the generated daos should store the date in UTC timezone instead of user's timezone. |
|
794 | + * |
|
795 | + * @return \string[] the list of tables |
|
796 | + */ |
|
797 | + public function generateAllDaosAndBeans($daoFactoryClassName, $daonamespace, $beannamespace, $storeInUtc) |
|
798 | + { |
|
799 | + $tdbmDaoGenerator = new TDBMDaoGenerator($this->schemaAnalyzer, $this->tdbmSchemaAnalyzer->getSchema(), $this->tdbmSchemaAnalyzer); |
|
800 | + |
|
801 | + return $tdbmDaoGenerator->generateAllDaosAndBeans($daoFactoryClassName, $daonamespace, $beannamespace, $storeInUtc); |
|
802 | + } |
|
803 | + |
|
804 | + /** |
|
805 | + * @param array<string, string> $tableToBeanMap |
|
806 | + */ |
|
807 | + public function setTableToBeanMap(array $tableToBeanMap) |
|
808 | + { |
|
809 | + $this->tableToBeanMap = $tableToBeanMap; |
|
810 | + } |
|
811 | + |
|
812 | + /** |
|
813 | + * Saves $object by INSERTing or UPDAT(E)ing it in the database. |
|
814 | + * |
|
815 | + * @param AbstractTDBMObject $object |
|
816 | + * |
|
817 | + * @throws TDBMException |
|
818 | + */ |
|
819 | + public function save(AbstractTDBMObject $object) |
|
820 | + { |
|
821 | + $status = $object->_getStatus(); |
|
822 | + |
|
823 | + // Let's attach this object if it is in detached state. |
|
824 | + if ($status === TDBMObjectStateEnum::STATE_DETACHED) { |
|
825 | + $object->_attach($this); |
|
826 | + $status = $object->_getStatus(); |
|
827 | + } |
|
828 | + |
|
829 | + if ($status === TDBMObjectStateEnum::STATE_NEW) { |
|
830 | + $dbRows = $object->_getDbRows(); |
|
831 | + |
|
832 | + $unindexedPrimaryKeys = array(); |
|
833 | + |
|
834 | + foreach ($dbRows as $dbRow) { |
|
835 | + $tableName = $dbRow->_getDbTableName(); |
|
836 | + |
|
837 | + $schema = $this->tdbmSchemaAnalyzer->getSchema(); |
|
838 | + $tableDescriptor = $schema->getTable($tableName); |
|
839 | + |
|
840 | + $primaryKeyColumns = $this->getPrimaryKeyColumns($tableName); |
|
841 | + |
|
842 | + if (empty($unindexedPrimaryKeys)) { |
|
843 | + $primaryKeys = $this->getPrimaryKeysForObjectFromDbRow($dbRow); |
|
844 | + } else { |
|
845 | + // First insert, the children must have the same primary key as the parent. |
|
846 | + $primaryKeys = $this->_getPrimaryKeysFromIndexedPrimaryKeys($tableName, $unindexedPrimaryKeys); |
|
847 | + $dbRow->_setPrimaryKeys($primaryKeys); |
|
848 | + } |
|
849 | + |
|
850 | + $references = $dbRow->_getReferences(); |
|
851 | + |
|
852 | + // Let's save all references in NEW or DETACHED state (we need their primary key) |
|
853 | + foreach ($references as $fkName => $reference) { |
|
854 | + $refStatus = $reference->_getStatus(); |
|
855 | + if ($refStatus === TDBMObjectStateEnum::STATE_NEW || $refStatus === TDBMObjectStateEnum::STATE_DETACHED) { |
|
856 | + $this->save($reference); |
|
857 | + } |
|
858 | + } |
|
859 | + |
|
860 | + $dbRowData = $dbRow->_getDbRow(); |
|
861 | + |
|
862 | + // Let's see if the columns for primary key have been set before inserting. |
|
863 | + // We assume that if one of the value of the PK has been set, the PK is set. |
|
864 | + $isPkSet = !empty($primaryKeys); |
|
865 | + |
|
866 | + /*if (!$isPkSet) { |
|
867 | 867 | // if there is no autoincrement and no pk set, let's go in error. |
868 | 868 | $isAutoIncrement = true; |
869 | 869 | |
@@ -881,25 +881,25 @@ discard block |
||
881 | 881 | |
882 | 882 | }*/ |
883 | 883 | |
884 | - $types = []; |
|
884 | + $types = []; |
|
885 | 885 | |
886 | - foreach ($dbRowData as $columnName => $value) { |
|
887 | - $columnDescriptor = $tableDescriptor->getColumn($columnName); |
|
888 | - $types[] = $columnDescriptor->getType(); |
|
889 | - } |
|
886 | + foreach ($dbRowData as $columnName => $value) { |
|
887 | + $columnDescriptor = $tableDescriptor->getColumn($columnName); |
|
888 | + $types[] = $columnDescriptor->getType(); |
|
889 | + } |
|
890 | 890 | |
891 | - $this->connection->insert($tableName, $dbRowData, $types); |
|
891 | + $this->connection->insert($tableName, $dbRowData, $types); |
|
892 | 892 | |
893 | - if (!$isPkSet && count($primaryKeyColumns) == 1) { |
|
894 | - $id = $this->connection->lastInsertId(); |
|
895 | - $primaryKeys[$primaryKeyColumns[0]] = $id; |
|
896 | - } |
|
893 | + if (!$isPkSet && count($primaryKeyColumns) == 1) { |
|
894 | + $id = $this->connection->lastInsertId(); |
|
895 | + $primaryKeys[$primaryKeyColumns[0]] = $id; |
|
896 | + } |
|
897 | 897 | |
898 | - // TODO: change this to some private magic accessor in future |
|
899 | - $dbRow->_setPrimaryKeys($primaryKeys); |
|
900 | - $unindexedPrimaryKeys = array_values($primaryKeys); |
|
898 | + // TODO: change this to some private magic accessor in future |
|
899 | + $dbRow->_setPrimaryKeys($primaryKeys); |
|
900 | + $unindexedPrimaryKeys = array_values($primaryKeys); |
|
901 | 901 | |
902 | - /* |
|
902 | + /* |
|
903 | 903 | * When attached, on "save", we check if the column updated is part of a primary key |
904 | 904 | * If this is part of a primary key, we call the _update_id method that updates the id in the list of known objects. |
905 | 905 | * This method should first verify that the id is not already used (and is not auto-incremented) |
@@ -909,7 +909,7 @@ discard block |
||
909 | 909 | * |
910 | 910 | */ |
911 | 911 | |
912 | - /*try { |
|
912 | + /*try { |
|
913 | 913 | $this->db_connection->exec($sql); |
914 | 914 | } catch (TDBMException $e) { |
915 | 915 | $this->db_onerror = true; |
@@ -928,391 +928,391 @@ discard block |
||
928 | 928 | } |
929 | 929 | }*/ |
930 | 930 | |
931 | - // Let's remove this object from the $new_objects static table. |
|
932 | - $this->removeFromToSaveObjectList($dbRow); |
|
933 | - |
|
934 | - // TODO: change this behaviour to something more sensible performance-wise |
|
935 | - // Maybe a setting to trigger this globally? |
|
936 | - //$this->status = TDBMObjectStateEnum::STATE_NOT_LOADED; |
|
937 | - //$this->db_modified_state = false; |
|
938 | - //$dbRow = array(); |
|
939 | - |
|
940 | - // Let's add this object to the list of objects in cache. |
|
941 | - $this->_addToCache($dbRow); |
|
942 | - } |
|
943 | - |
|
944 | - $object->_setStatus(TDBMObjectStateEnum::STATE_LOADED); |
|
945 | - } elseif ($status === TDBMObjectStateEnum::STATE_DIRTY) { |
|
946 | - $dbRows = $object->_getDbRows(); |
|
947 | - |
|
948 | - foreach ($dbRows as $dbRow) { |
|
949 | - $references = $dbRow->_getReferences(); |
|
950 | - |
|
951 | - // Let's save all references in NEW state (we need their primary key) |
|
952 | - foreach ($references as $fkName => $reference) { |
|
953 | - if ($reference->_getStatus() === TDBMObjectStateEnum::STATE_NEW) { |
|
954 | - $this->save($reference); |
|
955 | - } |
|
956 | - } |
|
957 | - |
|
958 | - // Let's first get the primary keys |
|
959 | - $tableName = $dbRow->_getDbTableName(); |
|
960 | - $dbRowData = $dbRow->_getDbRow(); |
|
961 | - |
|
962 | - $schema = $this->tdbmSchemaAnalyzer->getSchema(); |
|
963 | - $tableDescriptor = $schema->getTable($tableName); |
|
964 | - |
|
965 | - $primaryKeys = $dbRow->_getPrimaryKeys(); |
|
966 | - |
|
967 | - $types = []; |
|
968 | - |
|
969 | - foreach ($dbRowData as $columnName => $value) { |
|
970 | - $columnDescriptor = $tableDescriptor->getColumn($columnName); |
|
971 | - $types[] = $columnDescriptor->getType(); |
|
972 | - } |
|
973 | - foreach ($primaryKeys as $columnName => $value) { |
|
974 | - $columnDescriptor = $tableDescriptor->getColumn($columnName); |
|
975 | - $types[] = $columnDescriptor->getType(); |
|
976 | - } |
|
977 | - |
|
978 | - $this->connection->update($tableName, $dbRowData, $primaryKeys, $types); |
|
979 | - |
|
980 | - // Let's check if the primary key has been updated... |
|
981 | - $needsUpdatePk = false; |
|
982 | - foreach ($primaryKeys as $column => $value) { |
|
983 | - if (!isset($dbRowData[$column]) || $dbRowData[$column] != $value) { |
|
984 | - $needsUpdatePk = true; |
|
985 | - break; |
|
986 | - } |
|
987 | - } |
|
988 | - if ($needsUpdatePk) { |
|
989 | - $this->objectStorage->remove($tableName, $this->getObjectHash($primaryKeys)); |
|
990 | - $newPrimaryKeys = $this->getPrimaryKeysForObjectFromDbRow($dbRow); |
|
991 | - $dbRow->_setPrimaryKeys($newPrimaryKeys); |
|
992 | - $this->objectStorage->set($tableName, $this->getObjectHash($primaryKeys), $dbRow); |
|
993 | - } |
|
994 | - |
|
995 | - // Let's remove this object from the list of objects to save. |
|
996 | - $this->removeFromToSaveObjectList($dbRow); |
|
997 | - } |
|
998 | - |
|
999 | - $object->_setStatus(TDBMObjectStateEnum::STATE_LOADED); |
|
1000 | - } elseif ($status === TDBMObjectStateEnum::STATE_DELETED) { |
|
1001 | - throw new TDBMInvalidOperationException('This object has been deleted. It cannot be saved.'); |
|
1002 | - } |
|
1003 | - |
|
1004 | - // Finally, let's save all the many to many relationships to this bean. |
|
1005 | - $this->persistManyToManyRelationships($object); |
|
1006 | - } |
|
1007 | - |
|
1008 | - private function persistManyToManyRelationships(AbstractTDBMObject $object) |
|
1009 | - { |
|
1010 | - foreach ($object->_getCachedRelationships() as $pivotTableName => $storage) { |
|
1011 | - $tableDescriptor = $this->tdbmSchemaAnalyzer->getSchema()->getTable($pivotTableName); |
|
1012 | - list($localFk, $remoteFk) = $this->getPivotTableForeignKeys($pivotTableName, $object); |
|
1013 | - |
|
1014 | - foreach ($storage as $remoteBean) { |
|
1015 | - /* @var $remoteBean AbstractTDBMObject */ |
|
1016 | - $statusArr = $storage[$remoteBean]; |
|
1017 | - $status = $statusArr['status']; |
|
1018 | - $reverse = $statusArr['reverse']; |
|
1019 | - if ($reverse) { |
|
1020 | - continue; |
|
1021 | - } |
|
1022 | - |
|
1023 | - if ($status === 'new') { |
|
1024 | - $remoteBeanStatus = $remoteBean->_getStatus(); |
|
1025 | - if ($remoteBeanStatus === TDBMObjectStateEnum::STATE_NEW || $remoteBeanStatus === TDBMObjectStateEnum::STATE_DETACHED) { |
|
1026 | - // Let's save remote bean if needed. |
|
1027 | - $this->save($remoteBean); |
|
1028 | - } |
|
1029 | - |
|
1030 | - $filters = $this->getPivotFilters($object, $remoteBean, $localFk, $remoteFk); |
|
1031 | - |
|
1032 | - $types = []; |
|
1033 | - |
|
1034 | - foreach ($filters as $columnName => $value) { |
|
1035 | - $columnDescriptor = $tableDescriptor->getColumn($columnName); |
|
1036 | - $types[] = $columnDescriptor->getType(); |
|
1037 | - } |
|
1038 | - |
|
1039 | - $this->connection->insert($pivotTableName, $filters, $types); |
|
1040 | - |
|
1041 | - // Finally, let's mark relationships as saved. |
|
1042 | - $statusArr['status'] = 'loaded'; |
|
1043 | - $storage[$remoteBean] = $statusArr; |
|
1044 | - $remoteStorage = $remoteBean->_getCachedRelationships()[$pivotTableName]; |
|
1045 | - $remoteStatusArr = $remoteStorage[$object]; |
|
1046 | - $remoteStatusArr['status'] = 'loaded'; |
|
1047 | - $remoteStorage[$object] = $remoteStatusArr; |
|
1048 | - } elseif ($status === 'delete') { |
|
1049 | - $filters = $this->getPivotFilters($object, $remoteBean, $localFk, $remoteFk); |
|
1050 | - |
|
1051 | - $types = []; |
|
1052 | - |
|
1053 | - foreach ($filters as $columnName => $value) { |
|
1054 | - $columnDescriptor = $tableDescriptor->getColumn($columnName); |
|
1055 | - $types[] = $columnDescriptor->getType(); |
|
1056 | - } |
|
1057 | - |
|
1058 | - $this->connection->delete($pivotTableName, $filters, $types); |
|
1059 | - |
|
1060 | - // Finally, let's remove relationships completely from bean. |
|
1061 | - $storage->detach($remoteBean); |
|
1062 | - $remoteBean->_getCachedRelationships()[$pivotTableName]->detach($object); |
|
1063 | - } |
|
1064 | - } |
|
1065 | - } |
|
1066 | - } |
|
1067 | - |
|
1068 | - private function getPivotFilters(AbstractTDBMObject $localBean, AbstractTDBMObject $remoteBean, ForeignKeyConstraint $localFk, ForeignKeyConstraint $remoteFk) |
|
1069 | - { |
|
1070 | - $localBeanPk = $this->getPrimaryKeyValues($localBean); |
|
1071 | - $remoteBeanPk = $this->getPrimaryKeyValues($remoteBean); |
|
1072 | - $localColumns = $localFk->getLocalColumns(); |
|
1073 | - $remoteColumns = $remoteFk->getLocalColumns(); |
|
1074 | - |
|
1075 | - $localFilters = array_combine($localColumns, $localBeanPk); |
|
1076 | - $remoteFilters = array_combine($remoteColumns, $remoteBeanPk); |
|
1077 | - |
|
1078 | - return array_merge($localFilters, $remoteFilters); |
|
1079 | - } |
|
1080 | - |
|
1081 | - /** |
|
1082 | - * Returns the "values" of the primary key. |
|
1083 | - * This returns the primary key from the $primaryKey attribute, not the one stored in the columns. |
|
1084 | - * |
|
1085 | - * @param AbstractTDBMObject $bean |
|
1086 | - * |
|
1087 | - * @return array numerically indexed array of values. |
|
1088 | - */ |
|
1089 | - private function getPrimaryKeyValues(AbstractTDBMObject $bean) |
|
1090 | - { |
|
1091 | - $dbRows = $bean->_getDbRows(); |
|
1092 | - $dbRow = reset($dbRows); |
|
1093 | - |
|
1094 | - return array_values($dbRow->_getPrimaryKeys()); |
|
1095 | - } |
|
1096 | - |
|
1097 | - /** |
|
1098 | - * Returns a unique hash used to store the object based on its primary key. |
|
1099 | - * If the array contains only one value, then the value is returned. |
|
1100 | - * Otherwise, a hash representing the array is returned. |
|
1101 | - * |
|
1102 | - * @param array $primaryKeys An array of columns => values forming the primary key |
|
1103 | - * |
|
1104 | - * @return string |
|
1105 | - */ |
|
1106 | - public function getObjectHash(array $primaryKeys) |
|
1107 | - { |
|
1108 | - if (count($primaryKeys) === 1) { |
|
1109 | - return reset($primaryKeys); |
|
1110 | - } else { |
|
1111 | - ksort($primaryKeys); |
|
1112 | - |
|
1113 | - return md5(json_encode($primaryKeys)); |
|
1114 | - } |
|
1115 | - } |
|
1116 | - |
|
1117 | - /** |
|
1118 | - * Returns an array of primary keys from the object. |
|
1119 | - * The primary keys are extracted from the object columns and not from the primary keys stored in the |
|
1120 | - * $primaryKeys variable of the object. |
|
1121 | - * |
|
1122 | - * @param DbRow $dbRow |
|
1123 | - * |
|
1124 | - * @return array Returns an array of column => value |
|
1125 | - */ |
|
1126 | - public function getPrimaryKeysForObjectFromDbRow(DbRow $dbRow) |
|
1127 | - { |
|
1128 | - $table = $dbRow->_getDbTableName(); |
|
1129 | - $dbRowData = $dbRow->_getDbRow(); |
|
1130 | - |
|
1131 | - return $this->_getPrimaryKeysFromObjectData($table, $dbRowData); |
|
1132 | - } |
|
1133 | - |
|
1134 | - /** |
|
1135 | - * Returns an array of primary keys for the given row. |
|
1136 | - * The primary keys are extracted from the object columns. |
|
1137 | - * |
|
1138 | - * @param $table |
|
1139 | - * @param array $columns |
|
1140 | - * |
|
1141 | - * @return array |
|
1142 | - */ |
|
1143 | - public function _getPrimaryKeysFromObjectData($table, array $columns) |
|
1144 | - { |
|
1145 | - $primaryKeyColumns = $this->getPrimaryKeyColumns($table); |
|
1146 | - $values = array(); |
|
1147 | - foreach ($primaryKeyColumns as $column) { |
|
1148 | - if (isset($columns[$column])) { |
|
1149 | - $values[$column] = $columns[$column]; |
|
1150 | - } |
|
1151 | - } |
|
1152 | - |
|
1153 | - return $values; |
|
1154 | - } |
|
1155 | - |
|
1156 | - /** |
|
1157 | - * Attaches $object to this TDBMService. |
|
1158 | - * The $object must be in DETACHED state and will pass in NEW state. |
|
1159 | - * |
|
1160 | - * @param AbstractTDBMObject $object |
|
1161 | - * |
|
1162 | - * @throws TDBMInvalidOperationException |
|
1163 | - */ |
|
1164 | - public function attach(AbstractTDBMObject $object) |
|
1165 | - { |
|
1166 | - $object->_attach($this); |
|
1167 | - } |
|
1168 | - |
|
1169 | - /** |
|
1170 | - * Returns an associative array (column => value) for the primary keys from the table name and an |
|
1171 | - * indexed array of primary key values. |
|
1172 | - * |
|
1173 | - * @param string $tableName |
|
1174 | - * @param array $indexedPrimaryKeys |
|
1175 | - */ |
|
1176 | - public function _getPrimaryKeysFromIndexedPrimaryKeys($tableName, array $indexedPrimaryKeys) |
|
1177 | - { |
|
1178 | - $primaryKeyColumns = $this->tdbmSchemaAnalyzer->getSchema()->getTable($tableName)->getPrimaryKeyColumns(); |
|
1179 | - |
|
1180 | - if (count($primaryKeyColumns) !== count($indexedPrimaryKeys)) { |
|
1181 | - throw new TDBMException(sprintf('Wrong number of columns passed for primary key. Expected %s columns for table "%s", |
|
931 | + // Let's remove this object from the $new_objects static table. |
|
932 | + $this->removeFromToSaveObjectList($dbRow); |
|
933 | + |
|
934 | + // TODO: change this behaviour to something more sensible performance-wise |
|
935 | + // Maybe a setting to trigger this globally? |
|
936 | + //$this->status = TDBMObjectStateEnum::STATE_NOT_LOADED; |
|
937 | + //$this->db_modified_state = false; |
|
938 | + //$dbRow = array(); |
|
939 | + |
|
940 | + // Let's add this object to the list of objects in cache. |
|
941 | + $this->_addToCache($dbRow); |
|
942 | + } |
|
943 | + |
|
944 | + $object->_setStatus(TDBMObjectStateEnum::STATE_LOADED); |
|
945 | + } elseif ($status === TDBMObjectStateEnum::STATE_DIRTY) { |
|
946 | + $dbRows = $object->_getDbRows(); |
|
947 | + |
|
948 | + foreach ($dbRows as $dbRow) { |
|
949 | + $references = $dbRow->_getReferences(); |
|
950 | + |
|
951 | + // Let's save all references in NEW state (we need their primary key) |
|
952 | + foreach ($references as $fkName => $reference) { |
|
953 | + if ($reference->_getStatus() === TDBMObjectStateEnum::STATE_NEW) { |
|
954 | + $this->save($reference); |
|
955 | + } |
|
956 | + } |
|
957 | + |
|
958 | + // Let's first get the primary keys |
|
959 | + $tableName = $dbRow->_getDbTableName(); |
|
960 | + $dbRowData = $dbRow->_getDbRow(); |
|
961 | + |
|
962 | + $schema = $this->tdbmSchemaAnalyzer->getSchema(); |
|
963 | + $tableDescriptor = $schema->getTable($tableName); |
|
964 | + |
|
965 | + $primaryKeys = $dbRow->_getPrimaryKeys(); |
|
966 | + |
|
967 | + $types = []; |
|
968 | + |
|
969 | + foreach ($dbRowData as $columnName => $value) { |
|
970 | + $columnDescriptor = $tableDescriptor->getColumn($columnName); |
|
971 | + $types[] = $columnDescriptor->getType(); |
|
972 | + } |
|
973 | + foreach ($primaryKeys as $columnName => $value) { |
|
974 | + $columnDescriptor = $tableDescriptor->getColumn($columnName); |
|
975 | + $types[] = $columnDescriptor->getType(); |
|
976 | + } |
|
977 | + |
|
978 | + $this->connection->update($tableName, $dbRowData, $primaryKeys, $types); |
|
979 | + |
|
980 | + // Let's check if the primary key has been updated... |
|
981 | + $needsUpdatePk = false; |
|
982 | + foreach ($primaryKeys as $column => $value) { |
|
983 | + if (!isset($dbRowData[$column]) || $dbRowData[$column] != $value) { |
|
984 | + $needsUpdatePk = true; |
|
985 | + break; |
|
986 | + } |
|
987 | + } |
|
988 | + if ($needsUpdatePk) { |
|
989 | + $this->objectStorage->remove($tableName, $this->getObjectHash($primaryKeys)); |
|
990 | + $newPrimaryKeys = $this->getPrimaryKeysForObjectFromDbRow($dbRow); |
|
991 | + $dbRow->_setPrimaryKeys($newPrimaryKeys); |
|
992 | + $this->objectStorage->set($tableName, $this->getObjectHash($primaryKeys), $dbRow); |
|
993 | + } |
|
994 | + |
|
995 | + // Let's remove this object from the list of objects to save. |
|
996 | + $this->removeFromToSaveObjectList($dbRow); |
|
997 | + } |
|
998 | + |
|
999 | + $object->_setStatus(TDBMObjectStateEnum::STATE_LOADED); |
|
1000 | + } elseif ($status === TDBMObjectStateEnum::STATE_DELETED) { |
|
1001 | + throw new TDBMInvalidOperationException('This object has been deleted. It cannot be saved.'); |
|
1002 | + } |
|
1003 | + |
|
1004 | + // Finally, let's save all the many to many relationships to this bean. |
|
1005 | + $this->persistManyToManyRelationships($object); |
|
1006 | + } |
|
1007 | + |
|
1008 | + private function persistManyToManyRelationships(AbstractTDBMObject $object) |
|
1009 | + { |
|
1010 | + foreach ($object->_getCachedRelationships() as $pivotTableName => $storage) { |
|
1011 | + $tableDescriptor = $this->tdbmSchemaAnalyzer->getSchema()->getTable($pivotTableName); |
|
1012 | + list($localFk, $remoteFk) = $this->getPivotTableForeignKeys($pivotTableName, $object); |
|
1013 | + |
|
1014 | + foreach ($storage as $remoteBean) { |
|
1015 | + /* @var $remoteBean AbstractTDBMObject */ |
|
1016 | + $statusArr = $storage[$remoteBean]; |
|
1017 | + $status = $statusArr['status']; |
|
1018 | + $reverse = $statusArr['reverse']; |
|
1019 | + if ($reverse) { |
|
1020 | + continue; |
|
1021 | + } |
|
1022 | + |
|
1023 | + if ($status === 'new') { |
|
1024 | + $remoteBeanStatus = $remoteBean->_getStatus(); |
|
1025 | + if ($remoteBeanStatus === TDBMObjectStateEnum::STATE_NEW || $remoteBeanStatus === TDBMObjectStateEnum::STATE_DETACHED) { |
|
1026 | + // Let's save remote bean if needed. |
|
1027 | + $this->save($remoteBean); |
|
1028 | + } |
|
1029 | + |
|
1030 | + $filters = $this->getPivotFilters($object, $remoteBean, $localFk, $remoteFk); |
|
1031 | + |
|
1032 | + $types = []; |
|
1033 | + |
|
1034 | + foreach ($filters as $columnName => $value) { |
|
1035 | + $columnDescriptor = $tableDescriptor->getColumn($columnName); |
|
1036 | + $types[] = $columnDescriptor->getType(); |
|
1037 | + } |
|
1038 | + |
|
1039 | + $this->connection->insert($pivotTableName, $filters, $types); |
|
1040 | + |
|
1041 | + // Finally, let's mark relationships as saved. |
|
1042 | + $statusArr['status'] = 'loaded'; |
|
1043 | + $storage[$remoteBean] = $statusArr; |
|
1044 | + $remoteStorage = $remoteBean->_getCachedRelationships()[$pivotTableName]; |
|
1045 | + $remoteStatusArr = $remoteStorage[$object]; |
|
1046 | + $remoteStatusArr['status'] = 'loaded'; |
|
1047 | + $remoteStorage[$object] = $remoteStatusArr; |
|
1048 | + } elseif ($status === 'delete') { |
|
1049 | + $filters = $this->getPivotFilters($object, $remoteBean, $localFk, $remoteFk); |
|
1050 | + |
|
1051 | + $types = []; |
|
1052 | + |
|
1053 | + foreach ($filters as $columnName => $value) { |
|
1054 | + $columnDescriptor = $tableDescriptor->getColumn($columnName); |
|
1055 | + $types[] = $columnDescriptor->getType(); |
|
1056 | + } |
|
1057 | + |
|
1058 | + $this->connection->delete($pivotTableName, $filters, $types); |
|
1059 | + |
|
1060 | + // Finally, let's remove relationships completely from bean. |
|
1061 | + $storage->detach($remoteBean); |
|
1062 | + $remoteBean->_getCachedRelationships()[$pivotTableName]->detach($object); |
|
1063 | + } |
|
1064 | + } |
|
1065 | + } |
|
1066 | + } |
|
1067 | + |
|
1068 | + private function getPivotFilters(AbstractTDBMObject $localBean, AbstractTDBMObject $remoteBean, ForeignKeyConstraint $localFk, ForeignKeyConstraint $remoteFk) |
|
1069 | + { |
|
1070 | + $localBeanPk = $this->getPrimaryKeyValues($localBean); |
|
1071 | + $remoteBeanPk = $this->getPrimaryKeyValues($remoteBean); |
|
1072 | + $localColumns = $localFk->getLocalColumns(); |
|
1073 | + $remoteColumns = $remoteFk->getLocalColumns(); |
|
1074 | + |
|
1075 | + $localFilters = array_combine($localColumns, $localBeanPk); |
|
1076 | + $remoteFilters = array_combine($remoteColumns, $remoteBeanPk); |
|
1077 | + |
|
1078 | + return array_merge($localFilters, $remoteFilters); |
|
1079 | + } |
|
1080 | + |
|
1081 | + /** |
|
1082 | + * Returns the "values" of the primary key. |
|
1083 | + * This returns the primary key from the $primaryKey attribute, not the one stored in the columns. |
|
1084 | + * |
|
1085 | + * @param AbstractTDBMObject $bean |
|
1086 | + * |
|
1087 | + * @return array numerically indexed array of values. |
|
1088 | + */ |
|
1089 | + private function getPrimaryKeyValues(AbstractTDBMObject $bean) |
|
1090 | + { |
|
1091 | + $dbRows = $bean->_getDbRows(); |
|
1092 | + $dbRow = reset($dbRows); |
|
1093 | + |
|
1094 | + return array_values($dbRow->_getPrimaryKeys()); |
|
1095 | + } |
|
1096 | + |
|
1097 | + /** |
|
1098 | + * Returns a unique hash used to store the object based on its primary key. |
|
1099 | + * If the array contains only one value, then the value is returned. |
|
1100 | + * Otherwise, a hash representing the array is returned. |
|
1101 | + * |
|
1102 | + * @param array $primaryKeys An array of columns => values forming the primary key |
|
1103 | + * |
|
1104 | + * @return string |
|
1105 | + */ |
|
1106 | + public function getObjectHash(array $primaryKeys) |
|
1107 | + { |
|
1108 | + if (count($primaryKeys) === 1) { |
|
1109 | + return reset($primaryKeys); |
|
1110 | + } else { |
|
1111 | + ksort($primaryKeys); |
|
1112 | + |
|
1113 | + return md5(json_encode($primaryKeys)); |
|
1114 | + } |
|
1115 | + } |
|
1116 | + |
|
1117 | + /** |
|
1118 | + * Returns an array of primary keys from the object. |
|
1119 | + * The primary keys are extracted from the object columns and not from the primary keys stored in the |
|
1120 | + * $primaryKeys variable of the object. |
|
1121 | + * |
|
1122 | + * @param DbRow $dbRow |
|
1123 | + * |
|
1124 | + * @return array Returns an array of column => value |
|
1125 | + */ |
|
1126 | + public function getPrimaryKeysForObjectFromDbRow(DbRow $dbRow) |
|
1127 | + { |
|
1128 | + $table = $dbRow->_getDbTableName(); |
|
1129 | + $dbRowData = $dbRow->_getDbRow(); |
|
1130 | + |
|
1131 | + return $this->_getPrimaryKeysFromObjectData($table, $dbRowData); |
|
1132 | + } |
|
1133 | + |
|
1134 | + /** |
|
1135 | + * Returns an array of primary keys for the given row. |
|
1136 | + * The primary keys are extracted from the object columns. |
|
1137 | + * |
|
1138 | + * @param $table |
|
1139 | + * @param array $columns |
|
1140 | + * |
|
1141 | + * @return array |
|
1142 | + */ |
|
1143 | + public function _getPrimaryKeysFromObjectData($table, array $columns) |
|
1144 | + { |
|
1145 | + $primaryKeyColumns = $this->getPrimaryKeyColumns($table); |
|
1146 | + $values = array(); |
|
1147 | + foreach ($primaryKeyColumns as $column) { |
|
1148 | + if (isset($columns[$column])) { |
|
1149 | + $values[$column] = $columns[$column]; |
|
1150 | + } |
|
1151 | + } |
|
1152 | + |
|
1153 | + return $values; |
|
1154 | + } |
|
1155 | + |
|
1156 | + /** |
|
1157 | + * Attaches $object to this TDBMService. |
|
1158 | + * The $object must be in DETACHED state and will pass in NEW state. |
|
1159 | + * |
|
1160 | + * @param AbstractTDBMObject $object |
|
1161 | + * |
|
1162 | + * @throws TDBMInvalidOperationException |
|
1163 | + */ |
|
1164 | + public function attach(AbstractTDBMObject $object) |
|
1165 | + { |
|
1166 | + $object->_attach($this); |
|
1167 | + } |
|
1168 | + |
|
1169 | + /** |
|
1170 | + * Returns an associative array (column => value) for the primary keys from the table name and an |
|
1171 | + * indexed array of primary key values. |
|
1172 | + * |
|
1173 | + * @param string $tableName |
|
1174 | + * @param array $indexedPrimaryKeys |
|
1175 | + */ |
|
1176 | + public function _getPrimaryKeysFromIndexedPrimaryKeys($tableName, array $indexedPrimaryKeys) |
|
1177 | + { |
|
1178 | + $primaryKeyColumns = $this->tdbmSchemaAnalyzer->getSchema()->getTable($tableName)->getPrimaryKeyColumns(); |
|
1179 | + |
|
1180 | + if (count($primaryKeyColumns) !== count($indexedPrimaryKeys)) { |
|
1181 | + throw new TDBMException(sprintf('Wrong number of columns passed for primary key. Expected %s columns for table "%s", |
|
1182 | 1182 | got %s instead.', count($primaryKeyColumns), $tableName, count($indexedPrimaryKeys))); |
1183 | - } |
|
1184 | - |
|
1185 | - return array_combine($primaryKeyColumns, $indexedPrimaryKeys); |
|
1186 | - } |
|
1187 | - |
|
1188 | - /** |
|
1189 | - * Return the list of tables (from child to parent) joining the tables passed in parameter. |
|
1190 | - * Tables must be in a single line of inheritance. The method will find missing tables. |
|
1191 | - * |
|
1192 | - * Algorithm: one of those tables is the ultimate child. From this child, by recursively getting the parent, |
|
1193 | - * we must be able to find all other tables. |
|
1194 | - * |
|
1195 | - * @param string[] $tables |
|
1196 | - * |
|
1197 | - * @return string[] |
|
1198 | - */ |
|
1199 | - public function _getLinkBetweenInheritedTables(array $tables) |
|
1200 | - { |
|
1201 | - sort($tables); |
|
1202 | - |
|
1203 | - return $this->fromCache($this->cachePrefix.'_linkbetweeninheritedtables_'.implode('__split__', $tables), |
|
1204 | - function () use ($tables) { |
|
1205 | - return $this->_getLinkBetweenInheritedTablesWithoutCache($tables); |
|
1206 | - }); |
|
1207 | - } |
|
1208 | - |
|
1209 | - /** |
|
1210 | - * Return the list of tables (from child to parent) joining the tables passed in parameter. |
|
1211 | - * Tables must be in a single line of inheritance. The method will find missing tables. |
|
1212 | - * |
|
1213 | - * Algorithm: one of those tables is the ultimate child. From this child, by recursively getting the parent, |
|
1214 | - * we must be able to find all other tables. |
|
1215 | - * |
|
1216 | - * @param string[] $tables |
|
1217 | - * |
|
1218 | - * @return string[] |
|
1219 | - */ |
|
1220 | - private function _getLinkBetweenInheritedTablesWithoutCache(array $tables) |
|
1221 | - { |
|
1222 | - $schemaAnalyzer = $this->schemaAnalyzer; |
|
1223 | - |
|
1224 | - foreach ($tables as $currentTable) { |
|
1225 | - $allParents = [$currentTable]; |
|
1226 | - $currentFk = null; |
|
1227 | - while ($currentFk = $schemaAnalyzer->getParentRelationship($currentTable)) { |
|
1228 | - $currentTable = $currentFk->getForeignTableName(); |
|
1229 | - $allParents[] = $currentTable; |
|
1230 | - }; |
|
1231 | - |
|
1232 | - // Now, does the $allParents contain all the tables we want? |
|
1233 | - $notFoundTables = array_diff($tables, $allParents); |
|
1234 | - if (empty($notFoundTables)) { |
|
1235 | - // We have a winner! |
|
1236 | - return $allParents; |
|
1237 | - } |
|
1238 | - } |
|
1239 | - |
|
1240 | - throw new TDBMException(sprintf('The tables (%s) cannot be linked by an inheritance relationship.', implode(', ', $tables))); |
|
1241 | - } |
|
1242 | - |
|
1243 | - /** |
|
1244 | - * Returns the list of tables related to this table (via a parent or child inheritance relationship). |
|
1245 | - * |
|
1246 | - * @param string $table |
|
1247 | - * |
|
1248 | - * @return string[] |
|
1249 | - */ |
|
1250 | - public function _getRelatedTablesByInheritance($table) |
|
1251 | - { |
|
1252 | - return $this->fromCache($this->cachePrefix.'_relatedtables_'.$table, function () use ($table) { |
|
1253 | - return $this->_getRelatedTablesByInheritanceWithoutCache($table); |
|
1254 | - }); |
|
1255 | - } |
|
1256 | - |
|
1257 | - /** |
|
1258 | - * Returns the list of tables related to this table (via a parent or child inheritance relationship). |
|
1259 | - * |
|
1260 | - * @param string $table |
|
1261 | - * |
|
1262 | - * @return string[] |
|
1263 | - */ |
|
1264 | - private function _getRelatedTablesByInheritanceWithoutCache($table) |
|
1265 | - { |
|
1266 | - $schemaAnalyzer = $this->schemaAnalyzer; |
|
1267 | - |
|
1268 | - // Let's scan the parent tables |
|
1269 | - $currentTable = $table; |
|
1270 | - |
|
1271 | - $parentTables = []; |
|
1272 | - |
|
1273 | - // Get parent relationship |
|
1274 | - while ($currentFk = $schemaAnalyzer->getParentRelationship($currentTable)) { |
|
1275 | - $currentTable = $currentFk->getForeignTableName(); |
|
1276 | - $parentTables[] = $currentTable; |
|
1277 | - }; |
|
1278 | - |
|
1279 | - // Let's recurse in children |
|
1280 | - $childrenTables = $this->exploreChildrenTablesRelationships($schemaAnalyzer, $table); |
|
1281 | - |
|
1282 | - return array_merge(array_reverse($parentTables), $childrenTables); |
|
1283 | - } |
|
1284 | - |
|
1285 | - /** |
|
1286 | - * Explore all the children and descendant of $table and returns ForeignKeyConstraints on those. |
|
1287 | - * |
|
1288 | - * @param string $table |
|
1289 | - * |
|
1290 | - * @return string[] |
|
1291 | - */ |
|
1292 | - private function exploreChildrenTablesRelationships(SchemaAnalyzer $schemaAnalyzer, $table) |
|
1293 | - { |
|
1294 | - $tables = [$table]; |
|
1295 | - $keys = $schemaAnalyzer->getChildrenRelationships($table); |
|
1296 | - |
|
1297 | - foreach ($keys as $key) { |
|
1298 | - $tables = array_merge($tables, $this->exploreChildrenTablesRelationships($schemaAnalyzer, $key->getLocalTableName())); |
|
1299 | - } |
|
1300 | - |
|
1301 | - return $tables; |
|
1302 | - } |
|
1303 | - |
|
1304 | - /** |
|
1305 | - * Casts a foreign key into SQL, assuming table name is used with no alias. |
|
1306 | - * The returned value does contain only one table. For instance:. |
|
1307 | - * |
|
1308 | - * " LEFT JOIN table2 ON table1.id = table2.table1_id" |
|
1309 | - * |
|
1310 | - * @param ForeignKeyConstraint $fk |
|
1311 | - * @param bool $leftTableIsLocal |
|
1312 | - * |
|
1313 | - * @return string |
|
1314 | - */ |
|
1315 | - /*private function foreignKeyToSql(ForeignKeyConstraint $fk, $leftTableIsLocal) { |
|
1183 | + } |
|
1184 | + |
|
1185 | + return array_combine($primaryKeyColumns, $indexedPrimaryKeys); |
|
1186 | + } |
|
1187 | + |
|
1188 | + /** |
|
1189 | + * Return the list of tables (from child to parent) joining the tables passed in parameter. |
|
1190 | + * Tables must be in a single line of inheritance. The method will find missing tables. |
|
1191 | + * |
|
1192 | + * Algorithm: one of those tables is the ultimate child. From this child, by recursively getting the parent, |
|
1193 | + * we must be able to find all other tables. |
|
1194 | + * |
|
1195 | + * @param string[] $tables |
|
1196 | + * |
|
1197 | + * @return string[] |
|
1198 | + */ |
|
1199 | + public function _getLinkBetweenInheritedTables(array $tables) |
|
1200 | + { |
|
1201 | + sort($tables); |
|
1202 | + |
|
1203 | + return $this->fromCache($this->cachePrefix.'_linkbetweeninheritedtables_'.implode('__split__', $tables), |
|
1204 | + function () use ($tables) { |
|
1205 | + return $this->_getLinkBetweenInheritedTablesWithoutCache($tables); |
|
1206 | + }); |
|
1207 | + } |
|
1208 | + |
|
1209 | + /** |
|
1210 | + * Return the list of tables (from child to parent) joining the tables passed in parameter. |
|
1211 | + * Tables must be in a single line of inheritance. The method will find missing tables. |
|
1212 | + * |
|
1213 | + * Algorithm: one of those tables is the ultimate child. From this child, by recursively getting the parent, |
|
1214 | + * we must be able to find all other tables. |
|
1215 | + * |
|
1216 | + * @param string[] $tables |
|
1217 | + * |
|
1218 | + * @return string[] |
|
1219 | + */ |
|
1220 | + private function _getLinkBetweenInheritedTablesWithoutCache(array $tables) |
|
1221 | + { |
|
1222 | + $schemaAnalyzer = $this->schemaAnalyzer; |
|
1223 | + |
|
1224 | + foreach ($tables as $currentTable) { |
|
1225 | + $allParents = [$currentTable]; |
|
1226 | + $currentFk = null; |
|
1227 | + while ($currentFk = $schemaAnalyzer->getParentRelationship($currentTable)) { |
|
1228 | + $currentTable = $currentFk->getForeignTableName(); |
|
1229 | + $allParents[] = $currentTable; |
|
1230 | + }; |
|
1231 | + |
|
1232 | + // Now, does the $allParents contain all the tables we want? |
|
1233 | + $notFoundTables = array_diff($tables, $allParents); |
|
1234 | + if (empty($notFoundTables)) { |
|
1235 | + // We have a winner! |
|
1236 | + return $allParents; |
|
1237 | + } |
|
1238 | + } |
|
1239 | + |
|
1240 | + throw new TDBMException(sprintf('The tables (%s) cannot be linked by an inheritance relationship.', implode(', ', $tables))); |
|
1241 | + } |
|
1242 | + |
|
1243 | + /** |
|
1244 | + * Returns the list of tables related to this table (via a parent or child inheritance relationship). |
|
1245 | + * |
|
1246 | + * @param string $table |
|
1247 | + * |
|
1248 | + * @return string[] |
|
1249 | + */ |
|
1250 | + public function _getRelatedTablesByInheritance($table) |
|
1251 | + { |
|
1252 | + return $this->fromCache($this->cachePrefix.'_relatedtables_'.$table, function () use ($table) { |
|
1253 | + return $this->_getRelatedTablesByInheritanceWithoutCache($table); |
|
1254 | + }); |
|
1255 | + } |
|
1256 | + |
|
1257 | + /** |
|
1258 | + * Returns the list of tables related to this table (via a parent or child inheritance relationship). |
|
1259 | + * |
|
1260 | + * @param string $table |
|
1261 | + * |
|
1262 | + * @return string[] |
|
1263 | + */ |
|
1264 | + private function _getRelatedTablesByInheritanceWithoutCache($table) |
|
1265 | + { |
|
1266 | + $schemaAnalyzer = $this->schemaAnalyzer; |
|
1267 | + |
|
1268 | + // Let's scan the parent tables |
|
1269 | + $currentTable = $table; |
|
1270 | + |
|
1271 | + $parentTables = []; |
|
1272 | + |
|
1273 | + // Get parent relationship |
|
1274 | + while ($currentFk = $schemaAnalyzer->getParentRelationship($currentTable)) { |
|
1275 | + $currentTable = $currentFk->getForeignTableName(); |
|
1276 | + $parentTables[] = $currentTable; |
|
1277 | + }; |
|
1278 | + |
|
1279 | + // Let's recurse in children |
|
1280 | + $childrenTables = $this->exploreChildrenTablesRelationships($schemaAnalyzer, $table); |
|
1281 | + |
|
1282 | + return array_merge(array_reverse($parentTables), $childrenTables); |
|
1283 | + } |
|
1284 | + |
|
1285 | + /** |
|
1286 | + * Explore all the children and descendant of $table and returns ForeignKeyConstraints on those. |
|
1287 | + * |
|
1288 | + * @param string $table |
|
1289 | + * |
|
1290 | + * @return string[] |
|
1291 | + */ |
|
1292 | + private function exploreChildrenTablesRelationships(SchemaAnalyzer $schemaAnalyzer, $table) |
|
1293 | + { |
|
1294 | + $tables = [$table]; |
|
1295 | + $keys = $schemaAnalyzer->getChildrenRelationships($table); |
|
1296 | + |
|
1297 | + foreach ($keys as $key) { |
|
1298 | + $tables = array_merge($tables, $this->exploreChildrenTablesRelationships($schemaAnalyzer, $key->getLocalTableName())); |
|
1299 | + } |
|
1300 | + |
|
1301 | + return $tables; |
|
1302 | + } |
|
1303 | + |
|
1304 | + /** |
|
1305 | + * Casts a foreign key into SQL, assuming table name is used with no alias. |
|
1306 | + * The returned value does contain only one table. For instance:. |
|
1307 | + * |
|
1308 | + * " LEFT JOIN table2 ON table1.id = table2.table1_id" |
|
1309 | + * |
|
1310 | + * @param ForeignKeyConstraint $fk |
|
1311 | + * @param bool $leftTableIsLocal |
|
1312 | + * |
|
1313 | + * @return string |
|
1314 | + */ |
|
1315 | + /*private function foreignKeyToSql(ForeignKeyConstraint $fk, $leftTableIsLocal) { |
|
1316 | 1316 | $onClauses = []; |
1317 | 1317 | $foreignTableName = $this->connection->quoteIdentifier($fk->getForeignTableName()); |
1318 | 1318 | $foreignColumns = $fk->getForeignColumns(); |
@@ -1338,348 +1338,348 @@ discard block |
||
1338 | 1338 | } |
1339 | 1339 | }*/ |
1340 | 1340 | |
1341 | - /** |
|
1342 | - * Returns an identifier for the group of tables passed in parameter. |
|
1343 | - * |
|
1344 | - * @param string[] $relatedTables |
|
1345 | - * |
|
1346 | - * @return string |
|
1347 | - */ |
|
1348 | - private function getTableGroupName(array $relatedTables) |
|
1349 | - { |
|
1350 | - sort($relatedTables); |
|
1351 | - |
|
1352 | - return implode('_``_', $relatedTables); |
|
1353 | - } |
|
1354 | - |
|
1355 | - /** |
|
1356 | - * @param string $mainTable The name of the table queried |
|
1357 | - * @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) |
|
1358 | - * @param array $parameters |
|
1359 | - * @param string|null $orderString The ORDER BY part of the query. All columns must be prefixed by the table name (in the form: table.column) |
|
1360 | - * @param array $additionalTablesFetch |
|
1361 | - * @param string $mode |
|
1362 | - * @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. |
|
1363 | - * |
|
1364 | - * @return ResultIterator An object representing an array of results. |
|
1365 | - * |
|
1366 | - * @throws TDBMException |
|
1367 | - */ |
|
1368 | - public function findObjects($mainTable, $filter = null, array $parameters = array(), $orderString = null, array $additionalTablesFetch = array(), $mode = null, $className = null) |
|
1369 | - { |
|
1370 | - // $mainTable is not secured in MagicJoin, let's add a bit of security to avoid SQL injection. |
|
1371 | - if (!preg_match('/^[a-zA-Z_][a-zA-Z0-9_]*$/', $mainTable)) { |
|
1372 | - throw new TDBMException(sprintf("Invalid table name: '%s'", $mainTable)); |
|
1373 | - } |
|
1374 | - |
|
1375 | - list($filterString, $additionalParameters) = $this->buildFilterFromFilterBag($filter); |
|
1376 | - |
|
1377 | - $parameters = array_merge($parameters, $additionalParameters); |
|
1378 | - |
|
1379 | - // From the table name and the additional tables we want to fetch, let's build a list of all tables |
|
1380 | - // that must be part of the select columns. |
|
1381 | - |
|
1382 | - $tableGroups = []; |
|
1383 | - $allFetchedTables = $this->_getRelatedTablesByInheritance($mainTable); |
|
1384 | - $tableGroupName = $this->getTableGroupName($allFetchedTables); |
|
1385 | - foreach ($allFetchedTables as $table) { |
|
1386 | - $tableGroups[$table] = $tableGroupName; |
|
1387 | - } |
|
1388 | - |
|
1389 | - foreach ($additionalTablesFetch as $additionalTable) { |
|
1390 | - $relatedTables = $this->_getRelatedTablesByInheritance($additionalTable); |
|
1391 | - $tableGroupName = $this->getTableGroupName($relatedTables); |
|
1392 | - foreach ($relatedTables as $table) { |
|
1393 | - $tableGroups[$table] = $tableGroupName; |
|
1394 | - } |
|
1395 | - $allFetchedTables = array_merge($allFetchedTables, $relatedTables); |
|
1396 | - } |
|
1397 | - |
|
1398 | - // Let's remove any duplicate |
|
1399 | - $allFetchedTables = array_flip(array_flip($allFetchedTables)); |
|
1400 | - |
|
1401 | - $columnsList = []; |
|
1402 | - $columnDescList = []; |
|
1403 | - $schema = $this->tdbmSchemaAnalyzer->getSchema(); |
|
1404 | - |
|
1405 | - // Now, let's build the column list |
|
1406 | - foreach ($allFetchedTables as $table) { |
|
1407 | - foreach ($schema->getTable($table)->getColumns() as $column) { |
|
1408 | - $columnName = $column->getName(); |
|
1409 | - $columnDescList[] = [ |
|
1410 | - 'as' => $table.'____'.$columnName, |
|
1411 | - 'table' => $table, |
|
1412 | - 'column' => $columnName, |
|
1413 | - 'type' => $column->getType(), |
|
1414 | - 'tableGroup' => $tableGroups[$table], |
|
1415 | - ]; |
|
1416 | - $columnsList[] = $this->connection->quoteIdentifier($table).'.'.$this->connection->quoteIdentifier($columnName).' as '. |
|
1417 | - $this->connection->quoteIdentifier($table.'____'.$columnName); |
|
1418 | - } |
|
1419 | - } |
|
1420 | - |
|
1421 | - $sql = 'SELECT DISTINCT '.implode(', ', $columnsList).' FROM MAGICJOIN('.$mainTable.')'; |
|
1422 | - $countSql = 'SELECT COUNT(1) FROM MAGICJOIN('.$mainTable.')'; |
|
1423 | - |
|
1424 | - if (!empty($filterString)) { |
|
1425 | - $sql .= ' WHERE '.$filterString; |
|
1426 | - $countSql .= ' WHERE '.$filterString; |
|
1427 | - } |
|
1428 | - |
|
1429 | - if (!empty($orderString)) { |
|
1430 | - $sql .= ' ORDER BY '.$orderString; |
|
1431 | - $countSql .= ' ORDER BY '.$orderString; |
|
1432 | - } |
|
1433 | - |
|
1434 | - if ($mode !== null && $mode !== self::MODE_CURSOR && $mode !== self::MODE_ARRAY) { |
|
1435 | - throw new TDBMException("Unknown fetch mode: '".$this->mode."'"); |
|
1436 | - } |
|
1437 | - |
|
1438 | - $mode = $mode ?: $this->mode; |
|
1439 | - |
|
1440 | - return new ResultIterator($sql, $countSql, $parameters, $columnDescList, $this->objectStorage, $className, $this, $this->magicQuery, $mode); |
|
1441 | - } |
|
1442 | - |
|
1443 | - /** |
|
1444 | - * @param $table |
|
1445 | - * @param array $primaryKeys |
|
1446 | - * @param array $additionalTablesFetch |
|
1447 | - * @param bool $lazy Whether to perform lazy loading on this object or not. |
|
1448 | - * @param string $className |
|
1449 | - * |
|
1450 | - * @return AbstractTDBMObject |
|
1451 | - * |
|
1452 | - * @throws TDBMException |
|
1453 | - */ |
|
1454 | - public function findObjectByPk($table, array $primaryKeys, array $additionalTablesFetch = array(), $lazy = false, $className = null) |
|
1455 | - { |
|
1456 | - $primaryKeys = $this->_getPrimaryKeysFromObjectData($table, $primaryKeys); |
|
1457 | - $hash = $this->getObjectHash($primaryKeys); |
|
1458 | - |
|
1459 | - if ($this->objectStorage->has($table, $hash)) { |
|
1460 | - $dbRow = $this->objectStorage->get($table, $hash); |
|
1461 | - $bean = $dbRow->getTDBMObject(); |
|
1462 | - if ($className !== null && !is_a($bean, $className)) { |
|
1463 | - throw new TDBMException("TDBM cannot create a bean of class '".$className."'. The requested object was already loaded and its class is '".get_class($bean)."'"); |
|
1464 | - } |
|
1465 | - |
|
1466 | - return $bean; |
|
1467 | - } |
|
1468 | - |
|
1469 | - // Are we performing lazy fetching? |
|
1470 | - if ($lazy === true) { |
|
1471 | - // Can we perform lazy fetching? |
|
1472 | - $tables = $this->_getRelatedTablesByInheritance($table); |
|
1473 | - // Only allowed if no inheritance. |
|
1474 | - if (count($tables) === 1) { |
|
1475 | - if ($className === null) { |
|
1476 | - $className = isset($this->tableToBeanMap[$table]) ? $this->tableToBeanMap[$table] : 'Mouf\\Database\\TDBM\\TDBMObject'; |
|
1477 | - } |
|
1478 | - |
|
1479 | - // Let's construct the bean |
|
1480 | - if (!isset($reflectionClassCache[$className])) { |
|
1481 | - $reflectionClassCache[$className] = new \ReflectionClass($className); |
|
1482 | - } |
|
1483 | - // Let's bypass the constructor when creating the bean! |
|
1484 | - $bean = $reflectionClassCache[$className]->newInstanceWithoutConstructor(); |
|
1485 | - /* @var $bean AbstractTDBMObject */ |
|
1486 | - $bean->_constructLazy($table, $primaryKeys, $this); |
|
1487 | - } |
|
1488 | - } |
|
1489 | - |
|
1490 | - // Did not find the object in cache? Let's query it! |
|
1491 | - return $this->findObjectOrFail($table, $primaryKeys, [], $additionalTablesFetch, $className); |
|
1492 | - } |
|
1493 | - |
|
1494 | - /** |
|
1495 | - * Returns a unique bean (or null) according to the filters passed in parameter. |
|
1496 | - * |
|
1497 | - * @param string $mainTable The name of the table queried |
|
1498 | - * @param string|null $filterString 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) |
|
1499 | - * @param array $parameters |
|
1500 | - * @param array $additionalTablesFetch |
|
1501 | - * @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. |
|
1502 | - * |
|
1503 | - * @return AbstractTDBMObject|null The object we want, or null if no object matches the filters. |
|
1504 | - * |
|
1505 | - * @throws TDBMException |
|
1506 | - */ |
|
1507 | - public function findObject($mainTable, $filterString = null, array $parameters = array(), array $additionalTablesFetch = array(), $className = null) |
|
1508 | - { |
|
1509 | - $objects = $this->findObjects($mainTable, $filterString, $parameters, null, $additionalTablesFetch, self::MODE_ARRAY, $className); |
|
1510 | - $page = $objects->take(0, 2); |
|
1511 | - $count = $page->count(); |
|
1512 | - if ($count > 1) { |
|
1513 | - 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."); |
|
1514 | - } elseif ($count === 0) { |
|
1515 | - return; |
|
1516 | - } |
|
1517 | - |
|
1518 | - return $objects[0]; |
|
1519 | - } |
|
1520 | - |
|
1521 | - /** |
|
1522 | - * Returns a unique bean according to the filters passed in parameter. |
|
1523 | - * Throws a NoBeanFoundException if no bean was found for the filter passed in parameter. |
|
1524 | - * |
|
1525 | - * @param string $mainTable The name of the table queried |
|
1526 | - * @param string|null $filterString 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) |
|
1527 | - * @param array $parameters |
|
1528 | - * @param array $additionalTablesFetch |
|
1529 | - * @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. |
|
1530 | - * |
|
1531 | - * @return AbstractTDBMObject The object we want |
|
1532 | - * |
|
1533 | - * @throws TDBMException |
|
1534 | - */ |
|
1535 | - public function findObjectOrFail($mainTable, $filterString = null, array $parameters = array(), array $additionalTablesFetch = array(), $className = null) |
|
1536 | - { |
|
1537 | - $bean = $this->findObject($mainTable, $filterString, $parameters, $additionalTablesFetch, $className); |
|
1538 | - if ($bean === null) { |
|
1539 | - throw new NoBeanFoundException("No result found for query on table '".$mainTable."'"); |
|
1540 | - } |
|
1541 | - |
|
1542 | - return $bean; |
|
1543 | - } |
|
1544 | - |
|
1545 | - /** |
|
1546 | - * @param array $beanData An array of data: array<table, array<column, value>> |
|
1547 | - * |
|
1548 | - * @return array an array with first item = class name and second item = table name |
|
1549 | - */ |
|
1550 | - public function _getClassNameFromBeanData(array $beanData) |
|
1551 | - { |
|
1552 | - if (count($beanData) === 1) { |
|
1553 | - $tableName = array_keys($beanData)[0]; |
|
1554 | - } else { |
|
1555 | - foreach ($beanData as $table => $row) { |
|
1556 | - $tables = []; |
|
1557 | - $primaryKeyColumns = $this->getPrimaryKeyColumns($table); |
|
1558 | - $pkSet = false; |
|
1559 | - foreach ($primaryKeyColumns as $columnName) { |
|
1560 | - if ($row[$columnName] !== null) { |
|
1561 | - $pkSet = true; |
|
1562 | - break; |
|
1563 | - } |
|
1564 | - } |
|
1565 | - if ($pkSet) { |
|
1566 | - $tables[] = $table; |
|
1567 | - } |
|
1568 | - } |
|
1569 | - |
|
1570 | - // $tables contains the tables for this bean. Let's view the top most part of the hierarchy |
|
1571 | - $allTables = $this->_getLinkBetweenInheritedTables($tables); |
|
1572 | - $tableName = $allTables[0]; |
|
1573 | - } |
|
1574 | - |
|
1575 | - // Only one table in this bean. Life is sweat, let's look at its type: |
|
1576 | - if (isset($this->tableToBeanMap[$tableName])) { |
|
1577 | - return [$this->tableToBeanMap[$tableName], $tableName]; |
|
1578 | - } else { |
|
1579 | - return ['Mouf\\Database\\TDBM\\TDBMObject', $tableName]; |
|
1580 | - } |
|
1581 | - } |
|
1582 | - |
|
1583 | - /** |
|
1584 | - * Returns an item from cache or computes it using $closure and puts it in cache. |
|
1585 | - * |
|
1586 | - * @param string $key |
|
1587 | - * @param callable $closure |
|
1588 | - * |
|
1589 | - * @return mixed |
|
1590 | - */ |
|
1591 | - private function fromCache($key, callable $closure) |
|
1592 | - { |
|
1593 | - $item = $this->cache->fetch($key); |
|
1594 | - if ($item === false) { |
|
1595 | - $item = $closure(); |
|
1596 | - $this->cache->save($key, $item); |
|
1597 | - } |
|
1598 | - |
|
1599 | - return $item; |
|
1600 | - } |
|
1601 | - |
|
1602 | - /** |
|
1603 | - * Returns the foreign key object. |
|
1604 | - * |
|
1605 | - * @param string $table |
|
1606 | - * @param string $fkName |
|
1607 | - * |
|
1608 | - * @return ForeignKeyConstraint |
|
1609 | - */ |
|
1610 | - public function _getForeignKeyByName($table, $fkName) |
|
1611 | - { |
|
1612 | - return $this->tdbmSchemaAnalyzer->getSchema()->getTable($table)->getForeignKey($fkName); |
|
1613 | - } |
|
1614 | - |
|
1615 | - /** |
|
1616 | - * @param $pivotTableName |
|
1617 | - * @param AbstractTDBMObject $bean |
|
1618 | - * |
|
1619 | - * @return AbstractTDBMObject[] |
|
1620 | - */ |
|
1621 | - public function _getRelatedBeans($pivotTableName, AbstractTDBMObject $bean) |
|
1622 | - { |
|
1623 | - list($localFk, $remoteFk) = $this->getPivotTableForeignKeys($pivotTableName, $bean); |
|
1624 | - /* @var $localFk ForeignKeyConstraint */ |
|
1625 | - /* @var $remoteFk ForeignKeyConstraint */ |
|
1626 | - $remoteTable = $remoteFk->getForeignTableName(); |
|
1627 | - |
|
1628 | - $primaryKeys = $this->getPrimaryKeyValues($bean); |
|
1629 | - $columnNames = array_map(function ($name) use ($pivotTableName) { return $pivotTableName.'.'.$name; }, $localFk->getLocalColumns()); |
|
1630 | - |
|
1631 | - $filter = array_combine($columnNames, $primaryKeys); |
|
1632 | - |
|
1633 | - return $this->findObjects($remoteTable, $filter); |
|
1634 | - } |
|
1635 | - |
|
1636 | - /** |
|
1637 | - * @param $pivotTableName |
|
1638 | - * @param AbstractTDBMObject $bean The LOCAL bean |
|
1639 | - * |
|
1640 | - * @return ForeignKeyConstraint[] First item: the LOCAL bean, second item: the REMOTE bean. |
|
1641 | - * |
|
1642 | - * @throws TDBMException |
|
1643 | - */ |
|
1644 | - private function getPivotTableForeignKeys($pivotTableName, AbstractTDBMObject $bean) |
|
1645 | - { |
|
1646 | - $fks = array_values($this->tdbmSchemaAnalyzer->getSchema()->getTable($pivotTableName)->getForeignKeys()); |
|
1647 | - $table1 = $fks[0]->getForeignTableName(); |
|
1648 | - $table2 = $fks[1]->getForeignTableName(); |
|
1649 | - |
|
1650 | - $beanTables = array_map(function (DbRow $dbRow) { return $dbRow->_getDbTableName(); }, $bean->_getDbRows()); |
|
1651 | - |
|
1652 | - if (in_array($table1, $beanTables)) { |
|
1653 | - return [$fks[0], $fks[1]]; |
|
1654 | - } elseif (in_array($table2, $beanTables)) { |
|
1655 | - return [$fks[1], $fks[0]]; |
|
1656 | - } else { |
|
1657 | - throw new TDBMException("Unexpected bean type in getPivotTableForeignKeys. Awaiting beans from table {$table1} and {$table2} for pivot table {$pivotTableName}"); |
|
1658 | - } |
|
1659 | - } |
|
1660 | - |
|
1661 | - /** |
|
1662 | - * Returns a list of pivot tables linked to $bean. |
|
1663 | - * |
|
1664 | - * @param AbstractTDBMObject $bean |
|
1665 | - * |
|
1666 | - * @return string[] |
|
1667 | - */ |
|
1668 | - public function _getPivotTablesLinkedToBean(AbstractTDBMObject $bean) |
|
1669 | - { |
|
1670 | - $junctionTables = []; |
|
1671 | - $allJunctionTables = $this->schemaAnalyzer->detectJunctionTables(); |
|
1672 | - foreach ($bean->_getDbRows() as $dbRow) { |
|
1673 | - foreach ($allJunctionTables as $table) { |
|
1674 | - // There are exactly 2 FKs since this is a pivot table. |
|
1675 | - $fks = array_values($table->getForeignKeys()); |
|
1676 | - |
|
1677 | - if ($fks[0]->getForeignTableName() === $dbRow->_getDbTableName() || $fks[1]->getForeignTableName() === $dbRow->_getDbTableName()) { |
|
1678 | - $junctionTables[] = $table->getName(); |
|
1679 | - } |
|
1680 | - } |
|
1681 | - } |
|
1682 | - |
|
1683 | - return $junctionTables; |
|
1684 | - } |
|
1341 | + /** |
|
1342 | + * Returns an identifier for the group of tables passed in parameter. |
|
1343 | + * |
|
1344 | + * @param string[] $relatedTables |
|
1345 | + * |
|
1346 | + * @return string |
|
1347 | + */ |
|
1348 | + private function getTableGroupName(array $relatedTables) |
|
1349 | + { |
|
1350 | + sort($relatedTables); |
|
1351 | + |
|
1352 | + return implode('_``_', $relatedTables); |
|
1353 | + } |
|
1354 | + |
|
1355 | + /** |
|
1356 | + * @param string $mainTable The name of the table queried |
|
1357 | + * @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) |
|
1358 | + * @param array $parameters |
|
1359 | + * @param string|null $orderString The ORDER BY part of the query. All columns must be prefixed by the table name (in the form: table.column) |
|
1360 | + * @param array $additionalTablesFetch |
|
1361 | + * @param string $mode |
|
1362 | + * @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. |
|
1363 | + * |
|
1364 | + * @return ResultIterator An object representing an array of results. |
|
1365 | + * |
|
1366 | + * @throws TDBMException |
|
1367 | + */ |
|
1368 | + public function findObjects($mainTable, $filter = null, array $parameters = array(), $orderString = null, array $additionalTablesFetch = array(), $mode = null, $className = null) |
|
1369 | + { |
|
1370 | + // $mainTable is not secured in MagicJoin, let's add a bit of security to avoid SQL injection. |
|
1371 | + if (!preg_match('/^[a-zA-Z_][a-zA-Z0-9_]*$/', $mainTable)) { |
|
1372 | + throw new TDBMException(sprintf("Invalid table name: '%s'", $mainTable)); |
|
1373 | + } |
|
1374 | + |
|
1375 | + list($filterString, $additionalParameters) = $this->buildFilterFromFilterBag($filter); |
|
1376 | + |
|
1377 | + $parameters = array_merge($parameters, $additionalParameters); |
|
1378 | + |
|
1379 | + // From the table name and the additional tables we want to fetch, let's build a list of all tables |
|
1380 | + // that must be part of the select columns. |
|
1381 | + |
|
1382 | + $tableGroups = []; |
|
1383 | + $allFetchedTables = $this->_getRelatedTablesByInheritance($mainTable); |
|
1384 | + $tableGroupName = $this->getTableGroupName($allFetchedTables); |
|
1385 | + foreach ($allFetchedTables as $table) { |
|
1386 | + $tableGroups[$table] = $tableGroupName; |
|
1387 | + } |
|
1388 | + |
|
1389 | + foreach ($additionalTablesFetch as $additionalTable) { |
|
1390 | + $relatedTables = $this->_getRelatedTablesByInheritance($additionalTable); |
|
1391 | + $tableGroupName = $this->getTableGroupName($relatedTables); |
|
1392 | + foreach ($relatedTables as $table) { |
|
1393 | + $tableGroups[$table] = $tableGroupName; |
|
1394 | + } |
|
1395 | + $allFetchedTables = array_merge($allFetchedTables, $relatedTables); |
|
1396 | + } |
|
1397 | + |
|
1398 | + // Let's remove any duplicate |
|
1399 | + $allFetchedTables = array_flip(array_flip($allFetchedTables)); |
|
1400 | + |
|
1401 | + $columnsList = []; |
|
1402 | + $columnDescList = []; |
|
1403 | + $schema = $this->tdbmSchemaAnalyzer->getSchema(); |
|
1404 | + |
|
1405 | + // Now, let's build the column list |
|
1406 | + foreach ($allFetchedTables as $table) { |
|
1407 | + foreach ($schema->getTable($table)->getColumns() as $column) { |
|
1408 | + $columnName = $column->getName(); |
|
1409 | + $columnDescList[] = [ |
|
1410 | + 'as' => $table.'____'.$columnName, |
|
1411 | + 'table' => $table, |
|
1412 | + 'column' => $columnName, |
|
1413 | + 'type' => $column->getType(), |
|
1414 | + 'tableGroup' => $tableGroups[$table], |
|
1415 | + ]; |
|
1416 | + $columnsList[] = $this->connection->quoteIdentifier($table).'.'.$this->connection->quoteIdentifier($columnName).' as '. |
|
1417 | + $this->connection->quoteIdentifier($table.'____'.$columnName); |
|
1418 | + } |
|
1419 | + } |
|
1420 | + |
|
1421 | + $sql = 'SELECT DISTINCT '.implode(', ', $columnsList).' FROM MAGICJOIN('.$mainTable.')'; |
|
1422 | + $countSql = 'SELECT COUNT(1) FROM MAGICJOIN('.$mainTable.')'; |
|
1423 | + |
|
1424 | + if (!empty($filterString)) { |
|
1425 | + $sql .= ' WHERE '.$filterString; |
|
1426 | + $countSql .= ' WHERE '.$filterString; |
|
1427 | + } |
|
1428 | + |
|
1429 | + if (!empty($orderString)) { |
|
1430 | + $sql .= ' ORDER BY '.$orderString; |
|
1431 | + $countSql .= ' ORDER BY '.$orderString; |
|
1432 | + } |
|
1433 | + |
|
1434 | + if ($mode !== null && $mode !== self::MODE_CURSOR && $mode !== self::MODE_ARRAY) { |
|
1435 | + throw new TDBMException("Unknown fetch mode: '".$this->mode."'"); |
|
1436 | + } |
|
1437 | + |
|
1438 | + $mode = $mode ?: $this->mode; |
|
1439 | + |
|
1440 | + return new ResultIterator($sql, $countSql, $parameters, $columnDescList, $this->objectStorage, $className, $this, $this->magicQuery, $mode); |
|
1441 | + } |
|
1442 | + |
|
1443 | + /** |
|
1444 | + * @param $table |
|
1445 | + * @param array $primaryKeys |
|
1446 | + * @param array $additionalTablesFetch |
|
1447 | + * @param bool $lazy Whether to perform lazy loading on this object or not. |
|
1448 | + * @param string $className |
|
1449 | + * |
|
1450 | + * @return AbstractTDBMObject |
|
1451 | + * |
|
1452 | + * @throws TDBMException |
|
1453 | + */ |
|
1454 | + public function findObjectByPk($table, array $primaryKeys, array $additionalTablesFetch = array(), $lazy = false, $className = null) |
|
1455 | + { |
|
1456 | + $primaryKeys = $this->_getPrimaryKeysFromObjectData($table, $primaryKeys); |
|
1457 | + $hash = $this->getObjectHash($primaryKeys); |
|
1458 | + |
|
1459 | + if ($this->objectStorage->has($table, $hash)) { |
|
1460 | + $dbRow = $this->objectStorage->get($table, $hash); |
|
1461 | + $bean = $dbRow->getTDBMObject(); |
|
1462 | + if ($className !== null && !is_a($bean, $className)) { |
|
1463 | + throw new TDBMException("TDBM cannot create a bean of class '".$className."'. The requested object was already loaded and its class is '".get_class($bean)."'"); |
|
1464 | + } |
|
1465 | + |
|
1466 | + return $bean; |
|
1467 | + } |
|
1468 | + |
|
1469 | + // Are we performing lazy fetching? |
|
1470 | + if ($lazy === true) { |
|
1471 | + // Can we perform lazy fetching? |
|
1472 | + $tables = $this->_getRelatedTablesByInheritance($table); |
|
1473 | + // Only allowed if no inheritance. |
|
1474 | + if (count($tables) === 1) { |
|
1475 | + if ($className === null) { |
|
1476 | + $className = isset($this->tableToBeanMap[$table]) ? $this->tableToBeanMap[$table] : 'Mouf\\Database\\TDBM\\TDBMObject'; |
|
1477 | + } |
|
1478 | + |
|
1479 | + // Let's construct the bean |
|
1480 | + if (!isset($reflectionClassCache[$className])) { |
|
1481 | + $reflectionClassCache[$className] = new \ReflectionClass($className); |
|
1482 | + } |
|
1483 | + // Let's bypass the constructor when creating the bean! |
|
1484 | + $bean = $reflectionClassCache[$className]->newInstanceWithoutConstructor(); |
|
1485 | + /* @var $bean AbstractTDBMObject */ |
|
1486 | + $bean->_constructLazy($table, $primaryKeys, $this); |
|
1487 | + } |
|
1488 | + } |
|
1489 | + |
|
1490 | + // Did not find the object in cache? Let's query it! |
|
1491 | + return $this->findObjectOrFail($table, $primaryKeys, [], $additionalTablesFetch, $className); |
|
1492 | + } |
|
1493 | + |
|
1494 | + /** |
|
1495 | + * Returns a unique bean (or null) according to the filters passed in parameter. |
|
1496 | + * |
|
1497 | + * @param string $mainTable The name of the table queried |
|
1498 | + * @param string|null $filterString 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) |
|
1499 | + * @param array $parameters |
|
1500 | + * @param array $additionalTablesFetch |
|
1501 | + * @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. |
|
1502 | + * |
|
1503 | + * @return AbstractTDBMObject|null The object we want, or null if no object matches the filters. |
|
1504 | + * |
|
1505 | + * @throws TDBMException |
|
1506 | + */ |
|
1507 | + public function findObject($mainTable, $filterString = null, array $parameters = array(), array $additionalTablesFetch = array(), $className = null) |
|
1508 | + { |
|
1509 | + $objects = $this->findObjects($mainTable, $filterString, $parameters, null, $additionalTablesFetch, self::MODE_ARRAY, $className); |
|
1510 | + $page = $objects->take(0, 2); |
|
1511 | + $count = $page->count(); |
|
1512 | + if ($count > 1) { |
|
1513 | + 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."); |
|
1514 | + } elseif ($count === 0) { |
|
1515 | + return; |
|
1516 | + } |
|
1517 | + |
|
1518 | + return $objects[0]; |
|
1519 | + } |
|
1520 | + |
|
1521 | + /** |
|
1522 | + * Returns a unique bean according to the filters passed in parameter. |
|
1523 | + * Throws a NoBeanFoundException if no bean was found for the filter passed in parameter. |
|
1524 | + * |
|
1525 | + * @param string $mainTable The name of the table queried |
|
1526 | + * @param string|null $filterString 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) |
|
1527 | + * @param array $parameters |
|
1528 | + * @param array $additionalTablesFetch |
|
1529 | + * @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. |
|
1530 | + * |
|
1531 | + * @return AbstractTDBMObject The object we want |
|
1532 | + * |
|
1533 | + * @throws TDBMException |
|
1534 | + */ |
|
1535 | + public function findObjectOrFail($mainTable, $filterString = null, array $parameters = array(), array $additionalTablesFetch = array(), $className = null) |
|
1536 | + { |
|
1537 | + $bean = $this->findObject($mainTable, $filterString, $parameters, $additionalTablesFetch, $className); |
|
1538 | + if ($bean === null) { |
|
1539 | + throw new NoBeanFoundException("No result found for query on table '".$mainTable."'"); |
|
1540 | + } |
|
1541 | + |
|
1542 | + return $bean; |
|
1543 | + } |
|
1544 | + |
|
1545 | + /** |
|
1546 | + * @param array $beanData An array of data: array<table, array<column, value>> |
|
1547 | + * |
|
1548 | + * @return array an array with first item = class name and second item = table name |
|
1549 | + */ |
|
1550 | + public function _getClassNameFromBeanData(array $beanData) |
|
1551 | + { |
|
1552 | + if (count($beanData) === 1) { |
|
1553 | + $tableName = array_keys($beanData)[0]; |
|
1554 | + } else { |
|
1555 | + foreach ($beanData as $table => $row) { |
|
1556 | + $tables = []; |
|
1557 | + $primaryKeyColumns = $this->getPrimaryKeyColumns($table); |
|
1558 | + $pkSet = false; |
|
1559 | + foreach ($primaryKeyColumns as $columnName) { |
|
1560 | + if ($row[$columnName] !== null) { |
|
1561 | + $pkSet = true; |
|
1562 | + break; |
|
1563 | + } |
|
1564 | + } |
|
1565 | + if ($pkSet) { |
|
1566 | + $tables[] = $table; |
|
1567 | + } |
|
1568 | + } |
|
1569 | + |
|
1570 | + // $tables contains the tables for this bean. Let's view the top most part of the hierarchy |
|
1571 | + $allTables = $this->_getLinkBetweenInheritedTables($tables); |
|
1572 | + $tableName = $allTables[0]; |
|
1573 | + } |
|
1574 | + |
|
1575 | + // Only one table in this bean. Life is sweat, let's look at its type: |
|
1576 | + if (isset($this->tableToBeanMap[$tableName])) { |
|
1577 | + return [$this->tableToBeanMap[$tableName], $tableName]; |
|
1578 | + } else { |
|
1579 | + return ['Mouf\\Database\\TDBM\\TDBMObject', $tableName]; |
|
1580 | + } |
|
1581 | + } |
|
1582 | + |
|
1583 | + /** |
|
1584 | + * Returns an item from cache or computes it using $closure and puts it in cache. |
|
1585 | + * |
|
1586 | + * @param string $key |
|
1587 | + * @param callable $closure |
|
1588 | + * |
|
1589 | + * @return mixed |
|
1590 | + */ |
|
1591 | + private function fromCache($key, callable $closure) |
|
1592 | + { |
|
1593 | + $item = $this->cache->fetch($key); |
|
1594 | + if ($item === false) { |
|
1595 | + $item = $closure(); |
|
1596 | + $this->cache->save($key, $item); |
|
1597 | + } |
|
1598 | + |
|
1599 | + return $item; |
|
1600 | + } |
|
1601 | + |
|
1602 | + /** |
|
1603 | + * Returns the foreign key object. |
|
1604 | + * |
|
1605 | + * @param string $table |
|
1606 | + * @param string $fkName |
|
1607 | + * |
|
1608 | + * @return ForeignKeyConstraint |
|
1609 | + */ |
|
1610 | + public function _getForeignKeyByName($table, $fkName) |
|
1611 | + { |
|
1612 | + return $this->tdbmSchemaAnalyzer->getSchema()->getTable($table)->getForeignKey($fkName); |
|
1613 | + } |
|
1614 | + |
|
1615 | + /** |
|
1616 | + * @param $pivotTableName |
|
1617 | + * @param AbstractTDBMObject $bean |
|
1618 | + * |
|
1619 | + * @return AbstractTDBMObject[] |
|
1620 | + */ |
|
1621 | + public function _getRelatedBeans($pivotTableName, AbstractTDBMObject $bean) |
|
1622 | + { |
|
1623 | + list($localFk, $remoteFk) = $this->getPivotTableForeignKeys($pivotTableName, $bean); |
|
1624 | + /* @var $localFk ForeignKeyConstraint */ |
|
1625 | + /* @var $remoteFk ForeignKeyConstraint */ |
|
1626 | + $remoteTable = $remoteFk->getForeignTableName(); |
|
1627 | + |
|
1628 | + $primaryKeys = $this->getPrimaryKeyValues($bean); |
|
1629 | + $columnNames = array_map(function ($name) use ($pivotTableName) { return $pivotTableName.'.'.$name; }, $localFk->getLocalColumns()); |
|
1630 | + |
|
1631 | + $filter = array_combine($columnNames, $primaryKeys); |
|
1632 | + |
|
1633 | + return $this->findObjects($remoteTable, $filter); |
|
1634 | + } |
|
1635 | + |
|
1636 | + /** |
|
1637 | + * @param $pivotTableName |
|
1638 | + * @param AbstractTDBMObject $bean The LOCAL bean |
|
1639 | + * |
|
1640 | + * @return ForeignKeyConstraint[] First item: the LOCAL bean, second item: the REMOTE bean. |
|
1641 | + * |
|
1642 | + * @throws TDBMException |
|
1643 | + */ |
|
1644 | + private function getPivotTableForeignKeys($pivotTableName, AbstractTDBMObject $bean) |
|
1645 | + { |
|
1646 | + $fks = array_values($this->tdbmSchemaAnalyzer->getSchema()->getTable($pivotTableName)->getForeignKeys()); |
|
1647 | + $table1 = $fks[0]->getForeignTableName(); |
|
1648 | + $table2 = $fks[1]->getForeignTableName(); |
|
1649 | + |
|
1650 | + $beanTables = array_map(function (DbRow $dbRow) { return $dbRow->_getDbTableName(); }, $bean->_getDbRows()); |
|
1651 | + |
|
1652 | + if (in_array($table1, $beanTables)) { |
|
1653 | + return [$fks[0], $fks[1]]; |
|
1654 | + } elseif (in_array($table2, $beanTables)) { |
|
1655 | + return [$fks[1], $fks[0]]; |
|
1656 | + } else { |
|
1657 | + throw new TDBMException("Unexpected bean type in getPivotTableForeignKeys. Awaiting beans from table {$table1} and {$table2} for pivot table {$pivotTableName}"); |
|
1658 | + } |
|
1659 | + } |
|
1660 | + |
|
1661 | + /** |
|
1662 | + * Returns a list of pivot tables linked to $bean. |
|
1663 | + * |
|
1664 | + * @param AbstractTDBMObject $bean |
|
1665 | + * |
|
1666 | + * @return string[] |
|
1667 | + */ |
|
1668 | + public function _getPivotTablesLinkedToBean(AbstractTDBMObject $bean) |
|
1669 | + { |
|
1670 | + $junctionTables = []; |
|
1671 | + $allJunctionTables = $this->schemaAnalyzer->detectJunctionTables(); |
|
1672 | + foreach ($bean->_getDbRows() as $dbRow) { |
|
1673 | + foreach ($allJunctionTables as $table) { |
|
1674 | + // There are exactly 2 FKs since this is a pivot table. |
|
1675 | + $fks = array_values($table->getForeignKeys()); |
|
1676 | + |
|
1677 | + if ($fks[0]->getForeignTableName() === $dbRow->_getDbTableName() || $fks[1]->getForeignTableName() === $dbRow->_getDbTableName()) { |
|
1678 | + $junctionTables[] = $table->getName(); |
|
1679 | + } |
|
1680 | + } |
|
1681 | + } |
|
1682 | + |
|
1683 | + return $junctionTables; |
|
1684 | + } |
|
1685 | 1685 | } |
@@ -1201,7 +1201,7 @@ discard block |
||
1201 | 1201 | sort($tables); |
1202 | 1202 | |
1203 | 1203 | return $this->fromCache($this->cachePrefix.'_linkbetweeninheritedtables_'.implode('__split__', $tables), |
1204 | - function () use ($tables) { |
|
1204 | + function() use ($tables) { |
|
1205 | 1205 | return $this->_getLinkBetweenInheritedTablesWithoutCache($tables); |
1206 | 1206 | }); |
1207 | 1207 | } |
@@ -1249,7 +1249,7 @@ discard block |
||
1249 | 1249 | */ |
1250 | 1250 | public function _getRelatedTablesByInheritance($table) |
1251 | 1251 | { |
1252 | - return $this->fromCache($this->cachePrefix.'_relatedtables_'.$table, function () use ($table) { |
|
1252 | + return $this->fromCache($this->cachePrefix.'_relatedtables_'.$table, function() use ($table) { |
|
1253 | 1253 | return $this->_getRelatedTablesByInheritanceWithoutCache($table); |
1254 | 1254 | }); |
1255 | 1255 | } |
@@ -1509,7 +1509,7 @@ discard block |
||
1509 | 1509 | $objects = $this->findObjects($mainTable, $filterString, $parameters, null, $additionalTablesFetch, self::MODE_ARRAY, $className); |
1510 | 1510 | $page = $objects->take(0, 2); |
1511 | 1511 | $count = $page->count(); |
1512 | - if ($count > 1) { |
|
1512 | + if ($count>1) { |
|
1513 | 1513 | 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."); |
1514 | 1514 | } elseif ($count === 0) { |
1515 | 1515 | return; |
@@ -1626,7 +1626,7 @@ discard block |
||
1626 | 1626 | $remoteTable = $remoteFk->getForeignTableName(); |
1627 | 1627 | |
1628 | 1628 | $primaryKeys = $this->getPrimaryKeyValues($bean); |
1629 | - $columnNames = array_map(function ($name) use ($pivotTableName) { return $pivotTableName.'.'.$name; }, $localFk->getLocalColumns()); |
|
1629 | + $columnNames = array_map(function($name) use ($pivotTableName) { return $pivotTableName.'.'.$name; }, $localFk->getLocalColumns()); |
|
1630 | 1630 | |
1631 | 1631 | $filter = array_combine($columnNames, $primaryKeys); |
1632 | 1632 | |
@@ -1647,7 +1647,7 @@ discard block |
||
1647 | 1647 | $table1 = $fks[0]->getForeignTableName(); |
1648 | 1648 | $table2 = $fks[1]->getForeignTableName(); |
1649 | 1649 | |
1650 | - $beanTables = array_map(function (DbRow $dbRow) { return $dbRow->_getDbTableName(); }, $bean->_getDbRows()); |
|
1650 | + $beanTables = array_map(function(DbRow $dbRow) { return $dbRow->_getDbTableName(); }, $bean->_getDbRows()); |
|
1651 | 1651 | |
1652 | 1652 | if (in_array($table1, $beanTables)) { |
1653 | 1653 | return [$fks[0], $fks[1]]; |
@@ -43,7 +43,6 @@ discard block |
||
43 | 43 | /** |
44 | 44 | * Constructor. |
45 | 45 | * |
46 | - * @param Connection $dbConnection The connection to the database. |
|
47 | 46 | */ |
48 | 47 | public function __construct(SchemaAnalyzer $schemaAnalyzer, Schema $schema, TDBMSchemaAnalyzer $tdbmSchemaAnalyzer) |
49 | 48 | { |
@@ -100,6 +99,9 @@ discard block |
||
100 | 99 | * Generates in one method call the daos and the beans for one table. |
101 | 100 | * |
102 | 101 | * @param $tableName |
102 | + * @param string $daonamespace |
|
103 | + * @param string $beannamespace |
|
104 | + * @param boolean $storeInUtc |
|
103 | 105 | */ |
104 | 106 | public function generateDaoAndBean(Table $table, $daonamespace, $beannamespace, ClassNameMapper $classNameMapper, $storeInUtc) |
105 | 107 | { |
@@ -140,7 +142,7 @@ discard block |
||
140 | 142 | /** |
141 | 143 | * Returns the name of the base bean class from the table name. |
142 | 144 | * |
143 | - * @param $tableName |
|
145 | + * @param string $tableName |
|
144 | 146 | * |
145 | 147 | * @return string |
146 | 148 | */ |
@@ -152,7 +154,7 @@ discard block |
||
152 | 154 | /** |
153 | 155 | * Returns the name of the base DAO class from the table name. |
154 | 156 | * |
155 | - * @param $tableName |
|
157 | + * @param string $tableName |
|
156 | 158 | * |
157 | 159 | * @return string |
158 | 160 | */ |
@@ -223,9 +225,10 @@ discard block |
||
223 | 225 | /** |
224 | 226 | * Writes the PHP bean DAO with simple functions to create/get/save objects. |
225 | 227 | * |
226 | - * @param string $fileName The file that will be written (without the directory) |
|
227 | 228 | * @param string $className The name of the class |
228 | - * @param string $tableName The name of the table |
|
229 | + * @param string $table The name of the table |
|
230 | + * @param string $baseClassName |
|
231 | + * @param string $beanClassName |
|
229 | 232 | */ |
230 | 233 | public function generateDao($className, $baseClassName, $beanClassName, Table $table, $daonamespace, $beannamespace, ClassNameMapper $classNameMapper) |
231 | 234 | { |
@@ -468,6 +471,8 @@ discard block |
||
468 | 471 | * Generates the factory bean. |
469 | 472 | * |
470 | 473 | * @param Table[] $tableList |
474 | + * @param string $daoFactoryClassName |
|
475 | + * @param string $daoNamespace |
|
471 | 476 | */ |
472 | 477 | private function generateFactory(array $tableList, $daoFactoryClassName, $daoNamespace, ClassNameMapper $classNameMapper) |
473 | 478 | { |
@@ -4,7 +4,6 @@ |
||
4 | 4 | |
5 | 5 | use Doctrine\Common\Inflector\Inflector; |
6 | 6 | use Doctrine\DBAL\Driver\Connection; |
7 | -use Doctrine\DBAL\Schema\Column; |
|
8 | 7 | use Doctrine\DBAL\Schema\Schema; |
9 | 8 | use Doctrine\DBAL\Schema\Table; |
10 | 9 | use Doctrine\DBAL\Types\Type; |
@@ -18,188 +18,188 @@ discard block |
||
18 | 18 | */ |
19 | 19 | class TDBMDaoGenerator |
20 | 20 | { |
21 | - /** |
|
22 | - * @var SchemaAnalyzer |
|
23 | - */ |
|
24 | - private $schemaAnalyzer; |
|
25 | - |
|
26 | - /** |
|
27 | - * @var Schema |
|
28 | - */ |
|
29 | - private $schema; |
|
30 | - |
|
31 | - /** |
|
32 | - * The root directory of the project. |
|
33 | - * |
|
34 | - * @var string |
|
35 | - */ |
|
36 | - private $rootPath; |
|
37 | - |
|
38 | - /** |
|
39 | - * @var TDBMSchemaAnalyzer |
|
40 | - */ |
|
41 | - private $tdbmSchemaAnalyzer; |
|
42 | - |
|
43 | - /** |
|
44 | - * Constructor. |
|
45 | - * |
|
46 | - * @param Connection $dbConnection The connection to the database. |
|
47 | - */ |
|
48 | - public function __construct(SchemaAnalyzer $schemaAnalyzer, Schema $schema, TDBMSchemaAnalyzer $tdbmSchemaAnalyzer) |
|
49 | - { |
|
50 | - $this->schemaAnalyzer = $schemaAnalyzer; |
|
51 | - $this->schema = $schema; |
|
52 | - $this->tdbmSchemaAnalyzer = $tdbmSchemaAnalyzer; |
|
53 | - $this->rootPath = __DIR__.'/../../../../../../../../'; |
|
54 | - } |
|
55 | - |
|
56 | - /** |
|
57 | - * Generates all the daos and beans. |
|
58 | - * |
|
59 | - * @param string $daoFactoryClassName The classe name of the DAO factory |
|
60 | - * @param string $daonamespace The namespace for the DAOs, without trailing \ |
|
61 | - * @param string $beannamespace The Namespace for the beans, without trailing \ |
|
62 | - * @param bool $storeInUtc If the generated daos should store the date in UTC timezone instead of user's timezone. |
|
63 | - * |
|
64 | - * @return \string[] the list of tables |
|
65 | - * |
|
66 | - * @throws TDBMException |
|
67 | - */ |
|
68 | - public function generateAllDaosAndBeans($daoFactoryClassName, $daonamespace, $beannamespace, $storeInUtc) |
|
69 | - { |
|
70 | - // TODO: extract ClassNameMapper in its own package! |
|
71 | - $classNameMapper = ClassNameMapper::createFromComposerFile($this->rootPath.'composer.json'); |
|
72 | - |
|
73 | - // TODO: check that no class name ends with "Base". Otherwise, there will be name clash. |
|
74 | - |
|
75 | - $tableList = $this->schema->getTables(); |
|
76 | - |
|
77 | - // Remove all beans and daos from junction tables |
|
78 | - $junctionTables = $this->schemaAnalyzer->detectJunctionTables(); |
|
79 | - $junctionTableNames = array_map(function (Table $table) { |
|
80 | - return $table->getName(); |
|
81 | - }, $junctionTables); |
|
82 | - |
|
83 | - $tableList = array_filter($tableList, function (Table $table) use ($junctionTableNames) { |
|
84 | - return !in_array($table->getName(), $junctionTableNames); |
|
85 | - }); |
|
86 | - |
|
87 | - foreach ($tableList as $table) { |
|
88 | - $this->generateDaoAndBean($table, $daonamespace, $beannamespace, $classNameMapper, $storeInUtc); |
|
89 | - } |
|
90 | - |
|
91 | - $this->generateFactory($tableList, $daoFactoryClassName, $daonamespace, $classNameMapper); |
|
92 | - |
|
93 | - // Ok, let's return the list of all tables. |
|
94 | - // These will be used by the calling script to create Mouf instances. |
|
95 | - |
|
96 | - return array_map(function (Table $table) { return $table->getName(); }, $tableList); |
|
97 | - } |
|
98 | - |
|
99 | - /** |
|
100 | - * Generates in one method call the daos and the beans for one table. |
|
101 | - * |
|
102 | - * @param $tableName |
|
103 | - */ |
|
104 | - public function generateDaoAndBean(Table $table, $daonamespace, $beannamespace, ClassNameMapper $classNameMapper, $storeInUtc) |
|
105 | - { |
|
106 | - $tableName = $table->getName(); |
|
107 | - $daoName = $this->getDaoNameFromTableName($tableName); |
|
108 | - $beanName = $this->getBeanNameFromTableName($tableName); |
|
109 | - $baseBeanName = $this->getBaseBeanNameFromTableName($tableName); |
|
110 | - $baseDaoName = $this->getBaseDaoNameFromTableName($tableName); |
|
111 | - |
|
112 | - $this->generateBean($beanName, $baseBeanName, $table, $beannamespace, $classNameMapper, $storeInUtc); |
|
113 | - $this->generateDao($daoName, $baseDaoName, $beanName, $table, $daonamespace, $beannamespace, $classNameMapper); |
|
114 | - } |
|
115 | - |
|
116 | - /** |
|
117 | - * Returns the name of the bean class from the table name. |
|
118 | - * |
|
119 | - * @param $tableName |
|
120 | - * |
|
121 | - * @return string |
|
122 | - */ |
|
123 | - public static function getBeanNameFromTableName($tableName) |
|
124 | - { |
|
125 | - return self::toSingular(self::toCamelCase($tableName)).'Bean'; |
|
126 | - } |
|
127 | - |
|
128 | - /** |
|
129 | - * Returns the name of the DAO class from the table name. |
|
130 | - * |
|
131 | - * @param $tableName |
|
132 | - * |
|
133 | - * @return string |
|
134 | - */ |
|
135 | - public static function getDaoNameFromTableName($tableName) |
|
136 | - { |
|
137 | - return self::toSingular(self::toCamelCase($tableName)).'Dao'; |
|
138 | - } |
|
139 | - |
|
140 | - /** |
|
141 | - * Returns the name of the base bean class from the table name. |
|
142 | - * |
|
143 | - * @param $tableName |
|
144 | - * |
|
145 | - * @return string |
|
146 | - */ |
|
147 | - public static function getBaseBeanNameFromTableName($tableName) |
|
148 | - { |
|
149 | - return self::toSingular(self::toCamelCase($tableName)).'BaseBean'; |
|
150 | - } |
|
151 | - |
|
152 | - /** |
|
153 | - * Returns the name of the base DAO class from the table name. |
|
154 | - * |
|
155 | - * @param $tableName |
|
156 | - * |
|
157 | - * @return string |
|
158 | - */ |
|
159 | - public static function getBaseDaoNameFromTableName($tableName) |
|
160 | - { |
|
161 | - return self::toSingular(self::toCamelCase($tableName)).'BaseDao'; |
|
162 | - } |
|
163 | - |
|
164 | - /** |
|
165 | - * Writes the PHP bean file with all getters and setters from the table passed in parameter. |
|
166 | - * |
|
167 | - * @param string $className The name of the class |
|
168 | - * @param string $baseClassName The name of the base class which will be extended (name only, no directory) |
|
169 | - * @param Table $table The table |
|
170 | - * @param string $beannamespace The namespace of the bean |
|
171 | - * @param ClassNameMapper $classNameMapper |
|
172 | - * |
|
173 | - * @throws TDBMException |
|
174 | - */ |
|
175 | - public function generateBean($className, $baseClassName, Table $table, $beannamespace, ClassNameMapper $classNameMapper, $storeInUtc) |
|
176 | - { |
|
177 | - $beanDescriptor = new BeanDescriptor($table, $this->schemaAnalyzer, $this->schema, $this->tdbmSchemaAnalyzer); |
|
178 | - |
|
179 | - $str = $beanDescriptor->generatePhpCode($beannamespace); |
|
180 | - |
|
181 | - $possibleBaseFileNames = $classNameMapper->getPossibleFileNames($beannamespace.'\\'.$baseClassName); |
|
182 | - if (!$possibleBaseFileNames) { |
|
183 | - throw new TDBMException('Sorry, autoload namespace issue. The class "'.$beannamespace.'\\'.$baseClassName.'" is not autoloadable.'); |
|
184 | - } |
|
185 | - $possibleBaseFileName = $this->rootPath.$possibleBaseFileNames[0]; |
|
186 | - |
|
187 | - $this->ensureDirectoryExist($possibleBaseFileName); |
|
188 | - file_put_contents($possibleBaseFileName, $str); |
|
189 | - @chmod($possibleBaseFileName, 0664); |
|
190 | - |
|
191 | - $possibleFileNames = $classNameMapper->getPossibleFileNames($beannamespace.'\\'.$className); |
|
192 | - if (!$possibleFileNames) { |
|
193 | - // @codeCoverageIgnoreStart |
|
194 | - throw new TDBMException('Sorry, autoload namespace issue. The class "'.$beannamespace.'\\'.$className.'" is not autoloadable.'); |
|
195 | - // @codeCoverageIgnoreEnd |
|
196 | - } |
|
197 | - $possibleFileName = $this->rootPath.$possibleFileNames[0]; |
|
198 | - |
|
199 | - if (!file_exists($possibleFileName)) { |
|
200 | - $tableName = $table->getName(); |
|
201 | - |
|
202 | - $str = "<?php |
|
21 | + /** |
|
22 | + * @var SchemaAnalyzer |
|
23 | + */ |
|
24 | + private $schemaAnalyzer; |
|
25 | + |
|
26 | + /** |
|
27 | + * @var Schema |
|
28 | + */ |
|
29 | + private $schema; |
|
30 | + |
|
31 | + /** |
|
32 | + * The root directory of the project. |
|
33 | + * |
|
34 | + * @var string |
|
35 | + */ |
|
36 | + private $rootPath; |
|
37 | + |
|
38 | + /** |
|
39 | + * @var TDBMSchemaAnalyzer |
|
40 | + */ |
|
41 | + private $tdbmSchemaAnalyzer; |
|
42 | + |
|
43 | + /** |
|
44 | + * Constructor. |
|
45 | + * |
|
46 | + * @param Connection $dbConnection The connection to the database. |
|
47 | + */ |
|
48 | + public function __construct(SchemaAnalyzer $schemaAnalyzer, Schema $schema, TDBMSchemaAnalyzer $tdbmSchemaAnalyzer) |
|
49 | + { |
|
50 | + $this->schemaAnalyzer = $schemaAnalyzer; |
|
51 | + $this->schema = $schema; |
|
52 | + $this->tdbmSchemaAnalyzer = $tdbmSchemaAnalyzer; |
|
53 | + $this->rootPath = __DIR__.'/../../../../../../../../'; |
|
54 | + } |
|
55 | + |
|
56 | + /** |
|
57 | + * Generates all the daos and beans. |
|
58 | + * |
|
59 | + * @param string $daoFactoryClassName The classe name of the DAO factory |
|
60 | + * @param string $daonamespace The namespace for the DAOs, without trailing \ |
|
61 | + * @param string $beannamespace The Namespace for the beans, without trailing \ |
|
62 | + * @param bool $storeInUtc If the generated daos should store the date in UTC timezone instead of user's timezone. |
|
63 | + * |
|
64 | + * @return \string[] the list of tables |
|
65 | + * |
|
66 | + * @throws TDBMException |
|
67 | + */ |
|
68 | + public function generateAllDaosAndBeans($daoFactoryClassName, $daonamespace, $beannamespace, $storeInUtc) |
|
69 | + { |
|
70 | + // TODO: extract ClassNameMapper in its own package! |
|
71 | + $classNameMapper = ClassNameMapper::createFromComposerFile($this->rootPath.'composer.json'); |
|
72 | + |
|
73 | + // TODO: check that no class name ends with "Base". Otherwise, there will be name clash. |
|
74 | + |
|
75 | + $tableList = $this->schema->getTables(); |
|
76 | + |
|
77 | + // Remove all beans and daos from junction tables |
|
78 | + $junctionTables = $this->schemaAnalyzer->detectJunctionTables(); |
|
79 | + $junctionTableNames = array_map(function (Table $table) { |
|
80 | + return $table->getName(); |
|
81 | + }, $junctionTables); |
|
82 | + |
|
83 | + $tableList = array_filter($tableList, function (Table $table) use ($junctionTableNames) { |
|
84 | + return !in_array($table->getName(), $junctionTableNames); |
|
85 | + }); |
|
86 | + |
|
87 | + foreach ($tableList as $table) { |
|
88 | + $this->generateDaoAndBean($table, $daonamespace, $beannamespace, $classNameMapper, $storeInUtc); |
|
89 | + } |
|
90 | + |
|
91 | + $this->generateFactory($tableList, $daoFactoryClassName, $daonamespace, $classNameMapper); |
|
92 | + |
|
93 | + // Ok, let's return the list of all tables. |
|
94 | + // These will be used by the calling script to create Mouf instances. |
|
95 | + |
|
96 | + return array_map(function (Table $table) { return $table->getName(); }, $tableList); |
|
97 | + } |
|
98 | + |
|
99 | + /** |
|
100 | + * Generates in one method call the daos and the beans for one table. |
|
101 | + * |
|
102 | + * @param $tableName |
|
103 | + */ |
|
104 | + public function generateDaoAndBean(Table $table, $daonamespace, $beannamespace, ClassNameMapper $classNameMapper, $storeInUtc) |
|
105 | + { |
|
106 | + $tableName = $table->getName(); |
|
107 | + $daoName = $this->getDaoNameFromTableName($tableName); |
|
108 | + $beanName = $this->getBeanNameFromTableName($tableName); |
|
109 | + $baseBeanName = $this->getBaseBeanNameFromTableName($tableName); |
|
110 | + $baseDaoName = $this->getBaseDaoNameFromTableName($tableName); |
|
111 | + |
|
112 | + $this->generateBean($beanName, $baseBeanName, $table, $beannamespace, $classNameMapper, $storeInUtc); |
|
113 | + $this->generateDao($daoName, $baseDaoName, $beanName, $table, $daonamespace, $beannamespace, $classNameMapper); |
|
114 | + } |
|
115 | + |
|
116 | + /** |
|
117 | + * Returns the name of the bean class from the table name. |
|
118 | + * |
|
119 | + * @param $tableName |
|
120 | + * |
|
121 | + * @return string |
|
122 | + */ |
|
123 | + public static function getBeanNameFromTableName($tableName) |
|
124 | + { |
|
125 | + return self::toSingular(self::toCamelCase($tableName)).'Bean'; |
|
126 | + } |
|
127 | + |
|
128 | + /** |
|
129 | + * Returns the name of the DAO class from the table name. |
|
130 | + * |
|
131 | + * @param $tableName |
|
132 | + * |
|
133 | + * @return string |
|
134 | + */ |
|
135 | + public static function getDaoNameFromTableName($tableName) |
|
136 | + { |
|
137 | + return self::toSingular(self::toCamelCase($tableName)).'Dao'; |
|
138 | + } |
|
139 | + |
|
140 | + /** |
|
141 | + * Returns the name of the base bean class from the table name. |
|
142 | + * |
|
143 | + * @param $tableName |
|
144 | + * |
|
145 | + * @return string |
|
146 | + */ |
|
147 | + public static function getBaseBeanNameFromTableName($tableName) |
|
148 | + { |
|
149 | + return self::toSingular(self::toCamelCase($tableName)).'BaseBean'; |
|
150 | + } |
|
151 | + |
|
152 | + /** |
|
153 | + * Returns the name of the base DAO class from the table name. |
|
154 | + * |
|
155 | + * @param $tableName |
|
156 | + * |
|
157 | + * @return string |
|
158 | + */ |
|
159 | + public static function getBaseDaoNameFromTableName($tableName) |
|
160 | + { |
|
161 | + return self::toSingular(self::toCamelCase($tableName)).'BaseDao'; |
|
162 | + } |
|
163 | + |
|
164 | + /** |
|
165 | + * Writes the PHP bean file with all getters and setters from the table passed in parameter. |
|
166 | + * |
|
167 | + * @param string $className The name of the class |
|
168 | + * @param string $baseClassName The name of the base class which will be extended (name only, no directory) |
|
169 | + * @param Table $table The table |
|
170 | + * @param string $beannamespace The namespace of the bean |
|
171 | + * @param ClassNameMapper $classNameMapper |
|
172 | + * |
|
173 | + * @throws TDBMException |
|
174 | + */ |
|
175 | + public function generateBean($className, $baseClassName, Table $table, $beannamespace, ClassNameMapper $classNameMapper, $storeInUtc) |
|
176 | + { |
|
177 | + $beanDescriptor = new BeanDescriptor($table, $this->schemaAnalyzer, $this->schema, $this->tdbmSchemaAnalyzer); |
|
178 | + |
|
179 | + $str = $beanDescriptor->generatePhpCode($beannamespace); |
|
180 | + |
|
181 | + $possibleBaseFileNames = $classNameMapper->getPossibleFileNames($beannamespace.'\\'.$baseClassName); |
|
182 | + if (!$possibleBaseFileNames) { |
|
183 | + throw new TDBMException('Sorry, autoload namespace issue. The class "'.$beannamespace.'\\'.$baseClassName.'" is not autoloadable.'); |
|
184 | + } |
|
185 | + $possibleBaseFileName = $this->rootPath.$possibleBaseFileNames[0]; |
|
186 | + |
|
187 | + $this->ensureDirectoryExist($possibleBaseFileName); |
|
188 | + file_put_contents($possibleBaseFileName, $str); |
|
189 | + @chmod($possibleBaseFileName, 0664); |
|
190 | + |
|
191 | + $possibleFileNames = $classNameMapper->getPossibleFileNames($beannamespace.'\\'.$className); |
|
192 | + if (!$possibleFileNames) { |
|
193 | + // @codeCoverageIgnoreStart |
|
194 | + throw new TDBMException('Sorry, autoload namespace issue. The class "'.$beannamespace.'\\'.$className.'" is not autoloadable.'); |
|
195 | + // @codeCoverageIgnoreEnd |
|
196 | + } |
|
197 | + $possibleFileName = $this->rootPath.$possibleFileNames[0]; |
|
198 | + |
|
199 | + if (!file_exists($possibleFileName)) { |
|
200 | + $tableName = $table->getName(); |
|
201 | + |
|
202 | + $str = "<?php |
|
203 | 203 | /* |
204 | 204 | * This file has been automatically generated by TDBM. |
205 | 205 | * You can edit this file as it will not be overwritten. |
@@ -214,45 +214,45 @@ discard block |
||
214 | 214 | { |
215 | 215 | |
216 | 216 | }"; |
217 | - $this->ensureDirectoryExist($possibleFileName); |
|
218 | - file_put_contents($possibleFileName, $str); |
|
219 | - @chmod($possibleFileName, 0664); |
|
220 | - } |
|
221 | - } |
|
222 | - |
|
223 | - /** |
|
224 | - * Writes the PHP bean DAO with simple functions to create/get/save objects. |
|
225 | - * |
|
226 | - * @param string $fileName The file that will be written (without the directory) |
|
227 | - * @param string $className The name of the class |
|
228 | - * @param string $tableName The name of the table |
|
229 | - */ |
|
230 | - public function generateDao($className, $baseClassName, $beanClassName, Table $table, $daonamespace, $beannamespace, ClassNameMapper $classNameMapper) |
|
231 | - { |
|
232 | - $tableName = $table->getName(); |
|
233 | - $primaryKeyColumns = $table->getPrimaryKeyColumns(); |
|
234 | - |
|
235 | - $defaultSort = null; |
|
236 | - foreach ($table->getColumns() as $column) { |
|
237 | - $comments = $column->getComment(); |
|
238 | - $matches = array(); |
|
239 | - if (preg_match('/@defaultSort(\((desc|asc)\))*/', $comments, $matches) != 0) { |
|
240 | - $defaultSort = $data['column_name']; |
|
241 | - if (count($matches == 3)) { |
|
242 | - $defaultSortDirection = $matches[2]; |
|
243 | - } else { |
|
244 | - $defaultSortDirection = 'ASC'; |
|
245 | - } |
|
246 | - } |
|
247 | - } |
|
248 | - |
|
249 | - // FIXME: lowercase tables with _ in the name should work! |
|
250 | - $tableCamel = self::toSingular(self::toCamelCase($tableName)); |
|
251 | - |
|
252 | - $beanClassWithoutNameSpace = $beanClassName; |
|
253 | - $beanClassName = $beannamespace.'\\'.$beanClassName; |
|
254 | - |
|
255 | - $str = "<?php |
|
217 | + $this->ensureDirectoryExist($possibleFileName); |
|
218 | + file_put_contents($possibleFileName, $str); |
|
219 | + @chmod($possibleFileName, 0664); |
|
220 | + } |
|
221 | + } |
|
222 | + |
|
223 | + /** |
|
224 | + * Writes the PHP bean DAO with simple functions to create/get/save objects. |
|
225 | + * |
|
226 | + * @param string $fileName The file that will be written (without the directory) |
|
227 | + * @param string $className The name of the class |
|
228 | + * @param string $tableName The name of the table |
|
229 | + */ |
|
230 | + public function generateDao($className, $baseClassName, $beanClassName, Table $table, $daonamespace, $beannamespace, ClassNameMapper $classNameMapper) |
|
231 | + { |
|
232 | + $tableName = $table->getName(); |
|
233 | + $primaryKeyColumns = $table->getPrimaryKeyColumns(); |
|
234 | + |
|
235 | + $defaultSort = null; |
|
236 | + foreach ($table->getColumns() as $column) { |
|
237 | + $comments = $column->getComment(); |
|
238 | + $matches = array(); |
|
239 | + if (preg_match('/@defaultSort(\((desc|asc)\))*/', $comments, $matches) != 0) { |
|
240 | + $defaultSort = $data['column_name']; |
|
241 | + if (count($matches == 3)) { |
|
242 | + $defaultSortDirection = $matches[2]; |
|
243 | + } else { |
|
244 | + $defaultSortDirection = 'ASC'; |
|
245 | + } |
|
246 | + } |
|
247 | + } |
|
248 | + |
|
249 | + // FIXME: lowercase tables with _ in the name should work! |
|
250 | + $tableCamel = self::toSingular(self::toCamelCase($tableName)); |
|
251 | + |
|
252 | + $beanClassWithoutNameSpace = $beanClassName; |
|
253 | + $beanClassName = $beannamespace.'\\'.$beanClassName; |
|
254 | + |
|
255 | + $str = "<?php |
|
256 | 256 | |
257 | 257 | /* |
258 | 258 | * This file has been automatically generated by TDBM. |
@@ -339,9 +339,9 @@ discard block |
||
339 | 339 | } |
340 | 340 | "; |
341 | 341 | |
342 | - if (count($primaryKeyColumns) === 1) { |
|
343 | - $primaryKeyColumn = $primaryKeyColumns[0]; |
|
344 | - $str .= " |
|
342 | + if (count($primaryKeyColumns) === 1) { |
|
343 | + $primaryKeyColumn = $primaryKeyColumns[0]; |
|
344 | + $str .= " |
|
345 | 345 | /** |
346 | 346 | * Get $beanClassWithoutNameSpace specified by its ID (its primary key) |
347 | 347 | * If the primary key does not exist, an exception is thrown. |
@@ -356,8 +356,8 @@ discard block |
||
356 | 356 | return \$this->tdbmService->findObjectByPk('$tableName', ['$primaryKeyColumn' => \$id], [], \$lazyLoading); |
357 | 357 | } |
358 | 358 | "; |
359 | - } |
|
360 | - $str .= " |
|
359 | + } |
|
360 | + $str .= " |
|
361 | 361 | /** |
362 | 362 | * Deletes the $beanClassWithoutNameSpace passed in parameter. |
363 | 363 | * |
@@ -415,33 +415,33 @@ discard block |
||
415 | 415 | } |
416 | 416 | "; |
417 | 417 | |
418 | - $str .= ' |
|
418 | + $str .= ' |
|
419 | 419 | } |
420 | 420 | '; |
421 | 421 | |
422 | - $possibleBaseFileNames = $classNameMapper->getPossibleFileNames($daonamespace.'\\'.$baseClassName); |
|
423 | - if (!$possibleBaseFileNames) { |
|
424 | - // @codeCoverageIgnoreStart |
|
425 | - throw new TDBMException('Sorry, autoload namespace issue. The class "'.$baseClassName.'" is not autoloadable.'); |
|
426 | - // @codeCoverageIgnoreEnd |
|
427 | - } |
|
428 | - $possibleBaseFileName = $this->rootPath.$possibleBaseFileNames[0]; |
|
429 | - |
|
430 | - $this->ensureDirectoryExist($possibleBaseFileName); |
|
431 | - file_put_contents($possibleBaseFileName, $str); |
|
432 | - @chmod($possibleBaseFileName, 0664); |
|
433 | - |
|
434 | - $possibleFileNames = $classNameMapper->getPossibleFileNames($daonamespace.'\\'.$className); |
|
435 | - if (!$possibleFileNames) { |
|
436 | - // @codeCoverageIgnoreStart |
|
437 | - throw new TDBMException('Sorry, autoload namespace issue. The class "'.$className.'" is not autoloadable.'); |
|
438 | - // @codeCoverageIgnoreEnd |
|
439 | - } |
|
440 | - $possibleFileName = $this->rootPath.$possibleFileNames[0]; |
|
441 | - |
|
442 | - // Now, let's generate the "editable" class |
|
443 | - if (!file_exists($possibleFileName)) { |
|
444 | - $str = "<?php |
|
422 | + $possibleBaseFileNames = $classNameMapper->getPossibleFileNames($daonamespace.'\\'.$baseClassName); |
|
423 | + if (!$possibleBaseFileNames) { |
|
424 | + // @codeCoverageIgnoreStart |
|
425 | + throw new TDBMException('Sorry, autoload namespace issue. The class "'.$baseClassName.'" is not autoloadable.'); |
|
426 | + // @codeCoverageIgnoreEnd |
|
427 | + } |
|
428 | + $possibleBaseFileName = $this->rootPath.$possibleBaseFileNames[0]; |
|
429 | + |
|
430 | + $this->ensureDirectoryExist($possibleBaseFileName); |
|
431 | + file_put_contents($possibleBaseFileName, $str); |
|
432 | + @chmod($possibleBaseFileName, 0664); |
|
433 | + |
|
434 | + $possibleFileNames = $classNameMapper->getPossibleFileNames($daonamespace.'\\'.$className); |
|
435 | + if (!$possibleFileNames) { |
|
436 | + // @codeCoverageIgnoreStart |
|
437 | + throw new TDBMException('Sorry, autoload namespace issue. The class "'.$className.'" is not autoloadable.'); |
|
438 | + // @codeCoverageIgnoreEnd |
|
439 | + } |
|
440 | + $possibleFileName = $this->rootPath.$possibleFileNames[0]; |
|
441 | + |
|
442 | + // Now, let's generate the "editable" class |
|
443 | + if (!file_exists($possibleFileName)) { |
|
444 | + $str = "<?php |
|
445 | 445 | |
446 | 446 | /* |
447 | 447 | * This file has been automatically generated by TDBM. |
@@ -458,22 +458,22 @@ discard block |
||
458 | 458 | |
459 | 459 | } |
460 | 460 | "; |
461 | - $this->ensureDirectoryExist($possibleFileName); |
|
462 | - file_put_contents($possibleFileName, $str); |
|
463 | - @chmod($possibleFileName, 0664); |
|
464 | - } |
|
465 | - } |
|
466 | - |
|
467 | - /** |
|
468 | - * Generates the factory bean. |
|
469 | - * |
|
470 | - * @param Table[] $tableList |
|
471 | - */ |
|
472 | - private function generateFactory(array $tableList, $daoFactoryClassName, $daoNamespace, ClassNameMapper $classNameMapper) |
|
473 | - { |
|
474 | - // For each table, let's write a property. |
|
475 | - |
|
476 | - $str = "<?php |
|
461 | + $this->ensureDirectoryExist($possibleFileName); |
|
462 | + file_put_contents($possibleFileName, $str); |
|
463 | + @chmod($possibleFileName, 0664); |
|
464 | + } |
|
465 | + } |
|
466 | + |
|
467 | + /** |
|
468 | + * Generates the factory bean. |
|
469 | + * |
|
470 | + * @param Table[] $tableList |
|
471 | + */ |
|
472 | + private function generateFactory(array $tableList, $daoFactoryClassName, $daoNamespace, ClassNameMapper $classNameMapper) |
|
473 | + { |
|
474 | + // For each table, let's write a property. |
|
475 | + |
|
476 | + $str = "<?php |
|
477 | 477 | |
478 | 478 | /* |
479 | 479 | * This file has been automatically generated by TDBM. |
@@ -490,12 +490,12 @@ discard block |
||
490 | 490 | { |
491 | 491 | "; |
492 | 492 | |
493 | - foreach ($tableList as $table) { |
|
494 | - $tableName = $table->getName(); |
|
495 | - $daoClassName = $this->getDaoNameFromTableName($tableName); |
|
496 | - $daoInstanceName = self::toVariableName($daoClassName); |
|
493 | + foreach ($tableList as $table) { |
|
494 | + $tableName = $table->getName(); |
|
495 | + $daoClassName = $this->getDaoNameFromTableName($tableName); |
|
496 | + $daoInstanceName = self::toVariableName($daoClassName); |
|
497 | 497 | |
498 | - $str .= ' /** |
|
498 | + $str .= ' /** |
|
499 | 499 | * @var '.$daoClassName.' |
500 | 500 | */ |
501 | 501 | private $'.$daoInstanceName.'; |
@@ -520,155 +520,155 @@ discard block |
||
520 | 520 | } |
521 | 521 | |
522 | 522 | '; |
523 | - } |
|
523 | + } |
|
524 | 524 | |
525 | - $str .= ' |
|
525 | + $str .= ' |
|
526 | 526 | } |
527 | 527 | '; |
528 | 528 | |
529 | - $possibleFileNames = $classNameMapper->getPossibleFileNames($daoNamespace.'\\'.$daoFactoryClassName); |
|
530 | - if (!$possibleFileNames) { |
|
531 | - throw new TDBMException('Sorry, autoload namespace issue. The class "'.$daoNamespace.'\\'.$daoFactoryClassName.'" is not autoloadable.'); |
|
532 | - } |
|
533 | - $possibleFileName = $this->rootPath.$possibleFileNames[0]; |
|
534 | - |
|
535 | - $this->ensureDirectoryExist($possibleFileName); |
|
536 | - file_put_contents($possibleFileName, $str); |
|
537 | - @chmod($possibleFileName, 0664); |
|
538 | - } |
|
539 | - |
|
540 | - /** |
|
541 | - * Transforms a string to camelCase (except the first letter will be uppercase too). |
|
542 | - * Underscores and spaces are removed and the first letter after the underscore is uppercased. |
|
543 | - * |
|
544 | - * @param $str string |
|
545 | - * |
|
546 | - * @return string |
|
547 | - */ |
|
548 | - public static function toCamelCase($str) |
|
549 | - { |
|
550 | - $str = strtoupper(substr($str, 0, 1)).substr($str, 1); |
|
551 | - while (true) { |
|
552 | - if (strpos($str, '_') === false && strpos($str, ' ') === false) { |
|
553 | - break; |
|
554 | - } |
|
555 | - |
|
556 | - $pos = strpos($str, '_'); |
|
557 | - if ($pos === false) { |
|
558 | - $pos = strpos($str, ' '); |
|
559 | - } |
|
560 | - $before = substr($str, 0, $pos); |
|
561 | - $after = substr($str, $pos + 1); |
|
562 | - $str = $before.strtoupper(substr($after, 0, 1)).substr($after, 1); |
|
563 | - } |
|
564 | - |
|
565 | - return $str; |
|
566 | - } |
|
567 | - |
|
568 | - /** |
|
569 | - * Tries to put string to the singular form (if it is plural). |
|
570 | - * We assume the table names are in english. |
|
571 | - * |
|
572 | - * @param $str string |
|
573 | - * |
|
574 | - * @return string |
|
575 | - */ |
|
576 | - public static function toSingular($str) |
|
577 | - { |
|
578 | - return Inflector::singularize($str); |
|
579 | - } |
|
580 | - |
|
581 | - /** |
|
582 | - * Put the first letter of the string in lower case. |
|
583 | - * Very useful to transform a class name into a variable name. |
|
584 | - * |
|
585 | - * @param $str string |
|
586 | - * |
|
587 | - * @return string |
|
588 | - */ |
|
589 | - public static function toVariableName($str) |
|
590 | - { |
|
591 | - return strtolower(substr($str, 0, 1)).substr($str, 1); |
|
592 | - } |
|
593 | - |
|
594 | - /** |
|
595 | - * Ensures the file passed in parameter can be written in its directory. |
|
596 | - * |
|
597 | - * @param string $fileName |
|
598 | - * |
|
599 | - * @throws TDBMException |
|
600 | - */ |
|
601 | - private function ensureDirectoryExist($fileName) |
|
602 | - { |
|
603 | - $dirName = dirname($fileName); |
|
604 | - if (!file_exists($dirName)) { |
|
605 | - $old = umask(0); |
|
606 | - $result = mkdir($dirName, 0775, true); |
|
607 | - umask($old); |
|
608 | - if ($result === false) { |
|
609 | - throw new TDBMException("Unable to create directory: '".$dirName."'."); |
|
610 | - } |
|
611 | - } |
|
612 | - } |
|
613 | - |
|
614 | - /** |
|
615 | - * @param string $rootPath |
|
616 | - */ |
|
617 | - public function setRootPath($rootPath) |
|
618 | - { |
|
619 | - $this->rootPath = $rootPath; |
|
620 | - } |
|
621 | - |
|
622 | - /** |
|
623 | - * Transforms a DBAL type into a PHP type (for PHPDoc purpose). |
|
624 | - * |
|
625 | - * @param Type $type The DBAL type |
|
626 | - * |
|
627 | - * @return string The PHP type |
|
628 | - */ |
|
629 | - public static function dbalTypeToPhpType(Type $type) |
|
630 | - { |
|
631 | - $map = [ |
|
632 | - Type::TARRAY => 'array', |
|
633 | - Type::SIMPLE_ARRAY => 'array', |
|
634 | - Type::JSON_ARRAY => 'array', |
|
635 | - Type::BIGINT => 'string', |
|
636 | - Type::BOOLEAN => 'bool', |
|
637 | - Type::DATETIME => '\DateTimeInterface', |
|
638 | - Type::DATETIMETZ => '\DateTimeInterface', |
|
639 | - Type::DATE => '\DateTimeInterface', |
|
640 | - Type::TIME => '\DateTimeInterface', |
|
641 | - Type::DECIMAL => 'float', |
|
642 | - Type::INTEGER => 'int', |
|
643 | - Type::OBJECT => 'string', |
|
644 | - Type::SMALLINT => 'int', |
|
645 | - Type::STRING => 'string', |
|
646 | - Type::TEXT => 'string', |
|
647 | - Type::BINARY => 'string', |
|
648 | - Type::BLOB => 'string', |
|
649 | - Type::FLOAT => 'float', |
|
650 | - Type::GUID => 'string', |
|
651 | - ]; |
|
652 | - |
|
653 | - return isset($map[$type->getName()]) ? $map[$type->getName()] : $type->getName(); |
|
654 | - } |
|
655 | - |
|
656 | - /** |
|
657 | - * @param string $beanNamespace |
|
658 | - * |
|
659 | - * @return \string[] Returns a map mapping table name to beans name |
|
660 | - */ |
|
661 | - public function buildTableToBeanMap($beanNamespace) |
|
662 | - { |
|
663 | - $tableToBeanMap = []; |
|
664 | - |
|
665 | - $tables = $this->schema->getTables(); |
|
666 | - |
|
667 | - foreach ($tables as $table) { |
|
668 | - $tableName = $table->getName(); |
|
669 | - $tableToBeanMap[$tableName] = $beanNamespace.'\\'.self::getBeanNameFromTableName($tableName); |
|
670 | - } |
|
671 | - |
|
672 | - return $tableToBeanMap; |
|
673 | - } |
|
529 | + $possibleFileNames = $classNameMapper->getPossibleFileNames($daoNamespace.'\\'.$daoFactoryClassName); |
|
530 | + if (!$possibleFileNames) { |
|
531 | + throw new TDBMException('Sorry, autoload namespace issue. The class "'.$daoNamespace.'\\'.$daoFactoryClassName.'" is not autoloadable.'); |
|
532 | + } |
|
533 | + $possibleFileName = $this->rootPath.$possibleFileNames[0]; |
|
534 | + |
|
535 | + $this->ensureDirectoryExist($possibleFileName); |
|
536 | + file_put_contents($possibleFileName, $str); |
|
537 | + @chmod($possibleFileName, 0664); |
|
538 | + } |
|
539 | + |
|
540 | + /** |
|
541 | + * Transforms a string to camelCase (except the first letter will be uppercase too). |
|
542 | + * Underscores and spaces are removed and the first letter after the underscore is uppercased. |
|
543 | + * |
|
544 | + * @param $str string |
|
545 | + * |
|
546 | + * @return string |
|
547 | + */ |
|
548 | + public static function toCamelCase($str) |
|
549 | + { |
|
550 | + $str = strtoupper(substr($str, 0, 1)).substr($str, 1); |
|
551 | + while (true) { |
|
552 | + if (strpos($str, '_') === false && strpos($str, ' ') === false) { |
|
553 | + break; |
|
554 | + } |
|
555 | + |
|
556 | + $pos = strpos($str, '_'); |
|
557 | + if ($pos === false) { |
|
558 | + $pos = strpos($str, ' '); |
|
559 | + } |
|
560 | + $before = substr($str, 0, $pos); |
|
561 | + $after = substr($str, $pos + 1); |
|
562 | + $str = $before.strtoupper(substr($after, 0, 1)).substr($after, 1); |
|
563 | + } |
|
564 | + |
|
565 | + return $str; |
|
566 | + } |
|
567 | + |
|
568 | + /** |
|
569 | + * Tries to put string to the singular form (if it is plural). |
|
570 | + * We assume the table names are in english. |
|
571 | + * |
|
572 | + * @param $str string |
|
573 | + * |
|
574 | + * @return string |
|
575 | + */ |
|
576 | + public static function toSingular($str) |
|
577 | + { |
|
578 | + return Inflector::singularize($str); |
|
579 | + } |
|
580 | + |
|
581 | + /** |
|
582 | + * Put the first letter of the string in lower case. |
|
583 | + * Very useful to transform a class name into a variable name. |
|
584 | + * |
|
585 | + * @param $str string |
|
586 | + * |
|
587 | + * @return string |
|
588 | + */ |
|
589 | + public static function toVariableName($str) |
|
590 | + { |
|
591 | + return strtolower(substr($str, 0, 1)).substr($str, 1); |
|
592 | + } |
|
593 | + |
|
594 | + /** |
|
595 | + * Ensures the file passed in parameter can be written in its directory. |
|
596 | + * |
|
597 | + * @param string $fileName |
|
598 | + * |
|
599 | + * @throws TDBMException |
|
600 | + */ |
|
601 | + private function ensureDirectoryExist($fileName) |
|
602 | + { |
|
603 | + $dirName = dirname($fileName); |
|
604 | + if (!file_exists($dirName)) { |
|
605 | + $old = umask(0); |
|
606 | + $result = mkdir($dirName, 0775, true); |
|
607 | + umask($old); |
|
608 | + if ($result === false) { |
|
609 | + throw new TDBMException("Unable to create directory: '".$dirName."'."); |
|
610 | + } |
|
611 | + } |
|
612 | + } |
|
613 | + |
|
614 | + /** |
|
615 | + * @param string $rootPath |
|
616 | + */ |
|
617 | + public function setRootPath($rootPath) |
|
618 | + { |
|
619 | + $this->rootPath = $rootPath; |
|
620 | + } |
|
621 | + |
|
622 | + /** |
|
623 | + * Transforms a DBAL type into a PHP type (for PHPDoc purpose). |
|
624 | + * |
|
625 | + * @param Type $type The DBAL type |
|
626 | + * |
|
627 | + * @return string The PHP type |
|
628 | + */ |
|
629 | + public static function dbalTypeToPhpType(Type $type) |
|
630 | + { |
|
631 | + $map = [ |
|
632 | + Type::TARRAY => 'array', |
|
633 | + Type::SIMPLE_ARRAY => 'array', |
|
634 | + Type::JSON_ARRAY => 'array', |
|
635 | + Type::BIGINT => 'string', |
|
636 | + Type::BOOLEAN => 'bool', |
|
637 | + Type::DATETIME => '\DateTimeInterface', |
|
638 | + Type::DATETIMETZ => '\DateTimeInterface', |
|
639 | + Type::DATE => '\DateTimeInterface', |
|
640 | + Type::TIME => '\DateTimeInterface', |
|
641 | + Type::DECIMAL => 'float', |
|
642 | + Type::INTEGER => 'int', |
|
643 | + Type::OBJECT => 'string', |
|
644 | + Type::SMALLINT => 'int', |
|
645 | + Type::STRING => 'string', |
|
646 | + Type::TEXT => 'string', |
|
647 | + Type::BINARY => 'string', |
|
648 | + Type::BLOB => 'string', |
|
649 | + Type::FLOAT => 'float', |
|
650 | + Type::GUID => 'string', |
|
651 | + ]; |
|
652 | + |
|
653 | + return isset($map[$type->getName()]) ? $map[$type->getName()] : $type->getName(); |
|
654 | + } |
|
655 | + |
|
656 | + /** |
|
657 | + * @param string $beanNamespace |
|
658 | + * |
|
659 | + * @return \string[] Returns a map mapping table name to beans name |
|
660 | + */ |
|
661 | + public function buildTableToBeanMap($beanNamespace) |
|
662 | + { |
|
663 | + $tableToBeanMap = []; |
|
664 | + |
|
665 | + $tables = $this->schema->getTables(); |
|
666 | + |
|
667 | + foreach ($tables as $table) { |
|
668 | + $tableName = $table->getName(); |
|
669 | + $tableToBeanMap[$tableName] = $beanNamespace.'\\'.self::getBeanNameFromTableName($tableName); |
|
670 | + } |
|
671 | + |
|
672 | + return $tableToBeanMap; |
|
673 | + } |
|
674 | 674 | } |
@@ -76,11 +76,11 @@ discard block |
||
76 | 76 | |
77 | 77 | // Remove all beans and daos from junction tables |
78 | 78 | $junctionTables = $this->schemaAnalyzer->detectJunctionTables(); |
79 | - $junctionTableNames = array_map(function (Table $table) { |
|
79 | + $junctionTableNames = array_map(function(Table $table) { |
|
80 | 80 | return $table->getName(); |
81 | 81 | }, $junctionTables); |
82 | 82 | |
83 | - $tableList = array_filter($tableList, function (Table $table) use ($junctionTableNames) { |
|
83 | + $tableList = array_filter($tableList, function(Table $table) use ($junctionTableNames) { |
|
84 | 84 | return !in_array($table->getName(), $junctionTableNames); |
85 | 85 | }); |
86 | 86 | |
@@ -93,7 +93,7 @@ discard block |
||
93 | 93 | // Ok, let's return the list of all tables. |
94 | 94 | // These will be used by the calling script to create Mouf instances. |
95 | 95 | |
96 | - return array_map(function (Table $table) { return $table->getName(); }, $tableList); |
|
96 | + return array_map(function(Table $table) { return $table->getName(); }, $tableList); |
|
97 | 97 | } |
98 | 98 | |
99 | 99 | /** |
@@ -558,7 +558,7 @@ discard block |
||
558 | 558 | $pos = strpos($str, ' '); |
559 | 559 | } |
560 | 560 | $before = substr($str, 0, $pos); |
561 | - $after = substr($str, $pos + 1); |
|
561 | + $after = substr($str, $pos+1); |
|
562 | 562 | $str = $before.strtoupper(substr($after, 0, 1)).substr($after, 1); |
563 | 563 | } |
564 | 564 |
@@ -8,7 +8,7 @@ |
||
8 | 8 | <input type="hidden" id="selfedit" name="selfedit" value="<?php echo plainstring_to_htmlprotected($this->selfedit) ?>" /> |
9 | 9 | |
10 | 10 | <?php if (!$this->autoloadDetected) { |
11 | - ?> |
|
11 | + ?> |
|
12 | 12 | <div class="alert">Warning! TDBM could not detect the autoload section of your composer.json file. |
13 | 13 | Unless you are developing your own autoload system, you should configure <strong>composer.json</strong> to <a href="http://getcomposer.org/doc/01-basic-usage.md#autoloading" target="_blank">define a source directory and a root namespace using PSR-0</a>.</div> |
14 | 14 | <?php |
@@ -8,7 +8,7 @@ |
||
8 | 8 | <input type="hidden" id="selfedit" name="selfedit" value="<?php echo plainstring_to_htmlprotected($this->selfedit) ?>" /> |
9 | 9 | |
10 | 10 | <?php if (!$this->autoloadDetected) { |
11 | - ?> |
|
11 | + ?> |
|
12 | 12 | <div class="alert">Warning! TDBM could not detect the autoload section of your composer.json file. |
13 | 13 | Unless you are developing your own autoload system, you should configure <strong>composer.json</strong> to <a href="http://getcomposer.org/doc/01-basic-usage.md#autoloading" target="_blank">define a source directory and a root namespace using PSR-0</a>.</div> |
14 | 14 | <?php |
@@ -16,150 +16,150 @@ |
||
16 | 16 | */ |
17 | 17 | class TdbmController extends AbstractMoufInstanceController |
18 | 18 | { |
19 | - /** |
|
20 | - * @var HtmlBlock |
|
21 | - */ |
|
22 | - public $content; |
|
23 | - |
|
24 | - protected $daoNamespace; |
|
25 | - protected $beanNamespace; |
|
26 | - protected $daoFactoryName; |
|
27 | - protected $daoFactoryInstanceName; |
|
28 | - protected $autoloadDetected; |
|
29 | - protected $storeInUtc; |
|
30 | - |
|
31 | - /** |
|
32 | - * Admin page used to display the DAO generation form. |
|
33 | - * |
|
34 | - * @Action |
|
35 | - * //@Admin |
|
36 | - */ |
|
37 | - public function defaultAction($name, $selfedit = 'false') |
|
38 | - { |
|
39 | - $this->initController($name, $selfedit); |
|
40 | - |
|
41 | - // Fill variables |
|
42 | - if ($this->moufManager->getVariable('tdbmDefaultSourceDirectory_'.$name) != null) { |
|
43 | - $this->daoNamespace = $this->moufManager->getVariable('tdbmDefaultDaoNamespace_'.$name); |
|
44 | - $this->beanNamespace = $this->moufManager->getVariable('tdbmDefaultBeanNamespace_'.$name); |
|
45 | - $this->daoFactoryName = $this->moufManager->getVariable('tdbmDefaultDaoFactoryName_'.$name); |
|
46 | - $this->daoFactoryInstanceName = $this->moufManager->getVariable('tdbmDefaultDaoFactoryInstanceName_'.$name); |
|
47 | - $this->storeInUtc = $this->moufManager->getVariable('tdbmDefaultStoreInUtc_'.$name); |
|
48 | - } else { |
|
49 | - $this->daoNamespace = $this->moufManager->getVariable('tdbmDefaultDaoNamespace'); |
|
50 | - $this->beanNamespace = $this->moufManager->getVariable('tdbmDefaultBeanNamespace'); |
|
51 | - $this->daoFactoryName = $this->moufManager->getVariable('tdbmDefaultDaoFactoryName'); |
|
52 | - $this->daoFactoryInstanceName = $this->moufManager->getVariable('tdbmDefaultDaoFactoryInstanceName'); |
|
53 | - $this->storeInUtc = $this->moufManager->getVariable('tdbmDefaultStoreInUtc'); |
|
54 | - } |
|
55 | - |
|
56 | - if ($this->daoNamespace == null && $this->beanNamespace == null) { |
|
57 | - $classNameMapper = ClassNameMapper::createFromComposerFile(__DIR__.'/../../../../../../../../composer.json'); |
|
58 | - |
|
59 | - $autoloadNamespaces = $classNameMapper->getManagedNamespaces(); |
|
60 | - if ($autoloadNamespaces) { |
|
61 | - $this->autoloadDetected = true; |
|
62 | - $rootNamespace = $autoloadNamespaces[0]; |
|
63 | - $this->daoNamespace = $rootNamespace.'Dao'; |
|
64 | - $this->beanNamespace = $rootNamespace.'Dao\\Bean'; |
|
65 | - } else { |
|
66 | - $this->autoloadDetected = false; |
|
67 | - $this->daoNamespace = 'YourApplication\\Dao'; |
|
68 | - $this->beanNamespace = 'YourApplication\\Dao\\Bean'; |
|
69 | - } |
|
70 | - } else { |
|
71 | - $this->autoloadDetected = true; |
|
72 | - } |
|
73 | - |
|
74 | - $this->content->addFile(dirname(__FILE__).'/../../../../views/tdbmGenerate.php', $this); |
|
75 | - $this->template->toHtml(); |
|
76 | - } |
|
77 | - |
|
78 | - /** |
|
79 | - * This action generates the DAOs and Beans for the TDBM service passed in parameter. |
|
80 | - * |
|
81 | - * @Action |
|
82 | - * |
|
83 | - * @param string $name |
|
84 | - * @param bool $selfedit |
|
85 | - */ |
|
86 | - public function generate($name, $daonamespace, $beannamespace, $daofactoryclassname, $daofactoryinstancename, $storeInUtc = 0, $selfedit = 'false') |
|
87 | - { |
|
88 | - $this->initController($name, $selfedit); |
|
89 | - |
|
90 | - self::generateDaos($this->moufManager, $name, $daonamespace, $beannamespace, $daofactoryclassname, $daofactoryinstancename, $selfedit, $storeInUtc); |
|
91 | - |
|
92 | - // TODO: better: we should redirect to a screen that list the number of DAOs generated, etc... |
|
93 | - header('Location: '.ROOT_URL.'ajaxinstance/?name='.urlencode($name).'&selfedit='.$selfedit); |
|
94 | - } |
|
95 | - |
|
96 | - /** |
|
97 | - * This function generates the DAOs and Beans for the TDBM service passed in parameter. |
|
98 | - * |
|
99 | - * @param MoufManager $moufManager |
|
100 | - * @param string $name |
|
101 | - * @param string $daonamespace |
|
102 | - * @param string $beannamespace |
|
103 | - * @param string $daofactoryclassname |
|
104 | - * @param string $daofactoryinstancename |
|
105 | - * @param string $selfedit |
|
106 | - * @param bool $storeInUtc |
|
107 | - * |
|
108 | - * @throws \Mouf\MoufException |
|
109 | - */ |
|
110 | - public static function generateDaos(MoufManager $moufManager, $name, $daonamespace, $beannamespace, $daofactoryclassname, $daofactoryinstancename, $selfedit = 'false', $storeInUtc = null) |
|
111 | - { |
|
112 | - $moufManager->setVariable('tdbmDefaultDaoNamespace_'.$name, $daonamespace); |
|
113 | - $moufManager->setVariable('tdbmDefaultBeanNamespace_'.$name, $beannamespace); |
|
114 | - $moufManager->setVariable('tdbmDefaultDaoFactoryName_'.$name, $daofactoryclassname); |
|
115 | - $moufManager->setVariable('tdbmDefaultDaoFactoryInstanceName_'.$name, $daofactoryinstancename); |
|
116 | - $moufManager->setVariable('tdbmDefaultStoreInUtc_'.$name, $storeInUtc); |
|
117 | - |
|
118 | - // In case of instance renaming, let's use the last used settings |
|
119 | - $moufManager->setVariable('tdbmDefaultDaoNamespace', $daonamespace); |
|
120 | - $moufManager->setVariable('tdbmDefaultBeanNamespace', $beannamespace); |
|
121 | - $moufManager->setVariable('tdbmDefaultDaoFactoryName', $daofactoryclassname); |
|
122 | - $moufManager->setVariable('tdbmDefaultDaoFactoryInstanceName', $daofactoryinstancename); |
|
123 | - $moufManager->setVariable('tdbmDefaultStoreInUtc', $storeInUtc); |
|
124 | - |
|
125 | - // Remove first and last slash in namespace. |
|
126 | - if (strpos($daonamespace, '\\') === 0) { |
|
127 | - $daonamespace = substr($daonamespace, 1); |
|
128 | - } |
|
129 | - if (strpos($daonamespace, '\\') === strlen($daonamespace) - 1) { |
|
130 | - $daonamespace = substr($daonamespace, 0, strlen($daonamespace) - 1); |
|
131 | - } |
|
132 | - if (strpos($beannamespace, '\\') === 0) { |
|
133 | - $beannamespace = substr($beannamespace, 1); |
|
134 | - } |
|
135 | - if (strpos($beannamespace, '\\') === strlen($beannamespace) - 1) { |
|
136 | - $beannamespace = substr($beannamespace, 0, strlen($beannamespace) - 1); |
|
137 | - } |
|
138 | - |
|
139 | - $tdbmService = new InstanceProxy($name); |
|
140 | - /* @var $tdbmService TDBMService */ |
|
141 | - $tables = $tdbmService->generateAllDaosAndBeans($daofactoryclassname, $daonamespace, $beannamespace, $storeInUtc); |
|
142 | - |
|
143 | - $moufManager->declareComponent($daofactoryinstancename, $daonamespace.'\\'.$daofactoryclassname, false, MoufManager::DECLARE_ON_EXIST_KEEP_INCOMING_LINKS); |
|
144 | - |
|
145 | - $tableToBeanMap = []; |
|
146 | - |
|
147 | - //$tdbmServiceDescriptor = $moufManager->getInstanceDescriptor('tdbmService'); |
|
148 | - |
|
149 | - foreach ($tables as $table) { |
|
150 | - $daoName = TDBMDaoGenerator::getDaoNameFromTableName($table); |
|
151 | - |
|
152 | - $instanceName = TDBMDaoGenerator::toVariableName($daoName); |
|
153 | - if (!$moufManager->instanceExists($instanceName)) { |
|
154 | - $moufManager->declareComponent($instanceName, $daonamespace.'\\'.$daoName); |
|
155 | - } |
|
156 | - $moufManager->setParameterViaConstructor($instanceName, 0, $name, 'object'); |
|
157 | - $moufManager->bindComponentViaSetter($daofactoryinstancename, 'set'.$daoName, $instanceName); |
|
158 | - |
|
159 | - $tableToBeanMap[$table] = $beannamespace.'\\'.TDBMDaoGenerator::getBeanNameFromTableName($table); |
|
160 | - } |
|
161 | - $tdbmServiceDescriptor = $moufManager->getInstanceDescriptor($name); |
|
162 | - $tdbmServiceDescriptor->getSetterProperty('setTableToBeanMap')->setValue($tableToBeanMap); |
|
163 | - $moufManager->rewriteMouf(); |
|
164 | - } |
|
19 | + /** |
|
20 | + * @var HtmlBlock |
|
21 | + */ |
|
22 | + public $content; |
|
23 | + |
|
24 | + protected $daoNamespace; |
|
25 | + protected $beanNamespace; |
|
26 | + protected $daoFactoryName; |
|
27 | + protected $daoFactoryInstanceName; |
|
28 | + protected $autoloadDetected; |
|
29 | + protected $storeInUtc; |
|
30 | + |
|
31 | + /** |
|
32 | + * Admin page used to display the DAO generation form. |
|
33 | + * |
|
34 | + * @Action |
|
35 | + * //@Admin |
|
36 | + */ |
|
37 | + public function defaultAction($name, $selfedit = 'false') |
|
38 | + { |
|
39 | + $this->initController($name, $selfedit); |
|
40 | + |
|
41 | + // Fill variables |
|
42 | + if ($this->moufManager->getVariable('tdbmDefaultSourceDirectory_'.$name) != null) { |
|
43 | + $this->daoNamespace = $this->moufManager->getVariable('tdbmDefaultDaoNamespace_'.$name); |
|
44 | + $this->beanNamespace = $this->moufManager->getVariable('tdbmDefaultBeanNamespace_'.$name); |
|
45 | + $this->daoFactoryName = $this->moufManager->getVariable('tdbmDefaultDaoFactoryName_'.$name); |
|
46 | + $this->daoFactoryInstanceName = $this->moufManager->getVariable('tdbmDefaultDaoFactoryInstanceName_'.$name); |
|
47 | + $this->storeInUtc = $this->moufManager->getVariable('tdbmDefaultStoreInUtc_'.$name); |
|
48 | + } else { |
|
49 | + $this->daoNamespace = $this->moufManager->getVariable('tdbmDefaultDaoNamespace'); |
|
50 | + $this->beanNamespace = $this->moufManager->getVariable('tdbmDefaultBeanNamespace'); |
|
51 | + $this->daoFactoryName = $this->moufManager->getVariable('tdbmDefaultDaoFactoryName'); |
|
52 | + $this->daoFactoryInstanceName = $this->moufManager->getVariable('tdbmDefaultDaoFactoryInstanceName'); |
|
53 | + $this->storeInUtc = $this->moufManager->getVariable('tdbmDefaultStoreInUtc'); |
|
54 | + } |
|
55 | + |
|
56 | + if ($this->daoNamespace == null && $this->beanNamespace == null) { |
|
57 | + $classNameMapper = ClassNameMapper::createFromComposerFile(__DIR__.'/../../../../../../../../composer.json'); |
|
58 | + |
|
59 | + $autoloadNamespaces = $classNameMapper->getManagedNamespaces(); |
|
60 | + if ($autoloadNamespaces) { |
|
61 | + $this->autoloadDetected = true; |
|
62 | + $rootNamespace = $autoloadNamespaces[0]; |
|
63 | + $this->daoNamespace = $rootNamespace.'Dao'; |
|
64 | + $this->beanNamespace = $rootNamespace.'Dao\\Bean'; |
|
65 | + } else { |
|
66 | + $this->autoloadDetected = false; |
|
67 | + $this->daoNamespace = 'YourApplication\\Dao'; |
|
68 | + $this->beanNamespace = 'YourApplication\\Dao\\Bean'; |
|
69 | + } |
|
70 | + } else { |
|
71 | + $this->autoloadDetected = true; |
|
72 | + } |
|
73 | + |
|
74 | + $this->content->addFile(dirname(__FILE__).'/../../../../views/tdbmGenerate.php', $this); |
|
75 | + $this->template->toHtml(); |
|
76 | + } |
|
77 | + |
|
78 | + /** |
|
79 | + * This action generates the DAOs and Beans for the TDBM service passed in parameter. |
|
80 | + * |
|
81 | + * @Action |
|
82 | + * |
|
83 | + * @param string $name |
|
84 | + * @param bool $selfedit |
|
85 | + */ |
|
86 | + public function generate($name, $daonamespace, $beannamespace, $daofactoryclassname, $daofactoryinstancename, $storeInUtc = 0, $selfedit = 'false') |
|
87 | + { |
|
88 | + $this->initController($name, $selfedit); |
|
89 | + |
|
90 | + self::generateDaos($this->moufManager, $name, $daonamespace, $beannamespace, $daofactoryclassname, $daofactoryinstancename, $selfedit, $storeInUtc); |
|
91 | + |
|
92 | + // TODO: better: we should redirect to a screen that list the number of DAOs generated, etc... |
|
93 | + header('Location: '.ROOT_URL.'ajaxinstance/?name='.urlencode($name).'&selfedit='.$selfedit); |
|
94 | + } |
|
95 | + |
|
96 | + /** |
|
97 | + * This function generates the DAOs and Beans for the TDBM service passed in parameter. |
|
98 | + * |
|
99 | + * @param MoufManager $moufManager |
|
100 | + * @param string $name |
|
101 | + * @param string $daonamespace |
|
102 | + * @param string $beannamespace |
|
103 | + * @param string $daofactoryclassname |
|
104 | + * @param string $daofactoryinstancename |
|
105 | + * @param string $selfedit |
|
106 | + * @param bool $storeInUtc |
|
107 | + * |
|
108 | + * @throws \Mouf\MoufException |
|
109 | + */ |
|
110 | + public static function generateDaos(MoufManager $moufManager, $name, $daonamespace, $beannamespace, $daofactoryclassname, $daofactoryinstancename, $selfedit = 'false', $storeInUtc = null) |
|
111 | + { |
|
112 | + $moufManager->setVariable('tdbmDefaultDaoNamespace_'.$name, $daonamespace); |
|
113 | + $moufManager->setVariable('tdbmDefaultBeanNamespace_'.$name, $beannamespace); |
|
114 | + $moufManager->setVariable('tdbmDefaultDaoFactoryName_'.$name, $daofactoryclassname); |
|
115 | + $moufManager->setVariable('tdbmDefaultDaoFactoryInstanceName_'.$name, $daofactoryinstancename); |
|
116 | + $moufManager->setVariable('tdbmDefaultStoreInUtc_'.$name, $storeInUtc); |
|
117 | + |
|
118 | + // In case of instance renaming, let's use the last used settings |
|
119 | + $moufManager->setVariable('tdbmDefaultDaoNamespace', $daonamespace); |
|
120 | + $moufManager->setVariable('tdbmDefaultBeanNamespace', $beannamespace); |
|
121 | + $moufManager->setVariable('tdbmDefaultDaoFactoryName', $daofactoryclassname); |
|
122 | + $moufManager->setVariable('tdbmDefaultDaoFactoryInstanceName', $daofactoryinstancename); |
|
123 | + $moufManager->setVariable('tdbmDefaultStoreInUtc', $storeInUtc); |
|
124 | + |
|
125 | + // Remove first and last slash in namespace. |
|
126 | + if (strpos($daonamespace, '\\') === 0) { |
|
127 | + $daonamespace = substr($daonamespace, 1); |
|
128 | + } |
|
129 | + if (strpos($daonamespace, '\\') === strlen($daonamespace) - 1) { |
|
130 | + $daonamespace = substr($daonamespace, 0, strlen($daonamespace) - 1); |
|
131 | + } |
|
132 | + if (strpos($beannamespace, '\\') === 0) { |
|
133 | + $beannamespace = substr($beannamespace, 1); |
|
134 | + } |
|
135 | + if (strpos($beannamespace, '\\') === strlen($beannamespace) - 1) { |
|
136 | + $beannamespace = substr($beannamespace, 0, strlen($beannamespace) - 1); |
|
137 | + } |
|
138 | + |
|
139 | + $tdbmService = new InstanceProxy($name); |
|
140 | + /* @var $tdbmService TDBMService */ |
|
141 | + $tables = $tdbmService->generateAllDaosAndBeans($daofactoryclassname, $daonamespace, $beannamespace, $storeInUtc); |
|
142 | + |
|
143 | + $moufManager->declareComponent($daofactoryinstancename, $daonamespace.'\\'.$daofactoryclassname, false, MoufManager::DECLARE_ON_EXIST_KEEP_INCOMING_LINKS); |
|
144 | + |
|
145 | + $tableToBeanMap = []; |
|
146 | + |
|
147 | + //$tdbmServiceDescriptor = $moufManager->getInstanceDescriptor('tdbmService'); |
|
148 | + |
|
149 | + foreach ($tables as $table) { |
|
150 | + $daoName = TDBMDaoGenerator::getDaoNameFromTableName($table); |
|
151 | + |
|
152 | + $instanceName = TDBMDaoGenerator::toVariableName($daoName); |
|
153 | + if (!$moufManager->instanceExists($instanceName)) { |
|
154 | + $moufManager->declareComponent($instanceName, $daonamespace.'\\'.$daoName); |
|
155 | + } |
|
156 | + $moufManager->setParameterViaConstructor($instanceName, 0, $name, 'object'); |
|
157 | + $moufManager->bindComponentViaSetter($daofactoryinstancename, 'set'.$daoName, $instanceName); |
|
158 | + |
|
159 | + $tableToBeanMap[$table] = $beannamespace.'\\'.TDBMDaoGenerator::getBeanNameFromTableName($table); |
|
160 | + } |
|
161 | + $tdbmServiceDescriptor = $moufManager->getInstanceDescriptor($name); |
|
162 | + $tdbmServiceDescriptor->getSetterProperty('setTableToBeanMap')->setValue($tableToBeanMap); |
|
163 | + $moufManager->rewriteMouf(); |
|
164 | + } |
|
165 | 165 | } |
@@ -126,14 +126,14 @@ |
||
126 | 126 | if (strpos($daonamespace, '\\') === 0) { |
127 | 127 | $daonamespace = substr($daonamespace, 1); |
128 | 128 | } |
129 | - if (strpos($daonamespace, '\\') === strlen($daonamespace) - 1) { |
|
130 | - $daonamespace = substr($daonamespace, 0, strlen($daonamespace) - 1); |
|
129 | + if (strpos($daonamespace, '\\') === strlen($daonamespace)-1) { |
|
130 | + $daonamespace = substr($daonamespace, 0, strlen($daonamespace)-1); |
|
131 | 131 | } |
132 | 132 | if (strpos($beannamespace, '\\') === 0) { |
133 | 133 | $beannamespace = substr($beannamespace, 1); |
134 | 134 | } |
135 | - if (strpos($beannamespace, '\\') === strlen($beannamespace) - 1) { |
|
136 | - $beannamespace = substr($beannamespace, 0, strlen($beannamespace) - 1); |
|
135 | + if (strpos($beannamespace, '\\') === strlen($beannamespace)-1) { |
|
136 | + $beannamespace = substr($beannamespace, 0, strlen($beannamespace)-1); |
|
137 | 137 | } |
138 | 138 | |
139 | 139 | $tdbmService = new InstanceProxy($name); |
@@ -14,136 +14,136 @@ |
||
14 | 14 | */ |
15 | 15 | class TDBMSchemaAnalyzer |
16 | 16 | { |
17 | - private $connection; |
|
18 | - |
|
19 | - /** |
|
20 | - * @var Schema |
|
21 | - */ |
|
22 | - private $schema; |
|
23 | - |
|
24 | - /** |
|
25 | - * @var string |
|
26 | - */ |
|
27 | - private $cachePrefix; |
|
28 | - |
|
29 | - /** |
|
30 | - * @var Cache |
|
31 | - */ |
|
32 | - private $cache; |
|
33 | - |
|
34 | - /** |
|
35 | - * @var SchemaAnalyzer |
|
36 | - */ |
|
37 | - private $schemaAnalyzer; |
|
38 | - |
|
39 | - /** |
|
40 | - * @param Connection $connection The DBAL DB connection to use |
|
41 | - * @param Cache $cache A cache service to be used |
|
42 | - * @param SchemaAnalyzer $schemaAnalyzer The schema analyzer that will be used to find shortest paths... |
|
43 | - * Will be automatically created if not passed. |
|
44 | - */ |
|
45 | - public function __construct(Connection $connection, Cache $cache, SchemaAnalyzer $schemaAnalyzer) |
|
46 | - { |
|
47 | - $this->connection = $connection; |
|
48 | - $this->cache = $cache; |
|
49 | - $this->schemaAnalyzer = $schemaAnalyzer; |
|
50 | - } |
|
51 | - |
|
52 | - /** |
|
53 | - * Returns a unique ID for the current connection. Useful for namespacing cache entries in the current connection. |
|
54 | - * |
|
55 | - * @return string |
|
56 | - */ |
|
57 | - public function getCachePrefix() |
|
58 | - { |
|
59 | - if ($this->cachePrefix === null) { |
|
60 | - $this->cachePrefix = hash('md4', $this->connection->getHost().'-'.$this->connection->getPort().'-'.$this->connection->getDatabase().'-'.$this->connection->getDriver()->getName()); |
|
61 | - } |
|
62 | - |
|
63 | - return $this->cachePrefix; |
|
64 | - } |
|
65 | - |
|
66 | - /** |
|
67 | - * Returns the (cached) schema. |
|
68 | - * |
|
69 | - * @return Schema |
|
70 | - */ |
|
71 | - public function getSchema() |
|
72 | - { |
|
73 | - if ($this->schema === null) { |
|
74 | - $cacheKey = $this->getCachePrefix().'_schema'; |
|
75 | - if ($this->cache->contains($cacheKey)) { |
|
76 | - $this->schema = $this->cache->fetch($cacheKey); |
|
77 | - } else { |
|
78 | - $this->schema = $this->connection->getSchemaManager()->createSchema(); |
|
79 | - $this->cache->save($cacheKey, $this->schema); |
|
80 | - } |
|
81 | - } |
|
82 | - |
|
83 | - return $this->schema; |
|
84 | - } |
|
85 | - |
|
86 | - /** |
|
87 | - * Returns the list of pivot tables linked to table $tableName. |
|
88 | - * |
|
89 | - * @param string $tableName |
|
90 | - * |
|
91 | - * @return array|string[] |
|
92 | - */ |
|
93 | - public function getPivotTableLinkedToTable($tableName) |
|
94 | - { |
|
95 | - $cacheKey = $this->getCachePrefix().'_pivottables_link'; |
|
96 | - if ($this->cache->contains($cacheKey)) { |
|
97 | - return $this->cache->fetch($cacheKey); |
|
98 | - } |
|
99 | - |
|
100 | - $pivotTables = []; |
|
101 | - |
|
102 | - $junctionTables = $this->schemaAnalyzer->detectJunctionTables(); |
|
103 | - foreach ($junctionTables as $table) { |
|
104 | - $fks = $table->getForeignKeys(); |
|
105 | - foreach ($fks as $fk) { |
|
106 | - if ($fk->getForeignTableName() == $tableName) { |
|
107 | - $pivotTables[] = $table->getName(); |
|
108 | - break; |
|
109 | - } |
|
110 | - } |
|
111 | - } |
|
112 | - |
|
113 | - $this->cache->save($cacheKey, $pivotTables); |
|
114 | - |
|
115 | - return $pivotTables; |
|
116 | - } |
|
117 | - |
|
118 | - /** |
|
119 | - * Returns the list of foreign keys pointing to the table represented by this bean, excluding foreign keys |
|
120 | - * from junction tables and from inheritance. |
|
121 | - * |
|
122 | - * @return ForeignKeyConstraint[] |
|
123 | - */ |
|
124 | - public function getIncomingForeignKeys($tableName) |
|
125 | - { |
|
126 | - $junctionTables = $this->schemaAnalyzer->detectJunctionTables(); |
|
127 | - $junctionTableNames = array_map(function (Table $table) { return $table->getName(); }, $junctionTables); |
|
128 | - $childrenRelationships = $this->schemaAnalyzer->getChildrenRelationships($tableName); |
|
129 | - |
|
130 | - $fks = []; |
|
131 | - foreach ($this->getSchema()->getTables() as $table) { |
|
132 | - foreach ($table->getForeignKeys() as $fk) { |
|
133 | - if ($fk->getForeignTableName() === $tableName) { |
|
134 | - if (in_array($fk->getLocalTableName(), $junctionTableNames)) { |
|
135 | - continue; |
|
136 | - } |
|
137 | - foreach ($childrenRelationships as $childFk) { |
|
138 | - if ($fk->getLocalTableName() === $childFk->getLocalTableName() && $fk->getLocalColumns() === $childFk->getLocalColumns()) { |
|
139 | - continue 2; |
|
140 | - } |
|
141 | - } |
|
142 | - $fks[] = $fk; |
|
143 | - } |
|
144 | - } |
|
145 | - } |
|
146 | - |
|
147 | - return $fks; |
|
148 | - } |
|
17 | + private $connection; |
|
18 | + |
|
19 | + /** |
|
20 | + * @var Schema |
|
21 | + */ |
|
22 | + private $schema; |
|
23 | + |
|
24 | + /** |
|
25 | + * @var string |
|
26 | + */ |
|
27 | + private $cachePrefix; |
|
28 | + |
|
29 | + /** |
|
30 | + * @var Cache |
|
31 | + */ |
|
32 | + private $cache; |
|
33 | + |
|
34 | + /** |
|
35 | + * @var SchemaAnalyzer |
|
36 | + */ |
|
37 | + private $schemaAnalyzer; |
|
38 | + |
|
39 | + /** |
|
40 | + * @param Connection $connection The DBAL DB connection to use |
|
41 | + * @param Cache $cache A cache service to be used |
|
42 | + * @param SchemaAnalyzer $schemaAnalyzer The schema analyzer that will be used to find shortest paths... |
|
43 | + * Will be automatically created if not passed. |
|
44 | + */ |
|
45 | + public function __construct(Connection $connection, Cache $cache, SchemaAnalyzer $schemaAnalyzer) |
|
46 | + { |
|
47 | + $this->connection = $connection; |
|
48 | + $this->cache = $cache; |
|
49 | + $this->schemaAnalyzer = $schemaAnalyzer; |
|
50 | + } |
|
51 | + |
|
52 | + /** |
|
53 | + * Returns a unique ID for the current connection. Useful for namespacing cache entries in the current connection. |
|
54 | + * |
|
55 | + * @return string |
|
56 | + */ |
|
57 | + public function getCachePrefix() |
|
58 | + { |
|
59 | + if ($this->cachePrefix === null) { |
|
60 | + $this->cachePrefix = hash('md4', $this->connection->getHost().'-'.$this->connection->getPort().'-'.$this->connection->getDatabase().'-'.$this->connection->getDriver()->getName()); |
|
61 | + } |
|
62 | + |
|
63 | + return $this->cachePrefix; |
|
64 | + } |
|
65 | + |
|
66 | + /** |
|
67 | + * Returns the (cached) schema. |
|
68 | + * |
|
69 | + * @return Schema |
|
70 | + */ |
|
71 | + public function getSchema() |
|
72 | + { |
|
73 | + if ($this->schema === null) { |
|
74 | + $cacheKey = $this->getCachePrefix().'_schema'; |
|
75 | + if ($this->cache->contains($cacheKey)) { |
|
76 | + $this->schema = $this->cache->fetch($cacheKey); |
|
77 | + } else { |
|
78 | + $this->schema = $this->connection->getSchemaManager()->createSchema(); |
|
79 | + $this->cache->save($cacheKey, $this->schema); |
|
80 | + } |
|
81 | + } |
|
82 | + |
|
83 | + return $this->schema; |
|
84 | + } |
|
85 | + |
|
86 | + /** |
|
87 | + * Returns the list of pivot tables linked to table $tableName. |
|
88 | + * |
|
89 | + * @param string $tableName |
|
90 | + * |
|
91 | + * @return array|string[] |
|
92 | + */ |
|
93 | + public function getPivotTableLinkedToTable($tableName) |
|
94 | + { |
|
95 | + $cacheKey = $this->getCachePrefix().'_pivottables_link'; |
|
96 | + if ($this->cache->contains($cacheKey)) { |
|
97 | + return $this->cache->fetch($cacheKey); |
|
98 | + } |
|
99 | + |
|
100 | + $pivotTables = []; |
|
101 | + |
|
102 | + $junctionTables = $this->schemaAnalyzer->detectJunctionTables(); |
|
103 | + foreach ($junctionTables as $table) { |
|
104 | + $fks = $table->getForeignKeys(); |
|
105 | + foreach ($fks as $fk) { |
|
106 | + if ($fk->getForeignTableName() == $tableName) { |
|
107 | + $pivotTables[] = $table->getName(); |
|
108 | + break; |
|
109 | + } |
|
110 | + } |
|
111 | + } |
|
112 | + |
|
113 | + $this->cache->save($cacheKey, $pivotTables); |
|
114 | + |
|
115 | + return $pivotTables; |
|
116 | + } |
|
117 | + |
|
118 | + /** |
|
119 | + * Returns the list of foreign keys pointing to the table represented by this bean, excluding foreign keys |
|
120 | + * from junction tables and from inheritance. |
|
121 | + * |
|
122 | + * @return ForeignKeyConstraint[] |
|
123 | + */ |
|
124 | + public function getIncomingForeignKeys($tableName) |
|
125 | + { |
|
126 | + $junctionTables = $this->schemaAnalyzer->detectJunctionTables(); |
|
127 | + $junctionTableNames = array_map(function (Table $table) { return $table->getName(); }, $junctionTables); |
|
128 | + $childrenRelationships = $this->schemaAnalyzer->getChildrenRelationships($tableName); |
|
129 | + |
|
130 | + $fks = []; |
|
131 | + foreach ($this->getSchema()->getTables() as $table) { |
|
132 | + foreach ($table->getForeignKeys() as $fk) { |
|
133 | + if ($fk->getForeignTableName() === $tableName) { |
|
134 | + if (in_array($fk->getLocalTableName(), $junctionTableNames)) { |
|
135 | + continue; |
|
136 | + } |
|
137 | + foreach ($childrenRelationships as $childFk) { |
|
138 | + if ($fk->getLocalTableName() === $childFk->getLocalTableName() && $fk->getLocalColumns() === $childFk->getLocalColumns()) { |
|
139 | + continue 2; |
|
140 | + } |
|
141 | + } |
|
142 | + $fks[] = $fk; |
|
143 | + } |
|
144 | + } |
|
145 | + } |
|
146 | + |
|
147 | + return $fks; |
|
148 | + } |
|
149 | 149 | } |
@@ -124,7 +124,7 @@ |
||
124 | 124 | public function getIncomingForeignKeys($tableName) |
125 | 125 | { |
126 | 126 | $junctionTables = $this->schemaAnalyzer->detectJunctionTables(); |
127 | - $junctionTableNames = array_map(function (Table $table) { return $table->getName(); }, $junctionTables); |
|
127 | + $junctionTableNames = array_map(function(Table $table) { return $table->getName(); }, $junctionTables); |
|
128 | 128 | $childrenRelationships = $this->schemaAnalyzer->getChildrenRelationships($tableName); |
129 | 129 | |
130 | 130 | $fks = []; |