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