diff --git a/.travis.yml b/.travis.yml
deleted file mode 100644
index d4ddd7f..0000000
--- a/.travis.yml
+++ /dev/null
@@ -1,18 +0,0 @@
-language: php
-
-php:
- - 7.1
-
-env:
- matrix:
- - PREFER_LOWEST="--prefer-lowest"
- - PREFER_LOWEST=""
-
-before_script:
- - composer update --prefer-source $PREFER_LOWEST
-
-script:
- - ./vendor/bin/phpunit
-
-after_script:
- - ./vendor/bin/coveralls -v
diff --git a/README.md b/README.md
index 419fe35..a34890d 100644
--- a/README.md
+++ b/README.md
@@ -2,53 +2,10 @@
[](https://packagist.org/packages/mouf/database.tdbm)
[](https://packagist.org/packages/mouf/database.tdbm)
[](https://packagist.org/packages/mouf/database.tdbm)
-[](https://scrutinizer-ci.com/g/thecodingmachine/database.tdbm/?branch=4.3)
-[](https://travis-ci.org/thecodingmachine/database.tdbm)
-[](https://coveralls.io/github/thecodingmachine/database.tdbm?branch=4.3)
+[](https://scrutinizer-ci.com/g/thecodingmachine/database.tdbm/?branch=5.x)
About TDBM (The DataBase Machine)
=================================
-What is it?
------------
-
-THE DATABASE MACHINE (TDBM) is a PHP library designed to ease your access to your database.
-
-The goal behind TDBM is to make database access as easy as possible. Users should access their objects easily, and store those objects as easily.
-
-
-Design philosophy
------------------
-
-Design choices:
-
-- _TDBM starts with your database model and generates PHP files._ TDBM **understands your database model**. From it,
- it will generate PHP classes that will help you access your database. It will generate 2 kind of classes: *DAOs*
- that are services helping you access a given table, and *Beans* that are classes representing a row in your database.
- Because PHP objects are generated, it means you get a nice **autocompletion** in your favorite IDE.
-- _TDBM is really good at understanding the meaning and the intent behind your database model._
- TDBM has one of **the most powerful database model analyzer** that helps it
- map tables to objects.
- TDBM relies on your foreign key constraints to find joins between tables.
- TDBM finds these constraints itself in the database by querying the
- DB system. It can automatically detect pivot table to generate **many to many relationships**. It can also
- detect **inheritance** relationships.
-- _Simplicity first._ TDBM is meant to be easy to use and non obtrusive.
-- _Making simple tasks should be simple._ TDBM does not cover everything you can do with a complete ORM system.
- But it makes as simple as possible those tasks you do 80% of the time. For the remaining 20% (like performance critical requests, and so on), you can use SQL.
- For instance, TDBM has a **unique feature that guesses jointures for you**. No need to write joins anymore!
-- _No configuration._ There is no configuration needed for TDBM. You provide TDBM the name of your database, the user and password and you start using it.
-- _Based on Doctrine DBAL._ TDBM uses the Doctrine database abstraction layer for low level database access. It allows
- compatibility with a very wide range of databases.
-
-Ready to dive in? Let's get started!
-
-- [Install TDBM](doc/install.md)
-- [Access the database, perform queries, inserts and updates](doc/quickstart.md)
-- [Add limit and offsets to your queries](doc/limit_offset_resultset.md)
-- [Regenerating DAOs and beans](doc/generating_daos.md)
-- [Modeling inheritance](doc/modeling_inheritance.md)
-- [Improving memory usage](doc/memory_management.md)
-- [A quick comparison with Doctrine](doc/comparison_with_doctrine.md)
-- [TDBM internals](doc/internals.md)
+Check the documentation at https://github.com/thecodingmachine/tdbm
diff --git a/composer.json b/composer.json
index 2a0bf5a..8821695 100644
--- a/composer.json
+++ b/composer.json
@@ -20,34 +20,15 @@
],
"require" : {
"php" : ">=7.1",
- "mouf/magic-query" : "^1.2.1",
- "mouf/schema-analyzer": "^1.1",
- "doctrine/dbal": "~2.5",
- "doctrine/cache": "~1.5",
+ "thecodingmachine/tdbm" : "^5.0",
"mouf/database.doctrine-dbal-wrapper": "~1.1",
"mouf/utils.common.conditioninterface" : "~2.0",
- "psr/log": "~1.0",
"mouf/mouf": "~2.0.10",
- "doctrine/inflector": "~1.0",
- "beberlei/porpaginas": "~1.0",
- "mouf/classname-mapper": "~1.0",
"mouf/utils.common.doctrine-cache-wrapper": "~1.0",
- "greenlion/php-sql-parser": "^4.1",
- "phlib/logger": "^2.1",
- "symfony/console": "^2.0 || ^3.0",
- "mouf/utils.console": "^1.0",
- "mouf/utils.log.psr.multi-logger": "^1.0",
- "symfony/filesystem": "~2.7|~3.0"
+ "mouf/utils.console": "^1.0"
},
"require-dev" : {
- "phpunit/phpunit": "^5.5",
- "satooshi/php-coveralls": "^1.0",
- "wa72/simplelogger" : "^1.0",
- "friendsofphp/php-cs-fixer": "^2.1",
- "symfony/process": "^3.0"
- },
- "suggest" : {
- "ext/weakref" : "Allows efficient memory management. Useful for batches."
+ "friendsofphp/php-cs-fixer": "^2.1"
},
"autoload" : {
"psr-4" : {
@@ -67,7 +48,7 @@
"install" : [
{
"type" : "url",
- "url" : "tdbminstall2/",
+ "url" : "tdbminstall3/",
"description" : "The install process of TDBM proposes to set up the DAOs and beans for your default DB connection."
}
],
diff --git a/phpunit.xml.dist b/phpunit.xml.dist
deleted file mode 100644
index 5cb090a..0000000
--- a/phpunit.xml.dist
+++ /dev/null
@@ -1,45 +0,0 @@
-
-
-
-
-
- ./tests/Mouf/Database/TDBM/
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- src/Mouf
-
- src/Mouf/Database/TDBM/Controllers
- src/Mouf/Database/TDBM/Test
- src/Mouf/Database/TDBM/MoufConfiguration.php
- src/Mouf/Database/TDBM/Utils/MoufDiListener.php
-
-
-
-
-
-
-
-
diff --git a/src/Mouf/Database/TDBM/AbstractTDBMObject.php b/src/Mouf/Database/TDBM/AbstractTDBMObject.php
deleted file mode 100644
index 07a74c7..0000000
--- a/src/Mouf/Database/TDBM/AbstractTDBMObject.php
+++ /dev/null
@@ -1,645 +0,0 @@
-dbRows[$tableName] = new DbRow($this, $tableName, $primaryKeys, $tdbmService);
- }
-
- if ($tdbmService === null) {
- $this->_setStatus(TDBMObjectStateEnum::STATE_DETACHED);
- } else {
- $this->_attach($tdbmService);
- if (!empty($primaryKeys)) {
- $this->_setStatus(TDBMObjectStateEnum::STATE_NOT_LOADED);
- } else {
- $this->_setStatus(TDBMObjectStateEnum::STATE_NEW);
- }
- }
- }
-
- /**
- * Alternative constructor called when data is fetched from database via a SELECT.
- *
- * @param array $beanData array
>
- * @param TDBMService $tdbmService
- */
- public function _constructFromData(array $beanData, TDBMService $tdbmService)
- {
- $this->tdbmService = $tdbmService;
-
- foreach ($beanData as $table => $columns) {
- $this->dbRows[$table] = new DbRow($this, $table, $tdbmService->_getPrimaryKeysFromObjectData($table, $columns), $tdbmService, $columns);
- }
-
- $this->status = TDBMObjectStateEnum::STATE_LOADED;
- }
-
- /**
- * Alternative constructor called when bean is lazily loaded.
- *
- * @param string $tableName
- * @param array $primaryKeys
- * @param TDBMService $tdbmService
- */
- public function _constructLazy($tableName, array $primaryKeys, TDBMService $tdbmService)
- {
- $this->tdbmService = $tdbmService;
-
- $this->dbRows[$tableName] = new DbRow($this, $tableName, $primaryKeys, $tdbmService);
-
- $this->status = TDBMObjectStateEnum::STATE_NOT_LOADED;
- }
-
- public function _attach(TDBMService $tdbmService)
- {
- if ($this->status !== TDBMObjectStateEnum::STATE_DETACHED) {
- throw new TDBMInvalidOperationException('Cannot attach an object that is already attached to TDBM.');
- }
- $this->tdbmService = $tdbmService;
-
- // If we attach this object, we must work to make sure the tables are in ascending order (from low level to top level)
- $tableNames = $this->getUsedTables();
-
- $newDbRows = [];
-
- foreach ($tableNames as $table) {
- if (!isset($this->dbRows[$table])) {
- $this->registerTable($table);
- }
- $newDbRows[$table] = $this->dbRows[$table];
- }
- $this->dbRows = $newDbRows;
-
- $this->status = TDBMObjectStateEnum::STATE_NEW;
- foreach ($this->dbRows as $dbRow) {
- $dbRow->_attach($tdbmService);
- }
- }
-
- /**
- * Sets the state of the TDBM Object
- * One of TDBMObjectStateEnum::STATE_NEW, TDBMObjectStateEnum::STATE_NOT_LOADED, TDBMObjectStateEnum::STATE_LOADED, TDBMObjectStateEnum::STATE_DELETED.
- * $status = TDBMObjectStateEnum::STATE_NEW when a new object is created with DBMObject:getNewObject.
- * $status = TDBMObjectStateEnum::STATE_NOT_LOADED when the object has been retrieved with getObject but when no data has been accessed in it yet.
- * $status = TDBMObjectStateEnum::STATE_LOADED when the object is cached in memory.
- *
- * @param string $state
- */
- public function _setStatus($state)
- {
- $this->status = $state;
-
- // TODO: we might ignore the loaded => dirty state here! dirty status comes from the db_row itself.
- foreach ($this->dbRows as $dbRow) {
- $dbRow->_setStatus($state);
- }
-
- if ($state === TDBMObjectStateEnum::STATE_DELETED) {
- $this->onDelete();
- }
- }
-
- /**
- * Checks that $tableName is ok, or returns the only possible table name if "$tableName = null"
- * or throws an error.
- *
- * @param string $tableName
- *
- * @return string
- */
- private function checkTableName($tableName = null)
- {
- if ($tableName === null) {
- if (count($this->dbRows) > 1) {
- throw new TDBMException('This object is based on several tables. You must specify which table you are retrieving data from.');
- } elseif (count($this->dbRows) === 1) {
- $tableName = array_keys($this->dbRows)[0];
- }
- }
-
- return $tableName;
- }
-
- protected function get($var, $tableName = null)
- {
- $tableName = $this->checkTableName($tableName);
-
- if (!isset($this->dbRows[$tableName])) {
- return;
- }
-
- return $this->dbRows[$tableName]->get($var);
- }
-
- protected function set($var, $value, $tableName = null)
- {
- if ($tableName === null) {
- if (count($this->dbRows) > 1) {
- throw new TDBMException('This object is based on several tables. You must specify which table you are retrieving data from.');
- } elseif (count($this->dbRows) === 1) {
- $tableName = array_keys($this->dbRows)[0];
- } else {
- throw new TDBMException('Please specify a table for this object.');
- }
- }
-
- if (!isset($this->dbRows[$tableName])) {
- $this->registerTable($tableName);
- }
-
- $this->dbRows[$tableName]->set($var, $value);
- if ($this->dbRows[$tableName]->_getStatus() === TDBMObjectStateEnum::STATE_DIRTY) {
- $this->status = TDBMObjectStateEnum::STATE_DIRTY;
- }
- }
-
- /**
- * @param string $foreignKeyName
- * @param AbstractTDBMObject $bean
- */
- protected function setRef($foreignKeyName, AbstractTDBMObject $bean = null, $tableName = null)
- {
- if ($tableName === null) {
- if (count($this->dbRows) > 1) {
- throw new TDBMException('This object is based on several tables. You must specify which table you are retrieving data from.');
- } elseif (count($this->dbRows) === 1) {
- $tableName = array_keys($this->dbRows)[0];
- } else {
- throw new TDBMException('Please specify a table for this object.');
- }
- }
-
- if (!isset($this->dbRows[$tableName])) {
- $this->registerTable($tableName);
- }
-
- $oldLinkedBean = $this->dbRows[$tableName]->getRef($foreignKeyName);
- if ($oldLinkedBean !== null) {
- $oldLinkedBean->removeManyToOneRelationship($tableName, $foreignKeyName, $this);
- }
-
- $this->dbRows[$tableName]->setRef($foreignKeyName, $bean);
- if ($this->dbRows[$tableName]->_getStatus() === TDBMObjectStateEnum::STATE_DIRTY) {
- $this->status = TDBMObjectStateEnum::STATE_DIRTY;
- }
-
- if ($bean !== null) {
- $bean->setManyToOneRelationship($tableName, $foreignKeyName, $this);
- }
- }
-
- /**
- * @param string $foreignKeyName A unique name for this reference
- *
- * @return AbstractTDBMObject|null
- */
- protected function getRef($foreignKeyName, $tableName = null)
- {
- $tableName = $this->checkTableName($tableName);
-
- if (!isset($this->dbRows[$tableName])) {
- return;
- }
-
- return $this->dbRows[$tableName]->getRef($foreignKeyName);
- }
-
- /**
- * Adds a many to many relationship to this bean.
- *
- * @param string $pivotTableName
- * @param AbstractTDBMObject $remoteBean
- */
- protected function addRelationship($pivotTableName, AbstractTDBMObject $remoteBean)
- {
- $this->setRelationship($pivotTableName, $remoteBean, 'new');
- }
-
- /**
- * Returns true if there is a relationship to this bean.
- *
- * @param string $pivotTableName
- * @param AbstractTDBMObject $remoteBean
- *
- * @return bool
- */
- protected function hasRelationship($pivotTableName, AbstractTDBMObject $remoteBean)
- {
- $storage = $this->retrieveRelationshipsStorage($pivotTableName);
-
- if ($storage->contains($remoteBean)) {
- if ($storage[$remoteBean]['status'] !== 'delete') {
- return true;
- }
- }
-
- return false;
- }
-
- /**
- * Internal TDBM method. Removes a many to many relationship from this bean.
- *
- * @param string $pivotTableName
- * @param AbstractTDBMObject $remoteBean
- */
- public function _removeRelationship($pivotTableName, AbstractTDBMObject $remoteBean)
- {
- if (isset($this->relationships[$pivotTableName][$remoteBean]) && $this->relationships[$pivotTableName][$remoteBean]['status'] === 'new') {
- unset($this->relationships[$pivotTableName][$remoteBean]);
- unset($remoteBean->relationships[$pivotTableName][$this]);
- } else {
- $this->setRelationship($pivotTableName, $remoteBean, 'delete');
- }
- }
-
- /**
- * Sets many to many relationships for this bean.
- * Adds new relationships and removes unused ones.
- *
- * @param $pivotTableName
- * @param array $remoteBeans
- */
- protected function setRelationships($pivotTableName, array $remoteBeans)
- {
- $storage = $this->retrieveRelationshipsStorage($pivotTableName);
-
- foreach ($storage as $oldRemoteBean) {
- if (!in_array($oldRemoteBean, $remoteBeans, true)) {
- // $oldRemoteBean must be removed
- $this->_removeRelationship($pivotTableName, $oldRemoteBean);
- }
- }
-
- foreach ($remoteBeans as $remoteBean) {
- if (!$storage->contains($remoteBean) || $storage[$remoteBean]['status'] === 'delete') {
- // $remoteBean must be added
- $this->addRelationship($pivotTableName, $remoteBean);
- }
- }
- }
-
- /**
- * Returns the list of objects linked to this bean via $pivotTableName.
- *
- * @param $pivotTableName
- *
- * @return \SplObjectStorage
- */
- private function retrieveRelationshipsStorage($pivotTableName)
- {
- $storage = $this->getRelationshipStorage($pivotTableName);
- if ($this->status === TDBMObjectStateEnum::STATE_DETACHED || $this->status === TDBMObjectStateEnum::STATE_NEW || (isset($this->loadedRelationships[$pivotTableName]) && $this->loadedRelationships[$pivotTableName])) {
- return $storage;
- }
-
- $beans = $this->tdbmService->_getRelatedBeans($pivotTableName, $this);
- $this->loadedRelationships[$pivotTableName] = true;
-
- foreach ($beans as $bean) {
- if (isset($storage[$bean])) {
- $oldStatus = $storage[$bean]['status'];
- if ($oldStatus === 'delete') {
- // Keep deleted things deleted
- continue;
- }
- }
- $this->setRelationship($pivotTableName, $bean, 'loaded');
- }
-
- return $storage;
- }
-
- /**
- * Internal TDBM method. Returns the list of objects linked to this bean via $pivotTableName.
- *
- * @param $pivotTableName
- *
- * @return AbstractTDBMObject[]
- */
- public function _getRelationships($pivotTableName)
- {
- return $this->relationshipStorageToArray($this->retrieveRelationshipsStorage($pivotTableName));
- }
-
- private function relationshipStorageToArray(\SplObjectStorage $storage)
- {
- $beans = [];
- foreach ($storage as $bean) {
- $statusArr = $storage[$bean];
- if ($statusArr['status'] !== 'delete') {
- $beans[] = $bean;
- }
- }
-
- return $beans;
- }
-
- /**
- * Declares a relationship between.
- *
- * @param string $pivotTableName
- * @param AbstractTDBMObject $remoteBean
- * @param string $status
- */
- private function setRelationship($pivotTableName, AbstractTDBMObject $remoteBean, $status)
- {
- $storage = $this->getRelationshipStorage($pivotTableName);
- $storage->attach($remoteBean, ['status' => $status, 'reverse' => false]);
- if ($this->status === TDBMObjectStateEnum::STATE_LOADED) {
- $this->_setStatus(TDBMObjectStateEnum::STATE_DIRTY);
- }
-
- $remoteStorage = $remoteBean->getRelationshipStorage($pivotTableName);
- $remoteStorage->attach($this, ['status' => $status, 'reverse' => true]);
- }
-
- /**
- * Returns the SplObjectStorage associated to this relationship (creates it if it does not exists).
- *
- * @param string $pivotTableName
- *
- * @return \SplObjectStorage
- */
- private function getRelationshipStorage(string $pivotTableName) : \SplObjectStorage
- {
- return $this->relationships[$pivotTableName] ?? $this->relationships[$pivotTableName] = new \SplObjectStorage();
- }
-
- /**
- * Returns the SplObjectStorage associated to this relationship (creates it if it does not exists).
- *
- * @param string $tableName
- * @param string $foreignKeyName
- *
- * @return AlterableResultIterator
- */
- private function getManyToOneAlterableResultIterator(string $tableName, string $foreignKeyName) : AlterableResultIterator
- {
- $key = $tableName.'___'.$foreignKeyName;
-
- return $this->manyToOneRelationships[$key] ?? $this->manyToOneRelationships[$key] = new AlterableResultIterator();
- }
-
- /**
- * Declares a relationship between this bean and the bean pointing to it.
- *
- * @param string $tableName
- * @param string $foreignKeyName
- * @param AbstractTDBMObject $remoteBean
- */
- private function setManyToOneRelationship(string $tableName, string $foreignKeyName, AbstractTDBMObject $remoteBean)
- {
- $alterableResultIterator = $this->getManyToOneAlterableResultIterator($tableName, $foreignKeyName);
- $alterableResultIterator->add($remoteBean);
- }
-
- /**
- * Declares a relationship between this bean and the bean pointing to it.
- *
- * @param string $tableName
- * @param string $foreignKeyName
- * @param AbstractTDBMObject $remoteBean
- */
- private function removeManyToOneRelationship(string $tableName, string $foreignKeyName, AbstractTDBMObject $remoteBean)
- {
- $alterableResultIterator = $this->getManyToOneAlterableResultIterator($tableName, $foreignKeyName);
- $alterableResultIterator->remove($remoteBean);
- }
-
- /**
- * Returns the list of objects linked to this bean via a given foreign key.
- *
- * @param string $tableName
- * @param string $foreignKeyName
- * @param string $searchTableName
- * @param array $searchFilter
- * @param string $orderString The ORDER BY part of the query. All columns must be prefixed by the table name (in the form: table.column). WARNING : This parameter is not kept when there is an additionnal or removal object !
- *
- * @return AlterableResultIterator
- */
- protected function retrieveManyToOneRelationshipsStorage(string $tableName, string $foreignKeyName, string $searchTableName, array $searchFilter, $orderString = null) : AlterableResultIterator
- {
- $key = $tableName.'___'.$foreignKeyName;
- $alterableResultIterator = $this->getManyToOneAlterableResultIterator($tableName, $foreignKeyName);
- if ($this->status === TDBMObjectStateEnum::STATE_DETACHED || $this->status === TDBMObjectStateEnum::STATE_NEW || (isset($this->manyToOneRelationships[$key]) && $this->manyToOneRelationships[$key]->getUnderlyingResultIterator() !== null)) {
- return $alterableResultIterator;
- }
-
- $unalteredResultIterator = $this->tdbmService->findObjects($searchTableName, $searchFilter, [], $orderString);
-
- $alterableResultIterator->setResultIterator($unalteredResultIterator->getIterator());
-
- return $alterableResultIterator;
- }
-
- /**
- * Reverts any changes made to the object and resumes it to its DB state.
- * This can only be called on objects that come from database and that have not been deleted.
- * Otherwise, this will throw an exception.
- *
- * @throws TDBMException
- */
- public function discardChanges()
- {
- if ($this->status === TDBMObjectStateEnum::STATE_NEW || $this->status === TDBMObjectStateEnum::STATE_DETACHED) {
- throw new TDBMException("You cannot call discardChanges() on an object that has been created with the 'new' keyword and that has not yet been saved.");
- }
-
- if ($this->status === TDBMObjectStateEnum::STATE_DELETED) {
- throw new TDBMException('You cannot call discardChanges() on an object that has been deleted.');
- }
-
- $this->_setStatus(TDBMObjectStateEnum::STATE_NOT_LOADED);
- }
-
- /**
- * Method used internally by TDBM. You should not use it directly.
- * This method returns the status of the TDBMObject.
- * This is one of TDBMObjectStateEnum::STATE_NEW, TDBMObjectStateEnum::STATE_NOT_LOADED, TDBMObjectStateEnum::STATE_LOADED, TDBMObjectStateEnum::STATE_DELETED.
- * $status = TDBMObjectStateEnum::STATE_NEW when a new object is created with DBMObject:getNewObject.
- * $status = TDBMObjectStateEnum::STATE_NOT_LOADED when the object has been retrieved with getObject but when no data has been accessed in it yet.
- * $status = TDBMObjectStateEnum::STATE_LOADED when the object is cached in memory.
- *
- * @return string
- */
- public function _getStatus()
- {
- return $this->status;
- }
-
- /**
- * Override the native php clone function for TDBMObjects.
- */
- public function __clone()
- {
- // Let's clone the many to many relationships
- if ($this->status === TDBMObjectStateEnum::STATE_DETACHED) {
- $pivotTableList = array_keys($this->relationships);
- } else {
- $pivotTableList = $this->tdbmService->_getPivotTablesLinkedToBean($this);
- }
-
- foreach ($pivotTableList as $pivotTable) {
- $storage = $this->retrieveRelationshipsStorage($pivotTable);
-
- // Let's duplicate the reverse side of the relationship // This is useless: already done by "retrieveRelationshipsStorage"!!!
- /*foreach ($storage as $remoteBean) {
- $metadata = $storage[$remoteBean];
-
- $remoteStorage = $remoteBean->getRelationshipStorage($pivotTable);
- $remoteStorage->attach($this, ['status' => $metadata['status'], 'reverse' => !$metadata['reverse']]);
- }*/
- }
-
- // Let's clone each row
- foreach ($this->dbRows as $key => &$dbRow) {
- $dbRow = clone $dbRow;
- $dbRow->setTDBMObject($this);
- }
-
- $this->manyToOneRelationships = [];
-
- // Let's set the status to new (to enter the save function)
- $this->status = TDBMObjectStateEnum::STATE_DETACHED;
- }
-
- /**
- * Returns raw database rows.
- *
- * @return DbRow[] Key: table name, Value: DbRow object
- */
- public function _getDbRows()
- {
- return $this->dbRows;
- }
-
- private function registerTable($tableName)
- {
- $dbRow = new DbRow($this, $tableName);
-
- if (in_array($this->status, [TDBMObjectStateEnum::STATE_NOT_LOADED, TDBMObjectStateEnum::STATE_LOADED, TDBMObjectStateEnum::STATE_DIRTY])) {
- // Let's get the primary key for the new table
- $anotherDbRow = array_values($this->dbRows)[0];
- /* @var $anotherDbRow DbRow */
- $indexedPrimaryKeys = array_values($anotherDbRow->_getPrimaryKeys());
- $primaryKeys = $this->tdbmService->_getPrimaryKeysFromIndexedPrimaryKeys($tableName, $indexedPrimaryKeys);
- $dbRow->_setPrimaryKeys($primaryKeys);
- }
-
- $dbRow->_setStatus($this->status);
-
- $this->dbRows[$tableName] = $dbRow;
- // TODO: look at status (if not new)=> get primary key from tdbmservice
- }
-
- /**
- * Internal function: return the list of relationships.
- *
- * @return \SplObjectStorage[]
- */
- public function _getCachedRelationships()
- {
- return $this->relationships;
- }
-
- /**
- * Returns an array of used tables by this bean (from parent to child relationship).
- *
- * @return string[]
- */
- abstract protected function getUsedTables() : array;
-
- /**
- * Method called when the bean is removed from database.
- */
- protected function onDelete() : void
- {
- }
-}
diff --git a/src/Mouf/Database/TDBM/AlterableResultIterator.php b/src/Mouf/Database/TDBM/AlterableResultIterator.php
deleted file mode 100644
index 11c1503..0000000
--- a/src/Mouf/Database/TDBM/AlterableResultIterator.php
+++ /dev/null
@@ -1,287 +0,0 @@
- the object will be added to the resultset (if it is not found in it)
- * "delete" => the object will be removed from the resultset (if found).
- *
- * @var \SplObjectStorage
- */
- private $alterations;
-
- /**
- * The result array from the result set.
- *
- * @var array|null
- */
- private $resultArray;
-
- /**
- * @param \Iterator|null $resultIterator
- */
- public function __construct(\Iterator $resultIterator = null)
- {
- $this->resultIterator = $resultIterator;
- $this->alterations = new \SplObjectStorage();
- }
-
- /**
- * Sets a new iterator as the base iterator to be altered.
- *
- * @param \Iterator $resultIterator
- */
- public function setResultIterator(\Iterator $resultIterator)
- {
- $this->resultIterator = $resultIterator;
- $this->resultArray = null;
- }
-
- /**
- * Returns the non altered result iterator (or null if none exist).
- *
- * @return \Iterator|null
- */
- public function getUnderlyingResultIterator()
- {
- return $this->resultIterator;
- }
-
- /**
- * Adds an additional object to the result set (if not already available).
- *
- * @param $object
- */
- public function add($object)
- {
- $this->alterations->attach($object, 'add');
-
- if ($this->resultArray !== null) {
- $foundKey = array_search($object, $this->resultArray, true);
- if ($foundKey === false) {
- $this->resultArray[] = $object;
- }
- }
- }
-
- /**
- * Removes an object from the result set.
- *
- * @param $object
- */
- public function remove($object)
- {
- $this->alterations->attach($object, 'delete');
-
- if ($this->resultArray !== null) {
- $foundKey = array_search($object, $this->resultArray, true);
- if ($foundKey !== false) {
- unset($this->resultArray[$foundKey]);
- }
- }
- }
-
- /**
- * Casts the result set to a PHP array.
- *
- * @return array
- */
- public function toArray()
- {
- if ($this->resultArray === null) {
- if ($this->resultIterator !== null) {
- $this->resultArray = iterator_to_array($this->resultIterator);
- } else {
- $this->resultArray = [];
- }
-
- foreach ($this->alterations as $obj) {
- $action = $this->alterations->getInfo(); // return, if exists, associated with cur. obj. data; else NULL
-
- $foundKey = array_search($obj, $this->resultArray, true);
-
- if ($action === 'add' && $foundKey === false) {
- $this->resultArray[] = $obj;
- } elseif ($action === 'delete' && $foundKey !== false) {
- unset($this->resultArray[$foundKey]);
- }
- }
- }
-
- return array_values($this->resultArray);
- }
-
- /**
- * Whether a offset exists.
- *
- * @link http://php.net/manual/en/arrayaccess.offsetexists.php
- *
- * @param mixed $offset
- * An offset to check for.
- *
- *
- * @return bool true on success or false on failure.
- *
- *
- * The return value will be casted to boolean if non-boolean was returned
- *
- * @since 5.0.0
- */
- public function offsetExists($offset)
- {
- return isset($this->toArray()[$offset]);
- }
-
- /**
- * Offset to retrieve.
- *
- * @link http://php.net/manual/en/arrayaccess.offsetget.php
- *
- * @param mixed $offset
- * The offset to retrieve.
- *
- *
- * @return mixed Can return all value types
- *
- * @since 5.0.0
- */
- public function offsetGet($offset)
- {
- return $this->toArray()[$offset];
- }
-
- /**
- * Offset to set.
- *
- * @link http://php.net/manual/en/arrayaccess.offsetset.php
- *
- * @param mixed $offset
- * The offset to assign the value to.
- *
- * @param mixed $value
- * The value to set.
- *
- *
- * @since 5.0.0
- */
- public function offsetSet($offset, $value)
- {
- throw new TDBMInvalidOperationException('You can set values in a TDBM result set, even in an alterable one. Use the add method instead.');
- }
-
- /**
- * Offset to unset.
- *
- * @link http://php.net/manual/en/arrayaccess.offsetunset.php
- *
- * @param mixed $offset
- * The offset to unset.
- *
- *
- * @since 5.0.0
- */
- public function offsetUnset($offset)
- {
- throw new TDBMInvalidOperationException('You can unset values in a TDBM result set, even in an alterable one. Use the delete method instead.');
- }
-
- /**
- * @param int $offset
- *
- * @return \Porpaginas\Page
- */
- public function take($offset, $limit)
- {
- // TODO: replace this with a class implementing the map method.
- return new ArrayPage(array_slice($this->toArray(), $offset, $limit), $offset, $limit, count($this->toArray()));
- }
-
- /**
- * Return the number of all results in the paginatable.
- *
- * @return int
- */
- public function count()
- {
- return count($this->toArray());
- }
-
- /**
- * Return an iterator over all results of the paginatable.
- *
- * @return Iterator
- */
- public function getIterator()
- {
- if ($this->alterations->count() === 0) {
- if ($this->resultIterator !== null) {
- return $this->resultIterator;
- } else {
- return new \ArrayIterator([]);
- }
- } else {
- return new \ArrayIterator($this->toArray());
- }
- }
-
- /**
- * Specify data which should be serialized to JSON.
- *
- * @link http://php.net/manual/en/jsonserializable.jsonserialize.php
- *
- * @return mixed data which can be serialized by json_encode,
- * which is a value of any type other than a resource
- *
- * @since 5.4.0
- */
- public function jsonSerialize()
- {
- return $this->toArray();
- }
-
- /**
- * Returns only one value (the first) of the result set.
- * Returns null if no value exists.
- *
- * @return mixed|null
- */
- public function first()
- {
- $page = $this->take(0, 1);
- foreach ($page as $bean) {
- return $bean;
- }
-
- return;
- }
-
- /**
- * Returns a new iterator mapping any call using the $callable function.
- *
- * @param callable $callable
- *
- * @return MapIterator
- */
- public function map(callable $callable)
- {
- return new MapIterator($this->getIterator(), $callable);
- }
-}
diff --git a/src/Mouf/Database/TDBM/Commands/AlteredConfiguration.php b/src/Mouf/Database/TDBM/Commands/AlteredConfiguration.php
deleted file mode 100644
index 5e424e5..0000000
--- a/src/Mouf/Database/TDBM/Commands/AlteredConfiguration.php
+++ /dev/null
@@ -1,122 +0,0 @@
-configuration = $configuration;
- $this->logger = $configuration->getLogger();
- }
-
-
- /**
- * @return string
- */
- public function getBeanNamespace(): string
- {
- return $this->configuration->getBeanNamespace();
- }
-
- /**
- * @return string
- */
- public function getDaoNamespace(): string
- {
- return $this->configuration->getDaoNamespace();
- }
-
- /**
- * @return Connection
- */
- public function getConnection(): Connection
- {
- return $this->configuration->getConnection();
- }
-
- /**
- * @return Cache
- */
- public function getCache(): Cache
- {
- return $this->configuration->getCache();
- }
-
- /**
- * @return NamingStrategyInterface
- */
- public function getNamingStrategy(): NamingStrategyInterface
- {
- return $this->configuration->getNamingStrategy();
- }
-
- /**
- * @return SchemaAnalyzer
- */
- public function getSchemaAnalyzer(): SchemaAnalyzer
- {
- return $this->configuration->getSchemaAnalyzer();
- }
-
- /**
- * @return LoggerInterface
- */
- public function getLogger(): ?LoggerInterface
- {
- return $this->logger;
- }
-
- /**
- * @return GeneratorListenerInterface
- */
- public function getGeneratorEventDispatcher(): GeneratorListenerInterface
- {
- return $this->configuration->getGeneratorEventDispatcher();
- }
-
- /**
- * @param LoggerInterface $logger
- */
- public function setLogger(LoggerInterface $logger)
- {
- $this->logger = $logger;
- }
-
- /**
- * Returns a class able to find the place of a PHP file based on the class name.
- * Useful to find the path where DAOs and beans should be written to.
- *
- * @return PathFinderInterface
- */
- public function getPathFinder(): PathFinderInterface
- {
- return $this->configuration->getPathFinder();
- }
-}
diff --git a/src/Mouf/Database/TDBM/Commands/GenerateCommand.php b/src/Mouf/Database/TDBM/Commands/GenerateCommand.php
deleted file mode 100644
index 923e0e0..0000000
--- a/src/Mouf/Database/TDBM/Commands/GenerateCommand.php
+++ /dev/null
@@ -1,59 +0,0 @@
-configuration = $configuration;
- }
-
- protected function configure()
- {
- $this->setName('tdbm:generate')
- ->setDescription('Generates DAOs and beans.')
- ->setHelp('Use this command to generate or regenerate the DAOs and beans for your project.')
- ;
- }
-
- protected function execute(InputInterface $input, OutputInterface $output)
- {
- // TODO: externalize composer.json file for autoloading (no more parameters for generateAllDaosAndBeans)
-
- $alteredConf = new AlteredConfiguration($this->configuration);
-
-
- $loggers = [ new ConsoleLogger($output) ];
-
- $logger = $alteredConf->getLogger();
- if ($logger) {
- $loggers[] = $logger;
- }
-
- $multiLogger = new MultiLogger($loggers);
-
- $alteredConf->setLogger($multiLogger);
-
- $multiLogger->notice('Starting regenerating DAOs and beans');
-
- $tdbmService = new TDBMService($this->configuration);
- $tdbmService->generateAllDaosAndBeans();
-
- $multiLogger->notice('Finished regenerating DAOs and beans');
- }
-}
diff --git a/src/Mouf/Database/TDBM/Configuration.php b/src/Mouf/Database/TDBM/Configuration.php
deleted file mode 100644
index 68fae85..0000000
--- a/src/Mouf/Database/TDBM/Configuration.php
+++ /dev/null
@@ -1,181 +0,0 @@
-beanNamespace = rtrim($beanNamespace, '\\');
- $this->daoNamespace = rtrim($daoNamespace, '\\');
- $this->connection = $connection;
- $this->namingStrategy = $namingStrategy;
- if ($cache !== null) {
- $this->cache = $cache;
- } else {
- $this->cache = new VoidCache();
- }
- if ($schemaAnalyzer !== null) {
- $this->schemaAnalyzer = $schemaAnalyzer;
- } else {
- $this->schemaAnalyzer = new SchemaAnalyzer($this->connection->getSchemaManager(), $this->cache, $this->getConnectionUniqueId());
- }
- $this->logger = $logger;
- $this->generatorEventDispatcher = new GeneratorEventDispatcher($generatorListeners);
- $this->pathFinder = new PathFinder();
- }
-
- /**
- * @return string
- */
- public function getBeanNamespace(): string
- {
- return $this->beanNamespace;
- }
-
- /**
- * @return string
- */
- public function getDaoNamespace(): string
- {
- return $this->daoNamespace;
- }
-
- /**
- * @return Connection
- */
- public function getConnection(): Connection
- {
- return $this->connection;
- }
-
- /**
- * @return NamingStrategyInterface
- */
- public function getNamingStrategy(): NamingStrategyInterface
- {
- return $this->namingStrategy;
- }
-
- /**
- * @return Cache
- */
- public function getCache(): Cache
- {
- return $this->cache;
- }
-
- /**
- * @return SchemaAnalyzer
- */
- public function getSchemaAnalyzer(): SchemaAnalyzer
- {
- return $this->schemaAnalyzer;
- }
-
- /**
- * @return LoggerInterface
- */
- public function getLogger(): ?LoggerInterface
- {
- return $this->logger;
- }
-
- /**
- * @return GeneratorListenerInterface
- */
- public function getGeneratorEventDispatcher(): GeneratorListenerInterface
- {
- return $this->generatorEventDispatcher;
- }
-
-
-
- /**
- * Creates a unique cache key for the current connection.
- *
- * @return string
- */
- private function getConnectionUniqueId(): string
- {
- return hash('md4', $this->connection->getHost().'-'.$this->connection->getPort().'-'.$this->connection->getDatabase().'-'.$this->connection->getDriver()->getName());
- }
-
- /**
- * Returns a class able to find the place of a PHP file based on the class name.
- * Useful to find the path where DAOs and beans should be written to.
- *
- * @return PathFinderInterface
- */
- public function getPathFinder(): PathFinderInterface
- {
- return $this->pathFinder;
- }
-
- /**
- * @param PathFinderInterface $pathFinder
- */
- public function setPathFinder(PathFinderInterface $pathFinder)
- {
- $this->pathFinder = $pathFinder;
- }
-}
diff --git a/src/Mouf/Database/TDBM/ConfigurationInterface.php b/src/Mouf/Database/TDBM/ConfigurationInterface.php
deleted file mode 100644
index 84efdac..0000000
--- a/src/Mouf/Database/TDBM/ConfigurationInterface.php
+++ /dev/null
@@ -1,63 +0,0 @@
-moufManager = MoufManager::getMoufManagerHiddenInstance();
}
- $this->content->addFile(dirname(__FILE__).'/../../../../views/installStep1.php', $this);
+ $this->content->addFile(__DIR__.'/../../../../views/installStep1.php', $this);
$this->template->toHtml();
}
@@ -177,6 +177,10 @@ public function generate($daonamespace, $beannamespace, /*$storeInUtc = 0,*/ $se
$migratingFrom42 = true;
}
+ if ($this->moufManager->has('tdbmService') && $this->moufManager->getInstanceDescriptor('tdbmService')->getClassName() === 'Mouf\\Database\\TDBM\\TDBMService') {
+ $this->migrateNamespaceTo50($this->moufManager);
+ }
+
$namingStrategy = InstallUtils::getOrCreateInstance('namingStrategy', DefaultNamingStrategy::class, $this->moufManager);
if ($migratingFrom42) {
// Let's setup the naming strategy for compatibility
@@ -236,4 +240,27 @@ private function displayErrorMsg($msg)
$this->content->addFile(__DIR__.'/../../../../views/installError.php', $this);
$this->template->toHtml();
}
+
+ /**
+ * Migrate classes from old 4.x namespace (Mouf\Database\TDBM) to new 5.x namespace (TheCodingMachine\TDBM)
+ *
+ * @param MoufManager $moufManager
+ */
+ private function migrateNamespaceTo50(MoufManager $moufManager)
+ {
+ $instanceList = $moufManager->getInstancesList();
+
+ $migratedClasses = [
+ 'Mouf\\Database\\TDBM\\Configuration' => 'TheCodingMachine\\TDBM\\Configuration',
+ 'Mouf\\Database\\TDBM\\TDBMService' => 'TheCodingMachine\\TDBM\\TDBMService',
+ 'Mouf\\Database\\TDBM\\Commands\\GenerateCommand' => 'TheCodingMachine\\TDBM\\Commands\\GenerateCommand',
+ 'Mouf\\Database\\TDBM\\Utils\\DefaultNamingStrategy' => 'TheCodingMachine\\TDBM\\Utils\\DefaultNamingStrategy',
+ ];
+
+ foreach ($instanceList as $instanceName => $className) {
+ if (isset($migratedClasses[$className])) {
+ $moufManager->alterClass($instanceName, $migratedClasses[$className]);
+ }
+ }
+ }
}
diff --git a/src/Mouf/Database/TDBM/DbRow.php b/src/Mouf/Database/TDBM/DbRow.php
deleted file mode 100644
index 27b662a..0000000
--- a/src/Mouf/Database/TDBM/DbRow.php
+++ /dev/null
@@ -1,449 +0,0 @@
- value
- */
- private $primaryKeys;
-
- /**
- * You should never call the constructor directly. Instead, you should use the
- * TDBMService class that will create TDBMObjects for you.
- *
- * Used with id!=false when we want to retrieve an existing object
- * and id==false if we want a new object
- *
- * @param AbstractTDBMObject $object The object containing this db row
- * @param string $table_name
- * @param array $primaryKeys
- * @param TDBMService $tdbmService
- *
- * @throws TDBMException
- * @throws TDBMInvalidOperationException
- */
- public function __construct(AbstractTDBMObject $object, $table_name, array $primaryKeys = array(), TDBMService $tdbmService = null, array $dbRow = array())
- {
- $this->object = $object;
- $this->dbTableName = $table_name;
-
- $this->status = TDBMObjectStateEnum::STATE_DETACHED;
-
- if ($tdbmService === null) {
- if (!empty($primaryKeys)) {
- throw new TDBMException('You cannot pass an id to the DbRow constructor without passing also a TDBMService.');
- }
- } else {
- $this->tdbmService = $tdbmService;
-
- if (!empty($primaryKeys)) {
- $this->_setPrimaryKeys($primaryKeys);
- if (!empty($dbRow)) {
- $this->dbRow = $dbRow;
- $this->status = TDBMObjectStateEnum::STATE_LOADED;
- } else {
- $this->status = TDBMObjectStateEnum::STATE_NOT_LOADED;
- }
- $tdbmService->_addToCache($this);
- } else {
- $this->status = TDBMObjectStateEnum::STATE_NEW;
- $this->tdbmService->_addToToSaveObjectList($this);
- }
- }
- }
-
- public function _attach(TDBMService $tdbmService)
- {
- if ($this->status !== TDBMObjectStateEnum::STATE_DETACHED) {
- throw new TDBMInvalidOperationException('Cannot attach an object that is already attached to TDBM.');
- }
- $this->tdbmService = $tdbmService;
- $this->status = TDBMObjectStateEnum::STATE_NEW;
- $this->tdbmService->_addToToSaveObjectList($this);
- }
-
- /**
- * Sets the state of the TDBM Object
- * One of TDBMObjectStateEnum::STATE_NEW, TDBMObjectStateEnum::STATE_NOT_LOADED, TDBMObjectStateEnum::STATE_LOADED, TDBMObjectStateEnum::STATE_DELETED.
- * $status = TDBMObjectStateEnum::STATE_NEW when a new object is created with DBMObject:getNewObject.
- * $status = TDBMObjectStateEnum::STATE_NOT_LOADED when the object has been retrieved with getObject but when no data has been accessed in it yet.
- * $status = TDBMObjectStateEnum::STATE_LOADED when the object is cached in memory.
- *
- * @param string $state
- */
- public function _setStatus($state)
- {
- $this->status = $state;
- }
-
- /**
- * This is an internal method. You should not call this method yourself. The TDBM library will do it for you.
- * If the object is in state 'not loaded', this method performs a query in database to load the object.
- *
- * A TDBMException is thrown is no object can be retrieved (for instance, if the primary key specified
- * cannot be found).
- */
- public function _dbLoadIfNotLoaded()
- {
- if ($this->status == TDBMObjectStateEnum::STATE_NOT_LOADED) {
- $connection = $this->tdbmService->getConnection();
-
- /// buildFilterFromFilterBag($filter_bag)
- list($sql_where, $parameters) = $this->tdbmService->buildFilterFromFilterBag($this->primaryKeys);
-
- $sql = 'SELECT * FROM '.$connection->quoteIdentifier($this->dbTableName).' WHERE '.$sql_where;
- $result = $connection->executeQuery($sql, $parameters);
-
- if ($result->rowCount() === 0) {
- throw new TDBMException("Could not retrieve object from table \"$this->dbTableName\" using filter \"\".");
- }
-
- $row = $result->fetch(\PDO::FETCH_ASSOC);
-
- $this->dbRow = [];
- $types = $this->tdbmService->_getColumnTypesForTable($this->dbTableName);
-
- foreach ($row as $key => $value) {
- $this->dbRow[$key] = $types[$key]->convertToPHPValue($value, $connection->getDatabasePlatform());
- }
-
- $result->closeCursor();
-
- $this->status = TDBMObjectStateEnum::STATE_LOADED;
- }
- }
-
- public function get($var)
- {
- $this->_dbLoadIfNotLoaded();
-
- // Let's first check if the key exist.
- if (!isset($this->dbRow[$var])) {
- /*
- // Unable to find column.... this is an error if the object has been retrieved from database.
- // If it's a new object, well, that may not be an error after all!
- // Let's check if the column does exist in the table
- $column_exist = $this->db_connection->checkColumnExist($this->dbTableName, $var);
- // If the column DOES exist, then the object is new, and therefore, we should
- // return null.
- if ($column_exist === true) {
- return null;
- }
-
- // Let's try to be accurate in error reporting. The checkColumnExist returns an array of closest matches.
- $result_array = $column_exist;
-
- if (count($result_array)==1)
- $str = "Could not find column \"$var\" in table \"$this->dbTableName\". Maybe you meant this column: '".$result_array[0]."'";
- else
- $str = "Could not find column \"$var\" in table \"$this->dbTableName\". Maybe you meant one of those columns: '".implode("', '",$result_array)."'";
-
- throw new TDBMException($str);*/
- return;
- }
-
- $value = $this->dbRow[$var];
- if ($value instanceof \DateTime) {
- if (method_exists('DateTimeImmutable', 'createFromMutable')) { // PHP 5.6+ only
- return \DateTimeImmutable::createFromMutable($value);
- } else {
- return new \DateTimeImmutable($value->format('c'));
- }
- }
-
- return $this->dbRow[$var];
- }
-
- /**
- * Returns true if a column is set, false otherwise.
- *
- * @param string $var
- *
- * @return bool
- */
- /*public function has($var) {
- $this->_dbLoadIfNotLoaded();
-
- return isset($this->dbRow[$var]);
- }*/
-
- public function set($var, $value)
- {
- $this->_dbLoadIfNotLoaded();
-
- /*
- // Ok, let's start by checking the column type
- $type = $this->db_connection->getColumnType($this->dbTableName, $var);
-
- // Throws an exception if the type is not ok.
- if (!$this->db_connection->checkType($value, $type)) {
- throw new TDBMException("Error! Invalid value passed for attribute '$var' of table '$this->dbTableName'. Passed '$value', but expecting '$type'");
- }
- */
-
- /*if ($var == $this->getPrimaryKey() && isset($this->dbRow[$var]))
- throw new TDBMException("Error! Changing primary key value is forbidden.");*/
- $this->dbRow[$var] = $value;
- if ($this->tdbmService !== null && $this->status === TDBMObjectStateEnum::STATE_LOADED) {
- $this->status = TDBMObjectStateEnum::STATE_DIRTY;
- $this->tdbmService->_addToToSaveObjectList($this);
- }
- }
-
- /**
- * @param string $foreignKeyName
- * @param AbstractTDBMObject $bean
- */
- public function setRef($foreignKeyName, AbstractTDBMObject $bean = null)
- {
- $this->references[$foreignKeyName] = $bean;
-
- if ($this->tdbmService !== null && $this->status === TDBMObjectStateEnum::STATE_LOADED) {
- $this->status = TDBMObjectStateEnum::STATE_DIRTY;
- $this->tdbmService->_addToToSaveObjectList($this);
- }
- }
-
- /**
- * @param string $foreignKeyName A unique name for this reference
- *
- * @return AbstractTDBMObject|null
- */
- public function getRef($foreignKeyName)
- {
- if (array_key_exists($foreignKeyName, $this->references)) {
- return $this->references[$foreignKeyName];
- } elseif ($this->status === TDBMObjectStateEnum::STATE_NEW || $this->tdbmService === null) {
- // If the object is new and has no property, then it has to be empty.
- return;
- } else {
- $this->_dbLoadIfNotLoaded();
-
- // Let's match the name of the columns to the primary key values
- $fk = $this->tdbmService->_getForeignKeyByName($this->dbTableName, $foreignKeyName);
-
- $values = [];
- foreach ($fk->getLocalColumns() as $column) {
- if (!isset($this->dbRow[$column])) {
- return;
- }
- $values[] = $this->dbRow[$column];
- }
-
- $filter = array_combine($this->tdbmService->getPrimaryKeyColumns($fk->getForeignTableName()), $values);
-
- return $this->tdbmService->findObjectByPk($fk->getForeignTableName(), $filter, [], true);
- }
- }
-
- /**
- * Returns the name of the table this object comes from.
- *
- * @return string
- */
- public function _getDbTableName()
- {
- return $this->dbTableName;
- }
-
- /**
- * Method used internally by TDBM. You should not use it directly.
- * This method returns the status of the TDBMObject.
- * This is one of TDBMObjectStateEnum::STATE_NEW, TDBMObjectStateEnum::STATE_NOT_LOADED, TDBMObjectStateEnum::STATE_LOADED, TDBMObjectStateEnum::STATE_DELETED.
- * $status = TDBMObjectStateEnum::STATE_NEW when a new object is created with DBMObject:getNewObject.
- * $status = TDBMObjectStateEnum::STATE_NOT_LOADED when the object has been retrieved with getObject but when no data has been accessed in it yet.
- * $status = TDBMObjectStateEnum::STATE_LOADED when the object is cached in memory.
- *
- * @return string
- */
- public function _getStatus()
- {
- return $this->status;
- }
-
- /**
- * Override the native php clone function for TDBMObjects.
- */
- public function __clone()
- {
- // Let's load the row (before we lose the ID!)
- $this->_dbLoadIfNotLoaded();
-
- //Let's set the status to detached
- $this->status = TDBMObjectStateEnum::STATE_DETACHED;
-
- $this->primaryKeys = [];
-
- //Now unset the PK from the row
- if ($this->tdbmService) {
- $pk_array = $this->tdbmService->getPrimaryKeyColumns($this->dbTableName);
- foreach ($pk_array as $pk) {
- $this->dbRow[$pk] = null;
- }
- }
- }
-
- /**
- * Returns raw database row.
- *
- * @return array
- *
- * @throws TDBMMissingReferenceException
- */
- public function _getDbRow()
- {
- // Let's merge $dbRow and $references
- $dbRow = $this->dbRow;
-
- foreach ($this->references as $foreignKeyName => $reference) {
- // Let's match the name of the columns to the primary key values
- $fk = $this->tdbmService->_getForeignKeyByName($this->dbTableName, $foreignKeyName);
- $localColumns = $fk->getLocalColumns();
-
- if ($reference !== null) {
- $refDbRows = $reference->_getDbRows();
- $firstRefDbRow = reset($refDbRows);
- if ($firstRefDbRow->_getStatus() == TDBMObjectStateEnum::STATE_DELETED) {
- throw TDBMMissingReferenceException::referenceDeleted($this->dbTableName, $reference);
- }
- $pkValues = array_values($firstRefDbRow->_getPrimaryKeys());
- for ($i = 0, $count = count($localColumns); $i < $count; ++$i) {
- $dbRow[$localColumns[$i]] = $pkValues[$i];
- }
- } else {
- for ($i = 0, $count = count($localColumns); $i < $count; ++$i) {
- $dbRow[$localColumns[$i]] = null;
- }
- }
- }
-
- return $dbRow;
- }
-
- /**
- * Returns references array.
- *
- * @return AbstractTDBMObject[]
- */
- public function _getReferences()
- {
- return $this->references;
- }
-
- /**
- * Returns the values of the primary key.
- * This is set when the object is in "loaded" state.
- *
- * @return array
- */
- public function _getPrimaryKeys()
- {
- return $this->primaryKeys;
- }
-
- /**
- * Sets the values of the primary key.
- * This is set when the object is in "loaded" state.
- *
- * @param array $primaryKeys
- */
- public function _setPrimaryKeys(array $primaryKeys)
- {
- $this->primaryKeys = $primaryKeys;
- foreach ($this->primaryKeys as $column => $value) {
- $this->dbRow[$column] = $value;
- }
- }
-
- /**
- * Returns the TDBMObject this bean is associated to.
- *
- * @return AbstractTDBMObject
- */
- public function getTDBMObject()
- {
- return $this->object;
- }
-
- /**
- * Sets the TDBMObject this bean is associated to.
- * Only used when cloning.
- *
- * @param AbstractTDBMObject $object
- */
- public function setTDBMObject(AbstractTDBMObject $object)
- {
- $this->object = $object;
- }
-}
diff --git a/src/Mouf/Database/TDBM/DuplicateRowException.php b/src/Mouf/Database/TDBM/DuplicateRowException.php
deleted file mode 100644
index 8f8fe9d..0000000
--- a/src/Mouf/Database/TDBM/DuplicateRowException.php
+++ /dev/null
@@ -1,11 +0,0 @@
-getObject is called.
- * This can only happen if you use a filter bag as second parameter to the getObject method.
- */
-class DuplicateRowException extends TDBMException
-{
-}
diff --git a/src/Mouf/Database/TDBM/InnerResultArray.php b/src/Mouf/Database/TDBM/InnerResultArray.php
deleted file mode 100644
index 4a03683..0000000
--- a/src/Mouf/Database/TDBM/InnerResultArray.php
+++ /dev/null
@@ -1,126 +0,0 @@
-
- * An offset to check for.
- *
- *
- * @return bool true on success or false on failure.
- *
- *
- * The return value will be casted to boolean if non-boolean was returned
- *
- * @since 5.0.0
- */
- public function offsetExists($offset)
- {
- try {
- $this->toIndex($offset);
- } catch (TDBMInvalidOffsetException $e) {
- return false;
- }
-
- return true;
- }
-
- /**
- * Offset to retrieve.
- *
- * @link http://php.net/manual/en/arrayaccess.offsetget.php
- *
- * @param mixed $offset
- * The offset to retrieve.
- *
- *
- * @return mixed Can return all value types
- *
- * @since 5.0.0
- */
- public function offsetGet($offset)
- {
- $this->toIndex($offset);
-
- return $this->results[$offset];
- }
-
- private function toIndex($offset)
- {
- if ($offset < 0 || filter_var($offset, FILTER_VALIDATE_INT) === false) {
- throw new TDBMInvalidOffsetException('Trying to access result set using offset "'.$offset.'". An offset must be a positive integer.');
- }
- if ($this->statement === null) {
- $this->executeQuery();
- }
- while (!isset($this->results[$offset])) {
- $this->next();
- if ($this->current === null) {
- throw new TDBMInvalidOffsetException('Offset "'.$offset.'" does not exist in result set.');
- }
- }
- }
-
- public function next()
- {
- // Let's overload the next() method to store the result.
- if (isset($this->results[$this->key + 1])) {
- ++$this->key;
- $this->current = $this->results[$this->key];
- } else {
- parent::next();
- if ($this->current !== null) {
- $this->results[$this->key] = $this->current;
- }
- }
- }
-
- /**
- * Overloads the rewind implementation.
- * Do not reexecute the query.
- */
- public function rewind()
- {
- if (!$this->fetchStarted) {
- $this->executeQuery();
- }
- $this->key = -1;
- $this->next();
- }
-}
diff --git a/src/Mouf/Database/TDBM/InnerResultIterator.php b/src/Mouf/Database/TDBM/InnerResultIterator.php
deleted file mode 100644
index ae8749a..0000000
--- a/src/Mouf/Database/TDBM/InnerResultIterator.php
+++ /dev/null
@@ -1,295 +0,0 @@
-magicSql = $magicSql;
- $this->objectStorage = $objectStorage;
- $this->className = $className;
- $this->tdbmService = $tdbmService;
- $this->parameters = $parameters;
- $this->limit = $limit;
- $this->offset = $offset;
- $this->columnDescriptors = $columnDescriptors;
- $this->magicQuery = $magicQuery;
- $this->databasePlatform = $this->tdbmService->getConnection()->getDatabasePlatform();
- $this->logger = $logger;
- }
-
- protected function executeQuery()
- {
- $sql = $this->magicQuery->build($this->magicSql, $this->parameters);
- $sql = $this->tdbmService->getConnection()->getDatabasePlatform()->modifyLimitQuery($sql, $this->limit, $this->offset);
-
- $this->logger->debug('Running SQL request: '.$sql);
-
- $this->statement = $this->tdbmService->getConnection()->executeQuery($sql, $this->parameters);
-
- $this->fetchStarted = true;
- }
-
- /**
- * Counts found records (this is the number of records fetched, taking into account the LIMIT and OFFSET settings).
- *
- * @return int
- */
- public function count()
- {
- if (!$this->fetchStarted) {
- $this->executeQuery();
- }
-
- return $this->statement->rowCount();
- }
-
- /**
- * Fetches record at current cursor.
- *
- * @return AbstractTDBMObject|null
- */
- public function current()
- {
- return $this->current;
- }
-
- /**
- * Returns the current result's key.
- *
- * @return int
- */
- public function key()
- {
- return $this->key;
- }
-
- /**
- * Advances the cursor to the next result.
- * Casts the database result into one (or several) beans.
- */
- public function next()
- {
- $row = $this->statement->fetch(\PDO::FETCH_NUM);
- if ($row) {
-
- // array>>
- $beansData = [];
- foreach ($row as $i => $value) {
- $columnDescriptor = $this->columnDescriptors[$i];
-
- if ($columnDescriptor['tableGroup'] === null) {
- // A column can have no tableGroup (if it comes from an ORDER BY expression)
- continue;
- }
-
- // Let's cast the value according to its type
- $value = $columnDescriptor['type']->convertToPHPValue($value, $this->databasePlatform);
-
- $beansData[$columnDescriptor['tableGroup']][$columnDescriptor['table']][$columnDescriptor['column']] = $value;
- }
-
- $reflectionClassCache = [];
- $firstBean = true;
- foreach ($beansData as $beanData) {
-
- // Let's find the bean class name associated to the bean.
-
- list($actualClassName, $mainBeanTableName, $tablesUsed) = $this->tdbmService->_getClassNameFromBeanData($beanData);
-
- if ($this->className !== null) {
- $actualClassName = $this->className;
- }
-
- // Let's filter out the beanData that is not used (because it belongs to a part of the hierarchy that is not fetched:
- foreach ($beanData as $tableName => $descriptors) {
- if (!in_array($tableName, $tablesUsed)) {
- unset($beanData[$tableName]);
- }
- }
-
- // Must we create the bean? Let's see in the cache if we have a mapping DbRow?
- // Let's get the first object mapping a row:
- // We do this loop only for the first table
-
- $primaryKeys = $this->tdbmService->_getPrimaryKeysFromObjectData($mainBeanTableName, $beanData[$mainBeanTableName]);
- $hash = $this->tdbmService->getObjectHash($primaryKeys);
-
- if ($this->objectStorage->has($mainBeanTableName, $hash)) {
- $dbRow = $this->objectStorage->get($mainBeanTableName, $hash);
- $bean = $dbRow->getTDBMObject();
- } else {
- // Let's construct the bean
- if (!isset($reflectionClassCache[$actualClassName])) {
- $reflectionClassCache[$actualClassName] = new \ReflectionClass($actualClassName);
- }
- // Let's bypass the constructor when creating the bean!
- $bean = $reflectionClassCache[$actualClassName]->newInstanceWithoutConstructor();
- $bean->_constructFromData($beanData, $this->tdbmService);
- }
-
- // The first bean is the one containing the main table.
- if ($firstBean) {
- $firstBean = false;
- $this->current = $bean;
- }
- }
-
- ++$this->key;
- } else {
- $this->current = null;
- }
- }
-
- /**
- * Moves the cursor to the beginning of the result set.
- */
- public function rewind()
- {
- $this->executeQuery();
- $this->key = -1;
- $this->next();
- }
- /**
- * Checks if the cursor is reading a valid result.
- *
- * @return bool
- */
- public function valid()
- {
- return $this->current !== null;
- }
-
- /**
- * Whether a offset exists.
- *
- * @link http://php.net/manual/en/arrayaccess.offsetexists.php
- *
- * @param mixed $offset
- * An offset to check for.
- *
- *
- * @return bool true on success or false on failure.
- *
- *
- * The return value will be casted to boolean if non-boolean was returned
- *
- * @since 5.0.0
- */
- public function offsetExists($offset)
- {
- throw new TDBMInvalidOperationException('You cannot access this result set via index because it was fetched in CURSOR mode. Use ARRAY_MODE instead.');
- }
-
- /**
- * Offset to retrieve.
- *
- * @link http://php.net/manual/en/arrayaccess.offsetget.php
- *
- * @param mixed $offset
- * The offset to retrieve.
- *
- *
- * @return mixed Can return all value types
- *
- * @since 5.0.0
- */
- public function offsetGet($offset)
- {
- throw new TDBMInvalidOperationException('You cannot access this result set via index because it was fetched in CURSOR mode. Use ARRAY_MODE instead.');
- }
-
- /**
- * Offset to set.
- *
- * @link http://php.net/manual/en/arrayaccess.offsetset.php
- *
- * @param mixed $offset
- * The offset to assign the value to.
- *
- * @param mixed $value
- * The value to set.
- *
- *
- * @since 5.0.0
- */
- public function offsetSet($offset, $value)
- {
- throw new TDBMInvalidOperationException('You can set values in a TDBM result set.');
- }
-
- /**
- * Offset to unset.
- *
- * @link http://php.net/manual/en/arrayaccess.offsetunset.php
- *
- * @param mixed $offset
- * The offset to unset.
- *
- *
- * @since 5.0.0
- */
- public function offsetUnset($offset)
- {
- throw new TDBMInvalidOperationException('You can unset values in a TDBM result set.');
- }
-}
diff --git a/src/Mouf/Database/TDBM/MapIterator.php b/src/Mouf/Database/TDBM/MapIterator.php
deleted file mode 100644
index e557b8e..0000000
--- a/src/Mouf/Database/TDBM/MapIterator.php
+++ /dev/null
@@ -1,101 +0,0 @@
-iterator = new \ArrayIterator($iterator);
- } elseif (!($iterator instanceof Iterator)) {
- throw new TDBMException('$iterator parameter must be an instance of Iterator');
- } else {
- $this->iterator = $iterator;
- }
-
- if ($callable instanceof \Closure) {
- // make sure there's one argument
- $reflection = new \ReflectionObject($callable);
- if ($reflection->hasMethod('__invoke')) {
- $method = $reflection->getMethod('__invoke');
- if ($method->getNumberOfParameters() !== 1) {
- throw new TDBMException('$callable must accept one and only one parameter.');
- }
- }
- }
-
- $this->callable = $callable;
- }
-
- /**
- * Alters the current item with $this->callable and returns a new item.
- * Be careful with your types as we can't do static type checking here!
- *
- * @return mixed
- */
- public function current()
- {
- $callable = $this->callable;
-
- return $callable($this->iterator->current());
- }
-
- public function next()
- {
- $this->iterator->next();
- }
-
- public function key()
- {
- return $this->iterator->key();
- }
-
- public function valid()
- {
- return $this->iterator->valid();
- }
-
- public function rewind()
- {
- $this->iterator->rewind();
- }
-
- /**
- * Casts the iterator to a PHP array.
- *
- * @return array
- */
- public function toArray()
- {
- return iterator_to_array($this);
- }
-
- public function jsonSerialize()
- {
- return $this->toArray();
- }
-}
diff --git a/src/Mouf/Database/TDBM/MoufConfiguration.php b/src/Mouf/Database/TDBM/MoufConfiguration.php
index 8d4f82f..6259a36 100644
--- a/src/Mouf/Database/TDBM/MoufConfiguration.php
+++ b/src/Mouf/Database/TDBM/MoufConfiguration.php
@@ -3,14 +3,7 @@
namespace Mouf\Database\TDBM;
-use Doctrine\Common\Cache\Cache;
-use Doctrine\Common\Cache\VoidCache;
-use Doctrine\DBAL\Connection;
-use Mouf\Database\SchemaAnalyzer\SchemaAnalyzer;
-use Mouf\Database\TDBM\Utils\GeneratorEventDispatcher;
-use Mouf\Database\TDBM\Utils\GeneratorListenerInterface;
-use Mouf\Database\TDBM\Utils\NamingStrategyInterface;
-use Psr\Log\LoggerInterface;
+use TheCodingMachine\TDBM\Configuration;
/**
* Class containing configuration used only for Mouf specific tasks.
diff --git a/src/Mouf/Database/TDBM/NoBeanFoundException.php b/src/Mouf/Database/TDBM/NoBeanFoundException.php
deleted file mode 100644
index b388d8c..0000000
--- a/src/Mouf/Database/TDBM/NoBeanFoundException.php
+++ /dev/null
@@ -1,10 +0,0 @@
-findObjectOrFail is called.
- */
-class NoBeanFoundException extends TDBMException
-{
-}
diff --git a/src/Mouf/Database/TDBM/OrderByAnalyzer.php b/src/Mouf/Database/TDBM/OrderByAnalyzer.php
deleted file mode 100644
index e6ad1f9..0000000
--- a/src/Mouf/Database/TDBM/OrderByAnalyzer.php
+++ /dev/null
@@ -1,133 +0,0 @@
-cache = $cache;
- $this->cachePrefix = $cachePrefix;
- }
-
- /**
- * Returns an array for each sorted "column" in the form:.
- *
- * [
- * [
- * 'type' => 'colref',
- * 'table' => null,
- * 'column' => 'a',
- * 'direction' => 'ASC'
- * ],
- * [
- * 'type' => 'expr',
- * 'expr' => 'RAND()',
- * 'direction' => 'DESC'
- * ]
- * ]
- *
- * @param string $orderBy
- *
- * @return array
- */
- public function analyzeOrderBy(string $orderBy) : array
- {
- $key = $this->cachePrefix.'_order_by_analysis_'.$orderBy;
- $results = $this->cache->fetch($key);
- if ($results !== false) {
- return $results;
- }
- $results = $this->analyzeOrderByNoCache($orderBy);
- $this->cache->save($key, $results);
-
- return $results;
- }
-
- private function analyzeOrderByNoCache(string $orderBy) : array
- {
- $sqlParser = new PHPSQLParser();
- $sql = 'SELECT 1 FROM a ORDER BY '.$orderBy;
- $parsed = $sqlParser->parse($sql, true);
-
- $results = [];
-
- for ($i = 0, $count = count($parsed['ORDER']); $i < $count; ++$i) {
- $orderItem = $parsed['ORDER'][$i];
- if ($orderItem['expr_type'] === 'colref') {
- $parts = $orderItem['no_quotes']['parts'];
- $columnName = array_pop($parts);
- if (!empty($parts)) {
- $tableName = array_pop($parts);
- } else {
- $tableName = null;
- }
-
- $results[] = [
- 'type' => 'colref',
- 'table' => $tableName,
- 'column' => $columnName,
- 'direction' => $orderItem['direction'],
- ];
- } else {
- $position = $orderItem['position'];
- if ($i + 1 < $count) {
- $nextPosition = $parsed['ORDER'][$i + 1]['position'];
- $str = substr($sql, $position, $nextPosition - $position);
- } else {
- $str = substr($sql, $position);
- }
-
- $str = trim($str, " \t\r\n,");
-
- $results[] = [
- 'type' => 'expr',
- 'expr' => $this->trimDirection($str),
- 'direction' => $orderItem['direction'],
- ];
- }
- }
-
- return $results;
- }
-
- /**
- * Trims the ASC/DESC direction at the end of the string.
- *
- * @param string $sql
- *
- * @return string
- */
- private function trimDirection(string $sql) : string
- {
- preg_match('/^(.*)(\s+(DESC|ASC|))*$/Ui', $sql, $matches);
-
- return $matches[1];
- }
-}
diff --git a/src/Mouf/Database/TDBM/PageIterator.php b/src/Mouf/Database/TDBM/PageIterator.php
deleted file mode 100644
index 34f129c..0000000
--- a/src/Mouf/Database/TDBM/PageIterator.php
+++ /dev/null
@@ -1,267 +0,0 @@
-parentResult = $parentResult;
- $this->magicSql = $magicSql;
- $this->objectStorage = $objectStorage;
- $this->className = $className;
- $this->tdbmService = $tdbmService;
- $this->parameters = $parameters;
- $this->limit = $limit;
- $this->offset = $offset;
- $this->columnDescriptors = $columnDescriptors;
- $this->magicQuery = $magicQuery;
- $this->databasePlatform = $this->tdbmService->getConnection()->getDatabasePlatform();
- $this->mode = $mode;
- $this->logger = $logger;
- }
-
- /**
- * Retrieve an external iterator.
- *
- * @link http://php.net/manual/en/iteratoraggregate.getiterator.php
- *
- * @return InnerResultIterator An instance of an object implementing Iterator or
- * Traversable
- *
- * @since 5.0.0
- */
- public function getIterator()
- {
- if ($this->innerResultIterator === null) {
- if ($this->mode === TDBMService::MODE_CURSOR) {
- $this->innerResultIterator = new InnerResultIterator($this->magicSql, $this->parameters, $this->limit, $this->offset, $this->columnDescriptors, $this->objectStorage, $this->className, $this->tdbmService, $this->magicQuery, $this->logger);
- } else {
- $this->innerResultIterator = new InnerResultArray($this->magicSql, $this->parameters, $this->limit, $this->offset, $this->columnDescriptors, $this->objectStorage, $this->className, $this->tdbmService, $this->magicQuery, $this->logger);
- }
- }
-
- return $this->innerResultIterator;
- }
-
- /**
- * @return int
- */
- public function getCurrentOffset()
- {
- return $this->offset;
- }
-
- /**
- * @return int
- */
- public function getCurrentPage()
- {
- return floor($this->offset / $this->limit) + 1;
- }
-
- /**
- * @return int
- */
- public function getCurrentLimit()
- {
- return $this->limit;
- }
-
- /**
- * Return the number of results on the current page of the {@link Result}.
- *
- * @return int
- */
- public function count()
- {
- return $this->getIterator()->count();
- }
-
- /**
- * Return the number of ALL results in the paginatable of {@link Result}.
- *
- * @return int
- */
- public function totalCount()
- {
- return $this->parentResult->count();
- }
-
- /**
- * Casts the result set to a PHP array.
- *
- * @return array
- */
- public function toArray()
- {
- return iterator_to_array($this->getIterator());
- }
-
- /**
- * Returns a new iterator mapping any call using the $callable function.
- *
- * @param callable $callable
- *
- * @return MapIterator
- */
- public function map(callable $callable)
- {
- return new MapIterator($this->getIterator(), $callable);
- }
-
- /**
- * Whether a offset exists.
- *
- * @link http://php.net/manual/en/arrayaccess.offsetexists.php
- *
- * @param mixed $offset
- * An offset to check for.
- *
- *
- * @return bool true on success or false on failure.
- *
- *
- * The return value will be casted to boolean if non-boolean was returned
- *
- * @since 5.0.0
- */
- public function offsetExists($offset)
- {
- return $this->getIterator()->offsetExists($offset);
- }
-
- /**
- * Offset to retrieve.
- *
- * @link http://php.net/manual/en/arrayaccess.offsetget.php
- *
- * @param mixed $offset
- * The offset to retrieve.
- *
- *
- * @return mixed Can return all value types
- *
- * @since 5.0.0
- */
- public function offsetGet($offset)
- {
- return $this->getIterator()->offsetGet($offset);
- }
-
- /**
- * Offset to set.
- *
- * @link http://php.net/manual/en/arrayaccess.offsetset.php
- *
- * @param mixed $offset
- * The offset to assign the value to.
- *
- * @param mixed $value
- * The value to set.
- *
- *
- * @since 5.0.0
- */
- public function offsetSet($offset, $value)
- {
- return $this->getIterator()->offsetSet($offset, $value);
- }
-
- /**
- * Offset to unset.
- *
- * @link http://php.net/manual/en/arrayaccess.offsetunset.php
- *
- * @param mixed $offset
- * The offset to unset.
- *
- *
- * @since 5.0.0
- */
- public function offsetUnset($offset)
- {
- return $this->getIterator()->offsetUnset($offset);
- }
-
- /**
- * Specify data which should be serialized to JSON.
- *
- * @link http://php.net/manual/en/jsonserializable.jsonserialize.php
- *
- * @return mixed data which can be serialized by json_encode,
- * which is a value of any type other than a resource
- *
- * @since 5.4.0
- */
- public function jsonSerialize()
- {
- return array_map(function (AbstractTDBMObject $item) {
- return $item->jsonSerialize();
- }, $this->toArray());
- }
-}
diff --git a/src/Mouf/Database/TDBM/QueryFactory/AbstractQueryFactory.php b/src/Mouf/Database/TDBM/QueryFactory/AbstractQueryFactory.php
deleted file mode 100644
index 26cd34b..0000000
--- a/src/Mouf/Database/TDBM/QueryFactory/AbstractQueryFactory.php
+++ /dev/null
@@ -1,223 +0,0 @@
-tdbmService = $tdbmService;
- $this->schema = $schema;
- $this->orderByAnalyzer = $orderByAnalyzer;
- $this->orderBy = $orderBy;
- }
-
- /**
- * Returns the column list that must be fetched for the SQL request.
- *
- * Note: MySQL dictates that ORDER BYed columns should appear in the SELECT clause.
- *
- * @param string $mainTable
- * @param array $additionalTablesFetch
- * @param string|UncheckedOrderBy|null $orderBy
- *
- * @return array
- *
- * @throws \Doctrine\DBAL\Schema\SchemaException
- */
- protected function getColumnsList(string $mainTable, array $additionalTablesFetch = array(), $orderBy = null)
- {
- // From the table name and the additional tables we want to fetch, let's build a list of all tables
- // that must be part of the select columns.
-
- $connection = $this->tdbmService->getConnection();
-
- $tableGroups = [];
- $allFetchedTables = $this->tdbmService->_getRelatedTablesByInheritance($mainTable);
- $tableGroupName = $this->getTableGroupName($allFetchedTables);
- foreach ($allFetchedTables as $table) {
- $tableGroups[$table] = $tableGroupName;
- }
-
- $columnsList = [];
- $columnDescList = [];
- $sortColumn = 0;
- $reconstructedOrderBy = null;
-
- if (is_string($orderBy)) {
- $orderBy = trim($orderBy);
- if ($orderBy === '') {
- $orderBy = null;
- }
- }
-
- // Now, let's deal with "order by columns"
- if ($orderBy !== null) {
- if ($orderBy instanceof UncheckedOrderBy) {
- $securedOrderBy = false;
- $orderBy = $orderBy->getOrderBy();
- $reconstructedOrderBy = $orderBy;
- } else {
- $securedOrderBy = true;
- $reconstructedOrderBys = [];
- }
- $orderByColumns = $this->orderByAnalyzer->analyzeOrderBy($orderBy);
-
- // If we sort by a column, there is a high chance we will fetch the bean containing this column.
- // Hence, we should add the table to the $additionalTablesFetch
- foreach ($orderByColumns as $orderByColumn) {
- if ($orderByColumn['type'] === 'colref') {
- if ($orderByColumn['table'] !== null) {
- $additionalTablesFetch[] = $orderByColumn['table'];
- }
- if ($securedOrderBy) {
- $reconstructedOrderBys[] = ($orderByColumn['table'] !== null ? $connection->quoteIdentifier($orderByColumn['table']).'.' : '').$connection->quoteIdentifier($orderByColumn['column']).' '.$orderByColumn['direction'];
- }
- } elseif ($orderByColumn['type'] === 'expr') {
- $sortColumnName = 'sort_column_'.$sortColumn;
- $columnsList[] = $orderByColumn['expr'].' as '.$sortColumnName;
- $columnDescList[] = [
- 'tableGroup' => null,
- ];
- ++$sortColumn;
-
- if ($securedOrderBy) {
- throw new TDBMInvalidArgumentException('Invalid ORDER BY column: "'.$orderByColumn['expr'].'". If you want to use expression in your ORDER BY clause, you must wrap them in a UncheckedOrderBy object. For instance: new UncheckedOrderBy("col1 + col2 DESC")');
- }
- }
- }
-
- if ($reconstructedOrderBy === null) {
- $reconstructedOrderBy = implode(', ', $reconstructedOrderBys);
- }
- }
-
- foreach ($additionalTablesFetch as $additionalTable) {
- $relatedTables = $this->tdbmService->_getRelatedTablesByInheritance($additionalTable);
- $tableGroupName = $this->getTableGroupName($relatedTables);
- foreach ($relatedTables as $table) {
- $tableGroups[$table] = $tableGroupName;
- }
- $allFetchedTables = array_merge($allFetchedTables, $relatedTables);
- }
-
- // Let's remove any duplicate
- $allFetchedTables = array_flip(array_flip($allFetchedTables));
-
- // Now, let's build the column list
- foreach ($allFetchedTables as $table) {
- foreach ($this->schema->getTable($table)->getColumns() as $column) {
- $columnName = $column->getName();
- $columnDescList[] = [
- 'as' => $table.'____'.$columnName,
- 'table' => $table,
- 'column' => $columnName,
- 'type' => $column->getType(),
- 'tableGroup' => $tableGroups[$table],
- ];
- $columnsList[] = $connection->quoteIdentifier($table).'.'.$connection->quoteIdentifier($columnName).' as '.
- $connection->quoteIdentifier($table.'____'.$columnName);
- }
- }
-
- return [$columnDescList, $columnsList, $reconstructedOrderBy];
- }
-
- abstract protected function compute();
-
- /**
- * Returns an identifier for the group of tables passed in parameter.
- *
- * @param string[] $relatedTables
- *
- * @return string
- */
- protected function getTableGroupName(array $relatedTables)
- {
- sort($relatedTables);
-
- return implode('_``_', $relatedTables);
- }
-
- public function getMagicSql() : string
- {
- if ($this->magicSql === null) {
- $this->compute();
- }
-
- return $this->magicSql;
- }
-
- public function getMagicSqlCount() : string
- {
- if ($this->magicSqlCount === null) {
- $this->compute();
- }
-
- return $this->magicSqlCount;
- }
-
- public function getColumnDescriptors() : array
- {
- if ($this->columnDescList === null) {
- $this->compute();
- }
-
- return $this->columnDescList;
- }
-
- /**
- * Sets the ORDER BY directive executed in SQL.
- *
- * For instance:
- *
- * $queryFactory->sort('label ASC, status DESC');
- *
- * **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.
- * 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:
- *
- * $queryFactory->sort(new UncheckedOrderBy('RAND()'))
- *
- * @param string|UncheckedOrderBy|null $orderBy
- */
- public function sort($orderBy)
- {
- $this->orderBy = $orderBy;
- $this->magicSql = null;
- $this->magicSqlCount = null;
- $this->columnDescList = null;
- }
-}
diff --git a/src/Mouf/Database/TDBM/QueryFactory/FindObjectsFromSqlQueryFactory.php b/src/Mouf/Database/TDBM/QueryFactory/FindObjectsFromSqlQueryFactory.php
deleted file mode 100644
index d0f733d..0000000
--- a/src/Mouf/Database/TDBM/QueryFactory/FindObjectsFromSqlQueryFactory.php
+++ /dev/null
@@ -1,205 +0,0 @@
-mainTable = $mainTable;
- $this->from = $from;
- $this->filterString = $filterString;
- $this->schemaAnalyzer = $schemaAnalyzer;
- $this->cache = $cache;
- $this->cachePrefix = $cachePrefix;
- }
-
- protected function compute()
- {
- $connection = $this->tdbmService->getConnection();
-
- $columnsList = null;
-
- $allFetchedTables = $this->tdbmService->_getRelatedTablesByInheritance($this->mainTable);
-
- $columnDescList = [];
-
- $tableGroupName = $this->getTableGroupName($allFetchedTables);
-
- foreach ($this->schema->getTable($this->mainTable)->getColumns() as $column) {
- $columnName = $column->getName();
- $columnDescList[] = [
- 'as' => $columnName,
- 'table' => $this->mainTable,
- 'column' => $columnName,
- 'type' => $column->getType(),
- 'tableGroup' => $tableGroupName,
- ];
- }
-
- $sql = 'SELECT DISTINCT '.implode(', ', array_map(function ($columnDesc) {
- return $this->tdbmService->getConnection()->quoteIdentifier($this->mainTable).'.'.$this->tdbmService->getConnection()->quoteIdentifier($columnDesc['column']);
- }, $columnDescList)).' FROM '.$this->from;
-
- if (count($allFetchedTables) > 1) {
- list($columnDescList, $columnsList, $orderString) = $this->getColumnsList($this->mainTable, [], $this->orderBy);
- } elseif ($this->orderBy) {
- list(, , $orderString) = $this->getColumnsList($this->mainTable, [], $this->orderBy);
- }
-
- // Let's compute the COUNT.
- $pkColumnNames = $this->schema->getTable($this->mainTable)->getPrimaryKeyColumns();
- $pkColumnNames = array_map(function ($pkColumn) {
- return $this->tdbmService->getConnection()->quoteIdentifier($this->mainTable).'.'.$this->tdbmService->getConnection()->quoteIdentifier($pkColumn);
- }, $pkColumnNames);
-
- $countSql = 'SELECT COUNT(DISTINCT '.implode(', ', $pkColumnNames).') FROM '.$this->from;
-
- if (!empty($this->filterString)) {
- $sql .= ' WHERE '.$this->filterString;
- $countSql .= ' WHERE '.$this->filterString;
- }
-
- if (!empty($orderString)) {
- $sql .= ' ORDER BY '.$orderString;
- }
-
- if (stripos($countSql, 'GROUP BY') !== false) {
- throw new TDBMException('Unsupported use of GROUP BY in SQL request.');
- }
-
- if ($columnsList !== null) {
- $joinSql = '';
- $parentFks = $this->getParentRelationshipForeignKeys($this->mainTable);
- foreach ($parentFks as $fk) {
- $joinSql .= sprintf(' JOIN %s ON (%s.%s = %s.%s)',
- $connection->quoteIdentifier($fk->getForeignTableName()),
- $connection->quoteIdentifier($fk->getLocalTableName()),
- $connection->quoteIdentifier($fk->getLocalColumns()[0]),
- $connection->quoteIdentifier($fk->getForeignTableName()),
- $connection->quoteIdentifier($fk->getForeignColumns()[0])
- );
- }
-
- $childrenFks = $this->getChildrenRelationshipForeignKeys($this->mainTable);
- foreach ($childrenFks as $fk) {
- $joinSql .= sprintf(' LEFT JOIN %s ON (%s.%s = %s.%s)',
- $connection->quoteIdentifier($fk->getLocalTableName()),
- $connection->quoteIdentifier($fk->getForeignTableName()),
- $connection->quoteIdentifier($fk->getForeignColumns()[0]),
- $connection->quoteIdentifier($fk->getLocalTableName()),
- $connection->quoteIdentifier($fk->getLocalColumns()[0])
- );
- }
-
- $sql = 'SELECT '.implode(', ', $columnsList).' FROM ('.$sql.') AS '.$this->mainTable.' '.$joinSql;
- if (!empty($orderString)) {
- $sql .= ' ORDER BY '.$orderString;
- }
- }
-
- $this->magicSql = $sql;
- $this->magicSqlCount = $countSql;
- $this->columnDescList = $columnDescList;
- }
-
- /**
- * @param string $tableName
- *
- * @return ForeignKeyConstraint[]
- */
- private function getParentRelationshipForeignKeys($tableName)
- {
- return $this->fromCache($this->cachePrefix.'_parentrelationshipfks_'.$tableName, function () use ($tableName) {
- return $this->getParentRelationshipForeignKeysWithoutCache($tableName);
- });
- }
-
- /**
- * @param string $tableName
- *
- * @return ForeignKeyConstraint[]
- */
- private function getParentRelationshipForeignKeysWithoutCache($tableName)
- {
- $parentFks = [];
- $currentTable = $tableName;
- while ($currentFk = $this->schemaAnalyzer->getParentRelationship($currentTable)) {
- $currentTable = $currentFk->getForeignTableName();
- $parentFks[] = $currentFk;
- }
-
- return $parentFks;
- }
-
- /**
- * @param string $tableName
- *
- * @return ForeignKeyConstraint[]
- */
- private function getChildrenRelationshipForeignKeys(string $tableName) : array
- {
- return $this->fromCache($this->cachePrefix.'_childrenrelationshipfks_'.$tableName, function () use ($tableName) {
- return $this->getChildrenRelationshipForeignKeysWithoutCache($tableName);
- });
- }
-
- /**
- * @param string $tableName
- *
- * @return ForeignKeyConstraint[]
- */
- private function getChildrenRelationshipForeignKeysWithoutCache(string $tableName) : array
- {
- $children = $this->schemaAnalyzer->getChildrenRelationships($tableName);
-
- if (!empty($children)) {
- $fksTables = array_map(function (ForeignKeyConstraint $fk) {
- return $this->getChildrenRelationshipForeignKeys($fk->getLocalTableName());
- }, $children);
-
- $fks = array_merge($children, call_user_func_array('array_merge', $fksTables));
-
- return $fks;
- } else {
- return [];
- }
- }
-
- /**
- * Returns an item from cache or computes it using $closure and puts it in cache.
- *
- * @param string $key
- * @param callable $closure
- *
- * @return mixed
- */
- protected function fromCache(string $key, callable $closure)
- {
- $item = $this->cache->fetch($key);
- if ($item === false) {
- $item = $closure();
- $this->cache->save($key, $item);
- }
-
- return $item;
- }
-}
diff --git a/src/Mouf/Database/TDBM/QueryFactory/FindObjectsQueryFactory.php b/src/Mouf/Database/TDBM/QueryFactory/FindObjectsQueryFactory.php
deleted file mode 100644
index 3c76292..0000000
--- a/src/Mouf/Database/TDBM/QueryFactory/FindObjectsQueryFactory.php
+++ /dev/null
@@ -1,52 +0,0 @@
-mainTable = $mainTable;
- $this->additionalTablesFetch = $additionalTablesFetch;
- $this->filterString = $filterString;
- }
-
- protected function compute()
- {
- list($columnDescList, $columnsList, $orderString) = $this->getColumnsList($this->mainTable, $this->additionalTablesFetch, $this->orderBy);
-
- $sql = 'SELECT DISTINCT '.implode(', ', $columnsList).' FROM MAGICJOIN('.$this->mainTable.')';
-
- $pkColumnNames = $this->schema->getTable($this->mainTable)->getPrimaryKeyColumns();
- $pkColumnNames = array_map(function ($pkColumn) {
- return $this->tdbmService->getConnection()->quoteIdentifier($this->mainTable).'.'.$this->tdbmService->getConnection()->quoteIdentifier($pkColumn);
- }, $pkColumnNames);
-
- $countSql = 'SELECT COUNT(DISTINCT '.implode(', ', $pkColumnNames).') FROM MAGICJOIN('.$this->mainTable.')';
-
- if (!empty($this->filterString)) {
- $sql .= ' WHERE '.$this->filterString;
- $countSql .= ' WHERE '.$this->filterString;
- }
-
- if (!empty($orderString)) {
- $sql .= ' ORDER BY '.$orderString;
- }
-
- $this->magicSql = $sql;
- $this->magicSqlCount = $countSql;
- $this->columnDescList = $columnDescList;
- }
-}
diff --git a/src/Mouf/Database/TDBM/QueryFactory/QueryFactory.php b/src/Mouf/Database/TDBM/QueryFactory/QueryFactory.php
deleted file mode 100644
index 1db6d19..0000000
--- a/src/Mouf/Database/TDBM/QueryFactory/QueryFactory.php
+++ /dev/null
@@ -1,33 +0,0 @@
-sort('label ASC, status DESC');
- *
- * **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.
- * 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:
- *
- * $queryFactory->sort(new UncheckedOrderBy('RAND()'))
- *
- * @param string|UncheckedOrderBy|null $orderBy
- */
- public function sort($orderBy);
-
- public function getMagicSql() : string;
-
- public function getMagicSqlCount() : string;
-
- public function getColumnDescriptors() : array;
-}
diff --git a/src/Mouf/Database/TDBM/ResultIterator.php b/src/Mouf/Database/TDBM/ResultIterator.php
deleted file mode 100644
index cbf35a5..0000000
--- a/src/Mouf/Database/TDBM/ResultIterator.php
+++ /dev/null
@@ -1,316 +0,0 @@
-queryFactory = $queryFactory;
- $this->objectStorage = $objectStorage;
- $this->className = $className;
- $this->tdbmService = $tdbmService;
- $this->parameters = $parameters;
- $this->magicQuery = $magicQuery;
- $this->databasePlatform = $this->tdbmService->getConnection()->getDatabasePlatform();
- $this->mode = $mode;
- $this->logger = $logger;
- }
-
- protected function executeCountQuery()
- {
- $sql = $this->magicQuery->build($this->queryFactory->getMagicSqlCount(), $this->parameters);
- $this->logger->debug('Running count query: '.$sql);
- $this->totalCount = $this->tdbmService->getConnection()->fetchColumn($sql, $this->parameters);
- }
-
- /**
- * Counts found records (this is the number of records fetched, taking into account the LIMIT and OFFSET settings).
- *
- * @return int
- */
- public function count()
- {
- if ($this->totalCount === null) {
- $this->executeCountQuery();
- }
-
- return $this->totalCount;
- }
-
- /**
- * Casts the result set to a PHP array.
- *
- * @return array
- */
- public function toArray()
- {
- return iterator_to_array($this->getIterator());
- }
-
- /**
- * Returns a new iterator mapping any call using the $callable function.
- *
- * @param callable $callable
- *
- * @return MapIterator
- */
- public function map(callable $callable)
- {
- return new MapIterator($this->getIterator(), $callable);
- }
-
- /**
- * Retrieve an external iterator.
- *
- * @link http://php.net/manual/en/iteratoraggregate.getiterator.php
- *
- * @return InnerResultIterator An instance of an object implementing Iterator or
- * Traversable
- *
- * @since 5.0.0
- */
- public function getIterator()
- {
- if ($this->innerResultIterator === null) {
- if ($this->mode === TDBMService::MODE_CURSOR) {
- $this->innerResultIterator = new InnerResultIterator($this->queryFactory->getMagicSql(), $this->parameters, null, null, $this->queryFactory->getColumnDescriptors(), $this->objectStorage, $this->className, $this->tdbmService, $this->magicQuery, $this->logger);
- } else {
- $this->innerResultIterator = new InnerResultArray($this->queryFactory->getMagicSql(), $this->parameters, null, null, $this->queryFactory->getColumnDescriptors(), $this->objectStorage, $this->className, $this->tdbmService, $this->magicQuery, $this->logger);
- }
- }
-
- return $this->innerResultIterator;
- }
-
- /**
- * @param int $offset
- * @param int $limit
- *
- * @return PageIterator
- */
- public function take($offset, $limit)
- {
- 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);
- }
-
- /**
- * Whether a offset exists.
- *
- * @link http://php.net/manual/en/arrayaccess.offsetexists.php
- *
- * @param mixed $offset
- * An offset to check for.
- *
- *
- * @return bool true on success or false on failure.
- *
- *
- * The return value will be casted to boolean if non-boolean was returned
- *
- * @since 5.0.0
- */
- public function offsetExists($offset)
- {
- return $this->getIterator()->offsetExists($offset);
- }
-
- /**
- * Offset to retrieve.
- *
- * @link http://php.net/manual/en/arrayaccess.offsetget.php
- *
- * @param mixed $offset
- * The offset to retrieve.
- *
- *
- * @return mixed Can return all value types
- *
- * @since 5.0.0
- */
- public function offsetGet($offset)
- {
- return $this->getIterator()->offsetGet($offset);
- }
-
- /**
- * Offset to set.
- *
- * @link http://php.net/manual/en/arrayaccess.offsetset.php
- *
- * @param mixed $offset
- * The offset to assign the value to.
- *
- * @param mixed $value
- * The value to set.
- *
- *
- * @since 5.0.0
- */
- public function offsetSet($offset, $value)
- {
- return $this->getIterator()->offsetSet($offset, $value);
- }
-
- /**
- * Offset to unset.
- *
- * @link http://php.net/manual/en/arrayaccess.offsetunset.php
- *
- * @param mixed $offset
- * The offset to unset.
- *
- *
- * @since 5.0.0
- */
- public function offsetUnset($offset)
- {
- return $this->getIterator()->offsetUnset($offset);
- }
-
- /**
- * Specify data which should be serialized to JSON.
- *
- * @link http://php.net/manual/en/jsonserializable.jsonserialize.php
- *
- * @param bool $stopRecursion Parameter used internally by TDBM to
- * stop embedded objects from embedding
- * other objects
- *
- * @return mixed data which can be serialized by json_encode,
- * which is a value of any type other than a resource
- *
- * @since 5.4.0
- */
- public function jsonSerialize($stopRecursion = false)
- {
- return array_map(function (AbstractTDBMObject $item) use ($stopRecursion) {
- return $item->jsonSerialize($stopRecursion);
- }, $this->toArray());
- }
-
- /**
- * Returns only one value (the first) of the result set.
- * Returns null if no value exists.
- *
- * @return mixed|null
- */
- public function first()
- {
- $page = $this->take(0, 1);
- foreach ($page as $bean) {
- return $bean;
- }
-
- return;
- }
-
- /**
- * Sets the ORDER BY directive executed in SQL and returns a NEW ResultIterator.
- *
- * For instance:
- *
- * $resultSet = $resultSet->withOrder('label ASC, status DESC');
- *
- * **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.
- * 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:
- *
- * $resultSet->withOrder(new UncheckedOrderBy('RAND()'))
- *
- * @param string|UncheckedOrderBy|null $orderBy
- *
- * @return ResultIterator
- */
- public function withOrder($orderBy) : ResultIterator
- {
- $clone = clone $this;
- $clone->queryFactory = clone $this->queryFactory;
- $clone->queryFactory->sort($orderBy);
- $clone->innerResultIterator = null;
-
- return $clone;
- }
-
- /**
- * Sets new parameters for the SQL query and returns a NEW ResultIterator.
- *
- * For instance:
- *
- * $resultSet = $resultSet->withParameters('label ASC, status DESC');
- *
- * @param string|UncheckedOrderBy|null $orderBy
- *
- * @return ResultIterator
- */
- public function withParameters(array $parameters) : ResultIterator
- {
- $clone = clone $this;
- $clone->parameters = $parameters;
- $clone->innerResultIterator = null;
- $clone->totalCount = null;
-
- return $clone;
- }
-}
diff --git a/src/Mouf/Database/TDBM/StandardObjectStorage.php b/src/Mouf/Database/TDBM/StandardObjectStorage.php
deleted file mode 100644
index da8c00c..0000000
--- a/src/Mouf/Database/TDBM/StandardObjectStorage.php
+++ /dev/null
@@ -1,107 +0,0 @@
->
- */
- private $objects = array();
-
- /**
- * Sets an object in the storage.
- *
- * @param string $tableName
- * @param string $id
- * @param TDBMObject $dbRow
- */
- public function set($tableName, $id, DbRow $dbRow)
- {
- $this->objects[$tableName][$id] = $dbRow;
- }
-
- /**
- * Checks if an object is in the storage.
- *
- * @param string $tableName
- * @param string $id
- *
- * @return bool
- */
- public function has($tableName, $id)
- {
- return isset($this->objects[$tableName][$id]);
- }
-
- /**
- * Returns an object from the storage (or null if no object is set).
- *
- * @param string $tableName
- * @param string $id
- *
- * @return DbRow
- */
- public function get($tableName, $id)
- {
- if (isset($this->objects[$tableName][$id])) {
- return $this->objects[$tableName][$id];
- } else {
- return;
- }
- }
-
- /**
- * Removes an object from the storage.
- *
- * @param string $tableName
- * @param string $id
- */
- public function remove($tableName, $id)
- {
- unset($this->objects[$tableName][$id]);
- }
-
- /**
- * Applies the callback to all objects.
- *
- * @param callable $callback
- */
- public function apply(callable $callback)
- {
- foreach ($this->objects as $tableName => $table) {
- foreach ($table as $id => $obj) {
- $callback($obj, $tableName, $id);
- }
- }
- }
-}
diff --git a/src/Mouf/Database/TDBM/TDBMCyclicReferenceException.php b/src/Mouf/Database/TDBM/TDBMCyclicReferenceException.php
deleted file mode 100644
index 19c2a72..0000000
--- a/src/Mouf/Database/TDBM/TDBMCyclicReferenceException.php
+++ /dev/null
@@ -1,16 +0,0 @@
-getMessage().sprintf(" This object is referenced by an object of type '%s' (table '%s') via foreign key '%s'", get_class($object), $tableName, $fkName), $e->getCode(), $e);
- }
-}
diff --git a/src/Mouf/Database/TDBM/TDBMException.php b/src/Mouf/Database/TDBM/TDBMException.php
deleted file mode 100644
index 6106dcb..0000000
--- a/src/Mouf/Database/TDBM/TDBMException.php
+++ /dev/null
@@ -1,11 +0,0 @@
- $row) {
- $primaryKeyColumns = $tdbmService->getPrimaryKeyColumns($table);
- foreach ($primaryKeyColumns as $columnName) {
- if ($row[$columnName] !== null) {
- $pks[] = $table.'.'.$columnName.' => '.var_export($row[$columnName], true);
- }
- }
- }
-
- throw new self($e->getMessage().' (row in error: '.implode(', ', $pks).')', 0, $e);
- }
-}
diff --git a/src/Mouf/Database/TDBM/TDBMInvalidArgumentException.php b/src/Mouf/Database/TDBM/TDBMInvalidArgumentException.php
deleted file mode 100644
index 499e037..0000000
--- a/src/Mouf/Database/TDBM/TDBMInvalidArgumentException.php
+++ /dev/null
@@ -1,7 +0,0 @@
-$tdbmObject->myrow
- * or
- * $tdbmObject['myrow']
- * are both valid.
- *
- * @author David Negrier
- */
-class TDBMObject extends AbstractTDBMObject
-{
- public function getProperty($var, $tableName = null)
- {
- return $this->get($var, $tableName);
- }
-
- public function setProperty($var, $value, $tableName = null)
- {
- $this->set($var, $value, $tableName);
- }
-
- /**
- * Specify data which should be serialized to JSON.
- *
- * @link http://php.net/manual/en/jsonserializable.jsonserialize.php
- *
- * @return mixed data which can be serialized by json_encode,
- * which is a value of any type other than a resource
- *
- * @since 5.4.0
- */
- public function jsonSerialize()
- {
- throw new TDBMException('Json serialization is only implemented for generated beans.');
- }
-
- /**
- * Returns an array of used tables by this bean (from parent to child relationship).
- *
- * @return string[]
- */
- protected function getUsedTables() : array
- {
- $tableNames = array_keys($this->dbRows);
- $tableNames = $this->tdbmService->_getLinkBetweenInheritedTables($tableNames);
- $tableNames = array_reverse($tableNames);
-
- return $tableNames;
- }
-}
diff --git a/src/Mouf/Database/TDBM/TDBMObjectStateEnum.php b/src/Mouf/Database/TDBM/TDBMObjectStateEnum.php
deleted file mode 100644
index 0c3365b..0000000
--- a/src/Mouf/Database/TDBM/TDBMObjectStateEnum.php
+++ /dev/null
@@ -1,37 +0,0 @@
-connection = $connection;
- $this->cache = $cache;
- $this->schemaAnalyzer = $schemaAnalyzer;
- }
-
- /**
- * Returns a unique ID for the current connection. Useful for namespacing cache entries in the current connection.
- *
- * @return string
- */
- public function getCachePrefix()
- {
- if ($this->cachePrefix === null) {
- $this->cachePrefix = hash('md4', $this->connection->getHost().'-'.$this->connection->getPort().'-'.$this->connection->getDatabase().'-'.$this->connection->getDriver()->getName());
- }
-
- return $this->cachePrefix;
- }
-
- /**
- * Returns the (cached) schema.
- *
- * @return Schema
- */
- public function getSchema()
- {
- if ($this->schema === null) {
- $cacheKey = $this->getCachePrefix().'_schema';
- if ($this->cache->contains($cacheKey)) {
- $this->schema = $this->cache->fetch($cacheKey);
- } else {
- $this->schema = $this->connection->getSchemaManager()->createSchema();
- $this->cache->save($cacheKey, $this->schema);
- }
- }
-
- return $this->schema;
- }
-
- /**
- * Returns the list of pivot tables linked to table $tableName.
- *
- * @param string $tableName
- *
- * @return array|string[]
- */
- public function getPivotTableLinkedToTable($tableName)
- {
- $cacheKey = $this->getCachePrefix().'_pivottables_link_'.$tableName;
- if ($this->cache->contains($cacheKey)) {
- return $this->cache->fetch($cacheKey);
- }
-
- $pivotTables = [];
-
- $junctionTables = $this->schemaAnalyzer->detectJunctionTables(true);
- foreach ($junctionTables as $table) {
- $fks = $table->getForeignKeys();
- foreach ($fks as $fk) {
- if ($fk->getForeignTableName() == $tableName) {
- $pivotTables[] = $table->getName();
- break;
- }
- }
- }
-
- $this->cache->save($cacheKey, $pivotTables);
-
- return $pivotTables;
- }
-
- /**
- * Returns the list of foreign keys pointing to the table represented by this bean, excluding foreign keys
- * from junction tables and from inheritance.
- *
- * @return ForeignKeyConstraint[]
- */
- public function getIncomingForeignKeys($tableName)
- {
- $junctionTables = $this->schemaAnalyzer->detectJunctionTables(true);
- $junctionTableNames = array_map(function (Table $table) {
- return $table->getName();
- }, $junctionTables);
- $childrenRelationships = $this->schemaAnalyzer->getChildrenRelationships($tableName);
-
- $fks = [];
- foreach ($this->getSchema()->getTables() as $table) {
- foreach ($table->getForeignKeys() as $fk) {
- if ($fk->getForeignTableName() === $tableName) {
- if (in_array($fk->getLocalTableName(), $junctionTableNames)) {
- continue;
- }
- foreach ($childrenRelationships as $childFk) {
- if ($fk->getLocalTableName() === $childFk->getLocalTableName() && $fk->getLocalColumns() === $childFk->getLocalColumns()) {
- continue 2;
- }
- }
- $fks[] = $fk;
- }
- }
- }
-
- return $fks;
- }
-}
diff --git a/src/Mouf/Database/TDBM/TDBMService.php b/src/Mouf/Database/TDBM/TDBMService.php
deleted file mode 100644
index 30c0c73..0000000
--- a/src/Mouf/Database/TDBM/TDBMService.php
+++ /dev/null
@@ -1,1504 +0,0 @@
-objectStorage = new WeakrefObjectStorage();
- } else {
- $this->objectStorage = new StandardObjectStorage();
- }
- $this->connection = $configuration->getConnection();
- $this->cache = $configuration->getCache();
- $this->schemaAnalyzer = $configuration->getSchemaAnalyzer();
-
- $this->magicQuery = new MagicQuery($this->connection, $this->cache, $this->schemaAnalyzer);
-
- $this->tdbmSchemaAnalyzer = new TDBMSchemaAnalyzer($this->connection, $this->cache, $this->schemaAnalyzer);
- $this->cachePrefix = $this->tdbmSchemaAnalyzer->getCachePrefix();
-
- $this->toSaveObjects = new \SplObjectStorage();
- $logger = $configuration->getLogger();
- if ($logger === null) {
- $this->logger = new NullLogger();
- $this->rootLogger = new NullLogger();
- } else {
- $this->rootLogger = $logger;
- $this->setLogLevel(LogLevel::WARNING);
- }
- $this->orderByAnalyzer = new OrderByAnalyzer($this->cache, $this->cachePrefix);
- $this->beanNamespace = $configuration->getBeanNamespace();
- $this->namingStrategy = $configuration->getNamingStrategy();
- $this->configuration = $configuration;
- }
-
- /**
- * Returns the object used to connect to the database.
- *
- * @return Connection
- */
- public function getConnection(): Connection
- {
- return $this->connection;
- }
-
- /**
- * Sets the default fetch mode of the result sets returned by `findObjects`.
- * Can be one of: TDBMObjectArray::MODE_CURSOR or TDBMObjectArray::MODE_ARRAY.
- *
- * 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).
- * 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
- * several times. In cursor mode, you cannot access the result set by key. Use this mode for large datasets processed by batch.
- *
- * @param int $mode
- *
- * @return $this
- *
- * @throws TDBMException
- */
- public function setFetchMode($mode)
- {
- if ($mode !== self::MODE_CURSOR && $mode !== self::MODE_ARRAY) {
- throw new TDBMException("Unknown fetch mode: '".$this->mode."'");
- }
- $this->mode = $mode;
-
- return $this;
- }
-
- /**
- * Removes the given object from database.
- * This cannot be called on an object that is not attached to this TDBMService
- * (will throw a TDBMInvalidOperationException).
- *
- * @param AbstractTDBMObject $object the object to delete
- *
- * @throws TDBMException
- * @throws TDBMInvalidOperationException
- */
- public function delete(AbstractTDBMObject $object)
- {
- switch ($object->_getStatus()) {
- case TDBMObjectStateEnum::STATE_DELETED:
- // Nothing to do, object already deleted.
- return;
- case TDBMObjectStateEnum::STATE_DETACHED:
- throw new TDBMInvalidOperationException('Cannot delete a detached object');
- case TDBMObjectStateEnum::STATE_NEW:
- $this->deleteManyToManyRelationships($object);
- foreach ($object->_getDbRows() as $dbRow) {
- $this->removeFromToSaveObjectList($dbRow);
- }
- break;
- case TDBMObjectStateEnum::STATE_DIRTY:
- foreach ($object->_getDbRows() as $dbRow) {
- $this->removeFromToSaveObjectList($dbRow);
- }
- // And continue deleting...
- case TDBMObjectStateEnum::STATE_NOT_LOADED:
- case TDBMObjectStateEnum::STATE_LOADED:
- $this->deleteManyToManyRelationships($object);
- // Let's delete db rows, in reverse order.
- foreach (array_reverse($object->_getDbRows()) as $dbRow) {
- $tableName = $dbRow->_getDbTableName();
- $primaryKeys = $dbRow->_getPrimaryKeys();
- $this->connection->delete($tableName, $primaryKeys);
- $this->objectStorage->remove($dbRow->_getDbTableName(), $this->getObjectHash($primaryKeys));
- }
- break;
- // @codeCoverageIgnoreStart
- default:
- throw new TDBMInvalidOperationException('Unexpected status for bean');
- // @codeCoverageIgnoreEnd
- }
-
- $object->_setStatus(TDBMObjectStateEnum::STATE_DELETED);
- }
-
- /**
- * Removes all many to many relationships for this object.
- *
- * @param AbstractTDBMObject $object
- */
- private function deleteManyToManyRelationships(AbstractTDBMObject $object)
- {
- foreach ($object->_getDbRows() as $tableName => $dbRow) {
- $pivotTables = $this->tdbmSchemaAnalyzer->getPivotTableLinkedToTable($tableName);
- foreach ($pivotTables as $pivotTable) {
- $remoteBeans = $object->_getRelationships($pivotTable);
- foreach ($remoteBeans as $remoteBean) {
- $object->_removeRelationship($pivotTable, $remoteBean);
- }
- }
- }
- $this->persistManyToManyRelationships($object);
- }
-
- /**
- * This function removes the given object from the database. It will also remove all objects relied to the one given
- * by parameter before all.
- *
- * Notice: if the object has a multiple primary key, the function will not work.
- *
- * @param AbstractTDBMObject $objToDelete
- */
- public function deleteCascade(AbstractTDBMObject $objToDelete)
- {
- $this->deleteAllConstraintWithThisObject($objToDelete);
- $this->delete($objToDelete);
- }
-
- /**
- * This function is used only in TDBMService (private function)
- * It will call deleteCascade function foreach object relied with a foreign key to the object given by parameter.
- *
- * @param AbstractTDBMObject $obj
- */
- private function deleteAllConstraintWithThisObject(AbstractTDBMObject $obj)
- {
- $dbRows = $obj->_getDbRows();
- foreach ($dbRows as $dbRow) {
- $tableName = $dbRow->_getDbTableName();
- $pks = array_values($dbRow->_getPrimaryKeys());
- if (!empty($pks)) {
- $incomingFks = $this->tdbmSchemaAnalyzer->getIncomingForeignKeys($tableName);
-
- foreach ($incomingFks as $incomingFk) {
- $filter = array_combine($incomingFk->getLocalColumns(), $pks);
-
- $results = $this->findObjects($incomingFk->getLocalTableName(), $filter);
-
- foreach ($results as $bean) {
- $this->deleteCascade($bean);
- }
- }
- }
- }
- }
-
- /**
- * This function performs a save() of all the objects that have been modified.
- */
- public function completeSave()
- {
- foreach ($this->toSaveObjects as $dbRow) {
- $this->save($dbRow->getTDBMObject());
- }
- }
-
- /**
- * Takes in input a filter_bag (which can be about anything from a string to an array of TDBMObjects... see above from documentation),
- * and gives back a proper Filter object.
- *
- * @param mixed $filter_bag
- * @param int $counter
- *
- * @return array First item: filter string, second item: parameters
- *
- * @throws TDBMException
- */
- public function buildFilterFromFilterBag($filter_bag, $counter = 1)
- {
- if ($filter_bag === null) {
- return ['', []];
- } elseif (is_string($filter_bag)) {
- return [$filter_bag, []];
- } elseif (is_array($filter_bag)) {
- $sqlParts = [];
- $parameters = [];
- foreach ($filter_bag as $column => $value) {
- if (is_int($column)) {
- list($subSqlPart, $subParameters) = $this->buildFilterFromFilterBag($value, $counter);
- $sqlParts[] = $subSqlPart;
- $parameters += $subParameters;
- } else {
- $paramName = 'tdbmparam'.$counter;
- if (is_array($value)) {
- $sqlParts[] = $this->connection->quoteIdentifier($column).' IN :'.$paramName;
- } else {
- $sqlParts[] = $this->connection->quoteIdentifier($column).' = :'.$paramName;
- }
- $parameters[$paramName] = $value;
- ++$counter;
- }
- }
-
- return [implode(' AND ', $sqlParts), $parameters];
- } elseif ($filter_bag instanceof AbstractTDBMObject) {
- $sqlParts = [];
- $parameters = [];
- $dbRows = $filter_bag->_getDbRows();
- $dbRow = reset($dbRows);
- $primaryKeys = $dbRow->_getPrimaryKeys();
-
- foreach ($primaryKeys as $column => $value) {
- $paramName = 'tdbmparam'.$counter;
- $sqlParts[] = $this->connection->quoteIdentifier($dbRow->_getDbTableName()).'.'.$this->connection->quoteIdentifier($column).' = :'.$paramName;
- $parameters[$paramName] = $value;
- ++$counter;
- }
-
- return [implode(' AND ', $sqlParts), $parameters];
- } elseif ($filter_bag instanceof \Iterator) {
- return $this->buildFilterFromFilterBag(iterator_to_array($filter_bag), $counter);
- } else {
- 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.');
- }
- }
-
- /**
- * @param string $table
- *
- * @return string[]
- */
- public function getPrimaryKeyColumns($table)
- {
- if (!isset($this->primaryKeysColumns[$table])) {
- $this->primaryKeysColumns[$table] = $this->tdbmSchemaAnalyzer->getSchema()->getTable($table)->getPrimaryKeyColumns();
-
- // TODO TDBM4: See if we need to improve error reporting if table name does not exist.
-
- /*$arr = array();
- foreach ($this->connection->getPrimaryKey($table) as $col) {
- $arr[] = $col->name;
- }
- // The primaryKeysColumns contains only the column's name, not the DB_Column object.
- $this->primaryKeysColumns[$table] = $arr;
- if (empty($this->primaryKeysColumns[$table]))
- {
- // Unable to find primary key.... this is an error
- // Let's try to be precise in error reporting. Let's try to find the table.
- $tables = $this->connection->checkTableExist($table);
- if ($tables === true)
- throw new TDBMException("Could not find table primary key for table '$table'. Please define a primary key for this table.");
- elseif ($tables !== null) {
- if (count($tables)==1)
- $str = "Could not find table '$table'. Maybe you meant this table: '".$tables[0]."'";
- else
- $str = "Could not find table '$table'. Maybe you meant one of those tables: '".implode("', '",$tables)."'";
- throw new TDBMException($str);
- }
- }*/
- }
-
- return $this->primaryKeysColumns[$table];
- }
-
- /**
- * This is an internal function, you should not use it in your application.
- * This is used internally by TDBM to add an object to the object cache.
- *
- * @param DbRow $dbRow
- */
- public function _addToCache(DbRow $dbRow)
- {
- $primaryKey = $this->getPrimaryKeysForObjectFromDbRow($dbRow);
- $hash = $this->getObjectHash($primaryKey);
- $this->objectStorage->set($dbRow->_getDbTableName(), $hash, $dbRow);
- }
-
- /**
- * This is an internal function, you should not use it in your application.
- * This is used internally by TDBM to remove the object from the list of objects that have been
- * created/updated but not saved yet.
- *
- * @param DbRow $myObject
- */
- private function removeFromToSaveObjectList(DbRow $myObject)
- {
- unset($this->toSaveObjects[$myObject]);
- }
-
- /**
- * This is an internal function, you should not use it in your application.
- * This is used internally by TDBM to add an object to the list of objects that have been
- * created/updated but not saved yet.
- *
- * @param DbRow $myObject
- */
- public function _addToToSaveObjectList(DbRow $myObject)
- {
- $this->toSaveObjects[$myObject] = true;
- }
-
- /**
- * Generates all the daos and beans.
- *
- * @return \string[] the list of tables (key) and bean name (value)
- */
- public function generateAllDaosAndBeans()
- {
- // Purge cache before generating anything.
- $this->cache->deleteAll();
-
- $tdbmDaoGenerator = new TDBMDaoGenerator($this->configuration, $this->tdbmSchemaAnalyzer);
- $tdbmDaoGenerator->generateAllDaosAndBeans();
- }
-
- /**
- * Returns the fully qualified class name of the bean associated with table $tableName.
- *
- *
- * @param string $tableName
- *
- * @return string
- */
- public function getBeanClassName(string $tableName) : string
- {
- if (isset($this->tableToBeanMap[$tableName])) {
- return $this->tableToBeanMap[$tableName];
- } else {
- $className = $this->beanNamespace.'\\'.$this->namingStrategy->getBeanClassName($tableName);
-
- if (!class_exists($className)) {
- throw new TDBMInvalidArgumentException(sprintf('Could not find class "%s". Does table "%s" exist? If yes, consider regenerating the DAOs and beans.', $className, $tableName));
- }
-
- $this->tableToBeanMap[$tableName] = $className;
- return $className;
- }
- }
-
- /**
- * Saves $object by INSERTing or UPDAT(E)ing it in the database.
- *
- * @param AbstractTDBMObject $object
- *
- * @throws TDBMException
- */
- public function save(AbstractTDBMObject $object)
- {
- $status = $object->_getStatus();
-
- if ($status === null) {
- 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)));
- }
-
- // Let's attach this object if it is in detached state.
- if ($status === TDBMObjectStateEnum::STATE_DETACHED) {
- $object->_attach($this);
- $status = $object->_getStatus();
- }
-
- if ($status === TDBMObjectStateEnum::STATE_NEW) {
- $dbRows = $object->_getDbRows();
-
- $unindexedPrimaryKeys = array();
-
- foreach ($dbRows as $dbRow) {
- if ($dbRow->_getStatus() == TDBMObjectStateEnum::STATE_SAVING) {
- throw TDBMCyclicReferenceException::createCyclicReference($dbRow->_getDbTableName(), $object);
- }
- $dbRow->_setStatus(TDBMObjectStateEnum::STATE_SAVING);
- $tableName = $dbRow->_getDbTableName();
-
- $schema = $this->tdbmSchemaAnalyzer->getSchema();
- $tableDescriptor = $schema->getTable($tableName);
-
- $primaryKeyColumns = $this->getPrimaryKeyColumns($tableName);
-
- $references = $dbRow->_getReferences();
-
- // Let's save all references in NEW or DETACHED state (we need their primary key)
- foreach ($references as $fkName => $reference) {
- if ($reference !== null) {
- $refStatus = $reference->_getStatus();
- if ($refStatus === TDBMObjectStateEnum::STATE_NEW || $refStatus === TDBMObjectStateEnum::STATE_DETACHED) {
- try {
- $this->save($reference);
- } catch (TDBMCyclicReferenceException $e) {
- throw TDBMCyclicReferenceException::extendCyclicReference($e, $dbRow->_getDbTableName(), $object, $fkName);
- }
- }
- }
- }
-
- if (empty($unindexedPrimaryKeys)) {
- $primaryKeys = $this->getPrimaryKeysForObjectFromDbRow($dbRow);
- } else {
- // First insert, the children must have the same primary key as the parent.
- $primaryKeys = $this->_getPrimaryKeysFromIndexedPrimaryKeys($tableName, $unindexedPrimaryKeys);
- $dbRow->_setPrimaryKeys($primaryKeys);
- }
-
- $dbRowData = $dbRow->_getDbRow();
-
- // Let's see if the columns for primary key have been set before inserting.
- // We assume that if one of the value of the PK has been set, the PK is set.
- $isPkSet = !empty($primaryKeys);
-
- /*if (!$isPkSet) {
- // if there is no autoincrement and no pk set, let's go in error.
- $isAutoIncrement = true;
-
- foreach ($primaryKeyColumns as $pkColumnName) {
- $pkColumn = $tableDescriptor->getColumn($pkColumnName);
- if (!$pkColumn->getAutoincrement()) {
- $isAutoIncrement = false;
- }
- }
-
- if (!$isAutoIncrement) {
- $msg = "Error! You did not set the primary key(s) for the new object of type '$tableName'. The primary key is not set to 'autoincrement' so you must either set the primary key in the object or modify the DB model to create an primary key with auto-increment.";
- throw new TDBMException($msg);
- }
-
- }*/
-
- $types = [];
- $escapedDbRowData = [];
-
- foreach ($dbRowData as $columnName => $value) {
- $columnDescriptor = $tableDescriptor->getColumn($columnName);
- $types[] = $columnDescriptor->getType();
- $escapedDbRowData[$this->connection->quoteIdentifier($columnName)] = $value;
- }
-
- $this->connection->insert($tableName, $escapedDbRowData, $types);
-
- if (!$isPkSet && count($primaryKeyColumns) == 1) {
- $id = $this->connection->lastInsertId();
- $pkColumn = $primaryKeyColumns[0];
- // lastInsertId returns a string but the column type is usually a int. Let's convert it back to the correct type.
- $id = $tableDescriptor->getColumn($pkColumn)->getType()->convertToPHPValue($id, $this->getConnection()->getDatabasePlatform());
- $primaryKeys[$pkColumn] = $id;
- }
-
- // TODO: change this to some private magic accessor in future
- $dbRow->_setPrimaryKeys($primaryKeys);
- $unindexedPrimaryKeys = array_values($primaryKeys);
-
- /*
- * When attached, on "save", we check if the column updated is part of a primary key
- * If this is part of a primary key, we call the _update_id method that updates the id in the list of known objects.
- * This method should first verify that the id is not already used (and is not auto-incremented)
- *
- * In the object, the key is stored in an array of (column => value), that can be directly used to update the record.
- *
- *
- */
-
- /*try {
- $this->db_connection->exec($sql);
- } catch (TDBMException $e) {
- $this->db_onerror = true;
-
- // Strange..... if we do not have the line below, bad inserts are not catched.
- // It seems that destructors are called before the registered shutdown function (PHP >=5.0.5)
- //if ($this->tdbmService->isProgramExiting())
- // trigger_error("program exiting");
- trigger_error($e->getMessage(), E_USER_ERROR);
-
- if (!$this->tdbmService->isProgramExiting())
- throw $e;
- else
- {
- trigger_error($e->getMessage(), E_USER_ERROR);
- }
- }*/
-
- // Let's remove this object from the $new_objects static table.
- $this->removeFromToSaveObjectList($dbRow);
-
- // TODO: change this behaviour to something more sensible performance-wise
- // Maybe a setting to trigger this globally?
- //$this->status = TDBMObjectStateEnum::STATE_NOT_LOADED;
- //$this->db_modified_state = false;
- //$dbRow = array();
-
- // Let's add this object to the list of objects in cache.
- $this->_addToCache($dbRow);
- }
-
- $object->_setStatus(TDBMObjectStateEnum::STATE_LOADED);
- } elseif ($status === TDBMObjectStateEnum::STATE_DIRTY) {
- $dbRows = $object->_getDbRows();
-
- foreach ($dbRows as $dbRow) {
- $references = $dbRow->_getReferences();
-
- // Let's save all references in NEW state (we need their primary key)
- foreach ($references as $fkName => $reference) {
- if ($reference !== null && $reference->_getStatus() === TDBMObjectStateEnum::STATE_NEW) {
- $this->save($reference);
- }
- }
-
- // Let's first get the primary keys
- $tableName = $dbRow->_getDbTableName();
- $dbRowData = $dbRow->_getDbRow();
-
- $schema = $this->tdbmSchemaAnalyzer->getSchema();
- $tableDescriptor = $schema->getTable($tableName);
-
- $primaryKeys = $dbRow->_getPrimaryKeys();
-
- $types = [];
- $escapedDbRowData = [];
- $escapedPrimaryKeys = [];
-
- foreach ($dbRowData as $columnName => $value) {
- $columnDescriptor = $tableDescriptor->getColumn($columnName);
- $types[] = $columnDescriptor->getType();
- $escapedDbRowData[$this->connection->quoteIdentifier($columnName)] = $value;
- }
- foreach ($primaryKeys as $columnName => $value) {
- $columnDescriptor = $tableDescriptor->getColumn($columnName);
- $types[] = $columnDescriptor->getType();
- $escapedPrimaryKeys[$this->connection->quoteIdentifier($columnName)] = $value;
- }
-
- $this->connection->update($tableName, $escapedDbRowData, $escapedPrimaryKeys, $types);
-
- // Let's check if the primary key has been updated...
- $needsUpdatePk = false;
- foreach ($primaryKeys as $column => $value) {
- if (!isset($dbRowData[$column]) || $dbRowData[$column] != $value) {
- $needsUpdatePk = true;
- break;
- }
- }
- if ($needsUpdatePk) {
- $this->objectStorage->remove($tableName, $this->getObjectHash($primaryKeys));
- $newPrimaryKeys = $this->getPrimaryKeysForObjectFromDbRow($dbRow);
- $dbRow->_setPrimaryKeys($newPrimaryKeys);
- $this->objectStorage->set($tableName, $this->getObjectHash($primaryKeys), $dbRow);
- }
-
- // Let's remove this object from the list of objects to save.
- $this->removeFromToSaveObjectList($dbRow);
- }
-
- $object->_setStatus(TDBMObjectStateEnum::STATE_LOADED);
- } elseif ($status === TDBMObjectStateEnum::STATE_DELETED) {
- throw new TDBMInvalidOperationException('This object has been deleted. It cannot be saved.');
- }
-
- // Finally, let's save all the many to many relationships to this bean.
- $this->persistManyToManyRelationships($object);
- }
-
- private function persistManyToManyRelationships(AbstractTDBMObject $object)
- {
- foreach ($object->_getCachedRelationships() as $pivotTableName => $storage) {
- $tableDescriptor = $this->tdbmSchemaAnalyzer->getSchema()->getTable($pivotTableName);
- list($localFk, $remoteFk) = $this->getPivotTableForeignKeys($pivotTableName, $object);
-
- $toRemoveFromStorage = [];
-
- foreach ($storage as $remoteBean) {
- /* @var $remoteBean AbstractTDBMObject */
- $statusArr = $storage[$remoteBean];
- $status = $statusArr['status'];
- $reverse = $statusArr['reverse'];
- if ($reverse) {
- continue;
- }
-
- if ($status === 'new') {
- $remoteBeanStatus = $remoteBean->_getStatus();
- if ($remoteBeanStatus === TDBMObjectStateEnum::STATE_NEW || $remoteBeanStatus === TDBMObjectStateEnum::STATE_DETACHED) {
- // Let's save remote bean if needed.
- $this->save($remoteBean);
- }
-
- $filters = $this->getPivotFilters($object, $remoteBean, $localFk, $remoteFk);
-
- $types = [];
- $escapedFilters = [];
-
- foreach ($filters as $columnName => $value) {
- $columnDescriptor = $tableDescriptor->getColumn($columnName);
- $types[] = $columnDescriptor->getType();
- $escapedFilters[$this->connection->quoteIdentifier($columnName)] = $value;
- }
-
- $this->connection->insert($pivotTableName, $escapedFilters, $types);
-
- // Finally, let's mark relationships as saved.
- $statusArr['status'] = 'loaded';
- $storage[$remoteBean] = $statusArr;
- $remoteStorage = $remoteBean->_getCachedRelationships()[$pivotTableName];
- $remoteStatusArr = $remoteStorage[$object];
- $remoteStatusArr['status'] = 'loaded';
- $remoteStorage[$object] = $remoteStatusArr;
- } elseif ($status === 'delete') {
- $filters = $this->getPivotFilters($object, $remoteBean, $localFk, $remoteFk);
-
- $types = [];
-
- foreach ($filters as $columnName => $value) {
- $columnDescriptor = $tableDescriptor->getColumn($columnName);
- $types[] = $columnDescriptor->getType();
- }
-
- $this->connection->delete($pivotTableName, $filters, $types);
-
- // Finally, let's remove relationships completely from bean.
- $toRemoveFromStorage[] = $remoteBean;
-
- $remoteBean->_getCachedRelationships()[$pivotTableName]->detach($object);
- }
- }
-
- // Note: due to https://bugs.php.net/bug.php?id=65629, we cannot delete an element inside a foreach loop on a SplStorageObject.
- // Therefore, we cache elements in the $toRemoveFromStorage to remove them at a later stage.
- foreach ($toRemoveFromStorage as $remoteBean) {
- $storage->detach($remoteBean);
- }
- }
- }
-
- private function getPivotFilters(AbstractTDBMObject $localBean, AbstractTDBMObject $remoteBean, ForeignKeyConstraint $localFk, ForeignKeyConstraint $remoteFk)
- {
- $localBeanPk = $this->getPrimaryKeyValues($localBean);
- $remoteBeanPk = $this->getPrimaryKeyValues($remoteBean);
- $localColumns = $localFk->getLocalColumns();
- $remoteColumns = $remoteFk->getLocalColumns();
-
- $localFilters = array_combine($localColumns, $localBeanPk);
- $remoteFilters = array_combine($remoteColumns, $remoteBeanPk);
-
- return array_merge($localFilters, $remoteFilters);
- }
-
- /**
- * Returns the "values" of the primary key.
- * This returns the primary key from the $primaryKey attribute, not the one stored in the columns.
- *
- * @param AbstractTDBMObject $bean
- *
- * @return array numerically indexed array of values
- */
- private function getPrimaryKeyValues(AbstractTDBMObject $bean)
- {
- $dbRows = $bean->_getDbRows();
- $dbRow = reset($dbRows);
-
- return array_values($dbRow->_getPrimaryKeys());
- }
-
- /**
- * Returns a unique hash used to store the object based on its primary key.
- * If the array contains only one value, then the value is returned.
- * Otherwise, a hash representing the array is returned.
- *
- * @param array $primaryKeys An array of columns => values forming the primary key
- *
- * @return string
- */
- public function getObjectHash(array $primaryKeys)
- {
- if (count($primaryKeys) === 1) {
- return reset($primaryKeys);
- } else {
- ksort($primaryKeys);
-
- return md5(json_encode($primaryKeys));
- }
- }
-
- /**
- * Returns an array of primary keys from the object.
- * The primary keys are extracted from the object columns and not from the primary keys stored in the
- * $primaryKeys variable of the object.
- *
- * @param DbRow $dbRow
- *
- * @return array Returns an array of column => value
- */
- public function getPrimaryKeysForObjectFromDbRow(DbRow $dbRow)
- {
- $table = $dbRow->_getDbTableName();
- $dbRowData = $dbRow->_getDbRow();
-
- return $this->_getPrimaryKeysFromObjectData($table, $dbRowData);
- }
-
- /**
- * Returns an array of primary keys for the given row.
- * The primary keys are extracted from the object columns.
- *
- * @param $table
- * @param array $columns
- *
- * @return array
- */
- public function _getPrimaryKeysFromObjectData($table, array $columns)
- {
- $primaryKeyColumns = $this->getPrimaryKeyColumns($table);
- $values = array();
- foreach ($primaryKeyColumns as $column) {
- if (isset($columns[$column])) {
- $values[$column] = $columns[$column];
- }
- }
-
- return $values;
- }
-
- /**
- * Attaches $object to this TDBMService.
- * The $object must be in DETACHED state and will pass in NEW state.
- *
- * @param AbstractTDBMObject $object
- *
- * @throws TDBMInvalidOperationException
- */
- public function attach(AbstractTDBMObject $object)
- {
- $object->_attach($this);
- }
-
- /**
- * Returns an associative array (column => value) for the primary keys from the table name and an
- * indexed array of primary key values.
- *
- * @param string $tableName
- * @param array $indexedPrimaryKeys
- */
- public function _getPrimaryKeysFromIndexedPrimaryKeys($tableName, array $indexedPrimaryKeys)
- {
- $primaryKeyColumns = $this->tdbmSchemaAnalyzer->getSchema()->getTable($tableName)->getPrimaryKeyColumns();
-
- if (count($primaryKeyColumns) !== count($indexedPrimaryKeys)) {
- throw new TDBMException(sprintf('Wrong number of columns passed for primary key. Expected %s columns for table "%s",
- got %s instead.', count($primaryKeyColumns), $tableName, count($indexedPrimaryKeys)));
- }
-
- return array_combine($primaryKeyColumns, $indexedPrimaryKeys);
- }
-
- /**
- * Return the list of tables (from child to parent) joining the tables passed in parameter.
- * Tables must be in a single line of inheritance. The method will find missing tables.
- *
- * Algorithm: one of those tables is the ultimate child. From this child, by recursively getting the parent,
- * we must be able to find all other tables.
- *
- * @param string[] $tables
- *
- * @return string[]
- */
- public function _getLinkBetweenInheritedTables(array $tables)
- {
- sort($tables);
-
- return $this->fromCache($this->cachePrefix.'_linkbetweeninheritedtables_'.implode('__split__', $tables),
- function () use ($tables) {
- return $this->_getLinkBetweenInheritedTablesWithoutCache($tables);
- });
- }
-
- /**
- * Return the list of tables (from child to parent) joining the tables passed in parameter.
- * Tables must be in a single line of inheritance. The method will find missing tables.
- *
- * Algorithm: one of those tables is the ultimate child. From this child, by recursively getting the parent,
- * we must be able to find all other tables.
- *
- * @param string[] $tables
- *
- * @return string[]
- */
- private function _getLinkBetweenInheritedTablesWithoutCache(array $tables)
- {
- $schemaAnalyzer = $this->schemaAnalyzer;
-
- foreach ($tables as $currentTable) {
- $allParents = [$currentTable];
- while ($currentFk = $schemaAnalyzer->getParentRelationship($currentTable)) {
- $currentTable = $currentFk->getForeignTableName();
- $allParents[] = $currentTable;
- }
-
- // Now, does the $allParents contain all the tables we want?
- $notFoundTables = array_diff($tables, $allParents);
- if (empty($notFoundTables)) {
- // We have a winner!
- return $allParents;
- }
- }
-
- throw TDBMInheritanceException::create($tables);
- }
-
- /**
- * Returns the list of tables related to this table (via a parent or child inheritance relationship).
- *
- * @param string $table
- *
- * @return string[]
- */
- public function _getRelatedTablesByInheritance($table)
- {
- return $this->fromCache($this->cachePrefix.'_relatedtables_'.$table, function () use ($table) {
- return $this->_getRelatedTablesByInheritanceWithoutCache($table);
- });
- }
-
- /**
- * Returns the list of tables related to this table (via a parent or child inheritance relationship).
- *
- * @param string $table
- *
- * @return string[]
- */
- private function _getRelatedTablesByInheritanceWithoutCache($table)
- {
- $schemaAnalyzer = $this->schemaAnalyzer;
-
- // Let's scan the parent tables
- $currentTable = $table;
-
- $parentTables = [];
-
- // Get parent relationship
- while ($currentFk = $schemaAnalyzer->getParentRelationship($currentTable)) {
- $currentTable = $currentFk->getForeignTableName();
- $parentTables[] = $currentTable;
- }
-
- // Let's recurse in children
- $childrenTables = $this->exploreChildrenTablesRelationships($schemaAnalyzer, $table);
-
- return array_merge(array_reverse($parentTables), $childrenTables);
- }
-
- /**
- * Explore all the children and descendant of $table and returns ForeignKeyConstraints on those.
- *
- * @param string $table
- *
- * @return string[]
- */
- private function exploreChildrenTablesRelationships(SchemaAnalyzer $schemaAnalyzer, $table)
- {
- $tables = [$table];
- $keys = $schemaAnalyzer->getChildrenRelationships($table);
-
- foreach ($keys as $key) {
- $tables = array_merge($tables, $this->exploreChildrenTablesRelationships($schemaAnalyzer, $key->getLocalTableName()));
- }
-
- return $tables;
- }
-
- /**
- * Casts a foreign key into SQL, assuming table name is used with no alias.
- * The returned value does contain only one table. For instance:.
- *
- * " LEFT JOIN table2 ON table1.id = table2.table1_id"
- *
- * @param ForeignKeyConstraint $fk
- * @param bool $leftTableIsLocal
- *
- * @return string
- */
- /*private function foreignKeyToSql(ForeignKeyConstraint $fk, $leftTableIsLocal) {
- $onClauses = [];
- $foreignTableName = $this->connection->quoteIdentifier($fk->getForeignTableName());
- $foreignColumns = $fk->getForeignColumns();
- $localTableName = $this->connection->quoteIdentifier($fk->getLocalTableName());
- $localColumns = $fk->getLocalColumns();
- $columnCount = count($localTableName);
-
- for ($i = 0; $i < $columnCount; $i++) {
- $onClauses[] = sprintf("%s.%s = %s.%s",
- $localTableName,
- $this->connection->quoteIdentifier($localColumns[$i]),
- $foreignColumns,
- $this->connection->quoteIdentifier($foreignColumns[$i])
- );
- }
-
- $onClause = implode(' AND ', $onClauses);
-
- if ($leftTableIsLocal) {
- return sprintf(" LEFT JOIN %s ON (%s)", $foreignTableName, $onClause);
- } else {
- return sprintf(" LEFT JOIN %s ON (%s)", $localTableName, $onClause);
- }
- }*/
-
- /**
- * Returns a `ResultIterator` object representing filtered records of "$mainTable" .
- *
- * The findObjects method should be the most used query method in TDBM if you want to query the database for objects.
- * (Note: if you want to query the database for an object by its primary key, use the findObjectByPk method).
- *
- * The findObjects method takes in parameter:
- * - mainTable: the kind of bean you want to retrieve. In TDBM, a bean matches a database row, so the
- * `$mainTable` parameter should be the name of an existing table in database.
- * - filter: The filter is a filter bag. It is what you use to filter your request (the WHERE part in SQL).
- * It can be a string (SQL Where clause), or even a bean or an associative array (key = column to filter, value = value to find)
- * - parameters: The parameters used in the filter. If you pass a SQL string as a filter, be sure to avoid
- * concatenating parameters in the string (this leads to SQL injection and also to poor caching performance).
- * Instead, please consider passing parameters (see documentation for more details).
- * - additionalTablesFetch: An array of SQL tables names. The beans related to those tables will be fetched along
- * the main table. This is useful to avoid hitting the database with numerous subqueries.
- * - mode: The fetch mode of the result. See `setFetchMode()` method for more details.
- *
- * The `findObjects` method will return a `ResultIterator`. A `ResultIterator` is an object that behaves as an array
- * (in ARRAY mode) at least. It can be iterated using a `foreach` loop.
- *
- * Finally, if filter_bag is null, the whole table is returned.
- *
- * @param string $mainTable The name of the table queried
- * @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)
- * @param array $parameters
- * @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)
- * @param array $additionalTablesFetch
- * @param int $mode
- * @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
- *
- * @return ResultIterator An object representing an array of results
- *
- * @throws TDBMException
- */
- public function findObjects(string $mainTable, $filter = null, array $parameters = array(), $orderString = null, array $additionalTablesFetch = array(), $mode = null, string $className = null)
- {
- // $mainTable is not secured in MagicJoin, let's add a bit of security to avoid SQL injection.
- if (!preg_match('/^[a-zA-Z_][a-zA-Z0-9_]*$/', $mainTable)) {
- throw new TDBMException(sprintf("Invalid table name: '%s'", $mainTable));
- }
-
- $mode = $mode ?: $this->mode;
-
- list($filterString, $additionalParameters) = $this->buildFilterFromFilterBag($filter);
-
- $parameters = array_merge($parameters, $additionalParameters);
-
- $queryFactory = new FindObjectsQueryFactory($mainTable, $additionalTablesFetch, $filterString, $orderString, $this, $this->tdbmSchemaAnalyzer->getSchema(), $this->orderByAnalyzer);
-
- return new ResultIterator($queryFactory, $parameters, $this->objectStorage, $className, $this, $this->magicQuery, $mode, $this->logger);
- }
-
- /**
- * @param string $mainTable The name of the table queried
- * @param string $from The from sql statement
- * @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)
- * @param array $parameters
- * @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)
- * @param int $mode
- * @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
- *
- * @return ResultIterator An object representing an array of results
- *
- * @throws TDBMException
- */
- public function findObjectsFromSql(string $mainTable, string $from, $filter = null, array $parameters = array(), $orderString = null, $mode = null, string $className = null)
- {
- // $mainTable is not secured in MagicJoin, let's add a bit of security to avoid SQL injection.
- if (!preg_match('/^[a-zA-Z_][a-zA-Z0-9_]*$/', $mainTable)) {
- throw new TDBMException(sprintf("Invalid table name: '%s'", $mainTable));
- }
-
- $mode = $mode ?: $this->mode;
-
- list($filterString, $additionalParameters) = $this->buildFilterFromFilterBag($filter);
-
- $parameters = array_merge($parameters, $additionalParameters);
-
- $queryFactory = new FindObjectsFromSqlQueryFactory($mainTable, $from, $filterString, $orderString, $this, $this->tdbmSchemaAnalyzer->getSchema(), $this->orderByAnalyzer, $this->schemaAnalyzer, $this->cache, $this->cachePrefix);
-
- return new ResultIterator($queryFactory, $parameters, $this->objectStorage, $className, $this, $this->magicQuery, $mode, $this->logger);
- }
-
- /**
- * @param $table
- * @param array $primaryKeys
- * @param array $additionalTablesFetch
- * @param bool $lazy Whether to perform lazy loading on this object or not
- * @param string $className
- *
- * @return AbstractTDBMObject
- *
- * @throws TDBMException
- */
- public function findObjectByPk(string $table, array $primaryKeys, array $additionalTablesFetch = array(), bool $lazy = false, string $className = null)
- {
- $primaryKeys = $this->_getPrimaryKeysFromObjectData($table, $primaryKeys);
- $hash = $this->getObjectHash($primaryKeys);
-
- if ($this->objectStorage->has($table, $hash)) {
- $dbRow = $this->objectStorage->get($table, $hash);
- $bean = $dbRow->getTDBMObject();
- if ($className !== null && !is_a($bean, $className)) {
- throw new TDBMException("TDBM cannot create a bean of class '".$className."'. The requested object was already loaded and its class is '".get_class($bean)."'");
- }
-
- return $bean;
- }
-
- // Are we performing lazy fetching?
- if ($lazy === true) {
- // Can we perform lazy fetching?
- $tables = $this->_getRelatedTablesByInheritance($table);
- // Only allowed if no inheritance.
- if (count($tables) === 1) {
- if ($className === null) {
- try {
- $className = $this->getBeanClassName($table);
- } catch (TDBMInvalidArgumentException $e) {
- $className = TDBMObject::class;
- }
- }
-
- // Let's construct the bean
- if (!isset($this->reflectionClassCache[$className])) {
- $this->reflectionClassCache[$className] = new \ReflectionClass($className);
- }
- // Let's bypass the constructor when creating the bean!
- $bean = $this->reflectionClassCache[$className]->newInstanceWithoutConstructor();
- /* @var $bean AbstractTDBMObject */
- $bean->_constructLazy($table, $primaryKeys, $this);
-
- return $bean;
- }
- }
-
- // Did not find the object in cache? Let's query it!
- return $this->findObjectOrFail($table, $primaryKeys, [], $additionalTablesFetch, $className);
- }
-
- /**
- * Returns a unique bean (or null) according to the filters passed in parameter.
- *
- * @param string $mainTable The name of the table queried
- * @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)
- * @param array $parameters
- * @param array $additionalTablesFetch
- * @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
- *
- * @return AbstractTDBMObject|null The object we want, or null if no object matches the filters
- *
- * @throws TDBMException
- */
- public function findObject(string $mainTable, $filter = null, array $parameters = array(), array $additionalTablesFetch = array(), string $className = null)
- {
- $objects = $this->findObjects($mainTable, $filter, $parameters, null, $additionalTablesFetch, self::MODE_ARRAY, $className);
- $page = $objects->take(0, 2);
- $count = $page->count();
- if ($count > 1) {
- 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.");
- } elseif ($count === 0) {
- return;
- }
-
- return $page[0];
- }
-
- /**
- * Returns a unique bean (or null) according to the filters passed in parameter.
- *
- * @param string $mainTable The name of the table queried
- * @param string $from The from sql statement
- * @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)
- * @param array $parameters
- * @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
- *
- * @return AbstractTDBMObject|null The object we want, or null if no object matches the filters
- *
- * @throws TDBMException
- */
- public function findObjectFromSql($mainTable, $from, $filter = null, array $parameters = array(), $className = null)
- {
- $objects = $this->findObjectsFromSql($mainTable, $from, $filter, $parameters, null, self::MODE_ARRAY, $className);
- $page = $objects->take(0, 2);
- $count = $page->count();
- if ($count > 1) {
- 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.");
- } elseif ($count === 0) {
- return;
- }
-
- return $page[0];
- }
-
- /**
- * Returns a unique bean according to the filters passed in parameter.
- * Throws a NoBeanFoundException if no bean was found for the filter passed in parameter.
- *
- * @param string $mainTable The name of the table queried
- * @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)
- * @param array $parameters
- * @param array $additionalTablesFetch
- * @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
- *
- * @return AbstractTDBMObject The object we want
- *
- * @throws TDBMException
- */
- public function findObjectOrFail(string $mainTable, $filter = null, array $parameters = array(), array $additionalTablesFetch = array(), string $className = null)
- {
- $bean = $this->findObject($mainTable, $filter, $parameters, $additionalTablesFetch, $className);
- if ($bean === null) {
- throw new NoBeanFoundException("No result found for query on table '".$mainTable."'");
- }
-
- return $bean;
- }
-
- /**
- * @param array $beanData An array of data: array>
- *
- * @return array an array with first item = class name, second item = table name and third item = list of tables needed
- *
- * @throws TDBMInheritanceException
- */
- public function _getClassNameFromBeanData(array $beanData)
- {
- if (count($beanData) === 1) {
- $tableName = array_keys($beanData)[0];
- $allTables = [$tableName];
- } else {
- $tables = [];
- foreach ($beanData as $table => $row) {
- $primaryKeyColumns = $this->getPrimaryKeyColumns($table);
- $pkSet = false;
- foreach ($primaryKeyColumns as $columnName) {
- if ($row[$columnName] !== null) {
- $pkSet = true;
- break;
- }
- }
- if ($pkSet) {
- $tables[] = $table;
- }
- }
-
- // $tables contains the tables for this bean. Let's view the top most part of the hierarchy
- try {
- $allTables = $this->_getLinkBetweenInheritedTables($tables);
- } catch (TDBMInheritanceException $e) {
- throw TDBMInheritanceException::extendException($e, $this, $beanData);
- }
- $tableName = $allTables[0];
- }
-
- // Only one table in this bean. Life is sweat, let's look at its type:
- try {
- $className = $this->getBeanClassName($tableName);
- } catch (TDBMInvalidArgumentException $e) {
- $className = 'Mouf\\Database\\TDBM\\TDBMObject';
- }
-
- return [$className, $tableName, $allTables];
- }
-
- /**
- * Returns an item from cache or computes it using $closure and puts it in cache.
- *
- * @param string $key
- * @param callable $closure
- *
- * @return mixed
- */
- private function fromCache(string $key, callable $closure)
- {
- $item = $this->cache->fetch($key);
- if ($item === false) {
- $item = $closure();
- $this->cache->save($key, $item);
- }
-
- return $item;
- }
-
- /**
- * Returns the foreign key object.
- *
- * @param string $table
- * @param string $fkName
- *
- * @return ForeignKeyConstraint
- */
- public function _getForeignKeyByName(string $table, string $fkName)
- {
- return $this->tdbmSchemaAnalyzer->getSchema()->getTable($table)->getForeignKey($fkName);
- }
-
- /**
- * @param $pivotTableName
- * @param AbstractTDBMObject $bean
- *
- * @return AbstractTDBMObject[]
- */
- public function _getRelatedBeans(string $pivotTableName, AbstractTDBMObject $bean)
- {
- list($localFk, $remoteFk) = $this->getPivotTableForeignKeys($pivotTableName, $bean);
- /* @var $localFk ForeignKeyConstraint */
- /* @var $remoteFk ForeignKeyConstraint */
- $remoteTable = $remoteFk->getForeignTableName();
-
- $primaryKeys = $this->getPrimaryKeyValues($bean);
- $columnNames = array_map(function ($name) use ($pivotTableName) {
- return $pivotTableName.'.'.$name;
- }, $localFk->getLocalColumns());
-
- $filter = array_combine($columnNames, $primaryKeys);
-
- return $this->findObjects($remoteTable, $filter);
- }
-
- /**
- * @param $pivotTableName
- * @param AbstractTDBMObject $bean The LOCAL bean
- *
- * @return ForeignKeyConstraint[] First item: the LOCAL bean, second item: the REMOTE bean
- *
- * @throws TDBMException
- */
- private function getPivotTableForeignKeys(string $pivotTableName, AbstractTDBMObject $bean)
- {
- $fks = array_values($this->tdbmSchemaAnalyzer->getSchema()->getTable($pivotTableName)->getForeignKeys());
- $table1 = $fks[0]->getForeignTableName();
- $table2 = $fks[1]->getForeignTableName();
-
- $beanTables = array_map(function (DbRow $dbRow) {
- return $dbRow->_getDbTableName();
- }, $bean->_getDbRows());
-
- if (in_array($table1, $beanTables)) {
- return [$fks[0], $fks[1]];
- } elseif (in_array($table2, $beanTables)) {
- return [$fks[1], $fks[0]];
- } else {
- throw new TDBMException("Unexpected bean type in getPivotTableForeignKeys. Awaiting beans from table {$table1} and {$table2} for pivot table {$pivotTableName}");
- }
- }
-
- /**
- * Returns a list of pivot tables linked to $bean.
- *
- * @param AbstractTDBMObject $bean
- *
- * @return string[]
- */
- public function _getPivotTablesLinkedToBean(AbstractTDBMObject $bean)
- {
- $junctionTables = [];
- $allJunctionTables = $this->schemaAnalyzer->detectJunctionTables(true);
- foreach ($bean->_getDbRows() as $dbRow) {
- foreach ($allJunctionTables as $table) {
- // There are exactly 2 FKs since this is a pivot table.
- $fks = array_values($table->getForeignKeys());
-
- if ($fks[0]->getForeignTableName() === $dbRow->_getDbTableName() || $fks[1]->getForeignTableName() === $dbRow->_getDbTableName()) {
- $junctionTables[] = $table->getName();
- }
- }
- }
-
- return $junctionTables;
- }
-
- /**
- * Array of types for tables.
- * Key: table name
- * Value: array of types indexed by column.
- *
- * @var array[]
- */
- private $typesForTable = [];
-
- /**
- * @internal
- *
- * @param string $tableName
- *
- * @return Type[]
- */
- public function _getColumnTypesForTable(string $tableName)
- {
- if (!isset($typesForTable[$tableName])) {
- $columns = $this->tdbmSchemaAnalyzer->getSchema()->getTable($tableName)->getColumns();
- $typesForTable[$tableName] = array_map(function (Column $column) {
- return $column->getType();
- }, $columns);
- }
-
- return $typesForTable[$tableName];
- }
-
- /**
- * Sets the minimum log level.
- * $level must be one of Psr\Log\LogLevel::xxx.
- *
- * Defaults to LogLevel::WARNING
- *
- * @param string $level
- */
- public function setLogLevel(string $level)
- {
- $this->logger = new LevelFilter($this->rootLogger, $level);
- }
-}
diff --git a/src/Mouf/Database/TDBM/UncheckedOrderBy.php b/src/Mouf/Database/TDBM/UncheckedOrderBy.php
deleted file mode 100644
index cae6002..0000000
--- a/src/Mouf/Database/TDBM/UncheckedOrderBy.php
+++ /dev/null
@@ -1,43 +0,0 @@
-find methods.
- *
- * By default, TDBM is conservative and prevents an ORDERBY clause to be anything other than a sort on columns.
- * This is done to prevent SQL injections.
- *
- * If you need to order on an expression, you can wrap your ORDERBY clause in this class.
- *
- * For instance:
- *
- * $this->find(null, null, new UncheckedOrderBy('RAND()'));
- *
- * Note: you understand that arguments passed inside the `UncheckedOrderBy` constructor are NOT protected and
- * can be used for an SQL injection based attack. Therefore, you understand that you MUST NOT put input from the user
- * in this constructor.
- */
-class UncheckedOrderBy
-{
- /**
- * @var string
- */
- private $orderBy;
-
- /**
- * @param $orderBy
- */
- public function __construct(string $orderBy)
- {
- $this->orderBy = $orderBy;
- }
-
- /**
- * @return string
- */
- public function getOrderBy() : string
- {
- return $this->orderBy;
- }
-}
diff --git a/src/Mouf/Database/TDBM/Utils/AbstractBeanPropertyDescriptor.php b/src/Mouf/Database/TDBM/Utils/AbstractBeanPropertyDescriptor.php
deleted file mode 100644
index bf5a885..0000000
--- a/src/Mouf/Database/TDBM/Utils/AbstractBeanPropertyDescriptor.php
+++ /dev/null
@@ -1,139 +0,0 @@
-table = $table;
- }
-
- /**
- * Use the more complex name in case of conflict.
- */
- public function useAlternativeName()
- {
- $this->alternativeName = true;
- }
-
- /**
- * Returns the name of the class linked to this property or null if this is not a foreign key.
- *
- * @return null|string
- */
- abstract public function getClassName();
-
- /**
- * Returns the param annotation for this property (useful for constructor).
- *
- * @return string
- */
- abstract public function getParamAnnotation();
-
- public function getVariableName()
- {
- return '$'.$this->getLowerCamelCaseName();
- }
-
- public function getLowerCamelCaseName()
- {
- return TDBMDaoGenerator::toVariableName($this->getUpperCamelCaseName());
- }
-
- abstract public function getUpperCamelCaseName();
-
- public function getSetterName()
- {
- return 'set'.$this->getUpperCamelCaseName();
- }
-
- public function getGetterName()
- {
- return 'get'.$this->getUpperCamelCaseName();
- }
-
- /**
- * Returns the PHP code used in the ben constructor for this property.
- *
- * @return string
- */
- public function getConstructorAssignCode()
- {
- $str = ' $this->%s(%s);';
-
- return sprintf($str, $this->getSetterName(), $this->getVariableName());
- }
-
- /**
- * Returns true if the property is compulsory (and therefore should be fetched in the constructor).
- *
- * @return bool
- */
- abstract public function isCompulsory();
-
- /**
- * Returns true if the property has a default value.
- *
- * @return bool
- */
- abstract public function hasDefault();
-
- /**
- * Returns the code that assigns a value to its default value.
- *
- * @return string
- *
- * @throws \TDBMException
- */
- abstract public function assignToDefaultCode();
-
- /**
- * Returns true if the property is the primary key.
- *
- * @return bool
- */
- abstract public function isPrimaryKey();
-
- /**
- * @return Table
- */
- public function getTable()
- {
- return $this->table;
- }
-
- /**
- * Returns the PHP code for getters and setters.
- *
- * @return string
- */
- abstract public function getGetterSetterCode();
-
- /**
- * Returns the part of code useful when doing json serialization.
- *
- * @return string
- */
- abstract public function getJsonSerializeCode();
-}
diff --git a/src/Mouf/Database/TDBM/Utils/BeanDescriptor.php b/src/Mouf/Database/TDBM/Utils/BeanDescriptor.php
deleted file mode 100644
index 6e96ed0..0000000
--- a/src/Mouf/Database/TDBM/Utils/BeanDescriptor.php
+++ /dev/null
@@ -1,751 +0,0 @@
-table = $table;
- $this->schemaAnalyzer = $schemaAnalyzer;
- $this->schema = $schema;
- $this->tdbmSchemaAnalyzer = $tdbmSchemaAnalyzer;
- $this->namingStrategy = $namingStrategy;
- $this->initBeanPropertyDescriptors();
- }
-
- private function initBeanPropertyDescriptors()
- {
- $this->beanPropertyDescriptors = $this->getProperties($this->table);
- }
-
- /**
- * Returns the foreign-key the column is part of, if any. null otherwise.
- *
- * @param Table $table
- * @param Column $column
- *
- * @return ForeignKeyConstraint|null
- */
- private function isPartOfForeignKey(Table $table, Column $column)
- {
- $localColumnName = $column->getName();
- foreach ($table->getForeignKeys() as $foreignKey) {
- foreach ($foreignKey->getColumns() as $columnName) {
- if ($columnName === $localColumnName) {
- return $foreignKey;
- }
- }
- }
-
- return;
- }
-
- /**
- * @return AbstractBeanPropertyDescriptor[]
- */
- public function getBeanPropertyDescriptors()
- {
- return $this->beanPropertyDescriptors;
- }
-
- /**
- * Returns the list of columns that are not nullable and not autogenerated for a given table and its parent.
- *
- * @return AbstractBeanPropertyDescriptor[]
- */
- public function getConstructorProperties()
- {
- $constructorProperties = array_filter($this->beanPropertyDescriptors, function (AbstractBeanPropertyDescriptor $property) {
- return $property->isCompulsory();
- });
-
- return $constructorProperties;
- }
-
- /**
- * Returns the list of columns that have default values for a given table.
- *
- * @return AbstractBeanPropertyDescriptor[]
- */
- public function getPropertiesWithDefault()
- {
- $properties = $this->getPropertiesForTable($this->table);
- $defaultProperties = array_filter($properties, function (AbstractBeanPropertyDescriptor $property) {
- return $property->hasDefault();
- });
-
- return $defaultProperties;
- }
-
- /**
- * Returns the list of properties exposed as getters and setters in this class.
- *
- * @return AbstractBeanPropertyDescriptor[]
- */
- public function getExposedProperties(): array
- {
- $exposedProperties = array_filter($this->beanPropertyDescriptors, function (AbstractBeanPropertyDescriptor $property) {
- return $property->getTable()->getName() == $this->table->getName();
- });
-
- return $exposedProperties;
- }
-
- /**
- * Returns the list of properties for this table (including parent tables).
- *
- * @param Table $table
- *
- * @return AbstractBeanPropertyDescriptor[]
- */
- private function getProperties(Table $table)
- {
- $parentRelationship = $this->schemaAnalyzer->getParentRelationship($table->getName());
- if ($parentRelationship) {
- $parentTable = $this->schema->getTable($parentRelationship->getForeignTableName());
- $properties = $this->getProperties($parentTable);
- // we merge properties by overriding property names.
- $localProperties = $this->getPropertiesForTable($table);
- foreach ($localProperties as $name => $property) {
- // We do not override properties if this is a primary key!
- if ($property->isPrimaryKey()) {
- continue;
- }
- $properties[$name] = $property;
- }
- } else {
- $properties = $this->getPropertiesForTable($table);
- }
-
- return $properties;
- }
-
- /**
- * Returns the list of properties for this table (ignoring parent tables).
- *
- * @param Table $table
- *
- * @return AbstractBeanPropertyDescriptor[]
- */
- private function getPropertiesForTable(Table $table)
- {
- $parentRelationship = $this->schemaAnalyzer->getParentRelationship($table->getName());
- if ($parentRelationship) {
- $ignoreColumns = $parentRelationship->getLocalColumns();
- } else {
- $ignoreColumns = [];
- }
-
- $beanPropertyDescriptors = [];
-
- foreach ($table->getColumns() as $column) {
- if (array_search($column->getName(), $ignoreColumns) !== false) {
- continue;
- }
-
- $fk = $this->isPartOfForeignKey($table, $column);
- if ($fk !== null) {
- // Check that previously added descriptors are not added on same FK (can happen with multi key FK).
- foreach ($beanPropertyDescriptors as $beanDescriptor) {
- if ($beanDescriptor instanceof ObjectBeanPropertyDescriptor && $beanDescriptor->getForeignKey() === $fk) {
- continue 2;
- }
- }
- // Check that this property is not an inheritance relationship
- $parentRelationship = $this->schemaAnalyzer->getParentRelationship($table->getName());
- if ($parentRelationship === $fk) {
- continue;
- }
-
- $beanPropertyDescriptors[] = new ObjectBeanPropertyDescriptor($table, $fk, $this->schemaAnalyzer, $this->namingStrategy);
- } else {
- $beanPropertyDescriptors[] = new ScalarBeanPropertyDescriptor($table, $column, $this->namingStrategy);
- }
- }
-
- // Now, let's get the name of all properties and let's check there is no duplicate.
- /** @var $names AbstractBeanPropertyDescriptor[] */
- $names = [];
- foreach ($beanPropertyDescriptors as $beanDescriptor) {
- $name = $beanDescriptor->getUpperCamelCaseName();
- if (isset($names[$name])) {
- $names[$name]->useAlternativeName();
- $beanDescriptor->useAlternativeName();
- } else {
- $names[$name] = $beanDescriptor;
- }
- }
-
- // Final check (throw exceptions if problem arises)
- $names = [];
- foreach ($beanPropertyDescriptors as $beanDescriptor) {
- $name = $beanDescriptor->getUpperCamelCaseName();
- if (isset($names[$name])) {
- throw new TDBMException('Unsolvable name conflict while generating method name');
- } else {
- $names[$name] = $beanDescriptor;
- }
- }
-
- // Last step, let's rebuild the list with a map:
- $beanPropertyDescriptorsMap = [];
- foreach ($beanPropertyDescriptors as $beanDescriptor) {
- $beanPropertyDescriptorsMap[$beanDescriptor->getLowerCamelCaseName()] = $beanDescriptor;
- }
-
- return $beanPropertyDescriptorsMap;
- }
-
- private function generateBeanConstructor() : string
- {
- $constructorProperties = $this->getConstructorProperties();
-
- $constructorCode = ' /**
- * The constructor takes all compulsory arguments.
- *
-%s
- */
- public function __construct(%s)
- {
-%s%s }
- ';
-
- $paramAnnotations = [];
- $arguments = [];
- $assigns = [];
- $parentConstructorArguments = [];
-
- foreach ($constructorProperties as $property) {
- $className = $property->getClassName();
- if ($className) {
- $arguments[] = $className.' '.$property->getVariableName();
- } else {
- $arguments[] = $property->getVariableName();
- }
- $paramAnnotations[] = $property->getParamAnnotation();
- if ($property->getTable()->getName() === $this->table->getName()) {
- $assigns[] = $property->getConstructorAssignCode()."\n";
- } else {
- $parentConstructorArguments[] = $property->getVariableName();
- }
- }
-
- $parentConstructorCode = sprintf(" parent::__construct(%s);\n", implode(', ', $parentConstructorArguments));
-
- foreach ($this->getPropertiesWithDefault() as $property) {
- $assigns[] = $property->assignToDefaultCode()."\n";
- }
-
- return sprintf($constructorCode, implode("\n", $paramAnnotations), implode(', ', $arguments), $parentConstructorCode, implode('', $assigns));
- }
-
- public function getDirectForeignKeysDescriptors(): array
- {
- $fks = $this->tdbmSchemaAnalyzer->getIncomingForeignKeys($this->table->getName());
-
- $descriptors = [];
-
- foreach ($fks as $fk) {
- $descriptors[] = new DirectForeignKeyMethodDescriptor($fk, $this->table, $this->namingStrategy);
- }
-
- return $descriptors;
- }
-
- private function getPivotTableDescriptors(): array
- {
- $descs = [];
- foreach ($this->schemaAnalyzer->detectJunctionTables(true) as $table) {
- // There are exactly 2 FKs since this is a pivot table.
- $fks = array_values($table->getForeignKeys());
-
- if ($fks[0]->getForeignTableName() === $this->table->getName()) {
- list($localFk, $remoteFk) = $fks;
- } elseif ($fks[1]->getForeignTableName() === $this->table->getName()) {
- list($remoteFk, $localFk) = $fks;
- } else {
- continue;
- }
-
- $descs[] = new PivotTableMethodsDescriptor($table, $localFk, $remoteFk, $this->namingStrategy);
- }
-
- return $descs;
- }
-
- /**
- * Returns the list of method descriptors (and applies the alternative name if needed).
- *
- * @return MethodDescriptorInterface[]
- */
- private function getMethodDescriptors(): array
- {
- $directForeignKeyDescriptors = $this->getDirectForeignKeysDescriptors();
- $pivotTableDescriptors = $this->getPivotTableDescriptors();
-
- $descriptors = array_merge($directForeignKeyDescriptors, $pivotTableDescriptors);
-
- // Descriptors by method names
- $descriptorsByMethodName = [];
-
- foreach ($descriptors as $descriptor) {
- $descriptorsByMethodName[$descriptor->getName()][] = $descriptor;
- }
-
- foreach ($descriptorsByMethodName as $descriptorsForMethodName) {
- if (count($descriptorsForMethodName) > 1) {
- foreach ($descriptorsForMethodName as $descriptor) {
- $descriptor->useAlternativeName();
- }
- }
- }
-
- return $descriptors;
- }
-
- public function generateJsonSerialize(): string
- {
- $tableName = $this->table->getName();
- $parentFk = $this->schemaAnalyzer->getParentRelationship($tableName);
- if ($parentFk !== null) {
- $initializer = '$array = parent::jsonSerialize($stopRecursion);';
- } else {
- $initializer = '$array = [];';
- }
-
- $str = '
- /**
- * Serializes the object for JSON encoding.
- *
- * @param bool $stopRecursion Parameter used internally by TDBM to stop embedded objects from embedding other objects.
- * @return array
- */
- public function jsonSerialize($stopRecursion = false)
- {
- %s
-%s
-%s
- return $array;
- }
-';
-
- $propertiesCode = '';
- foreach ($this->beanPropertyDescriptors as $beanPropertyDescriptor) {
- $propertiesCode .= $beanPropertyDescriptor->getJsonSerializeCode();
- }
-
- // Many2many relationships
- $methodsCode = '';
- foreach ($this->getMethodDescriptors() as $methodDescriptor) {
- $methodsCode .= $methodDescriptor->getJsonSerializeCode();
- }
-
- return sprintf($str, $initializer, $propertiesCode, $methodsCode);
- }
-
- /**
- * Returns as an array the class we need to extend from and the list of use statements.
- *
- * @param ForeignKeyConstraint|null $parentFk
- * @return array
- */
- private function generateExtendsAndUseStatements(ForeignKeyConstraint $parentFk = null): array
- {
- $classes = [];
- if ($parentFk !== null) {
- $extends = $this->namingStrategy->getBeanClassName($parentFk->getForeignTableName());
- $classes[] = $extends;
- }
-
- foreach ($this->getBeanPropertyDescriptors() as $beanPropertyDescriptor) {
- $className = $beanPropertyDescriptor->getClassName();
- if (null !== $className) {
- $classes[] = $beanPropertyDescriptor->getClassName();
- }
- }
-
- foreach ($this->getMethodDescriptors() as $descriptor) {
- $classes = array_merge($classes, $descriptor->getUsedClasses());
- }
-
- $classes = array_unique($classes);
-
- return $classes;
- }
-
- /**
- * Writes the PHP bean file with all getters and setters from the table passed in parameter.
- *
- * @param string $beannamespace The namespace of the bean
- * @return string
- */
- public function generatePhpCode($beannamespace): string
- {
- $tableName = $this->table->getName();
- $baseClassName = $this->namingStrategy->getBaseBeanClassName($tableName);
- $className = $this->namingStrategy->getBeanClassName($tableName);
- $parentFk = $this->schemaAnalyzer->getParentRelationship($this->table->getName());
-
- $classes = $this->generateExtendsAndUseStatements($parentFk);
-
- $uses = array_map(function ($className) use ($beannamespace) {
- return 'use '.$beannamespace.'\\'.$className.";\n";
- }, $classes);
- $use = implode('', $uses);
-
- $extends = $this->getExtendedBeanClassName();
- if ($extends === null) {
- $extends = 'AbstractTDBMObject';
- $use .= "use Mouf\\Database\\TDBM\\AbstractTDBMObject;\n";
- }
-
- $str = "generateBeanConstructor();
-
- foreach ($this->getExposedProperties() as $property) {
- $str .= $property->getGetterSetterCode();
- }
-
- foreach ($this->getMethodDescriptors() as $methodDescriptor) {
- $str .= $methodDescriptor->getCode();
- }
- $str .= $this->generateJsonSerialize();
-
- $str .= $this->generateGetUsedTablesCode();
-
- $str .= $this->generateOnDeleteCode();
-
- $str .= '}
-';
-
- return $str;
- }
-
- /**
- * @param string $beanNamespace
- * @param string $beanClassName
- *
- * @return array first element: list of used beans, second item: PHP code as a string
- */
- public function generateFindByDaoCode($beanNamespace, $beanClassName)
- {
- $code = '';
- $usedBeans = [];
- foreach ($this->table->getIndexes() as $index) {
- if (!$index->isPrimary()) {
- list($usedBeansForIndex, $codeForIndex) = $this->generateFindByDaoCodeForIndex($index, $beanNamespace, $beanClassName);
- $code .= $codeForIndex;
- $usedBeans = array_merge($usedBeans, $usedBeansForIndex);
- }
- }
-
- return [$usedBeans, $code];
- }
-
- /**
- * @param Index $index
- * @param string $beanNamespace
- * @param string $beanClassName
- *
- * @return array first element: list of used beans, second item: PHP code as a string
- */
- private function generateFindByDaoCodeForIndex(Index $index, $beanNamespace, $beanClassName)
- {
- $columns = $index->getColumns();
- $usedBeans = [];
-
- /*
- * The list of elements building this index (expressed as columns or foreign keys)
- * @var AbstractBeanPropertyDescriptor[]
- */
- $elements = [];
-
- foreach ($columns as $column) {
- $fk = $this->isPartOfForeignKey($this->table, $this->table->getColumn($column));
- if ($fk !== null) {
- if (!in_array($fk, $elements)) {
- $elements[] = new ObjectBeanPropertyDescriptor($this->table, $fk, $this->schemaAnalyzer, $this->namingStrategy);
- }
- } else {
- $elements[] = new ScalarBeanPropertyDescriptor($this->table, $this->table->getColumn($column), $this->namingStrategy);
- }
- }
-
- // If the index is actually only a foreign key, let's bypass it entirely.
- if (count($elements) === 1 && $elements[0] instanceof ObjectBeanPropertyDescriptor) {
- return [[], ''];
- }
-
- $methodNameComponent = [];
- $functionParameters = [];
- $first = true;
- foreach ($elements as $element) {
- $methodNameComponent[] = $element->getUpperCamelCaseName();
- $functionParameter = $element->getClassName();
- if ($functionParameter) {
- $usedBeans[] = $beanNamespace.'\\'.$functionParameter;
- $functionParameter .= ' ';
- }
- $functionParameter .= $element->getVariableName();
- if ($first) {
- $first = false;
- } else {
- $functionParameter .= ' = null';
- }
- $functionParameters[] = $functionParameter;
- }
-
- $functionParametersString = implode(', ', $functionParameters);
-
- $count = 0;
-
- $params = [];
- $filterArrayCode = '';
- $commentArguments = [];
- foreach ($elements as $element) {
- $params[] = $element->getParamAnnotation();
- if ($element instanceof ScalarBeanPropertyDescriptor) {
- $filterArrayCode .= ' '.var_export($element->getColumnName(), true).' => '.$element->getVariableName().",\n";
- } else {
- ++$count;
- $filterArrayCode .= ' '.$count.' => '.$element->getVariableName().",\n";
- }
- $commentArguments[] = substr($element->getVariableName(), 1);
- }
- $paramsString = implode("\n", $params);
-
- if ($index->isUnique()) {
- $methodName = 'findOneBy'.implode('And', $methodNameComponent);
- $returnType = "{$beanClassName}";
-
- $code = "
- /**
- * Get a $beanClassName filtered by ".implode(', ', $commentArguments).".
- *
-$paramsString
- * @param array \$additionalTablesFetch A list of additional tables to fetch (for performance improvement)
- * @return $returnType
- */
- public function $methodName($functionParametersString, array \$additionalTablesFetch = array()) : $returnType
- {
- \$filter = [
-".$filterArrayCode." ];
- return \$this->findOne(\$filter, [], \$additionalTablesFetch);
- }
-";
- } else {
- $methodName = 'findBy'.implode('And', $methodNameComponent);
- $returnType = "{$beanClassName}[]|ResultIterator|ResultArray";
-
- $code = "
- /**
- * Get a list of $beanClassName filtered by ".implode(', ', $commentArguments).".
- *
-$paramsString
- * @param mixed \$orderBy The order string
- * @param array \$additionalTablesFetch A list of additional tables to fetch (for performance improvement)
- * @param string \$mode Either TDBMService::MODE_ARRAY or TDBMService::MODE_CURSOR (for large datasets). Defaults to TDBMService::MODE_ARRAY.
- * @return $returnType
- */
- public function $methodName($functionParametersString, \$orderBy = null, array \$additionalTablesFetch = array(), \$mode = null) : iterable
- {
- \$filter = [
-".$filterArrayCode." ];
- return \$this->find(\$filter, [], \$orderBy, \$additionalTablesFetch, \$mode);
- }
-";
- }
-
- return [$usedBeans, $code];
- }
-
- /**
- * Generates the code for the getUsedTable protected method.
- *
- * @return string
- */
- private function generateGetUsedTablesCode()
- {
- $hasParentRelationship = $this->schemaAnalyzer->getParentRelationship($this->table->getName()) !== null;
- if ($hasParentRelationship) {
- $code = sprintf(' $tables = parent::getUsedTables();
- $tables[] = %s;
-
- return $tables;', var_export($this->table->getName(), true));
- } else {
- $code = sprintf(' return [ %s ];', var_export($this->table->getName(), true));
- }
-
- return sprintf('
- /**
- * Returns an array of used tables by this bean (from parent to child relationship).
- *
- * @return string[]
- */
- protected function getUsedTables() : array
- {
-%s
- }
-', $code);
- }
-
- private function generateOnDeleteCode()
- {
- $code = '';
- $relationships = $this->getPropertiesForTable($this->table);
- foreach ($relationships as $relationship) {
- if ($relationship instanceof ObjectBeanPropertyDescriptor) {
- $code .= sprintf(' $this->setRef('.var_export($relationship->getForeignKey()->getName(), true).', null, '.var_export($this->table->getName(), true).");\n");
- }
- }
-
- if ($code) {
- return sprintf('
- /**
- * Method called when the bean is removed from database.
- *
- */
- protected function onDelete() : void
- {
- parent::onDelete();
-%s }
-', $code);
- }
-
- return '';
- }
-
- /**
- * Returns the bean class name (without the namespace).
- *
- * @return string
- */
- public function getBeanClassName() : string
- {
- return $this->namingStrategy->getBeanClassName($this->table->getName());
- }
-
- /**
- * Returns the base bean class name (without the namespace).
- *
- * @return string
- */
- public function getBaseBeanClassName() : string
- {
- return $this->namingStrategy->getBaseBeanClassName($this->table->getName());
- }
-
- /**
- * Returns the DAO class name (without the namespace).
- *
- * @return string
- */
- public function getDaoClassName() : string
- {
- return $this->namingStrategy->getDaoClassName($this->table->getName());
- }
-
- /**
- * Returns the base DAO class name (without the namespace).
- *
- * @return string
- */
- public function getBaseDaoClassName() : string
- {
- return $this->namingStrategy->getBaseDaoClassName($this->table->getName());
- }
-
- /**
- * Returns the table used to build this bean.
- *
- * @return Table
- */
- public function getTable(): Table
- {
- return $this->table;
- }
-
- /**
- * Returns the extended bean class name (without the namespace), or null if the bean is not extended.
- *
- * @return string
- */
- public function getExtendedBeanClassName(): ?string
- {
- $parentFk = $this->schemaAnalyzer->getParentRelationship($this->table->getName());
- if ($parentFk !== null) {
- return $this->namingStrategy->getBeanClassName($parentFk->getForeignTableName());
- } else {
- return null;
- }
- }
-}
diff --git a/src/Mouf/Database/TDBM/Utils/BeanDescriptorInterface.php b/src/Mouf/Database/TDBM/Utils/BeanDescriptorInterface.php
deleted file mode 100644
index c380481..0000000
--- a/src/Mouf/Database/TDBM/Utils/BeanDescriptorInterface.php
+++ /dev/null
@@ -1,60 +0,0 @@
-beanPrefix = $beanPrefix;
- }
-
- /**
- * Sets the string suffix to any bean class name.
- *
- * @param string $beanSuffix
- */
- public function setBeanSuffix(string $beanSuffix)
- {
- $this->beanSuffix = $beanSuffix;
- }
-
- /**
- * Sets the string prefix to any base bean class name.
- *
- * @param string $baseBeanPrefix
- */
- public function setBaseBeanPrefix(string $baseBeanPrefix)
- {
- $this->baseBeanPrefix = $baseBeanPrefix;
- }
-
- /**
- * Sets the string suffix to any base bean class name.
- *
- * @param string $baseBeanSuffix
- */
- public function setBaseBeanSuffix(string $baseBeanSuffix)
- {
- $this->baseBeanSuffix = $baseBeanSuffix;
- }
-
- /**
- * Sets the string prefix to any DAO class name.
- *
- * @param string $daoPrefix
- */
- public function setDaoPrefix(string $daoPrefix)
- {
- $this->daoPrefix = $daoPrefix;
- }
-
- /**
- * Sets the string suffix to any DAO class name.
- *
- * @param string $daoSuffix
- */
- public function setDaoSuffix(string $daoSuffix)
- {
- $this->daoSuffix = $daoSuffix;
- }
-
- /**
- * Sets the string prefix to any base DAO class name.
- *
- * @param string $baseDaoPrefix
- */
- public function setBaseDaoPrefix(string $baseDaoPrefix)
- {
- $this->baseDaoPrefix = $baseDaoPrefix;
- }
-
- /**
- * Sets the string suffix to any base DAO class name.
- *
- * @param string $baseDaoSuffix
- */
- public function setBaseDaoSuffix(string $baseDaoSuffix)
- {
- $this->baseDaoSuffix = $baseDaoSuffix;
- }
-
-
- /**
- * Returns the bean class name from the table name (excluding the namespace).
- *
- * @param string $tableName
- * @return string
- */
- public function getBeanClassName(string $tableName): string
- {
- return $this->beanPrefix.$this->toSingularCamelCase($tableName).$this->beanSuffix;
- }
-
- /**
- * Returns the base bean class name from the table name (excluding the namespace).
- *
- * @param string $tableName
- * @return string
- */
- public function getBaseBeanClassName(string $tableName): string
- {
- return $this->baseBeanPrefix.$this->toSingularCamelCase($tableName).$this->baseBeanSuffix;
- }
-
- /**
- * Returns the name of the DAO class from the table name (excluding the namespace).
- *
- * @param string $tableName
- * @return string
- */
- public function getDaoClassName(string $tableName): string
- {
- return $this->daoPrefix.$this->toSingularCamelCase($tableName).$this->daoSuffix;
- }
-
- /**
- * Returns the name of the base DAO class from the table name (excluding the namespace).
- *
- * @param string $tableName
- * @return string
- */
- public function getBaseDaoClassName(string $tableName): string
- {
- return $this->baseDaoPrefix.$this->toSingularCamelCase($tableName).$this->baseDaoSuffix;
- }
-
- /**
- * Tries to put string to the singular form (if it is plural) and camel case form.
- * We assume the table names are in english.
- *
- * @param $str string
- *
- * @return string
- */
- private function toSingularCamelCase(string $str): string
- {
- // Let's first check if this is not in the exceptions directory.
- if (isset($this->exceptions[$str])) {
- return $this->exceptions[$str];
- }
-
- $tokens = preg_split("/[_ ]+/", $str);
- $tokens = array_map([Inflector::class, 'singularize'], $tokens);
-
- $str = '';
- foreach ($tokens as $token) {
- $str .= ucfirst(Inflector::singularize($token));
- }
-
- return $str;
- }
-
- /**
- * Returns the class name for the DAO factory.
- *
- * @return string
- */
- public function getDaoFactoryClassName(): string
- {
- return 'DaoFactory';
- }
-
- /**
- * Sets exceptions in the naming of classes.
- * The key is the name of the table, the value the "base" name of beans and DAOs.
- *
- * This is very useful for dealing with plural to singular translations in non english table names.
- *
- * For instance if you are dealing with a table containing horses in French ("chevaux" that has a singular "cheval"):
- *
- * [
- * "chevaux" => "Cheval"
- * ]
- *
- * @param array $exceptions
- */
- public function setExceptions(array $exceptions)
- {
- $this->exceptions = $exceptions;
- }
-}
diff --git a/src/Mouf/Database/TDBM/Utils/DirectForeignKeyMethodDescriptor.php b/src/Mouf/Database/TDBM/Utils/DirectForeignKeyMethodDescriptor.php
deleted file mode 100644
index ba7b3ce..0000000
--- a/src/Mouf/Database/TDBM/Utils/DirectForeignKeyMethodDescriptor.php
+++ /dev/null
@@ -1,142 +0,0 @@
-fk = $fk;
- $this->mainTable = $mainTable;
- $this->namingStrategy = $namingStrategy;
- }
-
- /**
- * Returns the name of the method to be generated.
- *
- * @return string
- */
- public function getName() : string
- {
- if (!$this->useAlternateName) {
- return 'get'.TDBMDaoGenerator::toCamelCase($this->fk->getLocalTableName());
- } else {
- $methodName = 'get'.TDBMDaoGenerator::toCamelCase($this->fk->getLocalTableName()).'By';
-
- $camelizedColumns = array_map([TDBMDaoGenerator::class, 'toCamelCase'], $this->fk->getLocalColumns());
-
- $methodName .= implode('And', $camelizedColumns);
-
- return $methodName;
- }
- }
-
- /**
- * Requests the use of an alternative name for this method.
- */
- public function useAlternativeName()
- {
- $this->useAlternateName = true;
- }
-
- /**
- * Returns the code of the method.
- *
- * @return string
- */
- public function getCode() : string
- {
- $code = '';
-
- $getterCode = ' /**
- * Returns the list of %s pointing to this bean via the %s column.
- *
- * @return %s[]|AlterableResultIterator
- */
- public function %s() : AlterableResultIterator
- {
- return $this->retrieveManyToOneRelationshipsStorage(%s, %s, %s, %s);
- }
-
-';
-
- $beanClass = $this->namingStrategy->getBeanClassName($this->fk->getLocalTableName());
- $code .= sprintf($getterCode,
- $beanClass,
- implode(', ', $this->fk->getColumns()),
- $beanClass,
- $this->getName(),
- var_export($this->fk->getLocalTableName(), true),
- var_export($this->fk->getName(), true),
- var_export($this->fk->getLocalTableName(), true),
- $this->getFilters($this->fk)
- );
-
- return $code;
- }
-
- private function getFilters(ForeignKeyConstraint $fk) : string
- {
- $counter = 0;
- $parameters = [];
-
- $pkColumns = $this->mainTable->getPrimaryKeyColumns();
-
- foreach ($fk->getLocalColumns() as $columnName) {
- $pkColumn = $pkColumns[$counter];
- $parameters[] = sprintf('%s => $this->get(%s, %s)', var_export($fk->getLocalTableName().'.'.$columnName, true), var_export($pkColumn, true), var_export($this->fk->getForeignTableName(), true));
- ++$counter;
- }
- $parametersCode = '['.implode(', ', $parameters).']';
-
- return $parametersCode;
- }
-
- /**
- * Returns an array of classes that needs a "use" for this method.
- *
- * @return string[]
- */
- public function getUsedClasses() : array
- {
- return [$this->namingStrategy->getBeanClassName($this->fk->getForeignTableName())];
- }
-
- /**
- * Returns the code to past in jsonSerialize.
- *
- * @return string
- */
- public function getJsonSerializeCode() : string
- {
- return '';
- }
-}
diff --git a/src/Mouf/Database/TDBM/Utils/GeneratorEventDispatcher.php b/src/Mouf/Database/TDBM/Utils/GeneratorEventDispatcher.php
deleted file mode 100644
index d58b1d1..0000000
--- a/src/Mouf/Database/TDBM/Utils/GeneratorEventDispatcher.php
+++ /dev/null
@@ -1,34 +0,0 @@
-listeners = $listeners;
- }
-
- /**
- * @param ConfigurationInterface $configuration
- * @param BeanDescriptorInterface[] $beanDescriptors
- */
- public function onGenerate(ConfigurationInterface $configuration, array $beanDescriptors): void
- {
- foreach ($this->listeners as $listener) {
- $listener->onGenerate($configuration, $beanDescriptors);
- }
- }
-}
diff --git a/src/Mouf/Database/TDBM/Utils/GeneratorListenerInterface.php b/src/Mouf/Database/TDBM/Utils/GeneratorListenerInterface.php
deleted file mode 100644
index 6f9e63f..0000000
--- a/src/Mouf/Database/TDBM/Utils/GeneratorListenerInterface.php
+++ /dev/null
@@ -1,18 +0,0 @@
-foreignKey = $foreignKey;
- $this->schemaAnalyzer = $schemaAnalyzer;
- $this->namingStrategy = $namingStrategy;
- }
-
- /**
- * Returns the foreignkey the column is part of, if any. null otherwise.
- *
- * @return ForeignKeyConstraint|null
- */
- public function getForeignKey()
- {
- return $this->foreignKey;
- }
-
- /**
- * Returns the name of the class linked to this property or null if this is not a foreign key.
- *
- * @return null|string
- */
- public function getClassName()
- {
- return $this->namingStrategy->getBeanClassName($this->foreignKey->getForeignTableName());
- }
-
- /**
- * Returns the param annotation for this property (useful for constructor).
- *
- * @return string
- */
- public function getParamAnnotation()
- {
- $str = ' * @param %s %s';
-
- return sprintf($str, $this->getClassName(), $this->getVariableName());
- }
-
- public function getUpperCamelCaseName()
- {
- // First, are there many column or only one?
- // If one column, we name the setter after it. Otherwise, we name the setter after the table name
- if (count($this->foreignKey->getLocalColumns()) > 1) {
- $name = TDBMDaoGenerator::toSingular(TDBMDaoGenerator::toCamelCase($this->foreignKey->getForeignTableName()));
- if ($this->alternativeName) {
- $camelizedColumns = array_map(['Mouf\\Database\\TDBM\\Utils\\TDBMDaoGenerator', 'toCamelCase'], $this->foreignKey->getLocalColumns());
-
- $name .= 'By'.implode('And', $camelizedColumns);
- }
- } else {
- $column = $this->foreignKey->getLocalColumns()[0];
- // Let's remove any _id or id_.
- if (strpos(strtolower($column), 'id_') === 0) {
- $column = substr($column, 3);
- }
- if (strrpos(strtolower($column), '_id') === strlen($column) - 3) {
- $column = substr($column, 0, strlen($column) - 3);
- }
- $name = TDBMDaoGenerator::toCamelCase($column);
- if ($this->alternativeName) {
- $name .= 'Object';
- }
- }
-
- return $name;
- }
-
- /**
- * Returns true if the property is compulsory (and therefore should be fetched in the constructor).
- *
- * @return bool
- */
- public function isCompulsory()
- {
- // Are all columns nullable?
- $localColumnNames = $this->foreignKey->getLocalColumns();
-
- foreach ($localColumnNames as $name) {
- $column = $this->table->getColumn($name);
- if ($column->getNotnull()) {
- return true;
- }
- }
-
- return false;
- }
-
- /**
- * Returns true if the property has a default value.
- *
- * @return bool
- */
- public function hasDefault()
- {
- return false;
- }
-
- /**
- * Returns the code that assigns a value to its default value.
- *
- * @return string
- *
- * @throws \TDBMException
- */
- public function assignToDefaultCode()
- {
- throw new \TDBMException('Foreign key based properties cannot be assigned a default value.');
- }
-
- /**
- * Returns true if the property is the primary key.
- *
- * @return bool
- */
- public function isPrimaryKey()
- {
- $fkColumns = $this->foreignKey->getLocalColumns();
- sort($fkColumns);
-
- $pkColumns = $this->table->getPrimaryKeyColumns();
- sort($pkColumns);
-
- return $fkColumns == $pkColumns;
- }
-
- /**
- * Returns the PHP code for getters and setters.
- *
- * @return string
- */
- public function getGetterSetterCode()
- {
- $tableName = $this->table->getName();
- $getterName = $this->getGetterName();
- $setterName = $this->getSetterName();
- $isNullable = !$this->isCompulsory();
-
- $referencedBeanName = $this->namingStrategy->getBeanClassName($this->foreignKey->getForeignTableName());
-
- $str = ' /**
- * Returns the '.$referencedBeanName.' object bound to this object via the '.implode(' and ', $this->foreignKey->getLocalColumns()).' column.
- *
- * @return '.$referencedBeanName.($isNullable?'|null':'').'
- */
- public function '.$getterName.'(): '.($isNullable?'?':'').$referencedBeanName.'
- {
- return $this->getRef('.var_export($this->foreignKey->getName(), true).', '.var_export($tableName, true).');
- }
-
- /**
- * The setter for the '.$referencedBeanName.' object bound to this object via the '.implode(' and ', $this->foreignKey->getLocalColumns()).' column.
- *
- * @param '.$referencedBeanName.($isNullable?'|null':'').' $object
- */
- public function '.$setterName.'('.($isNullable?'?':'').$referencedBeanName.' $object) : void
- {
- $this->setRef('.var_export($this->foreignKey->getName(), true).', $object, '.var_export($tableName, true).');
- }
-
-';
-
- return $str;
- }
-
- /**
- * Returns the part of code useful when doing json serialization.
- *
- * @return string
- */
- public function getJsonSerializeCode()
- {
- return ' if (!$stopRecursion) {
- $object = $this->'.$this->getGetterName().'();
- $array['.var_export($this->getLowerCamelCaseName(), true).'] = $object ? $object->jsonSerialize(true) : null;
- }
-';
- }
-}
diff --git a/src/Mouf/Database/TDBM/Utils/PathFinder/NoPathFoundException.php b/src/Mouf/Database/TDBM/Utils/PathFinder/NoPathFoundException.php
deleted file mode 100644
index 9a122f1..0000000
--- a/src/Mouf/Database/TDBM/Utils/PathFinder/NoPathFoundException.php
+++ /dev/null
@@ -1,17 +0,0 @@
-composerFile = $composerFile;
- $this->useAutoloadDev = $useAutoloadDev;
- if ($rootPath === null) {
- $this->rootPath = dirname(__DIR__, 9);
- } else {
- $this->rootPath = $rootPath;
- }
- }
-
- private function getClassNameMapper() : ClassNameMapper
- {
- if ($this->classNameMapper === null) {
- $this->classNameMapper = ClassNameMapper::createFromComposerFile($this->composerFile, $this->rootPath, $this->useAutoloadDev);
- }
- return $this->classNameMapper;
- }
-
- /**
- * Returns the path of a class file given the fully qualified class name.
- *
- * @param string $className
- * @return \SplFileInfo
- * @throws NoPathFoundException
- */
- public function getPath(string $className): \SplFileInfo
- {
- $paths = $this->getClassNameMapper()->getPossibleFileNames($className);
- if (empty($paths)) {
- throw NoPathFoundException::create($className);
- }
- return new \SplFileInfo($this->rootPath.'/'.$paths[0]);
- }
-}
diff --git a/src/Mouf/Database/TDBM/Utils/PathFinder/PathFinderInterface.php b/src/Mouf/Database/TDBM/Utils/PathFinder/PathFinderInterface.php
deleted file mode 100644
index 46dd9e1..0000000
--- a/src/Mouf/Database/TDBM/Utils/PathFinder/PathFinderInterface.php
+++ /dev/null
@@ -1,16 +0,0 @@
-pivotTable = $pivotTable;
- $this->localFk = $localFk;
- $this->remoteFk = $remoteFk;
- $this->namingStrategy = $namingStrategy;
- }
-
- /**
- * Requests the use of an alternative name for this method.
- */
- public function useAlternativeName()
- {
- $this->useAlternateName = true;
- }
-
- /**
- * Returns the name of the method to be generated.
- *
- * @return string
- */
- public function getName() : string
- {
- if (!$this->useAlternateName) {
- return 'get'.TDBMDaoGenerator::toCamelCase($this->remoteFk->getForeignTableName());
- } else {
- return 'get'.TDBMDaoGenerator::toCamelCase($this->remoteFk->getForeignTableName()).'By'.TDBMDaoGenerator::toCamelCase($this->pivotTable->getName());
- }
- }
-
- /**
- * Returns the plural name.
- *
- * @return string
- */
- private function getPluralName() : string
- {
- if (!$this->useAlternateName) {
- return TDBMDaoGenerator::toCamelCase($this->remoteFk->getForeignTableName());
- } else {
- return TDBMDaoGenerator::toCamelCase($this->remoteFk->getForeignTableName()).'By'.TDBMDaoGenerator::toCamelCase($this->pivotTable->getName());
- }
- }
-
- /**
- * Returns the singular name.
- *
- * @return string
- */
- private function getSingularName() : string
- {
- if (!$this->useAlternateName) {
- return TDBMDaoGenerator::toCamelCase(TDBMDaoGenerator::toSingular($this->remoteFk->getForeignTableName()));
- } else {
- return TDBMDaoGenerator::toCamelCase(TDBMDaoGenerator::toSingular($this->remoteFk->getForeignTableName())).'By'.TDBMDaoGenerator::toCamelCase($this->pivotTable->getName());
- }
- }
-
- /**
- * Returns the code of the method.
- *
- * @return string
- */
- public function getCode() : string
- {
- $singularName = $this->getSingularName();
- $pluralName = $this->getPluralName();
- $remoteBeanName = $this->namingStrategy->getBeanClassName($this->remoteFk->getForeignTableName());
- $variableName = '$'.TDBMDaoGenerator::toVariableName($remoteBeanName);
- $pluralVariableName = $variableName.'s';
-
- $str = ' /**
- * Returns the list of %s associated to this bean via the %s pivot table.
- *
- * @return %s[]
- */
- public function get%s() : array
- {
- return $this->_getRelationships(%s);
- }
-';
-
- $getterCode = sprintf($str, $remoteBeanName, $this->pivotTable->getName(), $remoteBeanName, $pluralName, var_export($this->remoteFk->getLocalTableName(), true));
-
- $str = ' /**
- * Adds a relationship with %s associated to this bean via the %s pivot table.
- *
- * @param %s %s
- */
- public function add%s(%s %s) : void
- {
- $this->addRelationship(%s, %s);
- }
-';
-
- $adderCode = sprintf($str, $remoteBeanName, $this->pivotTable->getName(), $remoteBeanName, $variableName, $singularName, $remoteBeanName, $variableName, var_export($this->remoteFk->getLocalTableName(), true), $variableName);
-
- $str = ' /**
- * Deletes the relationship with %s associated to this bean via the %s pivot table.
- *
- * @param %s %s
- */
- public function remove%s(%s %s) : void
- {
- $this->_removeRelationship(%s, %s);
- }
-';
-
- $removerCode = sprintf($str, $remoteBeanName, $this->pivotTable->getName(), $remoteBeanName, $variableName, $singularName, $remoteBeanName, $variableName, var_export($this->remoteFk->getLocalTableName(), true), $variableName);
-
- $str = ' /**
- * Returns whether this bean is associated with %s via the %s pivot table.
- *
- * @param %s %s
- * @return bool
- */
- public function has%s(%s %s) : bool
- {
- return $this->hasRelationship(%s, %s);
- }
-';
-
- $hasCode = sprintf($str, $remoteBeanName, $this->pivotTable->getName(), $remoteBeanName, $variableName, $singularName, $remoteBeanName, $variableName, var_export($this->remoteFk->getLocalTableName(), true), $variableName);
-
- $str = ' /**
- * Sets all relationships with %s associated to this bean via the %s pivot table.
- * Exiting relationships will be removed and replaced by the provided relationships.
- *
- * @param %s[] %s
- */
- public function set%s(array %s) : void
- {
- $this->setRelationships(%s, %s);
- }
-';
-
- $setterCode = sprintf($str, $remoteBeanName, $this->pivotTable->getName(), $remoteBeanName, $pluralVariableName, $pluralName, $pluralVariableName, var_export($this->remoteFk->getLocalTableName(), true), $pluralVariableName);
-
- $code = $getterCode.$adderCode.$removerCode.$hasCode.$setterCode;
-
- return $code;
- }
-
- /**
- * Returns an array of classes that needs a "use" for this method.
- *
- * @return string[]
- */
- public function getUsedClasses() : array
- {
- return [$this->namingStrategy->getBeanClassName($this->remoteFk->getForeignTableName())];
- }
-
- /**
- * Returns the code to past in jsonSerialize.
- *
- * @return string
- */
- public function getJsonSerializeCode() : string
- {
- $remoteBeanName = $this->namingStrategy->getBeanClassName($this->remoteFk->getForeignTableName());
- $variableName = '$'.TDBMDaoGenerator::toVariableName($remoteBeanName);
-
- return ' if (!$stopRecursion) {
- $array[\''.lcfirst($this->getPluralName()).'\'] = array_map(function ('.$remoteBeanName.' '.$variableName.') {
- return '.$variableName.'->jsonSerialize(true);
- }, $this->'.$this->getName().'());
- }
-';
- }
-}
diff --git a/src/Mouf/Database/TDBM/Utils/ScalarBeanPropertyDescriptor.php b/src/Mouf/Database/TDBM/Utils/ScalarBeanPropertyDescriptor.php
deleted file mode 100644
index d191cf0..0000000
--- a/src/Mouf/Database/TDBM/Utils/ScalarBeanPropertyDescriptor.php
+++ /dev/null
@@ -1,215 +0,0 @@
-table = $table;
- $this->column = $column;
- $this->namingStrategy = $namingStrategy;
- }
-
- /**
- * Returns the foreign-key the column is part of, if any. null otherwise.
- *
- * @return ForeignKeyConstraint|null
- */
- public function getForeignKey()
- {
- return false;
- }
-
- /**
- * Returns the param annotation for this property (useful for constructor).
- *
- * @return string
- */
- public function getParamAnnotation()
- {
- $className = $this->getClassName();
- $paramType = $className ?: TDBMDaoGenerator::dbalTypeToPhpType($this->column->getType());
-
- $str = ' * @param %s %s';
-
- return sprintf($str, $paramType, $this->getVariableName());
- }
-
- public function getUpperCamelCaseName()
- {
- return TDBMDaoGenerator::toCamelCase($this->column->getName());
- }
-
- /**
- * Returns the name of the class linked to this property or null if this is not a foreign key.
- *
- * @return null|string
- */
- public function getClassName()
- {
- return;
- }
-
- /**
- * Returns true if the property is compulsory (and therefore should be fetched in the constructor).
- *
- * @return bool
- */
- public function isCompulsory()
- {
- return $this->column->getNotnull() && !$this->column->getAutoincrement() && $this->column->getDefault() === null;
- }
-
- /**
- * Returns true if the property has a default value.
- *
- * @return bool
- */
- public function hasDefault()
- {
- return $this->column->getDefault() !== null;
- }
-
- /**
- * Returns the code that assigns a value to its default value.
- *
- * @return string
- */
- public function assignToDefaultCode()
- {
- $str = ' $this->%s(%s);';
-
- $default = $this->column->getDefault();
-
- if (strtoupper($default) === 'CURRENT_TIMESTAMP') {
- $defaultCode = 'new \DateTimeImmutable()';
- } else {
- $defaultCode = var_export($this->column->getDefault(), true);
- }
-
- return sprintf($str, $this->getSetterName(), $defaultCode);
- }
-
- /**
- * Returns true if the property is the primary key.
- *
- * @return bool
- */
- public function isPrimaryKey()
- {
- return in_array($this->column->getName(), $this->table->getPrimaryKeyColumns());
- }
-
- /**
- * Returns the PHP code for getters and setters.
- *
- * @return string
- */
- public function getGetterSetterCode()
- {
- $type = $this->column->getType();
- $normalizedType = TDBMDaoGenerator::dbalTypeToPhpType($type);
-
- $columnGetterName = $this->getGetterName();
- $columnSetterName = $this->getSetterName();
-
- // A column type can be forced if it is not nullable and not auto-incrementable (for auto-increment columns, we can get "null" as long as the bean is not saved).
- $isNullable = !$this->column->getNotnull() || $this->column->getAutoincrement();
-
- $getterAndSetterCode = ' /**
- * The getter for the "%s" column.
- *
- * @return %s
- */
- public function %s() : %s%s
- {
- return $this->get(%s, %s);
- }
-
- /**
- * The setter for the "%s" column.
- *
- * @param %s $%s
- */
- public function %s(%s%s $%s) : void
- {
- $this->set(%s, $%s, %s);
- }
-
-';
-
- return sprintf($getterAndSetterCode,
- // Getter
- $this->column->getName(),
- $normalizedType.($isNullable ? '|null' : ''),
- $columnGetterName,
- ($isNullable ? '?' : ''),
- $normalizedType,
- var_export($this->column->getName(), true),
- var_export($this->table->getName(), true),
- // Setter
- $this->column->getName(),
- $normalizedType,
- $this->column->getName(),
- $columnSetterName,
- $this->column->getNotnull() ? '' : '?',
- $normalizedType,
- //$castTo,
- $this->column->getName(),
- var_export($this->column->getName(), true),
- $this->column->getName(),
- var_export($this->table->getName(), true)
- );
- }
-
- /**
- * Returns the part of code useful when doing json serialization.
- *
- * @return string
- */
- public function getJsonSerializeCode()
- {
- $type = $this->column->getType();
- $normalizedType = TDBMDaoGenerator::dbalTypeToPhpType($type);
-
- if ($normalizedType == '\\DateTimeInterface') {
- return ' $array['.var_export($this->getLowerCamelCaseName(), true).'] = ($this->'.$this->getGetterName().'() === null) ? null : $this->'.$this->getGetterName()."()->format('c');\n";
- } else {
- return ' $array['.var_export($this->getLowerCamelCaseName(), true).'] = $this->'.$this->getGetterName()."();\n";
- }
- }
-
- /**
- * Returns the column name.
- *
- * @return string
- */
- public function getColumnName()
- {
- return $this->column->getName();
- }
-}
diff --git a/src/Mouf/Database/TDBM/Utils/TDBMDaoGenerator.php b/src/Mouf/Database/TDBM/Utils/TDBMDaoGenerator.php
deleted file mode 100644
index 73bfc51..0000000
--- a/src/Mouf/Database/TDBM/Utils/TDBMDaoGenerator.php
+++ /dev/null
@@ -1,652 +0,0 @@
-configuration = $configuration;
- $this->schema = $tdbmSchemaAnalyzer->getSchema();
- $this->tdbmSchemaAnalyzer = $tdbmSchemaAnalyzer;
- $this->namingStrategy = $configuration->getNamingStrategy();
- $this->eventDispatcher = $configuration->getGeneratorEventDispatcher();
- }
-
- /**
- * Generates all the daos and beans.
- *
- * @throws TDBMException
- */
- public function generateAllDaosAndBeans(): void
- {
- // TODO: check that no class name ends with "Base". Otherwise, there will be name clash.
-
- $tableList = $this->schema->getTables();
-
- // Remove all beans and daos from junction tables
- $junctionTables = $this->configuration->getSchemaAnalyzer()->detectJunctionTables(true);
- $junctionTableNames = array_map(function (Table $table) {
- return $table->getName();
- }, $junctionTables);
-
- $tableList = array_filter($tableList, function (Table $table) use ($junctionTableNames) {
- return !in_array($table->getName(), $junctionTableNames);
- });
-
- $beanDescriptors = [];
-
- foreach ($tableList as $table) {
- $beanDescriptors[] = $this->generateDaoAndBean($table);
- }
-
-
- $this->generateFactory($tableList);
-
- // Let's call the list of listeners
- $this->eventDispatcher->onGenerate($this->configuration, $beanDescriptors);
- }
-
- /**
- * Generates in one method call the daos and the beans for one table.
- *
- * @param Table $table
- *
- * @return BeanDescriptor
- * @throws TDBMException
- */
- private function generateDaoAndBean(Table $table) : BeanDescriptor
- {
- $tableName = $table->getName();
- $daoName = $this->namingStrategy->getDaoClassName($tableName);
- $beanName = $this->namingStrategy->getBeanClassName($tableName);
- $baseBeanName = $this->namingStrategy->getBaseBeanClassName($tableName);
- $baseDaoName = $this->namingStrategy->getBaseDaoClassName($tableName);
-
- $beanDescriptor = new BeanDescriptor($table, $this->configuration->getSchemaAnalyzer(), $this->schema, $this->tdbmSchemaAnalyzer, $this->namingStrategy);
- $this->generateBean($beanDescriptor, $beanName, $baseBeanName, $table);
- $this->generateDao($beanDescriptor, $daoName, $baseDaoName, $beanName, $table);
- return $beanDescriptor;
- }
-
- /**
- * Writes the PHP bean file with all getters and setters from the table passed in parameter.
- *
- * @param BeanDescriptor $beanDescriptor
- * @param string $className The name of the class
- * @param string $baseClassName The name of the base class which will be extended (name only, no directory)
- * @param Table $table The table
- *
- * @throws TDBMException
- */
- public function generateBean(BeanDescriptor $beanDescriptor, $className, $baseClassName, Table $table)
- {
- $beannamespace = $this->configuration->getBeanNamespace();
- $str = $beanDescriptor->generatePhpCode($beannamespace);
-
- $possibleBaseFileName = $this->configuration->getPathFinder()->getPath($beannamespace.'\\Generated\\'.$baseClassName)->getPathname();
-
- $this->dumpFile($possibleBaseFileName, $str);
-
- $possibleFileName = $this->configuration->getPathFinder()->getPath($beannamespace.'\\'.$className)->getPathname();
-
- if (!file_exists($possibleFileName)) {
- $tableName = $table->getName();
- $str = "dumpFile($possibleFileName, $str);
- }
- }
-
- /**
- * Tries to find a @defaultSort annotation in one of the columns.
- *
- * @param Table $table
- *
- * @return array First item: column name, Second item: column order (asc/desc)
- */
- private function getDefaultSortColumnFromAnnotation(Table $table)
- {
- $defaultSort = null;
- $defaultSortDirection = null;
- foreach ($table->getColumns() as $column) {
- $comments = $column->getComment();
- $matches = [];
- if (preg_match('/@defaultSort(\((desc|asc)\))*/', $comments, $matches) != 0) {
- $defaultSort = $column->getName();
- if (count($matches) === 3) {
- $defaultSortDirection = $matches[2];
- } else {
- $defaultSortDirection = 'ASC';
- }
- }
- }
-
- return [$defaultSort, $defaultSortDirection];
- }
-
- /**
- * Writes the PHP bean DAO with simple functions to create/get/save objects.
- *
- * @param BeanDescriptor $beanDescriptor
- * @param string $className The name of the class
- * @param string $baseClassName
- * @param string $beanClassName
- * @param Table $table
- *
- * @throws TDBMException
- */
- private function generateDao(BeanDescriptor $beanDescriptor, string $className, string $baseClassName, string $beanClassName, Table $table)
- {
- $daonamespace = $this->configuration->getDaoNamespace();
- $beannamespace = $this->configuration->getBeanNamespace();
- $tableName = $table->getName();
- $primaryKeyColumns = $table->getPrimaryKeyColumns();
-
- list($defaultSort, $defaultSortDirection) = $this->getDefaultSortColumnFromAnnotation($table);
-
- // FIXME: lowercase tables with _ in the name should work!
- $tableCamel = self::toSingular(self::toCamelCase($tableName));
-
- $beanClassWithoutNameSpace = $beanClassName;
- $beanClassName = $beannamespace.'\\'.$beanClassName;
-
- list($usedBeans, $findByDaoCode) = $beanDescriptor->generateFindByDaoCode($beannamespace, $beanClassWithoutNameSpace);
-
- $usedBeans[] = $beanClassName;
- // Let's suppress duplicates in used beans (if any)
- $usedBeans = array_flip(array_flip($usedBeans));
- $useStatements = array_map(function ($usedBean) {
- return "use $usedBean;\n";
- }, $usedBeans);
-
- $str = "tdbmService = \$tdbmService;
- }
-
- /**
- * Persist the $beanClassWithoutNameSpace instance.
- *
- * @param $beanClassWithoutNameSpace \$obj The bean to save.
- */
- public function save($beanClassWithoutNameSpace \$obj)
- {
- \$this->tdbmService->save(\$obj);
- }
-
- /**
- * Get all $tableCamel records.
- *
- * @return {$beanClassWithoutNameSpace}[]|ResultIterator|ResultArray
- */
- public function findAll() : iterable
- {
- if (\$this->defaultSort) {
- \$orderBy = '$tableName.'.\$this->defaultSort.' '.\$this->defaultDirection;
- } else {
- \$orderBy = null;
- }
- return \$this->tdbmService->findObjects('$tableName', null, [], \$orderBy);
- }
- ";
-
- if (count($primaryKeyColumns) === 1) {
- $primaryKeyColumn = $primaryKeyColumns[0];
- $primaryKeyPhpType = self::dbalTypeToPhpType($table->getColumn($primaryKeyColumn)->getType());
- $str .= "
- /**
- * Get $beanClassWithoutNameSpace specified by its ID (its primary key)
- * If the primary key does not exist, an exception is thrown.
- *
- * @param string|int \$id
- * @param bool \$lazyLoading If set to true, the object will not be loaded right away. Instead, it will be loaded when you first try to access a method of the object.
- * @return $beanClassWithoutNameSpace
- * @throws TDBMException
- */
- public function getById($primaryKeyPhpType \$id, \$lazyLoading = false) : $beanClassWithoutNameSpace
- {
- return \$this->tdbmService->findObjectByPk('$tableName', ['$primaryKeyColumn' => \$id], [], \$lazyLoading);
- }
- ";
- }
- $str .= "
- /**
- * Deletes the $beanClassWithoutNameSpace passed in parameter.
- *
- * @param $beanClassWithoutNameSpace \$obj object to delete
- * @param bool \$cascade if true, it will delete all object linked to \$obj
- */
- public function delete($beanClassWithoutNameSpace \$obj, \$cascade = false) : void
- {
- if (\$cascade === true) {
- \$this->tdbmService->deleteCascade(\$obj);
- } else {
- \$this->tdbmService->delete(\$obj);
- }
- }
-
-
- /**
- * Get a list of $beanClassWithoutNameSpace specified by its filters.
- *
- * @param mixed \$filter The filter bag (see TDBMService::findObjects for complete description)
- * @param array \$parameters The parameters associated with the filter
- * @param mixed \$orderBy The order string
- * @param array \$additionalTablesFetch A list of additional tables to fetch (for performance improvement)
- * @param int \$mode Either TDBMService::MODE_ARRAY or TDBMService::MODE_CURSOR (for large datasets). Defaults to TDBMService::MODE_ARRAY.
- * @return {$beanClassWithoutNameSpace}[]|ResultIterator|ResultArray
- */
- protected function find(\$filter = null, array \$parameters = [], \$orderBy=null, array \$additionalTablesFetch = [], \$mode = null) : iterable
- {
- if (\$this->defaultSort && \$orderBy == null) {
- \$orderBy = '$tableName.'.\$this->defaultSort.' '.\$this->defaultDirection;
- }
- return \$this->tdbmService->findObjects('$tableName', \$filter, \$parameters, \$orderBy, \$additionalTablesFetch, \$mode);
- }
-
- /**
- * Get a list of $beanClassWithoutNameSpace specified by its filters.
- * Unlike the `find` method that guesses the FROM part of the statement, here you can pass the \$from part.
- *
- * You should not put an alias on the main table name. So your \$from variable should look like:
- *
- * \"$tableName JOIN ... ON ...\"
- *
- * @param string \$from The sql from statement
- * @param mixed \$filter The filter bag (see TDBMService::findObjects for complete description)
- * @param array \$parameters The parameters associated with the filter
- * @param mixed \$orderBy The order string
- * @param int \$mode Either TDBMService::MODE_ARRAY or TDBMService::MODE_CURSOR (for large datasets). Defaults to TDBMService::MODE_ARRAY.
- * @return {$beanClassWithoutNameSpace}[]|ResultIterator|ResultArray
- */
- protected function findFromSql(\$from, \$filter = null, array \$parameters = [], \$orderBy = null, \$mode = null) : iterable
- {
- if (\$this->defaultSort && \$orderBy == null) {
- \$orderBy = '$tableName.'.\$this->defaultSort.' '.\$this->defaultDirection;
- }
- return \$this->tdbmService->findObjectsFromSql('$tableName', \$from, \$filter, \$parameters, \$orderBy, \$mode);
- }
-
- /**
- * Get a single $beanClassWithoutNameSpace specified by its filters.
- *
- * @param mixed \$filter The filter bag (see TDBMService::findObjects for complete description)
- * @param array \$parameters The parameters associated with the filter
- * @param array \$additionalTablesFetch A list of additional tables to fetch (for performance improvement)
- * @return $beanClassWithoutNameSpace|null
- */
- protected function findOne(\$filter = null, array \$parameters = [], array \$additionalTablesFetch = []) : ?$beanClassWithoutNameSpace
- {
- return \$this->tdbmService->findObject('$tableName', \$filter, \$parameters, \$additionalTablesFetch);
- }
-
- /**
- * Get a single $beanClassWithoutNameSpace specified by its filters.
- * Unlike the `find` method that guesses the FROM part of the statement, here you can pass the \$from part.
- *
- * You should not put an alias on the main table name. So your \$from variable should look like:
- *
- * \"$tableName JOIN ... ON ...\"
- *
- * @param string \$from The sql from statement
- * @param mixed \$filter The filter bag (see TDBMService::findObjects for complete description)
- * @param array \$parameters The parameters associated with the filter
- * @return $beanClassWithoutNameSpace|null
- */
- protected function findOneFromSql(\$from, \$filter = null, array \$parameters = []) : ?$beanClassWithoutNameSpace
- {
- return \$this->tdbmService->findObjectFromSql('$tableName', \$from, \$filter, \$parameters);
- }
-
- /**
- * Sets the default column for default sorting.
- *
- * @param string \$defaultSort
- */
- public function setDefaultSort(string \$defaultSort) : void
- {
- \$this->defaultSort = \$defaultSort;
- }
-";
-
- $str .= $findByDaoCode;
- $str .= '}
-';
-
- $possibleBaseFileName = $this->configuration->getPathFinder()->getPath($daonamespace.'\\Generated\\'.$baseClassName)->getPathname();
-
- $this->dumpFile($possibleBaseFileName, $str);
-
- $possibleFileName = $this->configuration->getPathFinder()->getPath($daonamespace.'\\'.$className)->getPathname();
-
- // Now, let's generate the "editable" class
- if (!file_exists($possibleFileName)) {
- $str = "dumpFile($possibleFileName, $str);
- }
- }
-
- /**
- * Generates the factory bean.
- *
- * @param Table[] $tableList
- * @throws TDBMException
- */
- private function generateFactory(array $tableList) : void
- {
- $daoNamespace = $this->configuration->getDaoNamespace();
- $daoFactoryClassName = $this->namingStrategy->getDaoFactoryClassName();
-
- // For each table, let's write a property.
-
- $str = "getName();
- $daoClassName = $this->namingStrategy->getDaoClassName($tableName);
- $str .= "use {$daoNamespace}\\".$daoClassName.";\n";
- }
-
- $str .= "
-/**
- * The $daoFactoryClassName provides an easy access to all DAOs generated by TDBM.
- *
- */
-class $daoFactoryClassName
-{
-";
-
- foreach ($tableList as $table) {
- $tableName = $table->getName();
- $daoClassName = $this->namingStrategy->getDaoClassName($tableName);
- $daoInstanceName = self::toVariableName($daoClassName);
-
- $str .= ' /**
- * @var '.$daoClassName.'
- */
- private $'.$daoInstanceName.';
-
- /**
- * Returns an instance of the '.$daoClassName.' class.
- *
- * @return '.$daoClassName.'
- */
- public function get'.$daoClassName.'() : '.$daoClassName.'
- {
- return $this->'.$daoInstanceName.';
- }
-
- /**
- * Sets the instance of the '.$daoClassName.' class that will be returned by the factory getter.
- *
- * @param '.$daoClassName.' $'.$daoInstanceName.'
- */
- public function set'.$daoClassName.'('.$daoClassName.' $'.$daoInstanceName.') : void
- {
- $this->'.$daoInstanceName.' = $'.$daoInstanceName.';
- }';
- }
-
- $str .= '
-}
-';
-
- $possibleFileName = $this->configuration->getPathFinder()->getPath($daoNamespace.'\\Generated\\'.$daoFactoryClassName)->getPathname();
-
- $this->dumpFile($possibleFileName, $str);
- }
-
- /**
- * Transforms a string to camelCase (except the first letter will be uppercase too).
- * Underscores and spaces are removed and the first letter after the underscore is uppercased.
- *
- * @param $str string
- *
- * @return string
- */
- public static function toCamelCase($str)
- {
- $str = strtoupper(substr($str, 0, 1)).substr($str, 1);
- while (true) {
- if (strpos($str, '_') === false && strpos($str, ' ') === false) {
- break;
- }
-
- $pos = strpos($str, '_');
- if ($pos === false) {
- $pos = strpos($str, ' ');
- }
- $before = substr($str, 0, $pos);
- $after = substr($str, $pos + 1);
- $str = $before.strtoupper(substr($after, 0, 1)).substr($after, 1);
- }
-
- return $str;
- }
-
- /**
- * Tries to put string to the singular form (if it is plural).
- * We assume the table names are in english.
- *
- * @param $str string
- *
- * @return string
- */
- public static function toSingular($str)
- {
- return Inflector::singularize($str);
- }
-
- /**
- * Put the first letter of the string in lower case.
- * Very useful to transform a class name into a variable name.
- *
- * @param $str string
- *
- * @return string
- */
- public static function toVariableName($str)
- {
- return strtolower(substr($str, 0, 1)).substr($str, 1);
- }
-
- /**
- * Ensures the file passed in parameter can be written in its directory.
- *
- * @param string $fileName
- *
- * @throws TDBMException
- */
- private function ensureDirectoryExist(string $fileName)
- {
- $dirName = dirname($fileName);
- if (!file_exists($dirName)) {
- $old = umask(0);
- $result = mkdir($dirName, 0775, true);
- umask($old);
- if ($result === false) {
- throw new TDBMException("Unable to create directory: '".$dirName."'.");
- }
- }
- }
-
- private function dumpFile(string $fileName, string $content) : void
- {
- $this->ensureDirectoryExist($fileName);
- $fileSystem = new Filesystem();
- $fileSystem->dumpFile($fileName, $content);
- @chmod($fileName, 0664);
- }
-
- /**
- * Transforms a DBAL type into a PHP type (for PHPDoc purpose).
- *
- * @param Type $type The DBAL type
- *
- * @return string The PHP type
- */
- public static function dbalTypeToPhpType(Type $type)
- {
- $map = [
- Type::TARRAY => 'array',
- Type::SIMPLE_ARRAY => 'array',
- 'json' => 'array', // 'json' is supported from Doctrine DBAL 2.6 only.
- Type::JSON_ARRAY => 'array',
- Type::BIGINT => 'string',
- Type::BOOLEAN => 'bool',
- Type::DATETIME => '\DateTimeInterface',
- Type::DATETIMETZ => '\DateTimeInterface',
- Type::DATE => '\DateTimeInterface',
- Type::TIME => '\DateTimeInterface',
- Type::DECIMAL => 'float',
- Type::INTEGER => 'int',
- Type::OBJECT => 'string',
- Type::SMALLINT => 'int',
- Type::STRING => 'string',
- Type::TEXT => 'string',
- Type::BINARY => 'string',
- Type::BLOB => 'string',
- Type::FLOAT => 'float',
- Type::GUID => 'string',
- ];
-
- return isset($map[$type->getName()]) ? $map[$type->getName()] : $type->getName();
- }
-}
diff --git a/src/Mouf/Database/TDBM/Utils/VoidListener.php b/src/Mouf/Database/TDBM/Utils/VoidListener.php
deleted file mode 100644
index 9aed4eb..0000000
--- a/src/Mouf/Database/TDBM/Utils/VoidListener.php
+++ /dev/null
@@ -1,22 +0,0 @@
->
- */
- private $objects = array();
-
- /**
- * Every 10000 set in the dataset, we perform a cleanup to ensure the WeakRef instances
- * are removed if they are no more valid.
- * This is to avoid having memory used by dangling WeakRef instances.
- *
- * @var int
- */
- private $garbageCollectorCount = 0;
-
- /**
- * Sets an object in the storage.
- *
- * @param string $tableName
- * @param string $id
- * @param DbRow $dbRow
- */
- public function set($tableName, $id, DbRow $dbRow)
- {
- $this->objects[$tableName][$id] = new \WeakRef($dbRow);
- ++$this->garbageCollectorCount;
- if ($this->garbageCollectorCount == 10000) {
- $this->garbageCollectorCount = 0;
- $this->cleanupDanglingWeakRefs();
- }
- }
-
- /**
- * Checks if an object is in the storage.
- *
- * @param string $tableName
- * @param string $id
- *
- * @return bool
- */
- public function has($tableName, $id)
- {
- if (isset($this->objects[$tableName][$id])) {
- if ($this->objects[$tableName][$id]->valid()) {
- return true;
- } else {
- unset($this->objects[$tableName][$id]);
- }
- }
-
- return false;
- }
-
- /**
- * Returns an object from the storage (or null if no object is set).
- *
- * @param string $tableName
- * @param string $id
- *
- * @return DbRow
- */
- public function get($tableName, $id)
- {
- if (isset($this->objects[$tableName][$id])) {
- if ($this->objects[$tableName][$id]->valid()) {
- return $this->objects[$tableName][$id]->get();
- }
- } else {
- return;
- }
- }
-
- /**
- * Removes an object from the storage.
- *
- * @param string $tableName
- * @param string $id
- */
- public function remove($tableName, $id)
- {
- unset($this->objects[$tableName][$id]);
- }
-
- /**
- * Applies the callback to all objects.
- *
- * @param callable $callback
- */
- public function apply(callable $callback)
- {
- foreach ($this->objects as $tableName => $table) {
- foreach ($table as $id => $obj) {
- if ($obj->valid()) {
- $callback($obj->get(), $tableName, $id);
- } else {
- unset($this->objects[$tableName][$id]);
- }
- }
- }
- }
-
- private function cleanupDanglingWeakRefs()
- {
- foreach ($this->objects as $tableName => $table) {
- foreach ($table as $id => $obj) {
- if (!$obj->valid()) {
- unset($this->objects[$tableName][$id]);
- }
- }
- }
- }
-}
diff --git a/src/TdbmAdmin.php b/src/TdbmAdmin.php
index d220af4..3482e12 100644
--- a/src/TdbmAdmin.php
+++ b/src/TdbmAdmin.php
@@ -5,7 +5,7 @@
MoufUtils::registerMainMenu('dbMainMenu', 'DB', null, 'mainMenu', 70);
MoufUtils::registerMenuItem('dbTDBMAdminSubMenu', 'DAOs', null, 'dbMainMenu', 80);
-MoufUtils::registerChooseInstanceMenuItem('dbTDBMGenereateDAOAdminSubMenu', 'Generate DAOs', 'tdbmadmin/', 'Mouf\\Database\\TDBM\\TDBMService', 'dbTDBMAdminSubMenu', 10);
+MoufUtils::registerChooseInstanceMenuItem('dbTDBMGenereateDAOAdminSubMenu', 'Generate DAOs', 'tdbmadmin/', 'TheCodingMachine\\TDBM\\TDBMService', 'dbTDBMAdminSubMenu', 10);
// Controller declaration
$moufManager = MoufManager::getMoufManager();
@@ -13,6 +13,6 @@
$moufManager->bindComponents('tdbmadmin', 'template', 'moufTemplate');
$moufManager->bindComponents('tdbmadmin', 'content', 'block.content');
-$moufManager->declareComponent('tdbminstall2', 'Mouf\\Database\\TDBM\\Controllers\\TdbmInstallController', true);
-$moufManager->bindComponents('tdbminstall2', 'template', 'moufInstallTemplate');
-$moufManager->bindComponents('tdbminstall2', 'content', 'block.content');
+$moufManager->declareComponent('tdbminstall3', 'Mouf\\Database\\TDBM\\Controllers\\TdbmInstallController', true);
+$moufManager->bindComponents('tdbminstall3', 'template', 'moufInstallTemplate');
+$moufManager->bindComponents('tdbminstall3', 'content', 'block.content');
diff --git a/tests/Mouf/Database/TDBM/AlterableResultIteratorTest.php b/tests/Mouf/Database/TDBM/AlterableResultIteratorTest.php
deleted file mode 100644
index fb7474b..0000000
--- a/tests/Mouf/Database/TDBM/AlterableResultIteratorTest.php
+++ /dev/null
@@ -1,150 +0,0 @@
- 'a'];
- $b = (object) ['b' => 'c'];
- $c = (object) ['b' => 'c'];
-
- $iterator = new \ArrayIterator([$a, $b, $c]);
-
- $alterableResultIterator = new AlterableResultIterator($iterator);
-
- $this->assertEquals([$a, $b, $c], $alterableResultIterator->toArray());
- $this->assertEquals([$a, $b, $c], $alterableResultIterator->jsonSerialize());
- $this->assertEquals($a, $alterableResultIterator[0]);
- $this->assertTrue(isset($alterableResultIterator[0]));
- $this->assertCount(3, $alterableResultIterator);
- $this->assertEquals($a, $alterableResultIterator->first());
- }
-
- public function testEmptyResultSet()
- {
- $alterableResultIterator = new AlterableResultIterator();
-
- $this->assertEquals([], $alterableResultIterator->toArray());
-
- $this->assertEquals([], iterator_to_array($alterableResultIterator->getIterator()));
- $this->assertNull($alterableResultIterator->first());
- }
-
- public function testAlterEmptyResultSet()
- {
- $alterableResultIterator = new AlterableResultIterator();
-
- $a = (object) ['a' => 'a'];
- $b = (object) ['b' => 'c'];
- $c = (object) ['b' => 'c'];
-
- $alterableResultIterator->add($a);
- $alterableResultIterator->add($b);
- $alterableResultIterator->remove($b);
- $alterableResultIterator->remove($c);
-
- $this->assertEquals([$a], $alterableResultIterator->toArray());
- }
-
- public function testAlterFilledResultSet()
- {
- $a = (object) ['a' => 'a'];
- $b = (object) ['b' => 'c'];
- $c = (object) ['b' => 'c'];
-
- $iterator = new \ArrayIterator([$a, $b]);
-
- $alterableResultIterator = new AlterableResultIterator($iterator);
-
- $alterableResultIterator->add($c);
- $alterableResultIterator->remove($b);
-
- $this->assertEquals([$a, $c], $alterableResultIterator->toArray());
- $this->assertEquals([$c], iterator_to_array($alterableResultIterator->take(1, 1)));
- }
-
- public function testAddAfterToArray()
- {
- $a = (object) ['a' => 'a'];
- $b = (object) ['b' => 'c'];
- $c = (object) ['b' => 'c'];
-
- $iterator = new \ArrayIterator([$a, $b]);
-
- $alterableResultIterator = new AlterableResultIterator($iterator);
-
- $this->assertEquals([$a, $b], $alterableResultIterator->toArray());
-
- $alterableResultIterator->add($c);
- $alterableResultIterator->remove($b);
-
- $this->assertEquals([$a, $c], $alterableResultIterator->toArray());
- }
-
- public function testGetIterator()
- {
- $a = (object) ['a' => 'a'];
- $b = (object) ['b' => 'c'];
- $c = (object) ['b' => 'c'];
-
- $iterator = new \ArrayIterator([$a, $b]);
-
- $alterableResultIterator = new AlterableResultIterator($iterator);
-
- // Test getting the iterator with no alterations (should serve the initial iterator)
- $this->assertEquals([$a, $b], iterator_to_array($alterableResultIterator->getIterator()));
- $this->assertInstanceOf(\ArrayIterator::class, $alterableResultIterator->getIterator());
-
- $alterableResultIterator->add($c);
- $this->assertEquals([$a, $b, $c], iterator_to_array($alterableResultIterator->getIterator()));
- $this->assertInstanceOf(\ArrayIterator::class, $alterableResultIterator->getIterator());
- }
-
- public function testSetException()
- {
- $alterableResultIterator = new AlterableResultIterator();
- $this->expectException(TDBMInvalidOperationException::class);
- $alterableResultIterator[0] = 'foo';
- }
-
- public function testUnsetException()
- {
- $alterableResultIterator = new AlterableResultIterator();
- $this->expectException(TDBMInvalidOperationException::class);
- unset($alterableResultIterator[0]);
- }
-
- public function testMap()
- {
- $a = (object) ['foo' => 'bar'];
-
- $iterator = new \ArrayIterator([$a]);
-
- $alterableResultIterator = new AlterableResultIterator($iterator);
-
- $map = $alterableResultIterator->map(function ($item) {
- return $item->foo;
- });
-
- $this->assertEquals(['bar'], iterator_to_array($map));
- }
-
- public function testSetIterator()
- {
- $alterableResultIterator = new AlterableResultIterator();
-
- $a = (object) ['a' => 'a'];
- $b = (object) ['b' => 'c'];
- $c = (object) ['b' => 'c'];
-
- $iterator = new \ArrayIterator([$a, $b, $c]);
-
- $alterableResultIterator->setResultIterator($iterator);
-
- $this->assertEquals([$a, $b, $c], $alterableResultIterator->toArray());
- }
-}
diff --git a/tests/Mouf/Database/TDBM/Commands/AlteredConfigurationTest.php b/tests/Mouf/Database/TDBM/Commands/AlteredConfigurationTest.php
deleted file mode 100644
index e04dfea..0000000
--- a/tests/Mouf/Database/TDBM/Commands/AlteredConfigurationTest.php
+++ /dev/null
@@ -1,41 +0,0 @@
-getMockBuilder(Connection::class)->disableOriginalConstructor()->getMock();
- $namingStrategy = $this->getMockBuilder(NamingStrategyInterface::class)->disableOriginalConstructor()->getMock();
- $cache = $this->getMockBuilder(Cache::class)->disableOriginalConstructor()->getMock();
- $logger = $this->getMockBuilder(LoggerInterface::class)->disableOriginalConstructor()->getMock();
- $schemaAnalyzer = $this->getMockBuilder(SchemaAnalyzer::class)->disableOriginalConstructor()->getMock();
-
- $configuration = new Configuration('FooBean', 'FooDao', $connection, $namingStrategy, $cache, $schemaAnalyzer, $logger, []);
-
- $alteredConfiguration = new AlteredConfiguration($configuration);
-
- $this->assertSame($connection, $alteredConfiguration->getConnection());
- $this->assertSame($namingStrategy, $alteredConfiguration->getNamingStrategy());
- $this->assertSame($cache, $alteredConfiguration->getCache());
- $this->assertSame($logger, $alteredConfiguration->getLogger());
- $this->assertSame('FooBean', $alteredConfiguration->getBeanNamespace());
- $this->assertSame('FooDao', $alteredConfiguration->getDaoNamespace());
- $this->assertSame($configuration->getGeneratorEventDispatcher(), $alteredConfiguration->getGeneratorEventDispatcher());
- $this->assertSame($schemaAnalyzer, $alteredConfiguration->getSchemaAnalyzer());
- $this->assertSame($configuration->getPathFinder(), $alteredConfiguration->getPathFinder());
-
- $logger2 = new NullLogger();
- $alteredConfiguration->setLogger($logger2);
- $this->assertSame($logger2, $alteredConfiguration->getLogger());
- }
-}
diff --git a/tests/Mouf/Database/TDBM/Commands/GenerateCommandTest.php b/tests/Mouf/Database/TDBM/Commands/GenerateCommandTest.php
deleted file mode 100644
index badfc4f..0000000
--- a/tests/Mouf/Database/TDBM/Commands/GenerateCommandTest.php
+++ /dev/null
@@ -1,49 +0,0 @@
-callCommand(new GenerateCommand($this->getConfiguration()), $input);
-
- $this->assertContains('Finished regenerating DAOs and beans', $result);
- }
-
- /**
- * Calls the command passed in parameter. Returns the output.
- *
- * @param Command $command
- * @param InputInterface $input
- * @return string
- */
- protected function callCommand(Command $command, InputInterface $input) : string
- {
- $output = new BufferedOutput();
- $output->setVerbosity(OutputInterface::VERBOSITY_DEBUG);
-
- $r = new \ReflectionMethod($command, 'execute');
- $r->setAccessible(true);
- $r->invoke($command, $input, $output);
-
- return $output->fetch();
- }
-}
diff --git a/tests/Mouf/Database/TDBM/Dao/TestRoleDao.php b/tests/Mouf/Database/TDBM/Dao/TestRoleDao.php
deleted file mode 100644
index a07911d..0000000
--- a/tests/Mouf/Database/TDBM/Dao/TestRoleDao.php
+++ /dev/null
@@ -1,44 +0,0 @@
-findFromSql('roles JOIN roles_rights ON roles.id = roles_rights.role_id JOIN rights ON rights.label = roles_rights.right_label',
- 'rights.label = :right', array('right' => 'CAN_SING'), $orderBy);
- }
- /**
- * Returns the list of roles join rights where right label = CAN_SING.
- *
- * @return RoleBean[]
- */
- public function getRolesByRight($orderBy = null)
- {
- return $this->findFromSql('roles JOIN roles_rights ON roles.id = roles_rights.role_id JOIN rights ON rights.label = roles_rights.right_label',
- null, [], $orderBy);
- }
-
- /**
- * Returns the role join rights where right label = CAN_SING and role name = Singers.
- *
- * @return RoleBean
- */
- public function getRoleByRightCanSingAndNameSinger()
- {
- return $this->findOneFromSql('roles JOIN roles_rights ON roles.id = roles_rights.role_id JOIN rights ON rights.label = roles_rights.right_label',
- 'rights.label = :right AND name = :name', array('right' => 'CAN_SING', 'name' => 'Singers'));
- }
-}
diff --git a/tests/Mouf/Database/TDBM/Dao/TestUserDao.php b/tests/Mouf/Database/TDBM/Dao/TestUserDao.php
deleted file mode 100644
index cab81d4..0000000
--- a/tests/Mouf/Database/TDBM/Dao/TestUserDao.php
+++ /dev/null
@@ -1,103 +0,0 @@
-find(null, [], 'login ASC');
- }
- /**
- * Returns the list of users by alphabetical order.
- *
- * @return UserBean[]
- */
- public function getUsersFromSqlByAlphabeticalOrder()
- {
- // The third parameter will be used in the "ORDER BY" clause of the SQL query.
- return $this->findFromSql('users', null, [], 'login ASC');
- }
-
- /**
- * Returns the list of users whose login starts with $login.
- *
- * @param string $login
- * @param string $mode
- *
- * @return \Mouf\Database\TDBM\ResultIterator|\Mouf\Database\TDBM\Test\Dao\Bean\UserBean[]|\Mouf\Database\TDBM\Test\Dao\ResultArray
- */
- public function getUsersByLoginStartingWith($login = null, $mode = null)
- {
- return $this->find('login LIKE :login', ['login' => $login.'%'], null, [], $mode);
- }
-
- /**
- * Returns the user whose login is $login.
- *
- * @param string $login
- *
- * @return \Mouf\Database\TDBM\Test\Dao\Bean\UserBean
- */
- public function getUserByLogin($login)
- {
- return $this->findOne('login = :login', ['login' => $login]);
- }
-
- public function getUsersByManagerId($managerId)
- {
- return $this->find('contact.manager_id = :id!', ['id' => $managerId]);
- }
-
- /**
- * Triggers an error because table "contacts" does not exist.
- *
- * @return \Mouf\Database\TDBM\ResultIterator|\Mouf\Database\TDBM\Test\Dao\Bean\UserBean[]|\Mouf\Database\TDBM\Test\Dao\Generated\ResultArray
- */
- public function getUsersWrongTableName()
- {
- return $this->find('contacts.manager_id = 1');
- }
-
- /**
- * Returns a list of users, sorted by a table on an external column.
- *
- * @return \Mouf\Database\TDBM\ResultIterator|\Mouf\Database\TDBM\Test\Dao\Bean\UserBean[]|\Mouf\Database\TDBM\Test\Dao\Generated\ResultArray
- */
- public function getUsersByCountryName()
- {
- return $this->find(null, [], 'country.label DESC');
- }
-
- /**
- * A test to sort by function.
- *
- * @return \Mouf\Database\TDBM\ResultIterator|\Mouf\Database\TDBM\Test\Dao\Bean\UserBean[]|\Mouf\Database\TDBM\Test\Dao\Generated\ResultArray
- */
- public function getUsersByReversedCountryName()
- {
- return $this->find(null, [], new UncheckedOrderBy('REVERSE(country.label) ASC'));
- }
-
- /**
- * A test to check exceptions when providing expressions in ORDER BY clause.
- *
- * @return \Mouf\Database\TDBM\ResultIterator|\Mouf\Database\TDBM\Test\Dao\Bean\UserBean[]|\Mouf\Database\TDBM\Test\Dao\Generated\ResultArray
- */
- public function getUsersByInvalidOrderBy()
- {
- return $this->find(null, [], 'REVERSE(country.label) ASC');
- }
-}
diff --git a/tests/Mouf/Database/TDBM/DummyGeneratorListener.php b/tests/Mouf/Database/TDBM/DummyGeneratorListener.php
deleted file mode 100644
index 2e13d48..0000000
--- a/tests/Mouf/Database/TDBM/DummyGeneratorListener.php
+++ /dev/null
@@ -1,46 +0,0 @@
-configuration = $configuration;
- $this->beanDescriptors = $beanDescriptors;
- }
-
- /**
- * @return ConfigurationInterface
- */
- public function getConfiguration(): ConfigurationInterface
- {
- return $this->configuration;
- }
-
- /**
- * @return BeanDescriptorInterface[]
- */
- public function getBeanDescriptors(): array
- {
- return $this->beanDescriptors;
- }
-}
diff --git a/tests/Mouf/Database/TDBM/MapIteratorTest.php b/tests/Mouf/Database/TDBM/MapIteratorTest.php
deleted file mode 100644
index 048cbd0..0000000
--- a/tests/Mouf/Database/TDBM/MapIteratorTest.php
+++ /dev/null
@@ -1,54 +0,0 @@
-assertEquals($value, json_decode(json_encode($mapIterator), true));
- }
-}
diff --git a/tests/Mouf/Database/TDBM/OrderByAnalyzerTest.php b/tests/Mouf/Database/TDBM/OrderByAnalyzerTest.php
deleted file mode 100644
index df9fd46..0000000
--- a/tests/Mouf/Database/TDBM/OrderByAnalyzerTest.php
+++ /dev/null
@@ -1,67 +0,0 @@
-analyzeOrderBy('`a`, b desc, rand() DESC, masc, mytable.mycol');
-
- $this->assertCount(5, $results);
- $this->assertEquals([
- 'type' => 'colref',
- 'table' => null,
- 'column' => 'a',
- 'direction' => 'ASC',
- ], $results[0]);
- $this->assertEquals([
- 'type' => 'colref',
- 'table' => null,
- 'column' => 'b',
- 'direction' => 'DESC',
- ], $results[1]);
- $this->assertEquals([
- 'type' => 'expr',
- 'expr' => 'rand()',
- 'direction' => 'DESC',
- ], $results[2]);
- $this->assertEquals([
- 'type' => 'colref',
- 'table' => null,
- 'column' => 'masc',
- 'direction' => 'ASC',
- ], $results[3]);
- $this->assertEquals([
- 'type' => 'colref',
- 'table' => 'mytable',
- 'column' => 'mycol',
- 'direction' => 'ASC',
- ], $results[4]);
- }
-
- public function testExprWithAsc()
- {
- $analyzer = new OrderByAnalyzer(new VoidCache(), '');
- $results = $analyzer->analyzeOrderBy('foodesc + barasc');
-
- $this->assertCount(1, $results);
- $this->assertEquals([
- 'type' => 'expr',
- 'expr' => 'foodesc + barasc',
- 'direction' => 'ASC',
- ], $results[0]);
- }
-
- public function testCache()
- {
- $analyzer = new OrderByAnalyzer(new ArrayCache(), '');
- $results = $analyzer->analyzeOrderBy('foo');
- $results2 = $analyzer->analyzeOrderBy('foo');
- // For code coverage purpose
- }
-}
diff --git a/tests/Mouf/Database/TDBM/TDBMAbstractServiceTest.php b/tests/Mouf/Database/TDBM/TDBMAbstractServiceTest.php
deleted file mode 100644
index 3fa8bd2..0000000
--- a/tests/Mouf/Database/TDBM/TDBMAbstractServiceTest.php
+++ /dev/null
@@ -1,129 +0,0 @@
- $GLOBALS['db_username'],
- 'password' => $GLOBALS['db_password'],
- 'host' => $GLOBALS['db_host'],
- 'port' => $GLOBALS['db_port'],
- 'driver' => $GLOBALS['db_driver'],
- );
-
- $adminConn = DriverManager::getConnection($connectionParams, $config);
- $adminConn->getSchemaManager()->dropAndCreateDatabase($GLOBALS['db_name']);
-
- $connectionParams['dbname'] = $GLOBALS['db_name'];
-
- $dbConnection = DriverManager::getConnection($connectionParams, $config);
-
- self::loadSqlFile($dbConnection, __DIR__.'/../../../sql/tdbmunittest.sql');
- }
-
- protected function setUp()
- {
- $this->tdbmService = new TDBMService($this->getConfiguration());
- }
-
- protected function getDummyGeneratorListener() : DummyGeneratorListener
- {
- if ($this->dummyGeneratorListener === null) {
- $this->dummyGeneratorListener = new DummyGeneratorListener();
- }
- return $this->dummyGeneratorListener;
- }
-
- protected function getConfiguration() : ConfigurationInterface
- {
- if ($this->configuration === null) {
- $config = new \Doctrine\DBAL\Configuration();
-
- $connectionParams = array(
- 'user' => $GLOBALS['db_username'],
- 'password' => $GLOBALS['db_password'],
- 'host' => $GLOBALS['db_host'],
- 'port' => $GLOBALS['db_port'],
- 'driver' => $GLOBALS['db_driver'],
- 'dbname' => $GLOBALS['db_name'],
- );
-
- $this->dbConnection = DriverManager::getConnection($connectionParams, $config);
- $this->configuration = new Configuration('Mouf\\Database\\TDBM\\Test\\Dao\\Bean', 'Mouf\\Database\\TDBM\\Test\\Dao', $this->dbConnection, $this->getNamingStrategy(), new ArrayCache(), null, null, [$this->getDummyGeneratorListener()]);
- $this->configuration->setPathFinder(new PathFinder(null, dirname(__DIR__, 4)));
- }
- return $this->configuration;
- }
-
- protected static function loadSqlFile(Connection $connection, $sqlFile)
- {
- $sql = file_get_contents($sqlFile);
-
- $stmt = $connection->prepare($sql);
- $stmt->execute();
- }
-
- protected function getNamingStrategy()
- {
- $strategy = new DefaultNamingStrategy();
- $strategy->setBeanPrefix('');
- $strategy->setBeanSuffix('Bean');
- $strategy->setBaseBeanPrefix('');
- $strategy->setBaseBeanSuffix('BaseBean');
- $strategy->setDaoPrefix('');
- $strategy->setDaoSuffix('Dao');
- $strategy->setBaseDaoPrefix('');
- $strategy->setBaseDaoSuffix('BaseDao');
-
- return $strategy;
- }
-}
diff --git a/tests/Mouf/Database/TDBM/TDBMDaoGeneratorTest.php b/tests/Mouf/Database/TDBM/TDBMDaoGeneratorTest.php
deleted file mode 100644
index 5253fa0..0000000
--- a/tests/Mouf/Database/TDBM/TDBMDaoGeneratorTest.php
+++ /dev/null
@@ -1,1360 +0,0 @@
-tdbmService->getConnection()->getSchemaManager();
- $schemaAnalyzer = new SchemaAnalyzer($schemaManager);
- $tdbmSchemaAnalyzer = new TDBMSchemaAnalyzer($this->tdbmService->getConnection(), new ArrayCache(), $schemaAnalyzer);
- $this->tdbmDaoGenerator = new TDBMDaoGenerator($this->getConfiguration(), $tdbmSchemaAnalyzer);
- $this->rootPath = __DIR__.'/../../../../';
- //$this->tdbmDaoGenerator->setComposerFile($this->rootPath.'composer.json');
- }
-
- public function testDaoGeneration()
- {
- // Remove all previously generated files.
- $this->recursiveDelete($this->rootPath.'src/Mouf/Database/TDBM/Test/Dao/');
-
- $this->tdbmDaoGenerator->generateAllDaosAndBeans();
-
- // Let's require all files to check they are valid PHP!
- // Test the daoFactory
- require_once $this->rootPath.'src/Mouf/Database/TDBM/Test/Dao/Generated/DaoFactory.php';
- // Test the others
-
- $beanDescriptors = $this->getDummyGeneratorListener()->getBeanDescriptors();
-
- foreach ($beanDescriptors as $beanDescriptor) {
- $daoName = $beanDescriptor->getDaoClassName();
- $daoBaseName = $beanDescriptor->getBaseDaoClassName();
- $beanName = $beanDescriptor->getBeanClassName();
- $baseBeanName = $beanDescriptor->getBaseBeanClassName();
- require_once $this->rootPath.'src/Mouf/Database/TDBM/Test/Dao/Bean/Generated/'.$baseBeanName.'.php';
- require_once $this->rootPath.'src/Mouf/Database/TDBM/Test/Dao/Bean/'.$beanName.'.php';
- require_once $this->rootPath.'src/Mouf/Database/TDBM/Test/Dao/Generated/'.$daoBaseName.'.php';
- require_once $this->rootPath.'src/Mouf/Database/TDBM/Test/Dao/'.$daoName.'.php';
- }
-
- // Check that pivot tables do not generate DAOs or beans.
- $this->assertFalse(class_exists('Mouf\\Database\\TDBM\\Test\\Dao\\RolesRightDao'));
- }
-
- public function testGenerationException()
- {
- $configuration = new Configuration('UnknownVendor\\Dao', 'UnknownVendor\\Bean', $this->dbConnection, $this->getNamingStrategy());
-
- $schemaManager = $this->tdbmService->getConnection()->getSchemaManager();
- $schemaAnalyzer = new SchemaAnalyzer($schemaManager);
- $tdbmSchemaAnalyzer = new TDBMSchemaAnalyzer($this->tdbmService->getConnection(), new ArrayCache(), $schemaAnalyzer);
- $tdbmDaoGenerator = new TDBMDaoGenerator($configuration, $tdbmSchemaAnalyzer);
- $this->rootPath = __DIR__.'/../../../../';
- //$tdbmDaoGenerator->setComposerFile($this->rootPath.'composer.json');
-
- $this->expectException(NoPathFoundException::class);
- $tdbmDaoGenerator->generateAllDaosAndBeans();
- }
-
- /**
- * Delete a file or recursively delete a directory.
- *
- * @param string $str Path to file or directory
- * @return bool
- */
- private function recursiveDelete(string $str) : bool
- {
- if (is_file($str)) {
- return @unlink($str);
- } elseif (is_dir($str)) {
- $scan = glob(rtrim($str, '/') . '/*');
- foreach ($scan as $index => $path) {
- $this->recursiveDelete($path);
- }
-
- return @rmdir($str);
- }
- return false;
- }
-
- /**
- * @depends testDaoGeneration
- */
- public function testGetBeanClassName()
- {
- $this->assertEquals(UserBean::class, $this->tdbmService->getBeanClassName('users'));
- }
-
- /**
- * @depends testDaoGeneration
- */
- public function testGetBeanClassNameException()
- {
- $this->expectException(TDBMInvalidArgumentException::class);
- $this->tdbmService->getBeanClassName('not_exists');
- }
-
- /**
- * @depends testDaoGeneration
- */
- public function testGeneratedGetById()
- {
- $contactDao = new ContactDao($this->tdbmService);
- $contactBean = $contactDao->getById(1);
- $this->assertEquals(1, $contactBean->getId());
- $this->assertInstanceOf('\\DateTimeInterface', $contactBean->getCreatedAt());
-
- // FIXME: Question: que faire du paramètre stockage "UTC"????
- }
-
- /**
- * @depends testDaoGeneration
- */
- public function testGeneratedGetByIdLazyLoaded()
- {
- $roleDao = new RoleDao($this->tdbmService);
- $roleBean = $roleDao->getById(1, true);
- $this->assertEquals(1, $roleBean->getId());
- $this->assertInstanceOf('\\DateTimeInterface', $roleBean->getCreatedAt());
-
- $roleBean2 = $roleDao->getById(1, true);
- $this->assertTrue($roleBean === $roleBean2);
- }
-
- /**
- * @depends testDaoGeneration
- */
- public function testDefaultValueOnNewBean()
- {
- $roleBean = new RoleBean('my_role');
- $this->assertEquals(1, $roleBean->getStatus());
- }
-
- /**
- * @depends testDaoGeneration
- */
- public function testForeignKeyInBean()
- {
- $userDao = new UserDao($this->tdbmService);
- $userBean = $userDao->getById(1);
- $country = $userBean->getCountry();
-
- $this->assertEquals('UK', $country->getLabel());
-
- $userBean2 = $userDao->getById(1);
- $this->assertTrue($userBean === $userBean2);
-
- $contactDao = new ContactDao($this->tdbmService);
- $contactBean = $contactDao->getById(1);
-
- $this->assertTrue($userBean === $contactBean);
- }
-
- /**
- * @depends testDaoGeneration
- */
- public function testNewBeans()
- {
- $countryDao = new CountryDao($this->tdbmService);
- $userDao = new UserDao($this->tdbmService);
- $userBean = new UserBean('John Doe', 'john@doe.com', $countryDao->getById(2), 'john.doe');
- $userBean->setOrder(1); // Let's set a "protected keyword" column.
-
- $userDao->save($userBean);
-
- $this->assertNull($userBean->getManager());
- }
-
- /**
- * @depends testDaoGeneration
- */
- public function testDateTimeImmutableGetter()
- {
- $userDao = new UserDao($this->tdbmService);
- $user = $userDao->getById(1);
-
- $this->assertInstanceOf('\DateTimeImmutable', $user->getCreatedAt());
- }
-
- /**
- * @depends testDaoGeneration
- */
- public function testAssigningNewBeans()
- {
- $userDao = new UserDao($this->tdbmService);
- $countryBean = new CountryBean('Mexico');
- $userBean = new UserBean('Speedy Gonzalez', 'speedy@gonzalez.com', $countryBean, 'speedy.gonzalez');
- $this->assertEquals($countryBean, $userBean->getCountry());
-
- $userDao->save($userBean);
- }
-
- /**
- * @depends testAssigningNewBeans
- */
- public function testUpdatingProtectedColumn()
- {
- $userDao = new UserDao($this->tdbmService);
- $userBean = $userDao->findOneByLogin('speedy.gonzalez');
- $userBean->setOrder(2);
- $userDao->save($userBean);
- }
-
- /**
- * @depends testDaoGeneration
- */
- public function testAssigningExistingRelationship()
- {
- $userDao = new UserDao($this->tdbmService);
- $user = $userDao->getById(1);
- $countryDao = new CountryDao($this->tdbmService);
- $country = $countryDao->getById(2);
-
- $user->setCountry($country);
- $this->assertEquals(TDBMObjectStateEnum::STATE_DIRTY, $user->_getStatus());
- }
-
- /**
- * @depends testDaoGeneration
- */
- public function testDirectReversedRelationship()
- {
- $countryDao = new CountryDao($this->tdbmService);
- $country = $countryDao->getById(1);
- $users = $country->getUsers();
-
- $arr = $users->toArray();
-
- $this->assertCount(1, $arr);
- $this->assertInstanceOf('Mouf\\Database\\TDBM\\Test\\Dao\\Bean\\UserBean', $arr[0]);
- $this->assertEquals('jean.dupont', $arr[0]->getLogin());
-
- $newUser = new UserBean('Speedy Gonzalez', 'speedy@gonzalez.com', $country, 'speedy.gonzalez');
- $users = $country->getUsers();
-
- $arr = $users->toArray();
-
- $this->assertCount(2, $arr);
- $this->assertInstanceOf('Mouf\\Database\\TDBM\\Test\\Dao\\Bean\\UserBean', $arr[1]);
- $this->assertEquals('speedy.gonzalez', $arr[1]->getLogin());
- }
-
- /**
- * @depends testDaoGeneration
- */
- public function testDeleteInDirectReversedRelationship()
- {
- $countryDao = new CountryDao($this->tdbmService);
- $country = $countryDao->getById(1);
-
- $userDao = new UserDao($this->tdbmService);
- $newUser = new UserBean('John Snow', 'john@snow.com', $country, 'john.snow');
- $userDao->save($newUser);
-
- $users = $country->getUsers();
-
- $arr = $users->toArray();
-
- $this->assertCount(2, $arr);
-
- $userDao->delete($arr[1]);
-
- $users = $country->getUsers();
- $arr = $users->toArray();
- $this->assertCount(1, $arr);
- }
-
- /**
- * @depends testDaoGeneration
- */
- public function testJointureGetters()
- {
- $roleDao = new RoleDao($this->tdbmService);
- $role = $roleDao->getById(1);
- $users = $role->getUsers();
-
- $this->assertCount(2, $users);
- $this->assertInstanceOf('Mouf\\Database\\TDBM\\Test\\Dao\\Bean\\UserBean', $users[0]);
-
- $rights = $role->getRights();
-
- $this->assertCount(2, $rights);
- $this->assertInstanceOf('Mouf\\Database\\TDBM\\Test\\Dao\\Bean\\RightBean', $rights[0]);
- }
-
- /**
- * @depends testDaoGeneration
- */
- public function testNewBeanConstructor()
- {
- $role = new RoleBean('Newrole');
- $this->assertEquals(TDBMObjectStateEnum::STATE_DETACHED, $role->_getStatus());
- }
-
- /**
- * @depends testDaoGeneration
- */
- public function testJointureAdderOnNewBean()
- {
- $countryDao = new CountryDao($this->tdbmService);
- $country = $countryDao->getById(1);
- $user = new UserBean('Speedy Gonzalez', 'speedy@gonzalez.com', $country, 'speedy.gonzalez');
- $role = new RoleBean('Mouse');
- $user->addRole($role);
- $roles = $user->getRoles();
- $this->assertCount(1, $roles);
- $role = $roles[0];
- $this->assertInstanceOf('Mouf\\Database\\TDBM\\Test\\Dao\\Bean\\RoleBean', $role);
- $users = $role->getUsers();
- $this->assertCount(1, $users);
- $this->assertEquals($user, $users[0]);
-
- $role->removeUser($user);
- $this->assertCount(0, $role->getUsers());
- $this->assertCount(0, $user->getRoles());
- }
-
- /**
- * @depends testDaoGeneration
- */
- public function testJointureDeleteBeforeGetters()
- {
- $roleDao = new RoleDao($this->tdbmService);
- $userDao = new UserDao($this->tdbmService);
- $role = $roleDao->getById(1);
- $user = $userDao->getById(1);
-
- // We call removeUser BEFORE calling getUsers
- // This should work as expected.
- $role->removeUser($user);
- $users = $role->getUsers();
-
- $this->assertCount(1, $users);
- }
-
- /**
- * @depends testDaoGeneration
- */
- public function testJointureMultiAdd()
- {
- $countryDao = new CountryDao($this->tdbmService);
- $country = $countryDao->getById(1);
- $user = new UserBean('Speedy Gonzalez', 'speedy@gonzalez.com', $country, 'speedy.gonzalez');
- $role = new RoleBean('Mouse');
- $user->addRole($role);
- $role->addUser($user);
- $user->addRole($role);
-
- $this->assertCount(1, $user->getRoles());
- }
-
- /**
- * Step 1: we remove the role 1 from user 1 but save role 1.
- * Expected result: no save done.
- *
- * @depends testDaoGeneration
- */
- public function testJointureSave1()
- {
- $roleDao = new RoleDao($this->tdbmService);
- $role = $roleDao->getById(1);
- $userDao = new UserDao($this->tdbmService);
- $user = $userDao->getById(1);
-
- $this->assertTrue($user->hasRole($role));
- $this->assertTrue($role->hasUser($user));
- $user->removeRole($role);
- $this->assertFalse($user->hasRole($role));
- $this->assertFalse($role->hasUser($user));
- $roleDao->save($role);
-
- $this->assertEquals(TDBMObjectStateEnum::STATE_DIRTY, $user->_getStatus());
- $this->assertEquals(TDBMObjectStateEnum::STATE_LOADED, $role->_getStatus());
- }
-
- /**
- * Step 2: we check that nothing was saved
- * Expected result: no save done.
- *
- * @depends testJointureSave1
- */
- public function testJointureSave2()
- {
- $roleDao = new RoleDao($this->tdbmService);
- $role = $roleDao->getById(1);
- $this->assertCount(2, $role->getUsers());
- }
-
- /**
- * Step 3: we remove the role 1 from user 1 and save user 1.
- * Expected result: save done.
- *
- * @depends testJointureSave2
- */
- public function testJointureSave3()
- {
- $roleDao = new RoleDao($this->tdbmService);
- $role = $roleDao->getById(1);
- $userDao = new UserDao($this->tdbmService);
- $user = $userDao->getById(1);
-
- $this->assertCount(1, $user->getRoles());
- $user->removeRole($role);
- $this->assertCount(0, $user->getRoles());
- $userDao->save($user);
- $this->assertCount(0, $user->getRoles());
- }
-
- /**
- * Step 4: we check that save was done
- * Expected result: save done.
- *
- * @depends testJointureSave3
- */
- public function testJointureSave4()
- {
- $roleDao = new RoleDao($this->tdbmService);
- $role = $roleDao->getById(1);
- $this->assertCount(1, $role->getUsers());
- $userDao = new UserDao($this->tdbmService);
- $user = $userDao->getById(1);
- $this->assertCount(0, $user->getRoles());
- }
-
- /**
- * Step 5: we add the role 1 from user 1 and save user 1.
- * Expected result: save done.
- *
- * @depends testJointureSave4
- */
- public function testJointureSave5()
- {
- $roleDao = new RoleDao($this->tdbmService);
- $role = $roleDao->getById(1);
- $userDao = new UserDao($this->tdbmService);
- $user = $userDao->getById(1);
-
- $user->addRole($role);
- $this->assertCount(1, $user->getRoles());
- $userDao->save($user);
- }
-
- /**
- * Step 6: we check that save was done
- * Expected result: save done.
- *
- * @depends testJointureSave5
- */
- public function testJointureSave6()
- {
- $roleDao = new RoleDao($this->tdbmService);
- $role = $roleDao->getById(1);
- $this->assertCount(2, $role->getUsers());
- $userDao = new UserDao($this->tdbmService);
- $user = $userDao->getById(1);
- $this->assertCount(1, $user->getRoles());
- }
-
- /**
- * Step 7: we add a new role to user 1 and save user 1.
- * Expected result: save done, including the new role.
- *
- * @depends testJointureSave6
- */
- public function testJointureSave7()
- {
- $role = new RoleBean('my new role');
- $userDao = new UserDao($this->tdbmService);
- $user = $userDao->getById(1);
-
- $user->addRole($role);
- $userDao->save($user);
-
- $this->assertEquals(TDBMObjectStateEnum::STATE_LOADED, $role->_getStatus());
- }
-
- /**
- * Step 8: we check that save was done
- * Expected result: save done.
- *
- * @depends testJointureSave7
- */
- public function testJointureSave8()
- {
- $roleDao = new RoleDao($this->tdbmService);
- $userDao = new UserDao($this->tdbmService);
- $user = $userDao->getById(1);
-
- $roles = $user->getRoles();
- foreach ($roles as $role) {
- if ($role->getName() === 'my new role') {
- $selectedRole = $role;
- break;
- }
- }
- $this->assertNotNull($selectedRole);
-
- $this->assertCount(2, $user->getRoles());
-
- // Expected: relationship removed!
- $roleDao->delete($selectedRole);
-
- $this->assertCount(1, $user->getRoles());
- }
-
- /**
- * Step 9: Let's test the setXXX method.
- *
- * @depends testJointureSave8
- */
- public function testJointureSave9()
- {
- $roleDao = new RoleDao($this->tdbmService);
- $userDao = new UserDao($this->tdbmService);
- $user = $userDao->getById(1);
-
- // At this point, user 1 is linked to role 1.
- // Let's bind it to role 2.
- $user->setRoles([$roleDao->getById(2)]);
- $userDao->save($user);
- }
-
- /**
- * Step 10: Let's check results of 9.
- *
- * @depends testJointureSave9
- */
- public function testJointureSave10()
- {
- $userDao = new UserDao($this->tdbmService);
- $user = $userDao->getById(1);
-
- $roles = $user->getRoles();
-
- $this->assertCount(1, $roles);
- $this->assertEquals(2, $roles[0]->getId());
- }
-
- /**
- * @depends testDaoGeneration
- */
- public function testFindOrderBy()
- {
- $userDao = new TestUserDao($this->tdbmService);
- $users = $userDao->getUsersByAlphabeticalOrder();
-
- $this->assertCount(6, $users);
- $this->assertEquals('bill.shakespeare', $users[0]->getLogin());
- $this->assertEquals('jean.dupont', $users[1]->getLogin());
- }
-
- /**
- * @depends testDaoGeneration
- */
- public function testFindFromSqlOrderBy()
- {
- $userDao = new TestUserDao($this->tdbmService);
- $users = $userDao->getUsersFromSqlByAlphabeticalOrder();
-
- $this->assertCount(6, $users);
- $this->assertEquals('bill.shakespeare', $users[0]->getLogin());
- $this->assertEquals('jean.dupont', $users[1]->getLogin());
- }
-
- /**
- * @depends testDaoGeneration
- */
- public function testFindFromSqlOrderByJoinRole()
- {
- $roleDao = new TestRoleDao($this->tdbmService);
- $roles = $roleDao->getRolesByRightCanSing('roles.name DESC');
-
- $this->assertCount(2, $roles);
- $this->assertEquals('Singers', $roles[0]->getName());
- $this->assertEquals('Admins', $roles[1]->getName());
- }
-
- /**
- * @depends testDaoGeneration
- */
- public function testFindFilters()
- {
- $userDao = new TestUserDao($this->tdbmService);
- $users = $userDao->getUsersByLoginStartingWith('bill');
-
- $this->assertCount(1, $users);
- $this->assertEquals('bill.shakespeare', $users[0]->getLogin());
- }
-
- /**
- * @expectedException \Mouf\Database\TDBM\TDBMException
- * @depends testDaoGeneration
- */
- public function testFindMode()
- {
- $userDao = new TestUserDao($this->tdbmService);
- $users = $userDao->getUsersByLoginStartingWith('bill', TDBMService::MODE_CURSOR);
-
- $users[0];
- }
-
- /**
- * @depends testDaoGeneration
- */
- public function testFindAll()
- {
- $userDao = new TestUserDao($this->tdbmService);
- $users = $userDao->findAll();
-
- $this->assertCount(6, $users);
- }
-
- /**
- * @depends testDaoGeneration
- */
- public function testFindOne()
- {
- $userDao = new TestUserDao($this->tdbmService);
- $user = $userDao->getUserByLogin('bill.shakespeare');
-
- $this->assertEquals('bill.shakespeare', $user->getLogin());
- }
-
- /**
- * @depends testDaoGeneration
- */
- public function testJsonEncodeBean()
- {
- $userDao = new TestUserDao($this->tdbmService);
- $user = $userDao->getUserByLogin('bill.shakespeare');
-
- $jsonEncoded = json_encode($user);
- $userDecoded = json_decode($jsonEncoded, true);
-
- $this->assertEquals('bill.shakespeare', $userDecoded['login']);
-
- // test serialization of dates.
- $this->assertTrue(is_string($userDecoded['createdAt']));
- $this->assertEquals('2015-10-24', (new \DateTimeImmutable($userDecoded['createdAt']))->format('Y-m-d'));
- $this->assertNull($userDecoded['modifiedAt']);
-
- // testing many to 1 relationships
- $this->assertEquals('UK', $userDecoded['country']['label']);
-
- // testing many to many relationships
- $this->assertCount(1, $userDecoded['roles']);
- $this->assertArrayNotHasKey('users', $userDecoded['roles'][0]);
- $this->assertArrayNotHasKey('rights', $userDecoded['roles'][0]);
- }
-
- /**
- * @depends testDaoGeneration
- */
- public function testNullableForeignKey()
- {
- $userDao = new TestUserDao($this->tdbmService);
- $user = $userDao->getUserByLogin('john.smith');
-
- $this->assertNull(null, $user->getManager());
-
- $jsonEncoded = json_encode($user);
- $userDecoded = json_decode($jsonEncoded, true);
-
- $this->assertNull(null, $userDecoded['manager']);
- }
-
- /**
- * Test that setting (and saving) objects' references (foreign keys relations) to null is working.
- *
- * @depends testDaoGeneration
- */
- public function testSetToNullForeignKey()
- {
- $userDao = new TestUserDao($this->tdbmService);
- $user = $userDao->getUserByLogin('john.smith');
- $manager = $userDao->getUserByLogin('jean.dupont');
-
- $user->setManager($manager);
- $userDao->save($user);
-
- $user->setManager(null);
- $userDao->save($user);
- }
-
- /**
- * @depends testDaoGeneration
- * @expectedException \Mouf\Database\SchemaAnalyzer\SchemaAnalyzerTableNotFoundException
- * @expectedExceptionMessage Could not find table 'contacts'. Did you mean 'contact'?
- */
- public function testQueryOnWrongTableName()
- {
- $userDao = new TestUserDao($this->tdbmService);
- $users = $userDao->getUsersWrongTableName();
- $users->count();
- }
-
- /**
- * @depends testDaoGeneration
- */
- /*public function testQueryNullForeignKey()
- {
- $userDao = new TestUserDao($this->tdbmService);
- $users = $userDao->getUsersByManagerId(null);
- $this->assertCount(3, $users);
- }*/
-
- /**
- * @depends testDaoGeneration
- */
- public function testInnerJsonEncode()
- {
- $userDao = new TestUserDao($this->tdbmService);
- $user = $userDao->getUserByLogin('bill.shakespeare');
-
- $jsonEncoded = json_encode(['user' => $user]);
- $msgDecoded = json_decode($jsonEncoded, true);
-
- $this->assertEquals('bill.shakespeare', $msgDecoded['user']['login']);
- }
-
- /**
- * @depends testDaoGeneration
- */
- public function testArrayJsonEncode()
- {
- $userDao = new TestUserDao($this->tdbmService);
- $users = $userDao->getUsersByLoginStartingWith('bill');
-
- $jsonEncoded = json_encode($users);
- $msgDecoded = json_decode($jsonEncoded, true);
-
- $this->assertCount(1, $msgDecoded);
- }
-
- /**
- * @depends testDaoGeneration
- */
- public function testCursorJsonEncode()
- {
- $userDao = new TestUserDao($this->tdbmService);
- $users = $userDao->getUsersByLoginStartingWith('bill', TDBMService::MODE_CURSOR);
-
- $jsonEncoded = json_encode($users);
- $msgDecoded = json_decode($jsonEncoded, true);
-
- $this->assertCount(1, $msgDecoded);
- }
-
- /**
- * @depends testDaoGeneration
- */
- public function testPageJsonEncode()
- {
- $userDao = new TestUserDao($this->tdbmService);
- $users = $userDao->getUsersByLoginStartingWith('bill');
-
- $jsonEncoded = json_encode($users->take(0, 1));
- $msgDecoded = json_decode($jsonEncoded, true);
-
- $this->assertCount(1, $msgDecoded);
- }
-
- /**
- * @depends testDaoGeneration
- */
- public function testFirst()
- {
- $userDao = new TestUserDao($this->tdbmService);
- $users = $userDao->getUsersByLoginStartingWith('bill');
-
- $bill = $users->first();
- $this->assertEquals('bill.shakespeare', $bill->getLogin());
- }
-
- /**
- * @depends testDaoGeneration
- */
- public function testFirstNull()
- {
- $userDao = new TestUserDao($this->tdbmService);
- $users = $userDao->getUsersByLoginStartingWith('mike');
-
- $user = $users->first();
- $this->assertNull($user);
- }
-
- /**
- * @depends testDaoGeneration
- */
- public function testCloneBeanAttachedBean()
- {
- $userDao = new TestUserDao($this->tdbmService);
- $user = $userDao->getUserByLogin('bill.shakespeare');
- $this->assertEquals(4, $user->getId());
- $user2 = clone $user;
- $this->assertNull($user2->getId());
- $this->assertEquals('bill.shakespeare', $user2->getLogin());
- $this->assertEquals('Bill Shakespeare', $user2->getName());
- $this->assertEquals('UK', $user2->getCountry()->getLabel());
-
- // MANY 2 MANY must be duplicated
- $this->assertEquals('Writers', $user2->getRoles()[0]->getName());
-
- // Let's test saving this clone
- $user2->setLogin('william.shakespeare');
- $userDao->save($user2);
-
- $user3 = $userDao->getUserByLogin('william.shakespeare');
- $this->assertTrue($user3 === $user2);
- $userDao->delete($user3);
-
- // Finally, let's test the origin user still exists!
- $user4 = $userDao->getUserByLogin('bill.shakespeare');
- $this->assertEquals('bill.shakespeare', $user4->getLogin());
- }
-
- /**
- * @depends testDaoGeneration
- */
- public function testCloneNewBean()
- {
- $countryDao = new CountryDao($this->tdbmService);
- $roleDao = new RoleDao($this->tdbmService);
- $role = $roleDao->getById(1);
-
- $userBean = new UserBean('John Doe', 'john@doe.com', $countryDao->getById(2), 'john.doe');
- $userBean->addRole($role);
-
- $user2 = clone $userBean;
-
- $this->assertNull($user2->getId());
- $this->assertEquals('john.doe', $user2->getLogin());
- $this->assertEquals('John Doe', $user2->getName());
- $this->assertEquals('UK', $user2->getCountry()->getLabel());
-
- // MANY 2 MANY must be duplicated
- $this->assertEquals($role->getName(), $user2->getRoles()[0]->getName());
- }
-
- /**
- * @depends testDaoGeneration
- */
- public function testCascadeDelete()
- {
- $userDao = new TestUserDao($this->tdbmService);
- $countryDao = new CountryDao($this->tdbmService);
-
- $spain = new CountryBean('Spain');
- $sanchez = new UserBean('Manuel Sanchez', 'manuel@sanchez.com', $spain, 'manuel.sanchez');
-
- $countryDao->save($spain);
- $userDao->save($sanchez);
-
- $speedy2 = $userDao->getUserByLogin('manuel.sanchez');
- $this->assertTrue($sanchez === $speedy2);
-
- $exceptionTriggered = false;
- try {
- $countryDao->delete($spain);
- } catch (ForeignKeyConstraintViolationException $e) {
- $exceptionTriggered = true;
- }
- $this->assertTrue($exceptionTriggered);
-
- $countryDao->delete($spain, true);
-
- // Let's check that speed gonzalez was removed.
- $speedy3 = $userDao->getUserByLogin('manuel.sanchez');
- $this->assertNull($speedy3);
- }
-
- /**
- * @depends testDaoGeneration
- */
- public function testDiscardChanges()
- {
- $contactDao = new ContactDao($this->tdbmService);
- $contactBean = $contactDao->getById(1);
-
- $oldName = $contactBean->getName();
-
- $contactBean->setName('MyNewName');
-
- $contactBean->discardChanges();
-
- $this->assertEquals($oldName, $contactBean->getName());
- }
-
- /**
- * @expectedException \Mouf\Database\TDBM\TDBMException
- * @depends testDaoGeneration
- */
- public function testDiscardChangesOnNewBeanFails()
- {
- $person = new PersonBean('John Foo', new \DateTimeImmutable());
- $person->discardChanges();
- }
-
- /**
- * @expectedException \Mouf\Database\TDBM\TDBMException
- * @depends testDaoGeneration
- */
- public function testDiscardChangesOnDeletedBeanFails()
- {
- $userDao = new TestUserDao($this->tdbmService);
- $countryDao = new CountryDao($this->tdbmService);
-
- $sanchez = new UserBean('Manuel Sanchez', 'manuel@sanchez.com', $countryDao->getById(1), 'manuel.sanchez');
-
- $userDao->save($sanchez);
-
- $userDao->delete($sanchez);
-
- // Cannot discard changes on a bean that is already deleted.
- $sanchez->discardChanges();
- }
-
- /**
- * @depends testDaoGeneration
- */
- public function testUniqueIndexBasedSearch()
- {
- $userDao = new UserDao($this->tdbmService);
- $user = $userDao->findOneByLogin('bill.shakespeare');
-
- $this->assertEquals('bill.shakespeare', $user->getLogin());
- $this->assertEquals('Bill Shakespeare', $user->getName());
- }
-
- /**
- * @depends testDaoGeneration
- */
- public function testMultiColumnsIndexBasedSearch()
- {
- $countryDao = new CountryDao($this->tdbmService);
- $userDao = new UserDao($this->tdbmService);
- $users = $userDao->findByStatusAndCountry('on', $countryDao->getById(1));
-
- $this->assertEquals('jean.dupont', $users[0]->getLogin());
- }
-
- /**
- * @depends testDaoGeneration
- */
- public function testCreationInNullableDate()
- {
- $roleDao = new RoleDao($this->tdbmService);
-
- $role = new RoleBean('newbee');
- $roleDao->save($role);
-
- $this->assertNull($role->getCreatedAt());
- }
-
- /**
- * @depends testDaoGeneration
- */
- public function testUpdateInNullableDate()
- {
- $roleDao = new RoleDao($this->tdbmService);
-
- $role = new RoleBean('newbee');
- $roleDao->save($role);
-
- $role->setCreatedAt(null);
- $roleDao->save($role);
- $this->assertNull($role->getCreatedAt());
- }
-
- /**
- * @depends testDaoGeneration
- */
- public function testFindFromSql()
- {
- $roleDao = new TestRoleDao($this->tdbmService);
-
- $roles = $roleDao->getRolesByRightCanSing();
- $this->assertCount(2, $roles);
- $this->assertInstanceOf(RoleBean::class, $roles[0]);
- }
-
- /**
- * @depends testDaoGeneration
- */
- public function testFindOneFromSql()
- {
- $roleDao = new TestRoleDao($this->tdbmService);
-
- $role = $roleDao->getRoleByRightCanSingAndNameSinger();
- $this->assertInstanceOf(RoleBean::class, $role);
- }
-
- /**
- * @depends testDaoGeneration
- */
- public function testCreateEmptyExtendedBean()
- {
- // This test cases checks issue https://github.com/thecodingmachine/database.tdbm/issues/92
-
- $dogDao = new DogDao($this->tdbmService);
-
- // We are not filling no field that is part of dog table.
- $dog = new DogBean('Youki');
- $dog->setOrder(1);
-
- $dogDao->save($dog);
- }
-
- /**
- * @depends testCreateEmptyExtendedBean
- */
- public function testFetchEmptyExtendedBean()
- {
- // This test cases checks issue https://github.com/thecodingmachine/database.tdbm/issues/92
-
- $animalDao = new AnimalDao($this->tdbmService);
-
- // We are not filling no field that is part of dog table.
- $animalBean = $animalDao->getById(1);
-
- $this->assertInstanceOf(DogBean::class, $animalBean);
- }
-
- /**
- * @depends testDaoGeneration
- */
- public function testTwoBranchesHierarchy()
- {
- // This test cases checks issue https://github.com/thecodingmachine/mouf/issues/131
-
- $catDao = new CatDao($this->tdbmService);
-
- // We are not filling no field that is part of dog table.
- $cat = new CatBean('Mew');
- $cat->setOrder(2);
-
- $catDao->save($cat);
- }
-
- /**
- * @depends testTwoBranchesHierarchy
- */
- public function testFetchTwoBranchesHierarchy()
- {
- // This test cases checks issue https://github.com/thecodingmachine/mouf/issues/131
-
- $animalDao = new AnimalDao($this->tdbmService);
-
- $animalBean = $animalDao->getById(2);
-
- $this->assertInstanceOf(CatBean::class, $animalBean);
- /* @var $animalBean CatBean */
- $animalBean->setCutenessLevel(999);
-
- $animalDao->save($animalBean);
- }
-
- /**
- * @depends testDaoGeneration
- */
- public function testExceptionOnGetById()
- {
- $countryDao = new CountryDao($this->tdbmService);
- $this->expectException(\TypeError::class);
- $countryDao->getById(null);
- }
-
- /**
- * @depends testDaoGeneration
- */
- public function testDisconnectedManyToOne()
- {
- // This test cases checks issue https://github.com/thecodingmachine/database.tdbm/issues/99
-
- $country = new CountryBean('Spain');
-
- $user = new UserBean('John Doe', 'john@doe.com', $country, 'john.doe');
-
- $this->assertCount(1, $country->getUsers());
- $this->assertSame($user, $country->getUsers()[0]);
- }
-
- /**
- * @depends testDaoGeneration
- */
- public function testOrderByExternalCol()
- {
- // This test cases checks issue https://github.com/thecodingmachine/database.tdbm/issues/106
-
- $userDao = new TestUserDao($this->tdbmService);
- $users = $userDao->getUsersByCountryName();
-
- $this->assertEquals('UK', $users[0]->getCountry()->getLabel());
- }
-
- /**
- * @depends testDaoGeneration
- */
- public function testResultIteratorSort()
- {
- $userDao = new UserDao($this->tdbmService);
- $users = $userDao->findAll()->withOrder('country.label DESC');
-
- $this->assertEquals('UK', $users[0]->getCountry()->getLabel());
-
- $users = $users->withOrder('country.label ASC');
- $this->assertEquals('France', $users[0]->getCountry()->getLabel());
- }
-
- /**
- * @depends testDaoGeneration
- */
- public function testResultIteratorWithParameters()
- {
- $userDao = new TestUserDao($this->tdbmService);
- $users = $userDao->getUsersByLoginStartingWith()->withParameters(['login' => 'bill%']);
- $this->assertEquals('bill.shakespeare', $users[0]->getLogin());
-
- $users = $users->withParameters(['login' => 'jean%']);
- $this->assertEquals('jean.dupont', $users[0]->getLogin());
- }
-
- /**
- * @depends testDaoGeneration
- */
- public function testOrderByExpression()
- {
- $userDao = new TestUserDao($this->tdbmService);
- $users = $userDao->getUsersByReversedCountryName();
-
- $this->assertEquals('Jamaica', $users[0]->getCountry()->getLabel());
- }
-
- /**
- * @depends testDaoGeneration
- */
- public function testOrderByException()
- {
- $userDao = new TestUserDao($this->tdbmService);
- $users = $userDao->getUsersByInvalidOrderBy();
- $this->expectException(TDBMInvalidArgumentException::class);
- $user = $users[0];
- }
-
- /**
- * @depends testDaoGeneration
- */
- public function testOrderByProtectedColumn()
- {
- $animalDao = new AnimalDao($this->tdbmService);
- $animals = $animalDao->findAll();
- $animals = $animals->withOrder('`order` ASC');
-
- $this->assertInstanceOf(DogBean::class, $animals[0]);
- $this->assertInstanceOf(CatBean::class, $animals[1]);
-
- $animals = $animals->withOrder('`order` DESC');
-
- $this->assertInstanceOf(CatBean::class, $animals[0]);
- $this->assertInstanceOf(DogBean::class, $animals[1]);
- }
-
- /**
- * @depends testDaoGeneration
- */
- public function testGetOnAllNullableValues()
- {
- // Tests that a get performed on a column that has only nullable fields succeeds.
- $allNullable = new AllNullableBean();
- $this->assertNull($allNullable->getId());
- $this->assertNull($allNullable->getLabel());
- $this->assertNull($allNullable->getCountry());
- }
-
- /**
- * @depends testDaoGeneration
- */
- public function testExceptionOnMultipleInheritance()
- {
- $this->dbConnection->insert('animal', [
- 'id' => 99, 'name' => 'Snoofield',
- ]);
- $this->dbConnection->insert('dog', [
- 'id' => 99, 'race' => 'dog',
- ]);
- $this->dbConnection->insert('cat', [
- 'id' => 99, 'cuteness_level' => 0,
- ]);
-
- $catched = false;
- try {
- $animalDao = new AnimalDao($this->tdbmService);
- $animalDao->getById(99);
- } catch (TDBMInheritanceException $e) {
- $catched = true;
- }
- $this->assertTrue($catched, 'Exception TDBMInheritanceException was not catched');
-
- $this->dbConnection->delete('cat', ['id' => 99]);
- $this->dbConnection->delete('dog', ['id' => 99]);
- $this->dbConnection->delete('animal', ['id' => 99]);
- }
-
- /**
- * @depends testDaoGeneration
- */
- public function testReferenceNotSaved()
- {
- $boatDao = new BoatDao($this->tdbmService);
-
- $country = new CountryBean('Atlantis');
- $boat = new BoatBean($country, 'Titanic');
-
- $boatDao->save($boat);
- }
-
- /**
- * @depends testDaoGeneration
- */
- public function testReferenceDeleted()
- {
- $countryDao = new CountryDao($this->tdbmService);
- $boatDao = new BoatDao($this->tdbmService);
-
- $country = new CountryBean('Atlantis');
- $countryDao->save($country);
-
- $boat = new BoatBean($country, 'Titanic');
- $countryDao->delete($country);
-
- $this->expectException(TDBMMissingReferenceException::class);
- $boatDao->save($boat);
- }
-
- /**
- * @depends testDaoGeneration
- */
- public function testCyclicReferenceWithInheritance()
- {
- $userDao = new UserDao($this->tdbmService);
-
- $country = new CountryBean('Norrisland');
- $user = new UserBean('Chuck Norris', 'chuck@norris.com', $country, 'chuck.norris');
-
- $user->setManager($user);
-
- $this->expectException(TDBMCyclicReferenceException::class);
- $userDao->save($user);
- }
-
- /**
- * @depends testDaoGeneration
- */
- public function testCyclicReference()
- {
- $categoryDao = new CategoryDao($this->tdbmService);
-
- $category = new CategoryBean('Root');
-
- $category->setParent($category);
-
- $this->expectException(TDBMCyclicReferenceException::class);
- $categoryDao->save($category);
- }
-
- /**
- * @depends testDaoGeneration
- */
- public function testCorrectTypeForPrimaryKeyAfterSave()
- {
- $allNullableDao = new AllNullableDao($this->tdbmService);
- $allNullable = new AllNullableBean();
- $allNullableDao->save($allNullable);
- $id = $allNullable->getId();
-
- $this->assertTrue(is_int($id));
- }
-
- /**
- * @depends testDaoGeneration
- */
- public function testPSR2Compliance()
- {
- $process = new Process('vendor/bin/php-cs-fixer fix src/Mouf/Database/TDBM/Test/ --dry-run --diff --rules=@PSR2');
- $process->run();
-
- // executes after the command finishes
- if (!$process->isSuccessful()) {
- echo $process->getOutput();
- $this->fail('Generated code is not PRS2 compliant');
- }
- }
-
- /**
- * @depends testDaoGeneration
- */
- public function testFindOneByGeneration()
- {
- $reflectionMethod = new \ReflectionMethod(UserBaseDao::class, 'findOneByLogin');
- $parameters = $reflectionMethod->getParameters();
-
- $this->assertCount(2, $parameters);
- $this->assertSame('login', $parameters[0]->getName());
- $this->assertSame('additionalTablesFetch', $parameters[1]->getName());
- }
-}
diff --git a/tests/Mouf/Database/TDBM/TDBMSchemaAnalyzerTest.php b/tests/Mouf/Database/TDBM/TDBMSchemaAnalyzerTest.php
deleted file mode 100644
index fc317cb..0000000
--- a/tests/Mouf/Database/TDBM/TDBMSchemaAnalyzerTest.php
+++ /dev/null
@@ -1,118 +0,0 @@
-dbConnection->getSchemaManager(), new ArrayCache(), 'prefix_');
- $this->tdbmSchemaAnalyzer = new TDBMSchemaAnalyzer($this->dbConnection, new ArrayCache(), $schemaAnalyzer);
- }
-
- public function testGetSchema()
- {
- $schemaAnalyzer = new SchemaAnalyzer($this->dbConnection->getSchemaManager(), new ArrayCache(), 'prefix_');
- $cache = new ArrayCache();
- $tdbmSchemaAnalyzer1 = new TDBMSchemaAnalyzer($this->dbConnection, $cache, $schemaAnalyzer);
- $tdbmSchemaAnalyzer2 = new TDBMSchemaAnalyzer($this->dbConnection, $cache, $schemaAnalyzer);
-
- // Why don't we go in all lines of code????
- $schema1 = $tdbmSchemaAnalyzer1->getSchema();
- // One more time to go through cache!
- $schema2 = $tdbmSchemaAnalyzer2->getSchema();
- $this->assertTrue($schema1 === $schema2);
- }
-
- public function testGetIncomingForeignKeys()
- {
- $schemaAnalyzer = new SchemaAnalyzer($this->dbConnection->getSchemaManager(), new ArrayCache(), 'prefix_');
- $cache = new ArrayCache();
- $tdbmSchemaAnalyzer = new TDBMSchemaAnalyzer($this->dbConnection, $cache, $schemaAnalyzer);
-
- $fks = $tdbmSchemaAnalyzer->getIncomingForeignKeys('users');
- $this->assertCount(0, $fks);
- }
-
- public function testGetIncomingForeignKeys2()
- {
- $schemaAnalyzer = new SchemaAnalyzer($this->dbConnection->getSchemaManager(), new ArrayCache(), 'prefix_');
- $cache = new ArrayCache();
- $tdbmSchemaAnalyzer = new TDBMSchemaAnalyzer($this->dbConnection, $cache, $schemaAnalyzer);
-
- $fks = $tdbmSchemaAnalyzer->getIncomingForeignKeys('contact');
- $this->assertCount(1, $fks);
- }
-
- public function testGetIncomingForeignKeys3()
- {
- $schemaAnalyzer = new SchemaAnalyzer($this->dbConnection->getSchemaManager(), new ArrayCache(), 'prefix_');
- $cache = new ArrayCache();
- $tdbmSchemaAnalyzer = new TDBMSchemaAnalyzer($this->dbConnection, $cache, $schemaAnalyzer);
-
- $fks = $tdbmSchemaAnalyzer->getIncomingForeignKeys('country');
- $this->assertCount(3, $fks);
- $tables = [$fks[0]->getLocalTableName(), $fks[1]->getLocalTableName(), $fks[2]->getLocalTableName()];
- $this->assertContains('users', $tables);
- $this->assertContains('all_nullable', $tables);
- $this->assertContains('boats', $tables);
- }
-
- public function testGetPivotTableLinkedToTable()
- {
- $schemaAnalyzer = new SchemaAnalyzer($this->dbConnection->getSchemaManager(), new ArrayCache(), 'prefix_');
- $cache = new ArrayCache();
- $tdbmSchemaAnalyzer = new TDBMSchemaAnalyzer($this->dbConnection, $cache, $schemaAnalyzer);
-
- $pivotTables = $tdbmSchemaAnalyzer->getPivotTableLinkedToTable('rights');
- $this->assertCount(1, $pivotTables);
- $this->assertEquals('roles_rights', $pivotTables[0]);
-
- $pivotTables = $tdbmSchemaAnalyzer->getPivotTableLinkedToTable('animal');
- $this->assertCount(0, $pivotTables);
-
- $pivotTables = $tdbmSchemaAnalyzer->getPivotTableLinkedToTable('animal');
- $this->assertCount(0, $pivotTables);
- }
-
- /*public function testGetCompulsoryColumnsWithNoInheritance() {
- $table = $this->tdbmSchemaAnalyzer->getSchema()->getTable('country');
- $compulsoryColumns = $this->tdbmSchemaAnalyzer->getCompulsoryProperties($table);
- $this->assertCount(1, $compulsoryColumns);
- $this->assertArrayHasKey("label", $compulsoryColumns);
- }
-
- public function testGetCompulsoryColumnsWithInheritance() {
- $table = $this->tdbmSchemaAnalyzer->getSchema()->getTable('users');
- $compulsoryColumns = $this->tdbmSchemaAnalyzer->getCompulsoryProperties($table);
- $this->assertCount(5, $compulsoryColumns);
- $this->assertEquals(['name', 'created_at', 'email', 'country_id', 'login'], array_keys($compulsoryColumns));
- }*/
-}
diff --git a/tests/Mouf/Database/TDBM/TDBMServiceTest.php b/tests/Mouf/Database/TDBM/TDBMServiceTest.php
deleted file mode 100644
index 0e1c36e..0000000
--- a/tests/Mouf/Database/TDBM/TDBMServiceTest.php
+++ /dev/null
@@ -1,792 +0,0 @@
-assertEquals(['users', 'contact', 'person'], $this->tdbmService->_getLinkBetweenInheritedTables(['contact', 'users']));
- $this->assertEquals(['users', 'contact', 'person'], $this->tdbmService->_getLinkBetweenInheritedTables(['users', 'contact']));
- $this->assertEquals(['contact', 'person'], $this->tdbmService->_getLinkBetweenInheritedTables(['person', 'contact']));
- $this->assertEquals(['users', 'contact', 'person'], $this->tdbmService->_getLinkBetweenInheritedTables(['users']));
- $this->assertEquals(['person'], $this->tdbmService->_getLinkBetweenInheritedTables(['person']));
- }
-
- public function testGetRelatedTablesByInheritance()
- {
- $contactRelatedTables = $this->tdbmService->_getRelatedTablesByInheritance('contact');
- $this->assertCount(3, $contactRelatedTables);
- $this->assertContains('users', $contactRelatedTables);
- $this->assertContains('contact', $contactRelatedTables);
- $this->assertContains('person', $contactRelatedTables);
- $this->assertEquals(['person', 'contact', 'users'], $this->tdbmService->_getRelatedTablesByInheritance('users'));
- $this->assertEquals(['person', 'contact', 'users'], $this->tdbmService->_getRelatedTablesByInheritance('person'));
- }
-
- /**
- * @expectedException \Mouf\Database\TDBM\TDBMException
- *
- * @throws TDBMException
- */
- public function testGetPrimaryKeysFromIndexedPrimaryKeysException()
- {
- $this->tdbmService->_getPrimaryKeysFromIndexedPrimaryKeys('users', [5, 4]);
- }
-
- /**
- * @expectedException \Mouf\Database\TDBM\TDBMException
- *
- * @throws TDBMException
- */
- public function testGetLinkBetweenInheritedTablesExceptions()
- {
- $this->tdbmService->_getLinkBetweenInheritedTables(['contact', 'country']);
- }
-
- public function testHashPrimaryKey()
- {
- $reflection = new \ReflectionClass(get_class($this->tdbmService));
- $method = $reflection->getMethod('getObjectHash');
- $method->setAccessible(true);
-
- $result = $method->invokeArgs($this->tdbmService, [
- ['id' => 42],
- ]);
- $this->assertEquals(42, $result);
-
- // Check that multiple primary keys are insensitive to column order
- $result1 = $method->invokeArgs($this->tdbmService, [
- ['id1' => 42, 'id2' => 24],
- ]);
- $result2 = $method->invokeArgs($this->tdbmService, [
- ['id2' => 24, 'id1' => 42],
- ]);
- $this->assertEquals($result1, $result2);
- }
-
- public function testInsertAndUpdateAndDelete()
- {
- $object = new TDBMObject('users');
- $object->setProperty('login', 'john.doe');
- $object->setProperty('country_id', 3);
- $object->setProperty('name', 'John Doe', 'person');
- $object->setProperty('email', 'john@doe.com', 'contact');
-
- $this->tdbmService->save($object);
-
- $this->assertNotEmpty($object->getProperty('id', 'person'));
- $this->assertNotEmpty($object->getProperty('id', 'users'));
- $this->assertEquals($object->getProperty('id', 'person'), $object->getProperty('id', 'users'));
-
- $object->setProperty('country_id', 2, 'users');
-
- $this->tdbmService->save($object);
-
- $this->tdbmService->delete($object);
- }
-
- public function testInsertMultipleDataAtOnceInInheritance()
- {
- $object = new TDBMObject();
- $object->setProperty('login', 'jane.doe', 'users');
- $object->setProperty('name', 'Jane Doe', 'person');
- $object->setProperty('country_id', 1, 'users');
- $object->setProperty('email', 'jane@doe.com', 'contact');
-
- $this->tdbmService->save($object);
-
- $this->assertNotEmpty($object->getProperty('id', 'person'));
- $this->assertNotEmpty($object->getProperty('id', 'users'));
- $this->assertEquals($object->getProperty('id', 'person'), $object->getProperty('id', 'users'));
- }
-
- public function testCompleteSave()
- {
- $beans = $this->tdbmService->findObjects('users', 'users.login = :login', ['login' => 'jane.doe'], null, [], null, TDBMObject::class);
- $jane = $beans[0];
- $jane->setProperty('country_id', 2, 'users');
-
- $this->tdbmService->completeSave();
- }
-
- public function testCompleteSave2()
- {
- $beans = $this->tdbmService->findObjects('users', 'users.login = :login', ['login' => 'jane.doe'], null, [], null, TDBMObject::class);
- $jane = $beans[0];
-
- $this->assertEquals(2, $jane->getProperty('country_id', 'users'));
- }
-
- public function testUpdatePrimaryKey()
- {
- $object = new TDBMObject('rights');
- $object->setProperty('label', 'CAN_EDIT_BOUK');
-
- $this->tdbmService->save($object);
-
- $object->setProperty('label', 'CAN_EDIT_BOOK');
-
- $this->tdbmService->save($object);
- }
-
- /**
- * @expectedException \Mouf\Database\TDBM\TDBMInvalidOperationException
- *
- * @throws TDBMInvalidOperationException
- */
- public function testCannotDeleteDetachedObjects()
- {
- $object = new TDBMObject('rights');
- $object->setProperty('label', 'CAN_DELETE');
-
- $this->tdbmService->delete($object);
- }
-
- public function testDeleteNewObject()
- {
- $object = new TDBMObject('rights');
- $object->setProperty('label', 'CAN_DELETE');
-
- $this->tdbmService->attach($object);
-
- $this->tdbmService->delete($object);
-
- $exceptionRaised = false;
- try {
- $this->tdbmService->save($object);
- } catch (TDBMInvalidOperationException $e) {
- $exceptionRaised = true;
- }
- $this->assertTrue($exceptionRaised);
- }
-
- public function testDeleteLoadedObject()
- {
- $object = new TDBMObject('rights');
- $object->setProperty('label', 'CAN_DELETE');
-
- $this->tdbmService->save($object);
-
- $object->setProperty('label', 'CAN_DELETE2');
-
- $this->tdbmService->delete($object);
-
- // Try to delete a deleted object (this should do nothing)
- $this->tdbmService->delete($object);
- }
-
- public function testFindObjects()
- {
- /*$magicQuery = new MagicQuery($this->tdbmService->getConnection());
- $result = $magicQuery->parse("SELECT DISTINCT users.id, users.login FROM users");
- var_dump($result);*/
-
- $beans = $this->tdbmService->findObjects('contact', null, [], 'contact.id ASC', [], null, TDBMObject::class);
- $beans2 = $this->tdbmService->findObjects('contact', 'contact.id = :id', ['id' => 1], null, [], null, TDBMObject::class);
-
- foreach ($beans as $bean) {
- $bean1 = $bean;
- break;
- }
-
- foreach ($beans2 as $bean) {
- $bean2 = $bean;
- break;
- }
-
- $this->assertTrue($bean1 === $bean2);
- $this->assertEquals(5, $beans->count());
- $this->assertEquals(1, $beans2->count());
-
- //$this->assertTrue($beans[0] === $beans2[0]);
- //var_dump($beans);
- }
-
- public function testArrayAccess()
- {
- $beans = $this->tdbmService->findObjects('contact', null, [], 'contact.id ASC', [], null, TDBMObject::class);
-
- $this->assertTrue(isset($beans[0]));
- $this->assertFalse(isset($beans[42]));
- $this->assertEquals(1, $beans[0]->getProperty('id', 'person'));
-
- $result1 = [];
- foreach ($beans as $bean) {
- $result1[] = $bean;
- }
-
- $result2 = [];
- foreach ($beans as $bean) {
- $result2[] = $bean;
- }
-
- $this->assertEquals($result1, $result2);
- $this->assertTrue($result1[0] === $result2[0]);
- }
-
- /**
- * @expectedException \Mouf\Database\TDBM\TDBMInvalidOffsetException
- *
- * @throws TDBMInvalidOffsetException
- */
- public function testArrayAccessException()
- {
- $beans = $this->tdbmService->findObjects('contact', null, [], 'contact.id ASC', [], null, TDBMObject::class);
-
- $beans[-1];
- }
-
- /**
- * @expectedException \Mouf\Database\TDBM\TDBMInvalidOffsetException
- *
- * @throws TDBMInvalidOffsetException
- */
- public function testArrayAccessException2()
- {
- $beans = $this->tdbmService->findObjects('contact', null, [], 'contact.id ASC', [], null, TDBMObject::class);
-
- $beans['foo'];
- }
-
- /**
- * @expectedException \Mouf\Database\TDBM\TDBMException
- *
- * @throws TDBMException
- */
- public function testBeanGetException()
- {
- $beans = $this->tdbmService->findObjects('contact', null, [], 'contact.id ASC', [], null, TDBMObject::class);
- $bean = $beans[0];
-
- // we don't specify the table on inheritance table => exception.
- $bean->getProperty('id');
- }
-
- /**
- * @expectedException \Mouf\Database\TDBM\TDBMException
- *
- * @throws TDBMException
- */
- public function testBeanSetException()
- {
- $beans = $this->tdbmService->findObjects('contact', null, [], 'contact.id ASC', [], null, TDBMObject::class);
- $bean = $beans[0];
-
- // we don't specify the table on inheritance table => exception.
- $bean->setProperty('name', 'foo');
- }
-
- public function testTake()
- {
- $beans = $this->tdbmService->findObjects('contact', null, [], 'contact.id ASC', [], null, TDBMObject::class);
-
- $page = $beans->take(0, 2);
-
- $this->assertEquals(2, $page->count());
-
- $results = [];
- foreach ($page as $result) {
- $results[] = $result;
- }
- $this->assertCount(2, $results);
-
- $this->assertEquals(5, $page->totalCount());
-
- $page = $beans->take(1, 1);
-
- $this->assertEquals(1, $page->count());
-
- $resultArray = $page->toArray();
- $this->assertCount(1, $resultArray);
- $this->assertTrue($resultArray[0] === $page[0]);
- // Test page isset
- $this->assertTrue(isset($page[0]));
- }
-
- public function testTakeInCursorMode()
- {
- $beans = $this->tdbmService->findObjects('contact', null, [], 'contact.id ASC', [], TDBMService::MODE_CURSOR, TDBMObject::class);
-
- $page = $beans->take(0, 2);
-
- $this->assertEquals(2, $page->count());
- $this->assertEquals(0, $page->getCurrentOffset());
- $this->assertEquals(2, $page->getCurrentLimit());
- $this->assertEquals(1, $page->getCurrentPage());
-
- $results = [];
- foreach ($page as $result) {
- $results[] = $result;
- }
- $this->assertCount(2, $results);
-
- $this->assertEquals(5, $page->totalCount());
-
- $page = $beans->take(1, 1);
- $this->assertEquals(1, $page->getCurrentOffset());
- $this->assertEquals(1, $page->getCurrentLimit());
- $this->assertEquals(2, $page->getCurrentPage());
-
- $this->assertEquals(1, $page->count());
- }
-
- public function testMap()
- {
- $beans = $this->tdbmService->findObjects('person', null, [], 'person.id ASC', [], null, TDBMObject::class);
-
- $results = $beans->map(function ($item) {
- return $item->getProperty('id', 'person');
- })->toArray();
-
- $this->assertEquals([1, 2, 3, 4, 6], $results);
-
- // Same test with page
- $page = $beans->take(0, 2);
-
- $results = $page->map(function ($item) {
- return $item->getProperty('id', 'person');
- })->toArray();
-
- $this->assertEquals([1, 2], $results);
- }
-
- /**
- * @expectedException \Mouf\Database\TDBM\TDBMException
- *
- * @throws TDBMException
- */
- public function testUnsetException()
- {
- $beans = $this->tdbmService->findObjects('contact', null, [], 'contact.id ASC', [], null, TDBMObject::class);
-
- unset($beans[0]);
- }
-
- /**
- * @expectedException \Mouf\Database\TDBM\TDBMException
- *
- * @throws TDBMException
- */
- public function testSetException()
- {
- $beans = $this->tdbmService->findObjects('contact', null, [], 'contact.id ASC', [], null, TDBMObject::class);
-
- $beans[0] = 'foo';
- }
-
- /**
- * @expectedException \Mouf\Database\TDBM\TDBMException
- *
- * @throws TDBMException
- */
- public function testPageUnsetException()
- {
- $beans = $this->tdbmService->findObjects('contact', null, [], 'contact.id ASC', [], null, TDBMObject::class);
- $page = $beans->take(0, 1);
- unset($page[0]);
- }
-
- /**
- * @expectedException \Mouf\Database\TDBM\TDBMException
- *
- * @throws TDBMException
- */
- public function testPageSetException()
- {
- $beans = $this->tdbmService->findObjects('contact', null, [], 'contact.id ASC', [], null, TDBMObject::class);
- $page = $beans->take(0, 1);
- $page[0] = 'foo';
- }
-
- public function testToArray()
- {
- $beans = $this->tdbmService->findObjects('contact', 'contact.id = :id', ['id' => 1], null, [], null, TDBMObject::class);
-
- $beanArray = $beans->toArray();
-
- $this->assertCount(1, $beanArray);
- $this->assertEquals(1, $beanArray[0]->getProperty('id', 'contact'));
- }
-
- public function testCursorMode()
- {
- $beans = $this->tdbmService->findObjects('contact', 'contact.id = :id', ['id' => 1], null, [], TDBMService::MODE_CURSOR, TDBMObject::class);
-
- $this->assertInstanceOf('\\Mouf\\Database\\TDBM\\ResultIterator', $beans);
-
- $result = [];
- foreach ($beans as $bean) {
- $result[] = $bean;
- }
-
- $this->assertCount(1, $result);
-
- // In cursor mode, access by array causes an exception.
- $exceptionTriggered = false;
- try {
- $beans[0];
- } catch (TDBMInvalidOperationException $e) {
- $exceptionTriggered = true;
- }
- $this->assertTrue($exceptionTriggered);
-
- $exceptionTriggered = false;
- try {
- isset($beans[0]);
- } catch (TDBMInvalidOperationException $e) {
- $exceptionTriggered = true;
- }
- $this->assertTrue($exceptionTriggered);
- }
-
- public function testSetFetchMode()
- {
- $this->tdbmService->setFetchMode(TDBMService::MODE_CURSOR);
- $beans = $this->tdbmService->findObjects('contact', 'contact.id = :id', ['id' => 1], null, [], null, TDBMObject::class);
-
- $this->assertInstanceOf('\\Mouf\\Database\\TDBM\\ResultIterator', $beans);
-
- // In cursor mode, access by array causes an exception.
- $exceptionTriggered = false;
- try {
- $beans[0];
- } catch (TDBMInvalidOperationException $e) {
- $exceptionTriggered = true;
- }
- $this->assertTrue($exceptionTriggered);
- }
-
- /**
- * @expectedException \Mouf\Database\TDBM\TDBMException
- *
- * @throws TDBMException
- */
- public function testInvalidSetFetchMode()
- {
- $this->tdbmService->setFetchMode('foo');
- }
-
- /**
- * @expectedException \Mouf\Database\TDBM\TDBMException
- *
- * @throws TDBMException
- */
- public function testCursorModeException()
- {
- $beans = $this->tdbmService->findObjects('contact', 'contact.id = :id', ['id' => 1], null, [], 'foobaz');
- }
-
- /**
- * @expectedException \Mouf\Database\TDBM\TDBMException
- *
- * @throws TDBMException
- */
- public function testTableNameException()
- {
- $beans = $this->tdbmService->findObjects('foo bar');
- }
-
- public function testLinkedTableFetch()
- {
- $beans = $this->tdbmService->findObjects('contact', 'contact.id = :id', ['id' => 1], null, ['country'], null, TDBMObject::class);
- }
-
- public function testFindObject()
- {
- $bean = $this->tdbmService->findObject('contact', 'contact.id = :id', ['id' => -42], [], TDBMObject::class);
- $this->assertNull($bean);
- }
-
- /**
- * @expectedException \Mouf\Database\TDBM\NoBeanFoundException
- *
- * @throws NoBeanFoundException
- */
- public function testFindObjectOrFail()
- {
- $bean = $this->tdbmService->findObjectOrFail('contact', 'contact.id = :id', ['id' => -42], [], TDBMObject::class);
- }
-
- /**
- * @expectedException \Mouf\Database\TDBM\DuplicateRowException
- *
- * @throws DuplicateRowException
- */
- public function testFindObjectDuplicateRow()
- {
- $bean = $this->tdbmService->findObject('contact');
- }
-
- public function testFindObjectsByBean()
- {
- $countryBean = $this->tdbmService->findObject('country', 'id = :id', ['id' => 1], [], TDBMObject::class);
-
- $users = $this->tdbmService->findObjects('users', $countryBean, [], null, [], null, TDBMObject::class);
- $this->assertCount(1, $users);
- $this->assertEquals('jean.dupont', $users[0]->getProperty('login', 'users'));
- }
-
- /**
- * @expectedException \Mouf\Database\TDBM\TDBMException
- *
- * @throws TDBMException
- * @throws TDBMInvalidOperationException
- */
- public function testBeanWithoutStatus()
- {
- $object = new TDBMObject('users');
- $object->setProperty('login', 'john.doe');
- $object->setProperty('country_id', 3);
- $object->setProperty('name', 'John Doe', 'person');
- $object->setProperty('email', 'john@doe.com', 'contact');
- $object->_setStatus(null);
- $this->tdbmService->save($object);
- }
-
- public function testFindObjectsFromSql()
- {
- $roles = $this->tdbmService->findObjectsFromSql('roles', 'roles JOIN roles_rights ON roles.id = roles_rights.role_id JOIN rights ON rights.label = roles_rights.right_label',
- 'rights.label = :right', array('right' => 'CAN_SING'), 'name DESC');
- $this->assertCount(2, $roles);
- $this->assertInstanceOf(AbstractTDBMObject::class, $roles[0]);
- }
-
- /**
- * @expectedException \Mouf\Database\TDBM\TDBMException
- *
- * @throws TDBMException
- */
- public function testFindObjectsFromSqlBadTableName()
- {
- $this->tdbmService->findObjectsFromSql('#{azerty', 'roles JOIN roles_rights ON roles.id = roles_rights.role_id JOIN rights ON rights.label = roles_rights.right_label',
- 'rights.label = :right', array('right' => 'CAN_SING'), 'name DESC');
- }
-
- /**
- * @expectedException \Mouf\Database\TDBM\TDBMException
- *
- * @throws TDBMException
- */
- public function testFindObjectsFromSqlGroupBy()
- {
- $roles = $this->tdbmService->findObjectsFromSql('roles', 'roles JOIN roles_rights ON roles.id = roles_rights.role_id JOIN rights ON rights.label = roles_rights.right_label',
- 'rights.label = :right GROUP BY roles.name', array('right' => 'CAN_SING'), 'name DESC');
- $role = $roles[0];
- }
-
- public function testFindObjectFromSql()
- {
- $role = $this->tdbmService->findObjectFromSql('roles', 'roles JOIN roles_rights ON roles.id = roles_rights.role_id JOIN rights ON rights.label = roles_rights.right_label',
- 'rights.label = :right AND name = :name', array('right' => 'CAN_SING', 'name' => 'Singers'));
- $this->assertInstanceOf(AbstractTDBMObject::class, $role);
- }
-
- /**
- * @expectedException \Mouf\Database\TDBM\DuplicateRowException
- *
- * @throws DuplicateRowException
- */
- public function testFindObjectFromSqlException()
- {
- $this->tdbmService->findObjectFromSql('roles', 'roles JOIN roles_rights ON roles.id = roles_rights.role_id JOIN rights ON rights.label = roles_rights.right_label',
- 'rights.label = :right', array('right' => 'CAN_SING'));
- }
-
- public function testFindObjectsFromSqlHierarchyDown()
- {
- $users = $this->tdbmService->findObjectsFromSql('person', 'person', 'name LIKE :name OR name LIKE :name2',
- array('name' => 'Robert Marley', 'name2' => 'Bill Shakespeare'), null, null, TDBMObject::class);
- $this->assertCount(2, $users);
- $this->assertSame('robert.marley', $users[0]->getProperty('login', 'users'));
- }
-
- public function testFindObjectsFromSqlHierarchyUp()
- {
- $users = $this->tdbmService->findObjectsFromSql('users', 'users', 'login LIKE :login OR login LIKE :login2',
- array('login' => 'robert.marley', 'login2' => 'bill.shakespeare'), null, null, TDBMObject::class);
- $this->assertCount(2, $users);
- $this->assertSame('Robert Marley', $users[0]->getProperty('name', 'person'));
- }
-
- public function testLogger()
- {
- $arrayLogger = new ArrayLogger();
- $tdbmService = new TDBMService(new Configuration('Mouf\\Database\\TDBM\\Test\\Dao\\Bean', 'Mouf\\Database\\TDBM\\Test\\Dao', $this->dbConnection, $this->getNamingStrategy(), null, null, $arrayLogger));
-
- $tdbmService->setLogLevel(LogLevel::DEBUG);
- $beans = $tdbmService->findObjects('contact', null, [], 'contact.id ASC', [], null, TDBMObject::class);
- $beans->first();
-
- $this->assertNotEmpty($arrayLogger->get());
- }
-
- public function testFindObjectsCountWithOneToManyLink()
- {
- $countries = $this->tdbmService->findObjects('country', "users.status = 'on' OR users.status = 'off'");
-
- $this->assertEquals(3, $countries->count());
- }
-
- public function testFindObjectsFromSqlCountWithOneToManyLink()
- {
- $countries = $this->tdbmService->findObjectsFromSql('country', 'country LEFT JOIN users ON country.id = users.country_id', "users.status = 'on' OR users.status = 'off'");
-
- $this->assertEquals(3, $countries->count());
- }
-
- /*
- public function testObjectAsFilter() {
- $dpt = $this->tdbmService->getObject('departements', 1);
- $dpt2 = $this->tdbmService->getObject('departements', $dpt);
- $this->assertEquals($dpt, $dpt2);
- }
-
- public function testOneWayAndTheOpposite() {
- $this->tdbmService->getObjects('utilisateur_entite', new EqualFilter('entites', 'appellation', 'foo'));
- $this->tdbmService->getObjects('entites', new EqualFilter('utilisateur_entite', 'id_utilisateur', '1'));
- }
-
- public function testOneWayAndTheOpposite2() {
- $this->tdbmService->getObjects('utilisateur_entite', new EqualFilter('departements', 'id', '1'));
- $this->tdbmService->getObjects('departements', new EqualFilter('utilisateur_entite', 'id_utilisateur', '1'));
- }
-
- public function testOneWayAndTheOpposite3() {
- $this->tdbmService->getObjects('utilisateur_entite',
- [
- new EqualFilter('entites', 'appellation', 1),
- ]
- );
- $this->tdbmService->getObjects('entites', [
- new EqualFilter('departements', 'id', 1),
- new EqualFilter('utilisateur_entite', 'id_utilisateur', '1'),
- ]
- );
- }
-
- public function testOneWayAndTheOpposite4() {
- $this->tdbmService->getObjects('utilisateur_entite', null,
- [
- new OrderByColumn('entites', 'appellation', 'ASC'),
- ]
- );
- $this->tdbmService->getObjects('entites', new EqualFilter('utilisateur_entite', 'id_utilisateur', '1'),
- [
- new OrderByColumn('departements', 'id', 'ASC')
- ]
- );
- }
-
- public function testTDBMObjectArrayMultipleForeach() {
- $results = $this->tdbmService->getObjects('departements');
- $this->assertTrue(is_array($results));
- $count = 0;
- foreach ($results as $result) {
- $count++;
- }
- $this->assertEquals(95, $count);
-
- $count = 0;
- foreach ($results as $result) {
- $count++;
- }
- $this->assertEquals(95, $count);
-
- }
-
- public function testTDBMObjectsCursorMode() {
- $this->tdbmService->setFetchMode(TDBMService::MODE_CURSOR);
- $results = $this->tdbmService->getObjects('departements');
-
- $count = 0;
- foreach ($results as $result) {
- $count++;
- }
- $this->assertEquals(95, $count);
- }
-
- public function testTDBMObjectCursorMode() {
- $this->tdbmService->setFetchMode(TDBMService::MODE_CURSOR);
- $result = $this->tdbmService->getObject('departements', array(new EqualFilter('departements', 'id', 1)));
-
- $this->assertEquals("Ain", $result->nom);
- }
-
-
- public function testTDBMObjectArrayCount() {
- $results = $this->tdbmService->getObjects('departements');
- $this->assertEquals(95, count($results));
- $this->assertEquals(95, count($results));
-
- }
-
-
- public function testTDBMObjectArrayAccessByKey() {
- $results = $this->tdbmService->getObjects('departements');
-
- $this->assertEquals("Alpes Maritimes", $results[5]->nom);
- }
-
- public function testTDBMObjectArrayCountAfterForeach() {
- $results = $this->tdbmService->getObjects('departements');
- foreach ($results as $result) {
- // Do nothing
- }
- $this->assertEquals(95, count($results));
- }
-
- public function testStorage() {
- $results = $this->tdbmService->getObjects('departements');
-
- $result = $this->tdbmService->getObject('departements', 1);
-
- $this->assertTrue($results[0] === $result);
- }
-
- public function testCloneTDBMObject()
- {
- // Create a new object
- $object = $this->tdbmService->getNewObject('departements');
- $object->id_region = 22;
- $object->numero = '100';
- $object->nom = 'test';
- $object->nom_web = 'test';
- // Save the object
- $object->save();
-
- // Try to clone the object
- $cloneObject = clone $object;
- // Save the cloned object
- $cloneObject->save();
-
- $this->assertNotEquals($object->id, $cloneObject->id);
- $this->assertEquals($object->nom, $cloneObject->nom);
-
- $this->tdbmService->deleteObject($object);
- $this->tdbmService->deleteObject($cloneObject);
- }
- */
-}
diff --git a/tests/Mouf/Database/TDBM/Utils/BeanDescriptorTest.php b/tests/Mouf/Database/TDBM/Utils/BeanDescriptorTest.php
deleted file mode 100644
index 76b9f9c..0000000
--- a/tests/Mouf/Database/TDBM/Utils/BeanDescriptorTest.php
+++ /dev/null
@@ -1,96 +0,0 @@
-tdbmService->getConnection()->getSchemaManager();
- $this->schemaAnalyzer = new SchemaAnalyzer($schemaManager);
- $this->schema = $schemaManager->createSchema();
- $this->tdbmSchemaAnalyzer = new TDBMSchemaAnalyzer($this->tdbmService->getConnection(), new VoidCache(), $this->schemaAnalyzer);
- }
-
- public function testConstructor()
- {
- $usersTable = $this->schema->getTable('users');
- $beanDescriptor = new BeanDescriptor($usersTable, $this->schemaAnalyzer, $this->schema, $this->tdbmSchemaAnalyzer, new DefaultNamingStrategy(), new VoidListener());
- $propertyDescriptors = $beanDescriptor->getBeanPropertyDescriptors();
- $firstElem = reset($propertyDescriptors);
- $idProperty = $propertyDescriptors['id'];
- $this->assertEquals($firstElem, $idProperty);
- $this->assertEquals('person', $idProperty->getTable()->getName());
- $this->assertInstanceOf('Mouf\\Database\\TDBM\\Utils\\ScalarBeanPropertyDescriptor', $idProperty);
- $countryProperty = $propertyDescriptors['country'];
- $this->assertInstanceOf('Mouf\\Database\\TDBM\\Utils\\ObjectBeanPropertyDescriptor', $countryProperty);
- $nameProperty = $propertyDescriptors['name'];
- $this->assertInstanceOf('Mouf\\Database\\TDBM\\Utils\\ScalarBeanPropertyDescriptor', $nameProperty);
- }
-
- public function testGetConstructorProperties()
- {
- $usersTable = $this->schema->getTable('users');
- $beanDescriptor = new BeanDescriptor($usersTable, $this->schemaAnalyzer, $this->schema, $this->tdbmSchemaAnalyzer, new DefaultNamingStrategy(), new VoidListener());
- $constructorPropertyDescriptors = $beanDescriptor->getConstructorProperties();
- $this->assertArrayHasKey('name', $constructorPropertyDescriptors);
- // password is nullable
- $this->assertArrayNotHasKey('password', $constructorPropertyDescriptors);
- // id is autoincremented
- $this->assertArrayNotHasKey('id', $constructorPropertyDescriptors);
- }
-
- public function testGetTable()
- {
- $usersTable = $this->schema->getTable('users');
- $beanDescriptor = new BeanDescriptor($usersTable, $this->schemaAnalyzer, $this->schema, $this->tdbmSchemaAnalyzer, new DefaultNamingStrategy(), new VoidListener());
- $this->assertSame($usersTable, $beanDescriptor->getTable());
- }
-
- /*public function testGeneratePhpCode() {
- $usersTable = $this->schema->getTable("users");
- $beanDescriptor = new BeanDescriptor($usersTable, $this->schemaAnalyzer, $this->schema);
- $phpCode = $beanDescriptor->generatePhpCode("MyNamespace\\");
-
- echo $phpCode;
- }*/
-}
diff --git a/tests/Mouf/Database/TDBM/Utils/DefaultNamingStrategyTest.php b/tests/Mouf/Database/TDBM/Utils/DefaultNamingStrategyTest.php
deleted file mode 100644
index 87c5310..0000000
--- a/tests/Mouf/Database/TDBM/Utils/DefaultNamingStrategyTest.php
+++ /dev/null
@@ -1,82 +0,0 @@
-setBeanPrefix('');
- $strategy->setBeanSuffix('Bean');
-
- $this->assertSame('UserBean', $strategy->getBeanClassName("users"));
- $this->assertSame('UserBean', $strategy->getBeanClassName("user"));
- $this->assertSame('UserCountryBean', $strategy->getBeanClassName("users_countries"));
- $this->assertSame('UserCountryBean', $strategy->getBeanClassName("users countries"));
- }
-
- public function testGetBaseBeanName()
- {
- $strategy = new DefaultNamingStrategy();
- $strategy->setBaseBeanPrefix('');
- $strategy->setBaseBeanSuffix('BaseBean');
- $this->assertSame('UserBaseBean', $strategy->getBaseBeanClassName("users"));
- }
-
- public function testGetDaoName()
- {
- $strategy = new DefaultNamingStrategy();
- $strategy->setDaoPrefix('');
- $strategy->setDaoSuffix('Dao');
- $this->assertSame('UserDao', $strategy->getDaoClassName("users"));
- }
-
- public function testGetBaseDaoName()
- {
- $strategy = new DefaultNamingStrategy();
- $strategy->setBaseDaoPrefix('');
- $strategy->setBaseDaoSuffix('BaseDao');
- $this->assertSame('UserBaseDao', $strategy->getBaseDaoClassName("users"));
- }
-
- public function testGetBeanNameDefault()
- {
- $strategy = new DefaultNamingStrategy();
-
- $this->assertSame('User', $strategy->getBeanClassName("users"));
- }
-
- public function testGetBaseBeanNameDefault()
- {
- $strategy = new DefaultNamingStrategy();
- $this->assertSame('AbstractUser', $strategy->getBaseBeanClassName("users"));
- }
-
- public function testGetDaoNameDefault()
- {
- $strategy = new DefaultNamingStrategy();
- $this->assertSame('UserDao', $strategy->getDaoClassName("users"));
- }
-
- public function testGetBaseDaoNameDefault()
- {
- $strategy = new DefaultNamingStrategy();
- $this->assertSame('AbstractUserDao', $strategy->getBaseDaoClassName("users"));
- }
-
- public function testGetDaoFactory()
- {
- $strategy = new DefaultNamingStrategy();
- $this->assertSame('DaoFactory', $strategy->getDaoFactoryClassName());
- }
-
- public function testExceptions()
- {
- $strategy = new DefaultNamingStrategy();
- $strategy->setExceptions([
- 'chevaux' => 'Cheval'
- ]);
- $this->assertSame('ChevalDao', $strategy->getDaoClassName('chevaux'));
- }
-}
diff --git a/tests/Mouf/Database/TDBM/Utils/PathFinder/PathFinderTest.php b/tests/Mouf/Database/TDBM/Utils/PathFinder/PathFinderTest.php
deleted file mode 100644
index a6ac9c0..0000000
--- a/tests/Mouf/Database/TDBM/Utils/PathFinder/PathFinderTest.php
+++ /dev/null
@@ -1,22 +0,0 @@
-getPath(PathFinder::class)->getPathname());
- $expectedPath = (new \ReflectionClass(PathFinder::class))->getFileName();
-
- $this->assertSame($expectedPath, $path);
- }
-
- public function testGetPathNotFound()
- {
- $pathFinder = new PathFinder(null, dirname(__DIR__, 6));
- $this->expectException(NoPathFoundException::class);
- $pathFinder->getPath("Not\\Exist");
- }
-}
diff --git a/tests/Mouf/Database/TDBM/Utils/VoidListenerTest.php b/tests/Mouf/Database/TDBM/Utils/VoidListenerTest.php
deleted file mode 100644
index 025a0b8..0000000
--- a/tests/Mouf/Database/TDBM/Utils/VoidListenerTest.php
+++ /dev/null
@@ -1,17 +0,0 @@
-getMockBuilder(ConfigurationInterface::class)->getMock();
- $voidListener = new VoidListener();
- $voidListener->onGenerate($configuration, []);
-
- // Hum... no way to test nothing happened!
- }
-}
diff --git a/tests/bootstrap.php b/tests/bootstrap.php
deleted file mode 100644
index c07d9a6..0000000
--- a/tests/bootstrap.php
+++ /dev/null
@@ -1,7 +0,0 @@
-