This commit is contained in:
Xes
2025-08-14 22:41:49 +02:00
parent 2de81ccc46
commit 8ce45119b6
39774 changed files with 4309466 additions and 0 deletions

View File

@@ -0,0 +1,95 @@
<?php
/*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* This software consists of voluntary contributions made by many individuals
* and is licensed under the MIT license. For more information, see
* <http://www.doctrine-project.org>.
*/
namespace Doctrine\ORM\Persisters\Collection;
use Doctrine\ORM\EntityManagerInterface;
use Doctrine\ORM\UnitOfWork;
/**
* Base class for all collection persisters.
*
* @since 2.0
* @author Roman Borschel <roman@code-factory.org>
*/
abstract class AbstractCollectionPersister implements CollectionPersister
{
/**
* @var EntityManagerInterface
*/
protected $em;
/**
* @var \Doctrine\DBAL\Connection
*/
protected $conn;
/**
* @var UnitOfWork
*/
protected $uow;
/**
* The database platform.
*
* @var \Doctrine\DBAL\Platforms\AbstractPlatform
*/
protected $platform;
/**
* The quote strategy.
*
* @var \Doctrine\ORM\Mapping\QuoteStrategy
*/
protected $quoteStrategy;
/**
* Initializes a new instance of a class derived from AbstractCollectionPersister.
*
* @param EntityManagerInterface $em
*/
public function __construct(EntityManagerInterface $em)
{
$this->em = $em;
$this->uow = $em->getUnitOfWork();
$this->conn = $em->getConnection();
$this->platform = $this->conn->getDatabasePlatform();
$this->quoteStrategy = $em->getConfiguration()->getQuoteStrategy();
}
/**
* Check if entity is in a valid state for operations.
*
* @param object $entity
*
* @return bool
*/
protected function isValidEntityState($entity)
{
$entityState = $this->uow->getEntityState($entity, UnitOfWork::STATE_NEW);
if ($entityState === UnitOfWork::STATE_NEW) {
return false;
}
// If Entity is scheduled for inclusion, it is not in this collection.
// We can assure that because it would have return true before on array check
return ! ($entityState === UnitOfWork::STATE_MANAGED && $this->uow->isScheduledForInsert($entity));
}
}

View File

@@ -0,0 +1,112 @@
<?php
/*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* This software consists of voluntary contributions made by many individuals
* and is licensed under the MIT license. For more information, see
* <http://www.doctrine-project.org>.
*/
namespace Doctrine\ORM\Persisters\Collection;
use Doctrine\Common\Collections\Criteria;
use Doctrine\ORM\PersistentCollection;
/**
* Collection persister interface
* Define the behavior that should be implemented by all collection persisters.
*
* @author Fabio B. Silva <fabio.bat.silva@gmail.com>
* @since 2.5
*/
interface CollectionPersister
{
/**
* Deletes the persistent state represented by the given collection.
*
* @param \Doctrine\ORM\PersistentCollection $collection
*
* @return void
*/
public function delete(PersistentCollection $collection);
/**
* Updates the given collection, synchronizing its state with the database
* by inserting, updating and deleting individual elements.
*
* @param \Doctrine\ORM\PersistentCollection $collection
*
* @return void
*/
public function update(PersistentCollection $collection);
/**
* Counts the size of this persistent collection.
*
* @param \Doctrine\ORM\PersistentCollection $collection
*
* @return integer
*/
public function count(PersistentCollection $collection);
/**
* Slices elements.
*
* @param \Doctrine\ORM\PersistentCollection $collection
* @param integer $offset
* @param integer $length
*
* @return array
*/
public function slice(PersistentCollection $collection, $offset, $length = null);
/**
* Checks for existence of an element.
*
* @param \Doctrine\ORM\PersistentCollection $collection
* @param object $element
*
* @return boolean
*/
public function contains(PersistentCollection $collection, $element);
/**
* Checks for existence of a key.
*
* @param \Doctrine\ORM\PersistentCollection $collection
* @param mixed $key
*
* @return boolean
*/
public function containsKey(PersistentCollection $collection, $key);
/**
* Gets an element by key.
*
* @param \Doctrine\ORM\PersistentCollection $collection
* @param mixed $index
*
* @return mixed
*/
public function get(PersistentCollection $collection, $index);
/**
* Loads association entities matching the given Criteria object.
*
* @param \Doctrine\ORM\PersistentCollection $collection
* @param \Doctrine\Common\Collections\Criteria $criteria
*
* @return array
*/
public function loadCriteria(PersistentCollection $collection, Criteria $criteria);
}

View File

