ManyToManyMapping.php 7.58 KB
Newer Older
romanb's avatar
romanb committed
1
<?php
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
/*
 *  $Id$
 *
 * 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 LGPL. For more information, see
 * <http://www.doctrine-project.org>.
 */
romanb's avatar
romanb committed
21

22 23
namespace Doctrine\ORM\Mapping;

romanb's avatar
romanb committed
24 25 26 27
/**
 * A many-to-many mapping describes the mapping between two collections of
 * entities.
 *
28 29 30
 * <b>IMPORTANT NOTE:</b>
 *
 * The fields of this class are only public for 2 reasons:
31
 * 1) To allow fast READ access.
32 33 34
 * 2) To drastically reduce the size of a serialized instance (private/protected members
 *    get the whole class name, namespace inclusive, prepended to every property in
 *    the serialized representation).
35 36 37
 *    
 * Instances of this class are stored serialized in the metadata cache together with the
 * owning <tt>ClassMetadata</tt> instance.
38
 *
romanb's avatar
romanb committed
39
 * @since 2.0
40
 * @author Roman Borschel <roman@code-factory.org>
41
 * @author Giorgio Sironi <piccoloprincipeazzurro@gmail.com>
romanb's avatar
romanb committed
42
 */
43 44
class ManyToManyMapping extends AssociationMapping
{
romanb's avatar
romanb committed
45
    /**
46
     * READ-ONLY: Maps the columns in the relational table to the columns in the source table.
romanb's avatar
romanb committed
47
     */
48
    public $relationToSourceKeyColumns = array();
romanb's avatar
romanb committed
49

50
    /**
51
     * READ-ONLY: Maps the columns in the relation table to the columns in the target table.
52
     */
53
    public $relationToTargetKeyColumns = array();
54 55

    /**
56
     * READ-ONLY: List of aggregated column names on the join table.
57
     */
58
    public $joinTableColumns = array();
romanb's avatar
romanb committed
59
    
romanb's avatar
romanb committed
60 61
    /** FUTURE: The key column mapping, if any. The key column holds the keys of the Collection. */
    //public $keyColumn;
62 63