@@ -0,0 +1,794 @@
<?php
/*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* This software consists of voluntary contributions made by many individuals
* and is licensed under the MIT license. For more information, see
* <http://www.doctrine-project.org>.
*/
namespace Doctrine\ORM\Persisters\Collection;
use Doctrine\Common\Collections\Criteria;
use Doctrine\ORM\Mapping\ClassMetadata;
use Doctrine\ORM\Persisters\SqlValueVisitor;
use Doctrine\ORM\PersistentCollection;
use Doctrine\ORM\Query;
use Doctrine\ORM\Utility\PersisterHelper;
/**
* Persister for many-to-many collections.
*
* @author Roman Borschel <roman@code-factory.org>
* @author Guilherme Blanco <guilhermeblanco@hotmail.com>
* @author Alexander <iam.asm89@gmail.com>
* @since 2.0
*/
class ManyToManyPersister extends AbstractCollectionPersister
{
/**
* {@inheritdoc}
*/
public function delete(PersistentCollection $collection)
{
$mapping = $collection->getMapping();
if ( ! $mapping['isOwningSide']) {
return; // ignore inverse side
}
$types = [];
$class = $this->em->getClassMetadata($mapping['sourceEntity']);
foreach ($mapping['joinTable']['joinColumns'] as $joinColumn) {
$types[] = PersisterHelper::getTypeOfColumn($joinColumn['referencedColumnName'], $class, $this->em);
}
$this->conn->executeUpdate($this->getDeleteSQL($collection), $this->getDeleteSQLParameters($collection), $types);
}
/**
* {@inheritdoc}
*/
public function update(PersistentCollection $collection)
{
$mapping = $collection->getMapping();
if ( ! $mapping['isOwningSide']) {
return; // ignore inverse side
}
[$deleteSql, $deleteTypes] = $this->getDeleteRowSQL($collection);
[$insertSql, $insertTypes] = $this->getInsertRowSQL($collection);
foreach ($collection->getDeleteDiff() as $element) {
$this->conn->executeUpdate(
$deleteSql,
$this->getDeleteRowSQLParameters($collection, $element),
$deleteTypes
);
}
foreach ($collection->getInsertDiff() as $element) {
$this->conn->executeUpdate(
$insertSql,
$this->getInsertRowSQLParameters($collection, $element),
$insertTypes
);
}
}
/**
* {@inheritdoc}
*/
public function get(PersistentCollection $collection, $index)
{
$mapping = $collection->getMapping();
if ( ! isset($mapping['indexBy'])) {
throw new \BadMethodCallException("Selecting a collection by index is only supported on indexed collections.");
}
$persister = $this->uow->getEntityPersister($mapping['targetEntity']);
$mappedKey = $mapping['isOwningSide']
? $mapping['inversedBy']
: $mapping['mappedBy'];
return $persister->load([$mappedKey => $collection->getOwner(), $mapping['indexBy'] => $index], null, $mapping, [], 0, 1);
}
/**
* {@inheritdoc}
*/
public function count(PersistentCollection $collection)
{
$conditions = [];
$params = [];
$types = [];
$mapping = $collection->getMapping();
$id = $this->uow->getEntityIdentifier($collection->getOwner());
$sourceClass = $this->em->getClassMetadata($mapping['sourceEntity']);
$targetClass = $this->em->getClassMetadata($mapping['targetEntity']);
$association = ( ! $mapping['isOwningSide'])
? $targetClass->associationMappings[$mapping['mappedBy']]
: $mapping;
$joinTableName = $this->quoteStrategy->getJoinTableName($association, $sourceClass, $this->platform);
$joinColumns = ( ! $mapping['isOwningSide'])
? $association['joinTable']['inverseJoinColumns']
: $association['joinTable']['joinColumns'];
foreach ($joinColumns as $joinColumn) {
$columnName = $this->quoteStrategy->getJoinColumnName($joinColumn, $sourceClass, $this->platform);
$referencedName = $joinColumn['referencedColumnName'];
$conditions[] = 't.' . $columnName . ' = ?';
$params[] = $id[$sourceClass->getFieldForColumn($referencedName)];
$types[] = PersisterHelper::getTypeOfColumn($referencedName, $sourceClass, $this->em);
}
[$joinTargetEntitySQL, $filterSql] = $this->getFilterSql($mapping);
if ($filterSql) {
$conditions[] = $filterSql;
}
// If there is a provided criteria, make part of conditions
// @todo Fix this. Current SQL returns something like:
//
/*if ($criteria && ($expression = $criteria->getWhereExpression()) !== null) {
// A join is needed on the target entity
$targetTableName = $this->quoteStrategy->getTableName($targetClass, $this->platform);
$targetJoinSql = ' JOIN ' . $targetTableName . ' te'
. ' ON' . implode(' AND ', $this->getOnConditionSQL($association));
// And criteria conditions needs to be added
$persister = $this->uow->getEntityPersister($targetClass->name);
$visitor = new SqlExpressionVisitor($persister, $targetClass);
$conditions[] = $visitor->dispatch($expression);
$joinTargetEntitySQL = $targetJoinSql . $joinTargetEntitySQL;
}*/
$sql = 'SELECT COUNT(*)'
. ' FROM ' . $joinTableName . ' t'
. $joinTargetEntitySQL
. ' WHERE ' . implode(' AND ', $conditions);
return $this->conn->fetchColumn($sql, $params, 0, $types);
}
/**
* {@inheritDoc}
*/
public function slice(PersistentCollection $collection, $offset, $length = null)
{
$mapping = $collection->getMapping();
$persister = $this->uow->getEntityPersister($mapping['targetEntity']);
return $persister->getManyToManyCollection($mapping, $collection->getOwner(), $offset, $length);
}
/**
* {@inheritdoc}
*/
public function containsKey(PersistentCollection $collection, $key)
{
$mapping = $collection->getMapping();
if ( ! isset($mapping['indexBy'])) {
throw new \BadMethodCallException("Selecting a collection by index is only supported on indexed collections.");
}
[$quotedJoinTable, $whereClauses, $params, $types] = $this->getJoinTableRestrictionsWithKey(
$collection,
$key,
true
);
$sql = 'SELECT 1 FROM ' . $quotedJoinTable . ' WHERE ' . implode(' AND ', $whereClauses);
return (bool) $this->conn->fetchColumn($sql, $params, 0, $types);
}
/**
* {@inheritDoc}
*/
public function contains(PersistentCollection $collection, $element)
{
if ( ! $this->isValidEntityState($element)) {
return false;
}
[$quotedJoinTable, $whereClauses, $params, $types] = $this->getJoinTableRestrictions(
$collection,
$element,
true
);
$sql = 'SELECT 1 FROM ' . $quotedJoinTable . ' WHERE ' . implode(' AND ', $whereClauses);
return (bool) $this->conn->fetchColumn($sql, $params, 0, $types);
}
/**
* {@inheritDoc}
*/
public function loadCriteria(PersistentCollection $collection, Criteria $criteria)
{
$mapping = $collection->getMapping();
$owner = $collection->getOwner();
$ownerMetadata = $this->em->getClassMetadata(get_class($owner));
$id = $this->uow->getEntityIdentifier($owner);
$targetClass = $this->em->getClassMetadata($mapping['targetEntity']);
$onConditions = $this->getOnConditionSQL($mapping);
$whereClauses = $params = [];
if ( ! $mapping['isOwningSide']) {
$associationSourceClass = $targetClass;
$mapping = $targetClass->associationMappings[$mapping['mappedBy']];
$sourceRelationMode = 'relationToTargetKeyColumns';
} else {
$associationSourceClass = $ownerMetadata;
$sourceRelationMode = 'relationToSourceKeyColumns';
}
foreach ($mapping[$sourceRelationMode] as $key => $value) {
$whereClauses[] = sprintf('t.%s = ?', $key);
$params[] = $ownerMetadata->containsForeignIdentifier
? $id[$ownerMetadata->getFieldForColumn($value)]
: $id[$ownerMetadata->fieldNames[$value]];
}
$parameters = $this->expandCriteriaParameters($criteria);
foreach ($parameters as $parameter) {
[$name, $value, $operator] = $parameter;
$field = $this->quoteStrategy->getColumnName($name, $targetClass, $this->platform);
$whereClauses[] = sprintf('te.%s %s ?', $field, $operator);
$params[] = $value;
}
$tableName = $this->quoteStrategy->getTableName($targetClass, $this->platform);
$joinTable = $this->quoteStrategy->getJoinTableName($mapping, $associationSourceClass, $this->platform);
$rsm = new Query\ResultSetMappingBuilder($this->em);
$rsm->addRootEntityFromClassMetadata($targetClass->name, 'te');
$sql = 'SELECT ' . $rsm->generateSelectClause()
. ' FROM ' . $tableName . ' te'
. ' JOIN ' . $joinTable . ' t ON'
. implode(' AND ', $onConditions)
. ' WHERE ' . implode(' AND ', $whereClauses);
$sql .= $this->getOrderingSql($criteria, $targetClass);
$sql .= $this->getLimitSql($criteria);
$stmt = $this->conn->executeQuery($sql, $params);
return $this
->em
->newHydrator(Query::HYDRATE_OBJECT)
->hydrateAll($stmt, $rsm);
}
/**
* Generates the filter SQL for a given mapping.
*
* This method is not used for actually grabbing the related entities
* but when the extra-lazy collection methods are called on a filtered
* association. This is why besides the many to many table we also
* have to join in the actual entities table leading to additional
* JOIN.
*
* @param array $mapping Array containing mapping information.
*
* @return string[] ordered tuple:
* - JOIN condition to add to the SQL
* - WHERE condition to add to the SQL
*
* @psalm-return array{0: string, 1: string}
*/
public function getFilterSql($mapping)
{
$targetClass = $this->em->getClassMetadata($mapping['targetEntity']);
$rootClass = $this->em->getClassMetadata($targetClass->rootEntityName);
$filterSql = $this->generateFilterConditionSQL($rootClass, 'te');
if ('' === $filterSql) {
return ['', ''];
}
// A join is needed if there is filtering on the target entity
$tableName = $this->quoteStrategy->getTableName($rootClass, $this->platform);
$joinSql = ' JOIN ' . $tableName . ' te'
. ' ON' . implode(' AND ', $this->getOnConditionSQL($mapping));
return [$joinSql, $filterSql];
}
/**
* Generates the filter SQL for a given entity and table alias.
*
* @param ClassMetadata $targetEntity Metadata of the target entity.
* @param string $targetTableAlias The table alias of the joined/selected table.
*
* @return string The SQL query part to add to a query.
*/
protected function generateFilterConditionSQL(ClassMetadata $targetEntity, $targetTableAlias)
{
$filterClauses = [];
foreach ($this->em->getFilters()->getEnabledFilters() as $filter) {
if ($filterExpr = $filter->addFilterConstraint($targetEntity, $targetTableAlias)) {
$filterClauses[] = '(' . $filterExpr . ')';
}
}
return $filterClauses
? '(' . implode(' AND ', $filterClauses) . ')'
: '';
}
/**
* Generate ON condition
*
* @param array $mapping
*
* @return string[]
*
* @psalm-return list<string>
*/
protected function getOnConditionSQL($mapping)
{
$targetClass = $this->em->getClassMetadata($mapping['targetEntity']);
$association = ( ! $mapping['isOwningSide'])
? $targetClass->associationMappings[$mapping['mappedBy']]
: $mapping;
$joinColumns = $mapping['isOwningSide']
? $association['joinTable']['inverseJoinColumns']
: $association['joinTable']['joinColumns'];
$conditions = [];
foreach ($joinColumns as $joinColumn) {
$joinColumnName = $this->quoteStrategy->getJoinColumnName($joinColumn, $targetClass, $this->platform);
$refColumnName = $this->quoteStrategy->getReferencedJoinColumnName($joinColumn, $targetClass, $this->platform);
$conditions[] = ' t.' . $joinColumnName . ' = ' . 'te.' . $refColumnName;
}
return $conditions;
}
/**
* @return string
*/
protected function getDeleteSQL(PersistentCollection $collection)
{
$columns = [];
$mapping = $collection->getMapping();
$class = $this->em->getClassMetadata(get_class($collection->getOwner()));
$joinTable = $this->quoteStrategy->getJoinTableName($mapping, $class, $this->platform);
foreach ($mapping['joinTable']['joinColumns'] as $joinColumn) {
$columns[] = $this->quoteStrategy->getJoinColumnName($joinColumn, $class, $this->platform);
}
return 'DELETE FROM ' . $joinTable
. ' WHERE ' . implode(' = ? AND ', $columns) . ' = ?';
}
/**
* Internal note: Order of the parameters must be the same as the order of the columns in getDeleteSql.
*
* @return mixed[]
*/
protected function getDeleteSQLParameters(PersistentCollection $collection)
{
$mapping = $collection->getMapping();
$identifier = $this->uow->getEntityIdentifier($collection->getOwner());
// Optimization for single column identifier
if (count($mapping['relationToSourceKeyColumns']) === 1) {
return [reset($identifier)];
}
// Composite identifier
$sourceClass = $this->em->getClassMetadata($mapping['sourceEntity']);
$params = [];
foreach ($mapping['relationToSourceKeyColumns'] as $columnName => $refColumnName) {
$params[] = isset($sourceClass->fieldNames[$refColumnName])
? $identifier[$sourceClass->fieldNames[$refColumnName]]
: $identifier[$sourceClass->getFieldForColumn($refColumnName)];
}
return $params;
}
/**
* Gets the SQL statement used for deleting a row from the collection.
*
* @param \Doctrine\ORM\PersistentCollection $collection
*
* @return string[]|string[][] ordered tuple containing the SQL to be executed and an array
* of types for bound parameters
*
* @psalm-return array{0: string, 1: list<string>}
*/
protected function getDeleteRowSQL(PersistentCollection $collection)
{
$mapping = $collection->getMapping();
$class = $this->em->getClassMetadata($mapping['sourceEntity']);
$targetClass = $this->em->getClassMetadata($mapping['targetEntity']);
$columns = [];
$types = [];
foreach ($mapping['joinTable']['joinColumns'] as $joinColumn) {
$columns[] = $this->quoteStrategy->getJoinColumnName($joinColumn, $class, $this->platform);
$types[] = PersisterHelper::getTypeOfColumn($joinColumn['referencedColumnName'], $class, $this->em);
}
foreach ($mapping['joinTable']['inverseJoinColumns'] as $joinColumn) {
$columns[] = $this->quoteStrategy->getJoinColumnName($joinColumn, $targetClass, $this->platform);
$types[] = PersisterHelper::getTypeOfColumn($joinColumn['referencedColumnName'], $targetClass, $this->em);
}
return [
'DELETE FROM ' . $this->quoteStrategy->getJoinTableName($mapping, $class, $this->platform)
. ' WHERE ' . implode(' = ? AND ', $columns) . ' = ?',
$types,
];
}
/**
* Gets the SQL parameters for the corresponding SQL statement to delete the given
* element from the given collection.
*
* Internal note: Order of the parameters must be the same as the order of the columns in getDeleteRowSql.
*
* @param \Doctrine\ORM\PersistentCollection $collection
* @param mixed $element
*
* @return array
*
* @psalm-return list<mixed>
*/
protected function getDeleteRowSQLParameters(PersistentCollection $collection, $element)
{
return $this->collectJoinTableColumnParameters($collection, $element);
}
/**
* Gets the SQL statement used for inserting a row in the collection.
*
* @param \Doctrine\ORM\PersistentCollection $collection
*
* @return string[]|string[][] ordered tuple containing the SQL to be executed and an array
* of types for bound parameters
*
* @psalm-return array{0: string, 1: list<string>}
*/
protected function getInsertRowSQL(PersistentCollection $collection)
{
$columns = [];
$types = [];
$mapping = $collection->getMapping();
$class = $this->em->getClassMetadata($mapping['sourceEntity']);
$targetClass = $this->em->getClassMetadata($mapping['targetEntity']);
foreach ($mapping['joinTable']['joinColumns'] as $joinColumn) {
$columns[] = $this->quoteStrategy->getJoinColumnName($joinColumn, $targetClass, $this->platform);
$types[] = PersisterHelper::getTypeOfColumn($joinColumn['referencedColumnName'], $class, $this->em);
}
foreach ($mapping['joinTable']['inverseJoinColumns'] as $joinColumn) {
$columns[] = $this->quoteStrategy->getJoinColumnName($joinColumn, $targetClass, $this->platform);
$types[] = PersisterHelper::getTypeOfColumn($joinColumn['referencedColumnName'], $targetClass, $this->em);
}
return [
'INSERT INTO ' . $this->quoteStrategy->getJoinTableName($mapping, $class, $this->platform)
. ' (' . implode(', ', $columns) . ')'
. ' VALUES'
. ' (' . implode(', ', array_fill(0, count($columns), '?')) . ')',
$types,
];
}
/**
* Gets the SQL parameters for the corresponding SQL statement to insert the given
* element of the given collection into the database.
*
* Internal note: Order of the parameters must be the same as the order of the columns in getInsertRowSql.
*
* @param \Doctrine\ORM\PersistentCollection $collection
* @param mixed $element
*
* @return array
*
* @psalm-return list<mixed>
*/
protected function getInsertRowSQLParameters(PersistentCollection $collection, $element)
{
return $this->collectJoinTableColumnParameters($collection, $element);
}
/**
* Collects the parameters for inserting/deleting on the join table in the order
* of the join table columns as specified in ManyToManyMapping#joinTableColumns.
*
* @param \Doctrine\ORM\PersistentCollection $collection
* @param object $element
*
* @return mixed[]
*
* @psalm-return list<mixed>
*/
private function collectJoinTableColumnParameters(PersistentCollection $collection, $element)
{
$params = [];
$mapping = $collection->getMapping();
$isComposite = count($mapping['joinTableColumns']) > 2;
$identifier1 = $this->uow->getEntityIdentifier($collection->getOwner());
$identifier2 = $this->uow->getEntityIdentifier($element);
$class1 = $class2 = null;
if ($isComposite) {
$class1 = $this->em->getClassMetadata(get_class($collection->getOwner()));
$class2 = $collection->getTypeClass();
}
foreach ($mapping['joinTableColumns'] as $joinTableColumn) {
$isRelationToSource = isset($mapping['relationToSourceKeyColumns'][$joinTableColumn]);
if ( ! $isComposite) {
$params[] = $isRelationToSource ? array_pop($identifier1) : array_pop($identifier2);
continue;
}
if ($isRelationToSource) {
$params[] = $identifier1[$class1->getFieldForColumn($mapping['relationToSourceKeyColumns'][$joinTableColumn])];
continue;
}
$params[] = $identifier2[$class2->getFieldForColumn($mapping['relationToTargetKeyColumns'][$joinTableColumn])];
}
return $params;
}
/**
* @param \Doctrine\ORM\PersistentCollection $collection
* @param string $key
* @param boolean $addFilters Whether the filter SQL should be included or not.
*
* @return array ordered vector:
* - quoted join table name
* - where clauses to be added for filtering
* - parameters to be bound for filtering
* - types of the parameters to be bound for filtering
*
* @psalm-return array{0: string, 1: list<string>, 2: list<mixed>, 3: list<string>}
*/
private function getJoinTableRestrictionsWithKey(PersistentCollection $collection, $key, $addFilters)
{
$filterMapping = $collection->getMapping();
$mapping = $filterMapping;
$indexBy = $mapping['indexBy'];
$id = $this->uow->getEntityIdentifier($collection->getOwner());
$sourceClass = $this->em->getClassMetadata($mapping['sourceEntity']);
$targetClass = $this->em->getClassMetadata($mapping['targetEntity']);
if (! $mapping['isOwningSide']) {
$associationSourceClass = $this->em->getClassMetadata($mapping['targetEntity']);
$mapping = $associationSourceClass->associationMappings[$mapping['mappedBy']];
$joinColumns = $mapping['joinTable']['joinColumns'];
$sourceRelationMode = 'relationToTargetKeyColumns';
$targetRelationMode = 'relationToSourceKeyColumns';
} else {
$associationSourceClass = $this->em->getClassMetadata($mapping['sourceEntity']);
$joinColumns = $mapping['joinTable']['inverseJoinColumns'];
$sourceRelationMode = 'relationToSourceKeyColumns';
$targetRelationMode = 'relationToTargetKeyColumns';
}
$quotedJoinTable = $this->quoteStrategy->getJoinTableName($mapping, $associationSourceClass, $this->platform). ' t';
$whereClauses = [];
$params = [];
$types = [];
$joinNeeded = ! in_array($indexBy, $targetClass->identifier);
if ($joinNeeded) { // extra join needed if indexBy is not a @id
$joinConditions = [];
foreach ($joinColumns as $joinTableColumn) {
$joinConditions[] = 't.' . $joinTableColumn['name'] . ' = tr.' . $joinTableColumn['referencedColumnName'];
}
$tableName = $this->quoteStrategy->getTableName($targetClass, $this->platform);
$quotedJoinTable .= ' JOIN ' . $tableName . ' tr ON ' . implode(' AND ', $joinConditions);
$columnName = $targetClass->getColumnName($indexBy);
$whereClauses[] = 'tr.' . $columnName . ' = ?';
$params[] = $key;
$types[] = PersisterHelper::getTypeOfColumn($columnName, $targetClass, $this->em);
}
foreach ($mapping['joinTableColumns'] as $joinTableColumn) {
if (isset($mapping[$sourceRelationMode][$joinTableColumn])) {
$column = $mapping[$sourceRelationMode][$joinTableColumn];
$whereClauses[] = 't.' . $joinTableColumn . ' = ?';
$params[] = $sourceClass->containsForeignIdentifier
? $id[$sourceClass->getFieldForColumn($column)]
: $id[$sourceClass->fieldNames[$column]];
$types[] = PersisterHelper::getTypeOfColumn($column, $sourceClass, $this->em);
} elseif ( ! $joinNeeded) {
$column = $mapping[$targetRelationMode][$joinTableColumn];
$whereClauses[] = 't.' . $joinTableColumn . ' = ?';
$params[] = $key;
$types[] = PersisterHelper::getTypeOfColumn($column, $targetClass, $this->em);
}
}
if ($addFilters) {
[$joinTargetEntitySQL, $filterSql] = $this->getFilterSql($filterMapping);
if ($filterSql) {
$quotedJoinTable .= ' ' . $joinTargetEntitySQL;
$whereClauses[] = $filterSql;
}
}
return [$quotedJoinTable, $whereClauses, $params, $types];
}
/**
* @param \Doctrine\ORM\PersistentCollection $collection
* @param object $element
* @param boolean $addFilters Whether the filter SQL should be included or not.
*
* @return array ordered vector:
* - quoted join table name
* - where clauses to be added for filtering
* - parameters to be bound for filtering
* - types of the parameters to be bound for filtering
*
* @psalm-return array{0: string, 1: list<string>, 2: list<mixed>, 3: list<string>}
*/
private function getJoinTableRestrictions(PersistentCollection $collection, $element, $addFilters)
{
$filterMapping = $collection->getMapping();
$mapping = $filterMapping;
if ( ! $mapping['isOwningSide']) {
$sourceClass = $this->em->getClassMetadata($mapping['targetEntity']);
$targetClass = $this->em->getClassMetadata($mapping['sourceEntity']);
$sourceId = $this->uow->getEntityIdentifier($element);
$targetId = $this->uow->getEntityIdentifier($collection->getOwner());
$mapping = $sourceClass->associationMappings[$mapping['mappedBy']];
} else {
$sourceClass = $this->em->getClassMetadata($mapping['sourceEntity']);
$targetClass = $this->em->getClassMetadata($mapping['targetEntity']);
$sourceId = $this->uow->getEntityIdentifier($collection->getOwner());
$targetId = $this->uow->getEntityIdentifier($element);
}
$quotedJoinTable = $this->quoteStrategy->getJoinTableName($mapping, $sourceClass, $this->platform);
$whereClauses = [];
$params = [];
$types = [];
foreach ($mapping['joinTableColumns'] as $joinTableColumn) {
$whereClauses[] = ($addFilters ? 't.' : '') . $joinTableColumn . ' = ?';
if (isset($mapping['relationToTargetKeyColumns'][$joinTableColumn])) {
$targetColumn = $mapping['relationToTargetKeyColumns'][$joinTableColumn];
$params[] = $targetId[$targetClass->getFieldForColumn($targetColumn)];
$types[] = PersisterHelper::getTypeOfColumn($targetColumn, $targetClass, $this->em);
continue;
}
// relationToSourceKeyColumns
$targetColumn = $mapping['relationToSourceKeyColumns'][$joinTableColumn];
$params[] = $sourceId[$sourceClass->getFieldForColumn($targetColumn)];
$types[] = PersisterHelper::getTypeOfColumn($targetColumn, $sourceClass, $this->em);
}
if ($addFilters) {
$quotedJoinTable .= ' t';
[$joinTargetEntitySQL, $filterSql] = $this->getFilterSql($filterMapping);
if ($filterSql) {
$quotedJoinTable .= ' ' . $joinTargetEntitySQL;
$whereClauses[] = $filterSql;
}
}
return [$quotedJoinTable, $whereClauses, $params, $types];
}
/**
* Expands Criteria Parameters by walking the expressions and grabbing all
* parameters and types from it.
*
* @param \Doctrine\Common\Collections\Criteria $criteria
*
* @return array
*/
private function expandCriteriaParameters(Criteria $criteria)
{
$expression = $criteria->getWhereExpression();
if ($expression === null) {
return [];
}
$valueVisitor = new SqlValueVisitor();
$valueVisitor->dispatch($expression);
[, $types] = $valueVisitor->getParamsAndTypes();
return $types;
}
/**
* @param Criteria $criteria
* @param ClassMetadata $targetClass
* @return string
*/
private function getOrderingSql(Criteria $criteria, ClassMetadata $targetClass)
{
$orderings = $criteria->getOrderings();
if ($orderings) {
$orderBy = [];
foreach ($orderings as $name => $direction) {
$field = $this->quoteStrategy->getColumnName(
$name,
$targetClass,
$this->platform
);
$orderBy[] = $field . ' ' . $direction;
}
return ' ORDER BY ' . implode(', ', $orderBy);
}
return '';
}
/**
* @param Criteria $criteria
* @return string
* @throws \Doctrine\DBAL\DBALException
*/
private function getLimitSql(Criteria $criteria)
{
$limit = $criteria->getMaxResults();
$offset = $criteria->getFirstResult();
if ($limit !== null || $offset !== null) {
return $this->platform->modifyLimitQuery('', $limit, $offset);
}
return '';
}
}

View File

@@ -0,0 +1,271 @@
<?php
/*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* This software consists of voluntary contributions made by many individuals
* and is licensed under the MIT license. For more information, see
* <http://www.doctrine-project.org>.
*/
namespace Doctrine\ORM\Persisters\Collection;
use Doctrine\Common\Collections\Criteria;
use Doctrine\DBAL\Types\Type;
use Doctrine\ORM\PersistentCollection;
use Doctrine\ORM\Utility\PersisterHelper;
/**
* Persister for one-to-many collections.
*
* @author Roman Borschel <roman@code-factory.org>
* @author Guilherme Blanco <guilhermeblanco@hotmail.com>
* @author Alexander <iam.asm89@gmail.com>
* @since 2.0
*/
class OneToManyPersister extends AbstractCollectionPersister
{
/**
* {@inheritdoc}
*
* @return int|null
*/
public function delete(PersistentCollection $collection)
{
// The only valid case here is when you have weak entities. In this
// scenario, you have @OneToMany with orphanRemoval=true, and replacing
// the entire collection with a new would trigger this operation.
$mapping = $collection->getMapping();
if ( ! $mapping['orphanRemoval']) {
// Handling non-orphan removal should never happen, as @OneToMany
// can only be inverse side. For owning side one to many, it is
// required to have a join table, which would classify as a ManyToManyPersister.
return;
}
$targetClass = $this->em->getClassMetadata($mapping['targetEntity']);
return $targetClass->isInheritanceTypeJoined()
? $this->deleteJoinedEntityCollection($collection)
: $this->deleteEntityCollection($collection);
}
/**
* {@inheritdoc}
*/
public function update(PersistentCollection $collection)
{
// This can never happen. One to many can only be inverse side.
// For owning side one to many, it is required to have a join table,
// then classifying it as a ManyToManyPersister.
return;
}
/**
* {@inheritdoc}
*/
public function get(PersistentCollection $collection, $index)
{
$mapping = $collection->getMapping();
if ( ! isset($mapping['indexBy'])) {
throw new \BadMethodCallException("Selecting a collection by index is only supported on indexed collections.");
}
$persister = $this->uow->getEntityPersister($mapping['targetEntity']);
return $persister->load(
[
$mapping['mappedBy'] => $collection->getOwner(),
$mapping['indexBy'] => $index
],
null,
$mapping,
[],
null,
1
);
}
/**
* {@inheritdoc}
*/
public function count(PersistentCollection $collection)
{
$mapping = $collection->getMapping();
$persister = $this->uow->getEntityPersister($mapping['targetEntity']);
// only works with single id identifier entities. Will throw an
// exception in Entity Persisters if that is not the case for the
// 'mappedBy' field.
$criteria = new Criteria(Criteria::expr()->eq($mapping['mappedBy'], $collection->getOwner()));
return $persister->count($criteria);
}
/**
* {@inheritdoc}
*/
public function slice(PersistentCollection $collection, $offset, $length = null)
{
$mapping = $collection->getMapping();
$persister = $this->uow->getEntityPersister($mapping['targetEntity']);
return $persister->getOneToManyCollection($mapping, $collection->getOwner(), $offset, $length);
}
/**
* {@inheritdoc}
*/
public function containsKey(PersistentCollection $collection, $key)
{
$mapping = $collection->getMapping();
if ( ! isset($mapping['indexBy'])) {
throw new \BadMethodCallException("Selecting a collection by index is only supported on indexed collections.");
}
$persister = $this->uow->getEntityPersister($mapping['targetEntity']);
// only works with single id identifier entities. Will throw an
// exception in Entity Persisters if that is not the case for the
// 'mappedBy' field.
$criteria = new Criteria();
$criteria->andWhere(Criteria::expr()->eq($mapping['mappedBy'], $collection->getOwner()));
$criteria->andWhere(Criteria::expr()->eq($mapping['indexBy'], $key));
return (bool) $persister->count($criteria);
}
/**
* {@inheritdoc}
*/
public function contains(PersistentCollection $collection, $element)
{
if ( ! $this->isValidEntityState($element)) {
return false;
}
$mapping = $collection->getMapping();
$persister = $this->uow->getEntityPersister($mapping['targetEntity']);
// only works with single id identifier entities. Will throw an
// exception in Entity Persisters if that is not the case for the
// 'mappedBy' field.
$criteria = new Criteria(Criteria::expr()->eq($mapping['mappedBy'], $collection->getOwner()));
return $persister->exists($element, $criteria);
}
/**
* {@inheritdoc}
*/
public function loadCriteria(PersistentCollection $collection, Criteria $criteria)
{
throw new \BadMethodCallException("Filtering a collection by Criteria is not supported by this CollectionPersister.");
}
/**
* @param PersistentCollection $collection
*
* @return int
*
* @throws \Doctrine\DBAL\DBALException
*/
private function deleteEntityCollection(PersistentCollection $collection)
{
$mapping = $collection->getMapping();
$identifier = $this->uow->getEntityIdentifier($collection->getOwner());
$sourceClass = $this->em->getClassMetadata($mapping['sourceEntity']);
$targetClass = $this->em->getClassMetadata($mapping['targetEntity']);
$columns = [];
$parameters = [];
foreach ($targetClass->associationMappings[$mapping['mappedBy']]['joinColumns'] as $joinColumn) {
$columns[] = $this->quoteStrategy->getJoinColumnName($joinColumn, $targetClass, $this->platform);
$parameters[] = $identifier[$sourceClass->getFieldForColumn($joinColumn['referencedColumnName'])];
}
$statement = 'DELETE FROM ' . $this->quoteStrategy->getTableName($targetClass, $this->platform)
. ' WHERE ' . implode(' = ? AND ', $columns) . ' = ?';
return $this->conn->executeUpdate($statement, $parameters);
}
/**
* Delete Class Table Inheritance entities.
* A temporary table is needed to keep IDs to be deleted in both parent and child class' tables.
*
* Thanks Steve Ebersole (Hibernate) for idea on how to tackle reliably this scenario, we owe him a beer! =)
*
* @param PersistentCollection $collection
*
* @return int
*
* @throws \Doctrine\DBAL\DBALException
*/
private function deleteJoinedEntityCollection(PersistentCollection $collection)
{
$mapping = $collection->getMapping();
$sourceClass = $this->em->getClassMetadata($mapping['sourceEntity']);
$targetClass = $this->em->getClassMetadata($mapping['targetEntity']);
$rootClass = $this->em->getClassMetadata($targetClass->rootEntityName);
// 1) Build temporary table DDL
$tempTable = $this->platform->getTemporaryTableName($rootClass->getTemporaryIdTableName());
$idColumnNames = $rootClass->getIdentifierColumnNames();
$idColumnList = implode(', ', $idColumnNames);
$columnDefinitions = [];
foreach ($idColumnNames as $idColumnName) {
$columnDefinitions[$idColumnName] = [
'notnull' => true,
'type' => Type::getType(PersisterHelper::getTypeOfColumn($idColumnName, $rootClass, $this->em)),
];
}
$statement = $this->platform->getCreateTemporaryTableSnippetSQL() . ' ' . $tempTable
. ' (' . $this->platform->getColumnDeclarationListSQL($columnDefinitions) . ')';
$this->conn->executeUpdate($statement);
// 2) Build insert table records into temporary table
$query = $this->em->createQuery(
' SELECT t0.' . implode(', t0.', $rootClass->getIdentifierFieldNames())
. ' FROM ' . $targetClass->name . ' t0 WHERE t0.' . $mapping['mappedBy'] . ' = :owner'
)->setParameter('owner', $collection->getOwner());
$statement = 'INSERT INTO ' . $tempTable . ' (' . $idColumnList . ') ' . $query->getSQL();
$parameters = array_values($sourceClass->getIdentifierValues($collection->getOwner()));
$numDeleted = $this->conn->executeUpdate($statement, $parameters);
// 3) Delete records on each table in the hierarchy
$classNames = array_merge($targetClass->parentClasses, [$targetClass->name], $targetClass->subClasses);
foreach (array_reverse($classNames) as $className) {
$tableName = $this->quoteStrategy->getTableName($this->em->getClassMetadata($className), $this->platform);
$statement = 'DELETE FROM ' . $tableName . ' WHERE (' . $idColumnList . ')'
. ' IN (SELECT ' . $idColumnList . ' FROM ' . $tempTable . ')';
$this->conn->executeUpdate($statement);
}
// 4) Drop temporary table
$statement = $this->platform->getDropTemporaryTableSQL($tempTable);
$this->conn->executeUpdate($statement);
return $numDeleted;
}
}