    /**
64
     * READ-ONLY: Order this collection by the given DQL snippet.
65 66 67 68
     * 
     * Only simple unqualified field names and ASC|DESC are allowed
     *
     * @var array
69
     */
70 71
    public $orderBy;

romanb's avatar
romanb committed
72 73 74 75 76 77 78 79 80
    /**
     * Validates and completes the mapping.
     *
     * @param array $mapping
     * @override
     */
    protected function _validateAndCompleteMapping(array $mapping)
    {
        parent::_validateAndCompleteMapping($mapping);
81
        if ($this->isOwningSide) {
82
            // owning side MUST have a join table
83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102
            if ( ! isset($mapping['joinTable']) || ! $mapping['joinTable']) {
                // Apply default join table
                $sourceShortName = substr($this->sourceEntityName, strrpos($this->sourceEntityName, '\\') + 1);
                $targetShortName = substr($this->targetEntityName, strrpos($this->targetEntityName, '\\') + 1);
                $mapping['joinTable'] = array(
                    'name' => $sourceShortName .'_' . $targetShortName,
                    'joinColumns' => array(
                        array(
                            'name' => $sourceShortName . '_id',
                            'referencedColumnName' => 'id'
                        )
                    ),
                    'inverseJoinColumns' => array(
                        array(
                            'name' => $targetShortName . '_id',
                            'referencedColumnName' => 'id'
                        )
                    )
                );
                $this->joinTable = $mapping['joinTable'];
romanb's avatar
romanb committed
103
            }
104
            // owning side MUST specify joinColumns
105
            else if ( ! isset($mapping['joinTable']['joinColumns'])) {
106 107 108 109
                throw MappingException::missingRequiredOption(
                    $this->sourceFieldName, 'joinColumns', 
                    'Did you think of case sensitivity / plural s?'
                );
110 111
            }
            // owning side MUST specify inverseJoinColumns
112
            else if ( ! isset($mapping['joinTable']['inverseJoinColumns'])) {
113 114 115 116
                throw MappingException::missingRequiredOption(
                    $this->sourceFieldName, 'inverseJoinColumns', 
                    'Did you think of case sensitivity / plural s?'
                );
117
            }
118
            
119
            foreach ($mapping['joinTable']['joinColumns'] as $joinColumn) {
120
                $this->relationToSourceKeyColumns[$joinColumn['name']] = $joinColumn['referencedColumnName'];
121 122 123
                $this->joinTableColumns[] = $joinColumn['name'];
            }
            
124
            foreach ($mapping['joinTable']['inverseJoinColumns'] as $inverseJoinColumn) {
125
                $this->relationToTargetKeyColumns[$inverseJoinColumn['name']] = $inverseJoinColumn['referencedColumnName'];
126
                $this->joinTableColumns[] = $inverseJoinColumn['name'];
127
            }
romanb's avatar
romanb committed
128
        }
129 130

        if (isset($mapping['orderBy'])) {
131
            if ( ! is_array($mapping['orderBy'])) {
132
                throw new \InvalidArgumentException("'orderBy' is expected to be an array, not ".gettype($mapping['orderBy']));
133
            }
134
            $this->orderBy = $mapping['orderBy'];
135
        }
romanb's avatar
romanb committed
136
    }
137

138 139 140 141
    /**
     * Loads entities in $targetCollection using $em.
     * The data of $sourceEntity are used to restrict the collection
     * via the join table.
142 143 144 145
     * 
     * @param object The owner of the collection.
     * @param object The collection to populate.
     * @param array
146 147
     */
    public function load($sourceEntity, $targetCollection, $em, array $joinColumnValues = array())
148
    {
149 150
        $sourceClass = $em->getClassMetadata($this->sourceEntityName);
        $joinTableConditions = array();
151
        if ($this->isOwningSide) {
152
            foreach ($this->relationToSourceKeyColumns as $relationKeyColumn => $sourceKeyColumn) {
153
                // getting id
romanb's avatar
romanb committed
154
                if (isset($sourceClass->fieldNames[$sourceKeyColumn])) {
155
                    $joinTableConditions[$relationKeyColumn] = $sourceClass->reflFields[$sourceClass->fieldNames[$sourceKeyColumn]]->getValue($sourceEntity);
156
                } else {
157 158 159
                    throw MappingException::joinColumnMustPointToMappedField(
                        $sourceClass->name, $sourceKeyColumn
                    );
160 161 162
                }
            }
        } else {
163
            $owningAssoc = $em->getClassMetadata($this->targetEntityName)->associationMappings[$this->mappedBy];
164
            // TRICKY: since the association is inverted source and target are flipped
165
            foreach ($owningAssoc->relationToTargetKeyColumns as $relationKeyColumn => $sourceKeyColumn) {
166
                // getting id
romanb's avatar
romanb committed
167
                if (isset($sourceClass->fieldNames[$sourceKeyColumn])) {
168
                    $joinTableConditions[$relationKeyColumn] = $sourceClass->reflFields[$sourceClass->fieldNames[$sourceKeyColumn]]->getValue($sourceEntity);
169
                } else {
170 171 172
                    throw MappingException::joinColumnMustPointToMappedField(
                        $sourceClass->name, $sourceKeyColumn
                    );
173 174 175
                }
            }
        }
176

177
        $persister = $em->getUnitOfWork()->getEntityPersister($this->targetEntityName);
178
        $persister->loadManyToManyCollection($this, $joinTableConditions, $targetCollection);
179 180 181
    }

    public function isManyToMany()
romanb's avatar
romanb committed
182
    {
183
        return true;
romanb's avatar
romanb committed
184
    }
185
}