View File

@@ -0,0 +1,99 @@
<?php
/*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* This software consists of voluntary contributions made by many individuals
* and is licensed under the MIT license. For more information, see
* <http://www.doctrine-project.org>.
*/
namespace Doctrine\ORM\Persisters\Entity;
use Doctrine\ORM\Mapping\ClassMetadata;
use Doctrine\DBAL\Types\Type;
/**
* Base class for entity persisters that implement a certain inheritance mapping strategy.
* All these persisters are assumed to use a discriminator column to discriminate entity
* types in the hierarchy.
*
* @author Roman Borschel <roman@code-factory.org>
* @author Benjamin Eberlei <kontakt@beberlei.de>
* @since 2.0
*/
abstract class AbstractEntityInheritancePersister extends BasicEntityPersister
{
/**
* {@inheritdoc}
*/
protected function prepareInsertData($entity)
{
$data = parent::prepareInsertData($entity);
// Populate the discriminator column
$discColumn = $this->class->discriminatorColumn;
$this->columnTypes[$discColumn['name']] = $discColumn['type'];
$data[$this->getDiscriminatorColumnTableName()][$discColumn['name']] = $this->class->discriminatorValue;
return $data;
}
/**
* Gets the name of the table that contains the discriminator column.
*
* @return string The table name.
*/
abstract protected function getDiscriminatorColumnTableName();
/**
* {@inheritdoc}
*/
protected function getSelectColumnSQL($field, ClassMetadata $class, $alias = 'r')
{
$tableAlias = $alias == 'r' ? '' : $alias;
$fieldMapping = $class->fieldMappings[$field];
$columnAlias = $this->getSQLColumnAlias($fieldMapping['columnName']);
$sql = sprintf(
'%s.%s',
$this->getSQLTableAlias($class->name, $tableAlias),
$this->quoteStrategy->getColumnName($field, $class, $this->platform)
);
$this->currentPersisterContext->rsm->addFieldResult($alias, $columnAlias, $field, $class->name);
if (isset($fieldMapping['requireSQLConversion'])) {
$type = Type::getType($fieldMapping['type']);
$sql = $type->convertToPHPValueSQL($sql, $this->platform);
}
return $sql . ' AS ' . $columnAlias;
}
/**
* @param string $tableAlias
* @param string $joinColumnName
* @param string $quotedColumnName
*
* @param string $type
*
* @return string
*/
protected function getSelectJoinColumnSQL($tableAlias, $joinColumnName, $quotedColumnName, $type)
{
$columnAlias = $this->getSQLColumnAlias($joinColumnName);
$this->currentPersisterContext->rsm->addMetaResult('r', $columnAlias, $joinColumnName, false, $type);
return $tableAlias . '.' . $quotedColumnName . ' AS ' . $columnAlias;
}
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,103 @@
<?php
/*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* This software consists of voluntary contributions made by many individuals
* and is licensed under the MIT license. For more information, see
* <http://www.doctrine-project.org>.
*/
namespace Doctrine\ORM\Persisters\Entity;
use Doctrine\ORM\Query\ResultSetMapping;
use Doctrine\Persistence\Mapping\ClassMetadata;
/**
* A swappable persister context to use as a container for the current
* generated query/resultSetMapping/type binding information.
*
* This class is a utility class to be used only by the persister API
*
* This object is highly mutable due to performance reasons. Same reasoning
* behind its properties being public.
*
* @author Marco Pivetta <ocramius@gmail.com>
*/
class CachedPersisterContext
{
/**
* Metadata object that describes the mapping of the mapped entity class.
*
* @var \Doctrine\ORM\Mapping\ClassMetadata
*/
public $class;
/**
* ResultSetMapping that is used for all queries. Is generated lazily once per request.
*
* @var \Doctrine\ORM\Query\ResultSetMapping
*/
public $rsm;
/**
* The SELECT column list SQL fragment used for querying entities by this persister.
* This SQL fragment is only generated once per request, if at all.
*
* @var string|null
*/
public $selectColumnListSql;
/**
* The JOIN SQL fragment used to eagerly load all many-to-one and one-to-one
* associations configured as FETCH_EAGER, as well as all inverse one-to-one associations.
*
* @var string
*/
public $selectJoinSql;
/**
* Counter for creating unique SQL table and column aliases.
*
* @var integer
*/
public $sqlAliasCounter = 0;
/**
* Map from class names (FQCN) to the corresponding generated SQL table aliases.
*
* @var array
*/
public $sqlTableAliases = [];
/**
* Whether this persistent context is considering limit operations applied to the selection queries
*
* @var bool
*/
public $handlesLimits;
/**
* @param ClassMetadata $class
* @param ResultSetMapping $rsm
* @param bool $handlesLimits
*/
public function __construct(
ClassMetadata $class,
ResultSetMapping $rsm,
$handlesLimits
) {
$this->class = $class;
$this->rsm = $rsm;
$this->handlesLimits = (bool) $handlesLimits;
}
}

View File

@@ -0,0 +1,330 @@
<?php
/*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* This software consists of voluntary contributions made by many individuals
* and is licensed under the MIT license. For more information, see
* <http://www.doctrine-project.org>.
*/
namespace Doctrine\ORM\Persisters\Entity;
use Doctrine\ORM\PersistentCollection;
use Doctrine\Common\Collections\Criteria;
/**
* Entity persister interface
* Define the behavior that should be implemented by all entity persisters.
*
* @author Fabio B. Silva <fabio.bat.silva@gmail.com>
* @since 2.5
*/
interface EntityPersister
{
/**
* @return \Doctrine\ORM\Mapping\ClassMetadata
*/
public function getClassMetadata();
/**
* Gets the ResultSetMapping used for hydration.
*
* @return \Doctrine\ORM\Query\ResultSetMapping
*/
public function getResultSetMapping();
/**
* Get all queued inserts.
*
* @return array
*/
public function getInserts();
/**
* @TODO - It should not be here.
* But its necessary since JoinedSubclassPersister#executeInserts invoke the root persister.
*
* Gets the INSERT SQL used by the persister to persist a new entity.
*
* @return string
*/
public function getInsertSQL();
/**
* Gets the SELECT SQL to select one or more entities by a set of field criteria.
*
* @param array|\Doctrine\Common\Collections\Criteria $criteria
* @param array|null $assoc
* @param int|null $lockMode
* @param int|null $limit
* @param int|null $offset
* @param array|null $orderBy
*
* @return string
*/
public function getSelectSQL($criteria, $assoc = null, $lockMode = null, $limit = null, $offset = null, array $orderBy = null);
/**
* Get the COUNT SQL to count entities (optionally based on a criteria)
*
* @param array|\Doctrine\Common\Collections\Criteria $criteria
*
* @return string
*/
public function getCountSQL($criteria = []);
/**
* Expands the parameters from the given criteria and use the correct binding types if found.
*
* @param string[] $criteria
*
* @return array
*/
public function expandParameters($criteria);
/**
* Expands Criteria Parameters by walking the expressions and grabbing all parameters and types from it.
*
* @param \Doctrine\Common\Collections\Criteria $criteria
*
* @return array
*/
public function expandCriteriaParameters(Criteria $criteria);
/**
* Gets the SQL WHERE condition for matching a field with a given value.
*
* @param string $field
* @param mixed $value
* @param array|null $assoc
* @param string|null $comparison
*
* @return string
*/
public function getSelectConditionStatementSQL($field, $value, $assoc = null, $comparison = null);
/**
* Adds an entity to the queued insertions.
* The entity remains queued until {@link executeInserts} is invoked.
*
* @param object $entity The entity to queue for insertion.
*
* @return void
*/
public function addInsert($entity);
/**
* Executes all queued entity insertions and returns any generated post-insert
* identifiers that were created as a result of the insertions.
*
* If no inserts are queued, invoking this method is a NOOP.
*
* @return array An array of any generated post-insert IDs. This will be an empty array
* if the entity class does not use the IDENTITY generation strategy.
*/
public function executeInserts();
/**
* Updates a managed entity. The entity is updated according to its current changeset
* in the running UnitOfWork. If there is no changeset, nothing is updated.
*
* @param object $entity The entity to update.
*
* @return void
*/
public function update($entity);
/**
* Deletes a managed entity.
*
* The entity to delete must be managed and have a persistent identifier.
* The deletion happens instantaneously.
*
* Subclasses may override this method to customize the semantics of entity deletion.
*
* @param object $entity The entity to delete.
*
* @return bool TRUE if the entity got deleted in the database, FALSE otherwise.
*/
public function delete($entity);
/**
* Count entities (optionally filtered by a criteria)
*
* @param array|\Doctrine\Common\Collections\Criteria $criteria
*
* @return int
*/
public function count($criteria = []);
/**
* Gets the name of the table that owns the column the given field is mapped to.
*
* The default implementation in BasicEntityPersister always returns the name
* of the table the entity type of this persister is mapped to, since an entity
* is always persisted to a single table with a BasicEntityPersister.
*
* @param string $fieldName The field name.
*
* @return string The table name.
*/
public function getOwningTable($fieldName);
/**
* Loads an entity by a list of field criteria.
*
* @param array $criteria The criteria by which to load the entity.
* @param object|null $entity The entity to load the data into. If not specified, a new entity is created.
* @param array|null $assoc The association that connects the entity to load to another entity, if any.
* @param array $hints Hints for entity creation.
* @param int|null $lockMode One of the \Doctrine\DBAL\LockMode::* constants
* or NULL if no specific lock mode should be used
* for loading the entity.
* @param int|null $limit Limit number of results.
* @param array|null $orderBy Criteria to order by.
*
* @return object|null The loaded and managed entity instance or NULL if the entity can not be found.
*
* @todo Check identity map? loadById method? Try to guess whether $criteria is the id?
*/
public function load(array $criteria, $entity = null, $assoc = null, array $hints = [], $lockMode = null, $limit = null, array $orderBy = null);
/**
* Loads an entity by identifier.
*
* @param array $identifier The entity identifier.
* @param object|null $entity The entity to load the data into. If not specified, a new entity is created.
*
* @return object The loaded and managed entity instance or NULL if the entity can not be found.
*
* @todo Check parameters
*/
public function loadById(array $identifier, $entity = null);
/**
* Loads an entity of this persister's mapped class as part of a single-valued
* association from another entity.
*
* @param array $assoc The association to load.
* @param object $sourceEntity The entity that owns the association (not necessarily the "owning side").
* @param array $identifier The identifier of the entity to load. Must be provided if
* the association to load represents the owning side, otherwise
* the identifier is derived from the $sourceEntity.
*
* @return object The loaded and managed entity instance or NULL if the entity can not be found.
*
* @throws \Doctrine\ORM\Mapping\MappingException
*/
public function loadOneToOneEntity(array $assoc, $sourceEntity, array $identifier = []);
/**
* Refreshes a managed entity.
*
* @param array $id The identifier of the entity as an associative array from
* column or field names to values.
* @param object $entity The entity to refresh.
* @param int|null $lockMode One of the \Doctrine\DBAL\LockMode::* constants
* or NULL if no specific lock mode should be used
* for refreshing the managed entity.
*
* @return void
*/
public function refresh(array $id, $entity, $lockMode = null);
/**
* Loads Entities matching the given Criteria object.
*
* @param \Doctrine\Common\Collections\Criteria $criteria
*
* @return array
*/
public function loadCriteria(Criteria $criteria);
/**
* Loads a list of entities by a list of field criteria.
*
* @param array $criteria
* @param array|null $orderBy
* @param int|null $limit
* @param int|null $offset
*
* @return array
*/
public function loadAll(array $criteria = [], array $orderBy = null, $limit = null, $offset = null);
/**
* Gets (sliced or full) elements of the given collection.
*
* @param array $assoc
* @param object $sourceEntity
* @param int|null $offset
* @param int|null $limit
*
* @return array
*/
public function getManyToManyCollection(array $assoc, $sourceEntity, $offset = null, $limit = null);
/**
* Loads a collection of entities of a many-to-many association.
*
* @param array $assoc The association mapping of the association being loaded.
* @param object $sourceEntity The entity that owns the collection.
* @param PersistentCollection $collection The collection to fill.
*
* @return array
*/
public function loadManyToManyCollection(array $assoc, $sourceEntity, PersistentCollection $collection);
/**
* Loads a collection of entities in a one-to-many association.
*
* @param array $assoc
* @param object $sourceEntity
* @param PersistentCollection $collection The collection to load/fill.
*
* @return array
*/
public function loadOneToManyCollection(array $assoc, $sourceEntity, PersistentCollection $collection);
/**
* Locks all rows of this entity matching the given criteria with the specified pessimistic lock mode.
*
* @param array $criteria
* @param int $lockMode One of the Doctrine\DBAL\LockMode::* constants.
*
* @return void
*/
public function lock(array $criteria, $lockMode);
/**
* Returns an array with (sliced or full list) of elements in the specified collection.
*
* @param array $assoc
* @param object $sourceEntity
* @param int|null $offset
* @param int|null $limit
*
* @return array
*/
public function getOneToManyCollection(array $assoc, $sourceEntity, $offset = null, $limit = null);
/**
* Checks whether the given managed entity exists in the database.
*
* @param object $entity
* @param Criteria|null $extraConditions
*
* @return boolean TRUE if the entity exists in the database, FALSE otherwise.
*/
public function exists($entity, Criteria $extraConditions = null);
}

View File

@@ -0,0 +1,618 @@
<?php
/*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* This software consists of voluntary contributions made by many individuals
* and is licensed under the MIT license. For more information, see
* <http://www.doctrine-project.org>.
*/
namespace Doctrine\ORM\Persisters\Entity;
use Doctrine\ORM\Mapping\ClassMetadata;
use Doctrine\DBAL\LockMode;
use Doctrine\DBAL\Types\Type;
use Doctrine\Common\Collections\Criteria;
use Doctrine\ORM\Utility\PersisterHelper;
use function array_combine;
/**
* The joined subclass persister maps a single entity instance to several tables in the
* database as it is defined by the <tt>Class Table Inheritance</tt> strategy.
*
* @author Roman Borschel <roman@code-factory.org>
* @author Benjamin Eberlei <kontakt@beberlei.de>
* @author Alexander <iam.asm89@gmail.com>
* @since 2.0
* @see http://martinfowler.com/eaaCatalog/classTableInheritance.html
*/
class JoinedSubclassPersister extends AbstractEntityInheritancePersister
{
/**
* Map that maps column names to the table names that own them.
* This is mainly a temporary cache, used during a single request.
*
* @var array
*/
private $owningTableMap = [];
/**
* Map of table to quoted table names.
*
* @var array
*/
private $quotedTableMap = [];
/**
* {@inheritdoc}
*/
protected function getDiscriminatorColumnTableName()
{
$class = ($this->class->name !== $this->class->rootEntityName)
? $this->em->getClassMetadata($this->class->rootEntityName)
: $this->class;
return $class->getTableName();
}
/**
* This function finds the ClassMetadata instance in an inheritance hierarchy
* that is responsible for enabling versioning.
*
* @return \Doctrine\ORM\Mapping\ClassMetadata
*/
private function getVersionedClassMetadata()
{
if (isset($this->class->fieldMappings[$this->class->versionField]['inherited'])) {
$definingClassName = $this->class->fieldMappings[$this->class->versionField]['inherited'];
return $this->em->getClassMetadata($definingClassName);
}
return $this->class;
}
/**
* Gets the name of the table that owns the column the given field is mapped to.
*
* @param string $fieldName
*
* @return string
*
* @override
*/
public function getOwningTable($fieldName)
{
if (isset($this->owningTableMap[$fieldName])) {
return $this->owningTableMap[$fieldName];
}
switch (true) {
case isset($this->class->associationMappings[$fieldName]['inherited']):
$cm = $this->em->getClassMetadata($this->class->associationMappings[$fieldName]['inherited']);
break;
case isset($this->class->fieldMappings[$fieldName]['inherited']):
$cm = $this->em->getClassMetadata($this->class->fieldMappings[$fieldName]['inherited']);
break;
default:
$cm = $this->class;
break;
}
$tableName = $cm->getTableName();
$quotedTableName = $this->quoteStrategy->getTableName($cm, $this->platform);
$this->owningTableMap[$fieldName] = $tableName;
$this->quotedTableMap[$tableName] = $quotedTableName;
return $tableName;
}
/**
* {@inheritdoc}
*/
public function executeInserts()
{
if ( ! $this->queuedInserts) {
return [];
}
$postInsertIds = [];
$idGenerator = $this->class->idGenerator;
$isPostInsertId = $idGenerator->isPostInsertGenerator();
$rootClass = ($this->class->name !== $this->class->rootEntityName)
? $this->em->getClassMetadata($this->class->rootEntityName)
: $this->class;
// Prepare statement for the root table
$rootPersister = $this->em->getUnitOfWork()->getEntityPersister($rootClass->name);
$rootTableName = $rootClass->getTableName();
$rootTableStmt = $this->conn->prepare($rootPersister->getInsertSQL());
// Prepare statements for sub tables.
$subTableStmts = [];
if ($rootClass !== $this->class) {
$subTableStmts[$this->class->getTableName()] = $this->conn->prepare($this->getInsertSQL());
}
foreach ($this->class->parentClasses as $parentClassName) {
$parentClass = $this->em->getClassMetadata($parentClassName);
$parentTableName = $parentClass->getTableName();
if ($parentClass !== $rootClass) {
$parentPersister = $this->em->getUnitOfWork()->getEntityPersister($parentClassName);
$subTableStmts[$parentTableName] = $this->conn->prepare($parentPersister->getInsertSQL());
}
}
// Execute all inserts. For each entity:
// 1) Insert on root table
// 2) Insert on sub tables
foreach ($this->queuedInserts as $entity) {
$insertData = $this->prepareInsertData($entity);
// Execute insert on root table
$paramIndex = 1;
foreach ($insertData[$rootTableName] as $columnName => $value) {
$rootTableStmt->bindValue($paramIndex++, $value, $this->columnTypes[$columnName]);
}
$rootTableStmt->execute();
if ($isPostInsertId) {
$generatedId = $idGenerator->generate($this->em, $entity);
$id = [
$this->class->identifier[0] => $generatedId
];
$postInsertIds[] = [
'generatedId' => $generatedId,
'entity' => $entity,
];
} else {
$id = $this->em->getUnitOfWork()->getEntityIdentifier($entity);
}
if ($this->class->isVersioned) {
$this->assignDefaultVersionValue($entity, $id);
}
// Execute inserts on subtables.
// The order doesn't matter because all child tables link to the root table via FK.
foreach ($subTableStmts as $tableName => $stmt) {
/** @var \Doctrine\DBAL\Statement $stmt */
$paramIndex = 1;
$data = $insertData[$tableName] ?? [];
foreach ((array) $id as $idName => $idVal) {
$type = isset($this->columnTypes[$idName]) ? $this->columnTypes[$idName] : Type::STRING;
$stmt->bindValue($paramIndex++, $idVal, $type);
}
foreach ($data as $columnName => $value) {
if (!is_array($id) || !isset($id[$columnName])) {
$stmt->bindValue($paramIndex++, $value, $this->columnTypes[$columnName]);
}
}
$stmt->execute();
}
}
$rootTableStmt->closeCursor();
foreach ($subTableStmts as $stmt) {
$stmt->closeCursor();
}
$this->queuedInserts = [];
return $postInsertIds;
}
/**
* {@inheritdoc}
*/
public function update($entity)
{
$updateData = $this->prepareUpdateData($entity);
if ( ! $updateData) {
return;
}
if (($isVersioned = $this->class->isVersioned) === false) {
return;
}
$versionedClass = $this->getVersionedClassMetadata();
$versionedTable = $versionedClass->getTableName();
foreach ($updateData as $tableName => $data) {
$tableName = $this->quotedTableMap[$tableName];
$versioned = $isVersioned && $versionedTable === $tableName;
$this->updateTable($entity, $tableName, $data, $versioned);
}
// Make sure the table with the version column is updated even if no columns on that
// table were affected.
if ($isVersioned) {
if ( ! isset($updateData[$versionedTable])) {
$tableName = $this->quoteStrategy->getTableName($versionedClass, $this->platform);
$this->updateTable($entity, $tableName, [], true);
}
$identifiers = $this->em->getUnitOfWork()->getEntityIdentifier($entity);
$this->assignDefaultVersionValue($entity, $identifiers);
}
}
/**
* {@inheritdoc}
*/
public function delete($entity)
{
$identifier = $this->em->getUnitOfWork()->getEntityIdentifier($entity);
$id = array_combine($this->class->getIdentifierColumnNames(), $identifier);
$this->deleteJoinTableRecords($identifier);
// If the database platform supports FKs, just
// delete the row from the root table. Cascades do the rest.
if ($this->platform->supportsForeignKeyConstraints()) {
$rootClass = $this->em->getClassMetadata($this->class->rootEntityName);
$rootTable = $this->quoteStrategy->getTableName($rootClass, $this->platform);
$rootTypes = $this->getClassIdentifiersTypes($rootClass);
return (bool) $this->conn->delete($rootTable, $id, $rootTypes);
}
// Delete from all tables individually, starting from this class' table up to the root table.
$rootTable = $this->quoteStrategy->getTableName($this->class, $this->platform);
$rootTypes = $this->getClassIdentifiersTypes($this->class);
$affectedRows = $this->conn->delete($rootTable, $id, $rootTypes);
foreach ($this->class->parentClasses as $parentClass) {
$parentMetadata = $this->em->getClassMetadata($parentClass);
$parentTable = $this->quoteStrategy->getTableName($parentMetadata, $this->platform);
$parentTypes = $this->getClassIdentifiersTypes($parentMetadata);
$this->conn->delete($parentTable, $id, $parentTypes);
}
return (bool) $affectedRows;
}
/**
* {@inheritdoc}
*/
public function getSelectSQL($criteria, $assoc = null, $lockMode = null, $limit = null, $offset = null, array $orderBy = null)
{
$this->switchPersisterContext($offset, $limit);
$baseTableAlias = $this->getSQLTableAlias($this->class->name);
$joinSql = $this->getJoinSql($baseTableAlias);
if ($assoc != null && $assoc['type'] == ClassMetadata::MANY_TO_MANY) {
$joinSql .= $this->getSelectManyToManyJoinSQL($assoc);
}
$conditionSql = ($criteria instanceof Criteria)
? $this->getSelectConditionCriteriaSQL($criteria)
: $this->getSelectConditionSQL($criteria, $assoc);
// If the current class in the root entity, add the filters
if ($filterSql = $this->generateFilterConditionSQL($this->em->getClassMetadata($this->class->rootEntityName), $this->getSQLTableAlias($this->class->rootEntityName))) {
$conditionSql .= $conditionSql
? ' AND ' . $filterSql
: $filterSql;
}
$orderBySql = '';
if ($assoc !== null && isset($assoc['orderBy'])) {
$orderBy = $assoc['orderBy'];
}
if ($orderBy) {
$orderBySql = $this->getOrderBySQL($orderBy, $baseTableAlias);
}
$lockSql = '';
switch ($lockMode) {
case LockMode::PESSIMISTIC_READ:
$lockSql = ' ' . $this->platform->getReadLockSQL();
break;
case LockMode::PESSIMISTIC_WRITE:
$lockSql = ' ' . $this->platform->getWriteLockSQL();
break;
}
$tableName = $this->quoteStrategy->getTableName($this->class, $this->platform);
$from = ' FROM ' . $tableName . ' ' . $baseTableAlias;
$where = $conditionSql != '' ? ' WHERE ' . $conditionSql : '';
$lock = $this->platform->appendLockHint($from, $lockMode);
$columnList = $this->getSelectColumnsSQL();
$query = 'SELECT ' . $columnList
. $lock
. $joinSql
. $where
. $orderBySql;
return $this->platform->modifyLimitQuery($query, $limit, $offset) . $lockSql;
}
/**
* {@inheritDoc}
*/
public function getCountSQL($criteria = [])
{
$tableName = $this->quoteStrategy->getTableName($this->class, $this->platform);
$baseTableAlias = $this->getSQLTableAlias($this->class->name);
$joinSql = $this->getJoinSql($baseTableAlias);
$conditionSql = ($criteria instanceof Criteria)
? $this->getSelectConditionCriteriaSQL($criteria)
: $this->getSelectConditionSQL($criteria);
$filterSql = $this->generateFilterConditionSQL($this->em->getClassMetadata($this->class->rootEntityName), $this->getSQLTableAlias($this->class->rootEntityName));
if ('' !== $filterSql) {
$conditionSql = $conditionSql
? $conditionSql . ' AND ' . $filterSql
: $filterSql;
}
$sql = 'SELECT COUNT(*) '
. 'FROM ' . $tableName . ' ' . $baseTableAlias
. $joinSql
. (empty($conditionSql) ? '' : ' WHERE ' . $conditionSql);
return $sql;
}
/**
* {@inheritdoc}
*/
protected function getLockTablesSql($lockMode)
{
$joinSql = '';
$identifierColumns = $this->class->getIdentifierColumnNames();
$baseTableAlias = $this->getSQLTableAlias($this->class->name);
// INNER JOIN parent tables
foreach ($this->class->parentClasses as $parentClassName) {
$conditions = [];
$tableAlias = $this->getSQLTableAlias($parentClassName);
$parentClass = $this->em->getClassMetadata($parentClassName);
$joinSql .= ' INNER JOIN ' . $this->quoteStrategy->getTableName($parentClass, $this->platform) . ' ' . $tableAlias . ' ON ';
foreach ($identifierColumns as $idColumn) {
$conditions[] = $baseTableAlias . '.' . $idColumn . ' = ' . $tableAlias . '.' . $idColumn;
}
$joinSql .= implode(' AND ', $conditions);
}
return parent::getLockTablesSql($lockMode) . $joinSql;
}
/**
* Ensure this method is never called. This persister overrides getSelectEntitiesSQL directly.
*
* @return string
*/
protected function getSelectColumnsSQL()
{
// Create the column list fragment only once
if ($this->currentPersisterContext->selectColumnListSql !== null) {
return $this->currentPersisterContext->selectColumnListSql;
}
$columnList = [];
$discrColumn = $this->class->discriminatorColumn['name'];
$discrColumnType = $this->class->discriminatorColumn['type'];
$baseTableAlias = $this->getSQLTableAlias($this->class->name);
$resultColumnName = $this->platform->getSQLResultCasing($discrColumn);
$this->currentPersisterContext->rsm->addEntityResult($this->class->name, 'r');
$this->currentPersisterContext->rsm->setDiscriminatorColumn('r', $resultColumnName);
$this->currentPersisterContext->rsm->addMetaResult('r', $resultColumnName, $discrColumn, false, $discrColumnType);
// Add regular columns
foreach ($this->class->fieldMappings as $fieldName => $mapping) {
$class = isset($mapping['inherited'])
? $this->em->getClassMetadata($mapping['inherited'])
: $this->class;
$columnList[] = $this->getSelectColumnSQL($fieldName, $class);
}
// Add foreign key columns
foreach ($this->class->associationMappings as $mapping) {
if ( ! $mapping['isOwningSide'] || ! ($mapping['type'] & ClassMetadata::TO_ONE)) {
continue;
}
$tableAlias = isset($mapping['inherited'])
? $this->getSQLTableAlias($mapping['inherited'])
: $baseTableAlias;
$targetClass = $this->em->getClassMetadata($mapping['targetEntity']);
foreach ($mapping['joinColumns'] as $joinColumn) {
$columnList[] = $this->getSelectJoinColumnSQL(
$tableAlias,
$joinColumn['name'],
$this->quoteStrategy->getJoinColumnName($joinColumn, $this->class, $this->platform),
PersisterHelper::getTypeOfColumn($joinColumn['referencedColumnName'], $targetClass, $this->em)
);
}
}
// Add discriminator column (DO NOT ALIAS, see AbstractEntityInheritancePersister#processSQLResult).
$tableAlias = ($this->class->rootEntityName == $this->class->name)
? $baseTableAlias
: $this->getSQLTableAlias($this->class->rootEntityName);
$columnList[] = $tableAlias . '.' . $discrColumn;
// sub tables
foreach ($this->class->subClasses as $subClassName) {
$subClass = $this->em->getClassMetadata($subClassName);
$tableAlias = $this->getSQLTableAlias($subClassName);
// Add subclass columns
foreach ($subClass->fieldMappings as $fieldName => $mapping) {
if (isset($mapping['inherited'])) {
continue;
}
$columnList[] = $this->getSelectColumnSQL($fieldName, $subClass);
}
// Add join columns (foreign keys)
foreach ($subClass->associationMappings as $mapping) {
if ( ! $mapping['isOwningSide']
|| ! ($mapping['type'] & ClassMetadata::TO_ONE)
|| isset($mapping['inherited'])) {
continue;
}
$targetClass = $this->em->getClassMetadata($mapping['targetEntity']);
foreach ($mapping['joinColumns'] as $joinColumn) {
$columnList[] = $this->getSelectJoinColumnSQL(
$tableAlias,
$joinColumn['name'],
$this->quoteStrategy->getJoinColumnName($joinColumn, $subClass, $this->platform),
PersisterHelper::getTypeOfColumn($joinColumn['referencedColumnName'], $targetClass, $this->em)
);
}
}
}
$this->currentPersisterContext->selectColumnListSql = implode(', ', $columnList);
return $this->currentPersisterContext->selectColumnListSql;
}
/**
* {@inheritdoc}
*/
protected function getInsertColumnList()
{
// Identifier columns must always come first in the column list of subclasses.
$columns = $this->class->parentClasses
? $this->class->getIdentifierColumnNames()
: [];
foreach ($this->class->reflFields as $name => $field) {
if (isset($this->class->fieldMappings[$name]['inherited'])
&& ! isset($this->class->fieldMappings[$name]['id'])
|| isset($this->class->associationMappings[$name]['inherited'])
|| ($this->class->isVersioned && $this->class->versionField == $name)
|| isset($this->class->embeddedClasses[$name])) {
continue;
}
if (isset($this->class->associationMappings[$name])) {
$assoc = $this->class->associationMappings[$name];
if ($assoc['type'] & ClassMetadata::TO_ONE && $assoc['isOwningSide']) {
foreach ($assoc['targetToSourceKeyColumns'] as $sourceCol) {
$columns[] = $sourceCol;
}
}
} else if ($this->class->name != $this->class->rootEntityName ||
! $this->class->isIdGeneratorIdentity() || $this->class->identifier[0] != $name) {
$columns[] = $this->quoteStrategy->getColumnName($name, $this->class, $this->platform);
$this->columnTypes[$name] = $this->class->fieldMappings[$name]['type'];
}
}
// Add discriminator column if it is the topmost class.
if ($this->class->name == $this->class->rootEntityName) {
$columns[] = $this->class->discriminatorColumn['name'];
}
return $columns;
}
/**
* {@inheritdoc}
*/
protected function assignDefaultVersionValue($entity, array $id)
{
$value = $this->fetchVersionValue($this->getVersionedClassMetadata(), $id);
$this->class->setFieldValue($entity, $this->class->versionField, $value);
}
/**
* @param string $baseTableAlias
*
* @return string
*/
private function getJoinSql($baseTableAlias)
{
$joinSql = '';
$identifierColumn = $this->class->getIdentifierColumnNames();
// INNER JOIN parent tables
foreach ($this->class->parentClasses as $parentClassName) {
$conditions = [];
$parentClass = $this->em->getClassMetadata($parentClassName);
$tableAlias = $this->getSQLTableAlias($parentClassName);
$joinSql .= ' INNER JOIN ' . $this->quoteStrategy->getTableName($parentClass, $this->platform) . ' ' . $tableAlias . ' ON ';
foreach ($identifierColumn as $idColumn) {
$conditions[] = $baseTableAlias . '.' . $idColumn . ' = ' . $tableAlias . '.' . $idColumn;
}
$joinSql .= implode(' AND ', $conditions);
}
// OUTER JOIN sub tables
foreach ($this->class->subClasses as $subClassName) {
$conditions = [];
$subClass = $this->em->getClassMetadata($subClassName);
$tableAlias = $this->getSQLTableAlias($subClassName);
$joinSql .= ' LEFT JOIN ' . $this->quoteStrategy->getTableName($subClass, $this->platform) . ' ' . $tableAlias . ' ON ';
foreach ($identifierColumn as $idColumn) {
$conditions[] = $baseTableAlias . '.' . $idColumn . ' = ' . $tableAlias . '.' . $idColumn;
}
$joinSql .= implode(' AND ', $conditions);
}
return $joinSql;
}
}

View File

@@ -0,0 +1,192 @@
<?php
/*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* This software consists of voluntary contributions made by many individuals
* and is licensed under the MIT license. For more information, see
* <http://www.doctrine-project.org>.
*/
namespace Doctrine\ORM\Persisters\Entity;
use Doctrine\ORM\Mapping\ClassMetadata;
use Doctrine\Common\Collections\Criteria;
use Doctrine\ORM\Utility\PersisterHelper;
/**
* Persister for entities that participate in a hierarchy mapped with the
* SINGLE_TABLE strategy.
*
* @author Roman Borschel <roman@code-factory.org>
* @author Benjamin Eberlei <kontakt@beberlei.de>
* @author Alexander <iam.asm89@gmail.com>
* @since 2.0
* @link http://martinfowler.com/eaaCatalog/singleTableInheritance.html
*/
class SingleTablePersister extends AbstractEntityInheritancePersister
{
/**
* {@inheritdoc}
*/
protected function getDiscriminatorColumnTableName()
{
return $this->class->getTableName();
}
/**
* {@inheritdoc}
*/
protected function getSelectColumnsSQL()
{
if ($this->currentPersisterContext->selectColumnListSql !== null) {
return $this->currentPersisterContext->selectColumnListSql;
}
$columnList[] = parent::getSelectColumnsSQL();
$rootClass = $this->em->getClassMetadata($this->class->rootEntityName);
$tableAlias = $this->getSQLTableAlias($rootClass->name);
// Append discriminator column
$discrColumn = $this->class->discriminatorColumn['name'];
$discrColumnType = $this->class->discriminatorColumn['type'];
$columnList[] = $tableAlias . '.' . $discrColumn;
$resultColumnName = $this->platform->getSQLResultCasing($discrColumn);
$this->currentPersisterContext->rsm->setDiscriminatorColumn('r', $resultColumnName);
$this->currentPersisterContext->rsm->addMetaResult('r', $resultColumnName, $discrColumn, false, $discrColumnType);
// Append subclass columns
foreach ($this->class->subClasses as $subClassName) {
$subClass = $this->em->getClassMetadata($subClassName);
// Regular columns
foreach ($subClass->fieldMappings as $fieldName => $mapping) {
if (isset($mapping['inherited'])) {
continue;
}
$columnList[] = $this->getSelectColumnSQL($fieldName, $subClass);
}
// Foreign key columns
foreach ($subClass->associationMappings as $assoc) {
if ( ! $assoc['isOwningSide'] || ! ($assoc['type'] & ClassMetadata::TO_ONE) || isset($assoc['inherited'])) {
continue;
}
$targetClass = $this->em->getClassMetadata($assoc['targetEntity']);
foreach ($assoc['joinColumns'] as $joinColumn) {
$columnList[] = $this->getSelectJoinColumnSQL(
$tableAlias,
$joinColumn['name'],
$this->quoteStrategy->getJoinColumnName($joinColumn, $subClass, $this->platform),
PersisterHelper::getTypeOfColumn($joinColumn['referencedColumnName'], $targetClass, $this->em)
);
}
}
}
$this->currentPersisterContext->selectColumnListSql = implode(', ', $columnList);
return $this->currentPersisterContext->selectColumnListSql;
}
/**
* {@inheritdoc}
*/
protected function getInsertColumnList()
{
$columns = parent::getInsertColumnList();
// Add discriminator column to the INSERT SQL
$columns[] = $this->class->discriminatorColumn['name'];
return $columns;
}
/**
* {@inheritdoc}
*/
protected function getSQLTableAlias($className, $assocName = '')
{
return parent::getSQLTableAlias($this->class->rootEntityName, $assocName);
}
/**
* {@inheritdoc}
*/
protected function getSelectConditionSQL(array $criteria, $assoc = null)
{
$conditionSql = parent::getSelectConditionSQL($criteria, $assoc);
if ($conditionSql) {
$conditionSql .= ' AND ';
}
return $conditionSql . $this->getSelectConditionDiscriminatorValueSQL();
}
/**
* {@inheritdoc}
*/
protected function getSelectConditionCriteriaSQL(Criteria $criteria)
{
$conditionSql = parent::getSelectConditionCriteriaSQL($criteria);
if ($conditionSql) {
$conditionSql .= ' AND ';
}
return $conditionSql . $this->getSelectConditionDiscriminatorValueSQL();
}
/**
* @return string
*/
protected function getSelectConditionDiscriminatorValueSQL()
{
$values = [];
if ($this->class->discriminatorValue !== null) { // discriminators can be 0
$values[] = $this->conn->quote($this->class->discriminatorValue);
}
$discrValues = array_flip($this->class->discriminatorMap);
foreach ($this->class->subClasses as $subclassName) {
$values[] = $this->conn->quote($discrValues[$subclassName]);
}
$values = implode(', ', $values);
$discColumn = $this->class->discriminatorColumn['name'];
$tableAlias = $this->getSQLTableAlias($this->class->name);
return $tableAlias . '.' . $discColumn . ' IN (' . $values . ')';
}
/**
* {@inheritdoc}
*/
protected function generateFilterConditionSQL(ClassMetadata $targetEntity, $targetTableAlias)
{
// Ensure that the filters are applied to the root entity of the inheritance tree
$targetEntity = $this->em->getClassMetadata($targetEntity->rootEntityName);
// we don't care about the $targetTableAlias, in a STI there is only one table.
return parent::generateFilterConditionSQL($targetEntity, $targetTableAlias);
}
}

View File

@@ -0,0 +1,40 @@
<?php
/*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* This software consists of voluntary contributions made by many individuals
* and is licensed under the MIT license. For more information, see
* <http://www.doctrine-project.org>.
*/
namespace Doctrine\ORM\Persisters;
use Doctrine\ORM\ORMException;
class PersisterException extends ORMException
{
/**
* @param string $class
* @param string $associationName
*
* @return PersisterException
*/
static public function matchingAssocationFieldRequiresObject($class, $associationName)
{
return new self(sprintf(
"Cannot match on %s::%s with a non-object value. Matching objects by id is " .
"not compatible with matching on an in-memory collection, which compares objects by reference.",
$class, $associationName
));
}
}

View File

@@ -0,0 +1,122 @@
<?php
/*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* This software consists of voluntary contributions made by many individuals
* and is licensed under the MIT license. For more information, see
* <http://www.doctrine-project.org>.
*/
namespace Doctrine\ORM\Persisters;
use Doctrine\ORM\Mapping\ClassMetadata;
use Doctrine\Common\Collections\Expr\ExpressionVisitor;
use Doctrine\Common\Collections\Expr\Comparison;
use Doctrine\Common\Collections\Expr\Value;
use Doctrine\Common\Collections\Expr\CompositeExpression;
use Doctrine\ORM\Persisters\Entity\BasicEntityPersister;
/**
* Visit Expressions and generate SQL WHERE conditions from them.
*
* @author Benjamin Eberlei <kontakt@beberlei.de>
* @since 2.3
*/
class SqlExpressionVisitor extends ExpressionVisitor
{
/**
* @var \Doctrine\ORM\Persisters\Entity\BasicEntityPersister
*/
private $persister;
/**
* @var \Doctrine\ORM\Mapping\ClassMetadata
*/
private $classMetadata;
/**
* @param \Doctrine\ORM\Persisters\Entity\BasicEntityPersister $persister
* @param \Doctrine\ORM\Mapping\ClassMetadata $classMetadata
*/
public function __construct(BasicEntityPersister $persister, ClassMetadata $classMetadata)
{
$this->persister = $persister;
$this->classMetadata = $classMetadata;
}
/**
* Converts a comparison expression into the target query language output.
*
* @param \Doctrine\Common\Collections\Expr\Comparison $comparison
*
* @return mixed
*/
public function walkComparison(Comparison $comparison)
{
$field = $comparison->getField();
$value = $comparison->getValue()->getValue(); // shortcut for walkValue()
if (isset($this->classMetadata->associationMappings[$field]) &&
$value !== null &&
! is_object($value) &&
! in_array($comparison->getOperator(), [Comparison::IN, Comparison::NIN])) {
throw PersisterException::matchingAssocationFieldRequiresObject($this->classMetadata->name, $field);
}
return $this->persister->getSelectConditionStatementSQL($field, $value, null, $comparison->getOperator());
}
/**
* Converts a composite expression into the target query language output.
*
* @param \Doctrine\Common\Collections\Expr\CompositeExpression $expr
*
* @return mixed
*
* @throws \RuntimeException
*/
public function walkCompositeExpression(CompositeExpression $expr)
{
$expressionList = [];
foreach ($expr->getExpressionList() as $child) {
$expressionList[] = $this->dispatch($child);
}
switch($expr->getType()) {
case CompositeExpression::TYPE_AND:
return '(' . implode(' AND ', $expressionList) . ')';
case CompositeExpression::TYPE_OR:
return '(' . implode(' OR ', $expressionList) . ')';
default:
throw new \RuntimeException("Unknown composite " . $expr->getType());
}
}
/**
* Converts a value expression into the target query language part.
*
* @param \Doctrine\Common\Collections\Expr\Value $value
*
* @return mixed
*/
public function walkValue(Value $value)
{
return '?';
}
}

View File

@@ -0,0 +1,130 @@
<?php
/*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* This software consists of voluntary contributions made by many individuals
* and is licensed under the MIT license. For more information, see
* <http://www.doctrine-project.org>.
*/
namespace Doctrine\ORM\Persisters;
use Doctrine\Common\Collections\Expr\ExpressionVisitor;
use Doctrine\Common\Collections\Expr\Comparison;
use Doctrine\Common\Collections\Expr\Value;
use Doctrine\Common\Collections\Expr\CompositeExpression;
/**
* Extract the values from a criteria/expression
*
* @author Benjamin Eberlei <kontakt@beberlei.de>
*/
class SqlValueVisitor extends ExpressionVisitor
{
/**
* @var array
*/
private $values = [];
/**
* @var array
*/
private $types = [];
/**
* Converts a comparison expression into the target query language output.
*
* @param \Doctrine\Common\Collections\Expr\Comparison $comparison
*
* @return void
*/
public function walkComparison(Comparison $comparison)
{
$value = $this->getValueFromComparison($comparison);
$field = $comparison->getField();
$operator = $comparison->getOperator();
if (($operator === Comparison::EQ || $operator === Comparison::IS) && $value === null) {
return;
} else if ($operator === Comparison::NEQ && $value === null) {
return;
}
$this->values[] = $value;
$this->types[] = [$field, $value, $operator];
}
/**
* Converts a composite expression into the target query language output.
*
* @param \Doctrine\Common\Collections\Expr\CompositeExpression $expr
*
* @return void
*/
public function walkCompositeExpression(CompositeExpression $expr)
{
foreach ($expr->getExpressionList() as $child) {
$this->dispatch($child);
}
}
/**
* Converts a value expression into the target query language part.
*
* @param \Doctrine\Common\Collections\Expr\Value $value
*
* @return mixed
*/
public function walkValue(Value $value)
{
return;
}
/**
* Returns the Parameters and Types necessary for matching the last visited expression.
*
* @return mixed[][]
*
* @psalm-return array{0: array, 1: array}
*/
public function getParamsAndTypes()
{
return [$this->values, $this->types];
}
/**
* Returns the value from a Comparison. In case of a CONTAINS comparison,
* the value is wrapped in %-signs, because it will be used in a LIKE clause.
*
* @param \Doctrine\Common\Collections\Expr\Comparison $comparison
* @return mixed
*/
protected function getValueFromComparison(Comparison $comparison)
{
$value = $comparison->getValue()->getValue();
switch ($comparison->getOperator()) {
case Comparison::CONTAINS:
return "%{$value}%";
case Comparison::STARTS_WITH:
return "{$value}%";
case Comparison::ENDS_WITH:
return "%{$value}";
default:
return $value;
}
}
}