text:
<?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 LGPL. For more information, see
 * <http://www.doctrine-project.org>.
 */

namespace Doctrine\ORM\Mapping\Driver;

use Doctrine\ORM\Mapping\ClassMetadataInfo,
    Doctrine\ORM\Mapping\MappingException;

/**
 * The YamlDriver reads the mapping metadata from yaml schema files.
 *
 * @since 2.0
 * @author Benjamin Eberlei <kontakt@beberlei.de>
 * @author Guilherme Blanco <guilhermeblanco@hotmail.com>
 * @author Jonathan H. Wage <jonwage@gmail.com>
 * @author Roman Borschel <roman@code-factory.org>
 */
class YamlDriver extends AbstractFileDriver
{
    /**
     * {@inheritdoc}
     */
    protected $_fileExtension = '.dcm.yml';

    /**
     * {@inheritdoc}
     */
    public function loadMetadataForClass($className, ClassMetadataInfo $metadata)
    {
        $element = $this->getElement($className);

        if ($element['type'] == 'entity') {
            $metadata->setCustomRepositoryClass(
                isset($element['repositoryClass']) ? $element['repositoryClass'] : null
            );
            if (isset($element['readOnly']) && $element['readOnly'] == true) {
                $metadata->markReadOnly();
            }
        } else if ($element['type'] == 'mappedSuperclass') {
            $metadata->isMappedSuperclass = true;
        } else {
            throw MappingException::classIsNotAValidEntityOrMappedSuperClass($className);
        }

        // Evaluate root level properties
        $table = array();
        if (isset($element['table'])) {
            $table['name'] = $element['table'];
        }
        $metadata->setPrimaryTable($table);

        // Evaluate named queries
        if (isset($element['namedQueries'])) {
            foreach ($element['namedQueries'] as $name => $queryMapping) {
                if (is_string($queryMapping)) {
                    $queryMapping = array('query' => $queryMapping);
                }

                if ( ! isset($queryMapping['name'])) {
                    $queryMapping['name'] = $name;
                }

                $metadata->addNamedQuery($queryMapping);
            }
        }

        /* not implemented specially anyway. use table = schema.table
        if (isset($element['schema'])) {
            $metadata->table['schema'] = $element['schema'];
        }*/

        if (isset($element['inheritanceType'])) {
            $metadata->setInheritanceType(constant('Doctrine\ORM\Mapping\ClassMetadata::INHERITANCE_TYPE_' . strtoupper($element['inheritanceType'])));

            if ($metadata->inheritanceType != \Doctrine\ORM\Mapping\ClassMetadata::INHERITANCE_TYPE_NONE) {
                // Evaluate discriminatorColumn
                if (isset($element['discriminatorColumn'])) {
                    $discrColumn = $element['discriminatorColumn'];
                    $metadata->setDiscriminatorColumn(array(
                        'name' => $discrColumn['name'],
                        'type' => $discrColumn['type'],
                        'length' => $discrColumn['length']
                    ));
                } else {
                    $metadata->setDiscriminatorColumn(array('name' => 'dtype', 'type' => 'string', 'length' => 255));
                }

                // Evaluate discriminatorMap
                if (isset($element['discriminatorMap'])) {
                    $metadata->setDiscriminatorMap($element['discriminatorMap']);
                }
            }
        }

        // Evaluate changeTrackingPolicy
        if (isset($element['changeTrackingPolicy'])) {
            $metadata->setChangeTrackingPolicy(constant('Doctrine\ORM\Mapping\ClassMetadata::CHANGETRACKING_'
                    . strtoupper($element['changeTrackingPolicy'])));
        }

        // Evaluate indexes
        if (isset($element['indexes'])) {
            foreach ($element['indexes'] as $name => $index) {
                if ( ! isset($index['name'])) {
                    $index['name'] = $name;
                }

                if (is_string($index['columns'])) {
                    $columns = explode(',', $index['columns']);
                } else {
                    $columns = $index['columns'];
                }

                $metadata->table['indexes'][$index['name']] = array(
                    'columns' => $columns
                );
            }
        }

        // Evaluate uniqueConstraints
        if (isset($element['uniqueConstraints'])) {
            foreach ($element['uniqueConstraints'] as $name => $unique) {
                if ( ! isset($unique['name'])) {
                    $unique['name'] = $name;
                }

                if (is_string($unique['columns'])) {
                    $columns = explode(',', $unique['columns']);
                } else {
                    $columns = $unique['columns'];
                }

                $metadata->table['uniqueConstraints'][$unique['name']] = array(
                    'columns' => $columns
                );
            }
        }

        $associationIds = array();
        if (isset($element['id'])) {
            // Evaluate identifier settings
            foreach ($element['id'] as $name => $idElement) {
                if (isset($idElement['associationKey']) && $idElement['associationKey'] == true) {
                    $associationIds[$name] = true;
                    continue;
                }

                if (!isset($idElement['type'])) {
                    throw MappingException::propertyTypeIsRequired($className, $name);
                }

                $mapping = array(
                    'id' => true,
                    'fieldName' => $name,
                    'type' => $idElement['type']
                );

                if (isset($idElement['column'])) {
                    $mapping['columnName'] = $idElement['column'];
                }

                if (isset($idElement['length'])) {
                    $mapping['length'] = $idElement['length'];
                }

                $metadata->mapField($mapping);

                if (isset($idElement['generator'])) {
                    $metadata->setIdGeneratorType(constant('Doctrine\ORM\Mapping\ClassMetadata::GENERATOR_TYPE_'
                            . strtoupper($idElement['generator']['strategy'])));
                }
                // Check for SequenceGenerator/TableGenerator definition
                if (isset($idElement['sequenceGenerator'])) {
                    $metadata->setSequenceGeneratorDefinition($idElement['sequenceGenerator']);
                } else if (isset($idElement['tableGenerator'])) {
                    throw MappingException::tableIdGeneratorNotImplemented($className);
                }
            }
        }

        // Evaluate fields
        if (isset($element['fields'])) {
            foreach ($element['fields'] as $name => $fieldMapping) {
                if (!isset($fieldMapping['type'])) {
                    throw MappingException::propertyTypeIsRequired($className, $name);
                }

                $e = explode('(', $fieldMapping['type']);
                $fieldMapping['type'] = $e[0];
                if (isset($e[1])) {
                    $fieldMapping['length'] = substr($e[1], 0, strlen($e[1]) - 1);
                }
                $mapping = array(
                    'fieldName' => $name,
                    'type' => $fieldMapping['type']
                );
                if (isset($fieldMapping['id'])) {
                    $mapping['id'] = true;
                    if (isset($fieldMapping['generator']['strategy'])) {
                        $metadata->setIdGeneratorType(constant('Doctrine\ORM\Mapping\ClassMetadata::GENERATOR_TYPE_'
                                . strtoupper($fieldMapping['generator']['strategy'])));
                    }
                }
                if (isset($fieldMapping['column'])) {
                    $mapping['columnName'] = $fieldMapping['column'];
                }
                if (isset($fieldMapping['length'])) {
                    $mapping['length'] = $fieldMapping['length'];
                }
                if (isset($fieldMapping['precision'])) {
                    $mapping['precision'] = $fieldMapping['precision'];
                }
                if (isset($fieldMapping['scale'])) {
                    $mapping['scale'] = $fieldMapping['scale'];
                }
                if (isset($fieldMapping['unique'])) {
                    $mapping['unique'] = (bool)$fieldMapping['unique'];
                }
                if (isset($fieldMapping['options'])) {
                    $mapping['options'] = $fieldMapping['options'];
                }
                if (isset($fieldMapping['nullable'])) {
                    $mapping['nullable'] = $fieldMapping['nullable'];
                }
                if (isset($fieldMapping['version']) && $fieldMapping['version']) {
                    $metadata->setVersionMapping($mapping);
                }
                if (isset($fieldMapping['columnDefinition'])) {
                    $mapping['columnDefinition'] = $fieldMapping['columnDefinition'];
                }

                $metadata->mapField($mapping);
            }
        }

        // Evaluate oneToOne relationships
        if (isset($element['oneToOne'])) {
            foreach ($element['oneToOne'] as $name => $oneToOneElement) {
                $mapping = array(
                    'fieldName' => $name,
                    'targetEntity' => $oneToOneElement['targetEntity']
                );

                if (isset($associationIds[$mapping['fieldName']])) {
                    $mapping['id'] = true;
                }

                if (isset($oneToOneElement['fetch'])) {
                    $mapping['fetch'] = constant('Doctrine\ORM\Mapping\ClassMetadata::FETCH_' . $oneToOneElement['fetch']);
                }

                if (isset($oneToOneElement['mappedBy'])) {
                    $mapping['mappedBy'] = $oneToOneElement['mappedBy'];
                } else {
                    if (isset($oneToOneElement['inversedBy'])) {
                        $mapping['inversedBy'] = $oneToOneElement['inversedBy'];
                    }

                    $joinColumns = array();

                    if (isset($oneToOneElement['joinColumn'])) {
                        $joinColumns[] = $this->_getJoinColumnMapping($oneToOneElement['joinColumn']);
                    } else if (isset($oneToOneElement['joinColumns'])) {
                        foreach ($oneToOneElement['joinColumns'] as $name => $joinColumnElement) {
                            if (!isset($joinColumnElement['name'])) {
                                $joinColumnElement['name'] = $name;
                            }

                            $joinColumns[] = $this->_getJoinColumnMapping($joinColumnElement);
                        }
                    }

                    $mapping['joinColumns'] = $joinColumns;
                }

                if (isset($oneToOneElement['cascade'])) {
                    $mapping['cascade'] = $oneToOneElement['cascade'];
                }

                if (isset($oneToOneElement['orphanRemoval'])) {
                    $mapping['orphanRemoval'] = (bool)$oneToOneElement['orphanRemoval'];
                }

                $metadata->mapOneToOne($mapping);
            }
        }

        // Evaluate oneToMany relationships
        if (isset($element['oneToMany'])) {
            foreach ($element['oneToMany'] as $name => $oneToManyElement) {
                $mapping = array(
                    'fieldName' => $name,
                    'targetEntity' => $oneToManyElement['targetEntity'],
                    'mappedBy' => $oneToManyElement['mappedBy']
                );

                if (isset($oneToManyElement['fetch'])) {
                    $mapping['fetch'] = constant('Doctrine\ORM\Mapping\ClassMetadata::FETCH_' . $oneToManyElement['fetch']);
                }

                if (isset($oneToManyElement['cascade'])) {
                    $mapping['cascade'] = $oneToManyElement['cascade'];
                }

                if (isset($oneToManyElement['orphanRemoval'])) {
                    $mapping['orphanRemoval'] = (bool)$oneToManyElement['orphanRemoval'];
                }

                if (isset($oneToManyElement['orderBy'])) {
                    $mapping['orderBy'] = $oneToManyElement['orderBy'];
                }

                if (isset($oneToManyElement['indexBy'])) {
                    $mapping['indexBy'] = $oneToManyElement['indexBy'];
                }

                $metadata->mapOneToMany($mapping);
            }
        }

        // Evaluate manyToOne relationships
        if (isset($element['manyToOne'])) {
            foreach ($element['manyToOne'] as $name => $manyToOneElement) {
                $mapping = array(
                    'fieldName' => $name,
                    'targetEntity' => $manyToOneElement['targetEntity']
                );

                if (isset($associationIds[$mapping['fieldName']])) {
                    $mapping['id'] = true;
                }

                if (isset($manyToOneElement['fetch'])) {
                    $mapping['fetch'] = constant('Doctrine\ORM\Mapping\ClassMetadata::FETCH_' . $manyToOneElement['fetch']);
                }

                if (isset($manyToOneElement['inversedBy'])) {
                    $mapping['inversedBy'] = $manyToOneElement['inversedBy'];
                }

                $joinColumns = array();

                if (isset($manyToOneElement['joinColumn'])) {
                    $joinColumns[] = $this->_getJoinColumnMapping($manyToOneElement['joinColumn']);
                } else if (isset($manyToOneElement['joinColumns'])) {
                    foreach ($manyToOneElement['joinColumns'] as $name => $joinColumnElement) {
                        if (!isset($joinColumnElement['name'])) {
                            $joinColumnElement['name'] = $name;
                        }

                        $joinColumns[] = $this->_getJoinColumnMapping($joinColumnElement);
                    }
                }

                $mapping['joinColumns'] = $joinColumns;

                if (isset($manyToOneElement['cascade'])) {
                    $mapping['cascade'] = $manyToOneElement['cascade'];
                }

                if (isset($manyToOneElement['orphanRemoval'])) {
                    $mapping['orphanRemoval'] = (bool)$manyToOneElement['orphanRemoval'];
                }

                $metadata->mapManyToOne($mapping);
            }
        }

        // Evaluate manyToMany relationships
        if (isset($element['manyToMany'])) {
            foreach ($element['manyToMany'] as $name => $manyToManyElement) {
                $mapping = array(
                    'fieldName' => $name,
                    'targetEntity' => $manyToManyElement['targetEntity']
                );

                if (isset($manyToManyElement['fetch'])) {
                    $mapping['fetch'] = constant('Doctrine\ORM\Mapping\ClassMetadata::FETCH_' . $manyToManyElement['fetch']);
                }

                if (isset($manyToManyElement['mappedBy'])) {
                    $mapping['mappedBy'] = $manyToManyElement['mappedBy'];
                } else if (isset($manyToManyElement['joinTable'])) {
                    if (isset($manyToManyElement['inversedBy'])) {
                        $mapping['inversedBy'] = $manyToManyElement['inversedBy'];
                    }

                    $joinTableElement = $manyToManyElement['joinTable'];
                    $joinTable = array(
                        'name' => $joinTableElement['name']
                    );

                    if (isset($joinTableElement['schema'])) {
                        $joinTable['schema'] = $joinTableElement['schema'];
                    }

                    foreach ($joinTableElement['joinColumns'] as $name => $joinColumnElement) {
                        if (!isset($joinColumnElement['name'])) {
                            $joinColumnElement['name'] = $name;
                        }

                        $joinTable['joinColumns'][] = $this->_getJoinColumnMapping($joinColumnElement);
                    }

                    foreach ($joinTableElement['inverseJoinColumns'] as $name => $joinColumnElement) {
                        if (!isset($joinColumnElement['name'])) {
                            $joinColumnElement['name'] = $name;
                        }

                        $joinTable['inverseJoinColumns'][] = $this->_getJoinColumnMapping($joinColumnElement);
                    }

                    $mapping['joinTable'] = $joinTable;
                }

                if (isset($manyToManyElement['cascade'])) {
                    $mapping['cascade'] = $manyToManyElement['cascade'];
                }

                if (isset($manyToManyElement['orphanRemoval'])) {
                    $mapping['orphanRemoval'] = (bool)$manyToManyElement['orphanRemoval'];
                }

                if (isset($manyToManyElement['orderBy'])) {
                    $mapping['orderBy'] = $manyToManyElement['orderBy'];
                }

                if (isset($manyToManyElement['indexBy'])) {
                    $mapping['indexBy'] = $manyToManyElement['indexBy'];
                }

                $metadata->mapManyToMany($mapping);
            }
        }

        // Evaluate lifeCycleCallbacks
        if (isset($element['lifecycleCallbacks'])) {
            foreach ($element['lifecycleCallbacks'] as $type => $methods) {
                foreach ($methods as $method) {
                    $metadata->addLifecycleCallback($method, constant('Doctrine\ORM\Events::' . $type));
                }
            }
        }
    }

    /**
     * Constructs a joinColumn mapping array based on the information
     * found in the given join column element.
     *
     * @param $joinColumnElement The array join column element
     * @return array The mapping array.
     */
    private function _getJoinColumnMapping($joinColumnElement)
    {
        $joinColumn = array(
            'name' => $joinColumnElement['name'],
            'referencedColumnName' => $joinColumnElement['referencedColumnName']
        );

        if (isset($joinColumnElement['fieldName'])) {
            $joinColumn['fieldName'] = (string) $joinColumnElement['fieldName'];
        }

        if (isset($joinColumnElement['unique'])) {
            $joinColumn['unique'] = (bool) $joinColumnElement['unique'];
        }

        if (isset($joinColumnElement['nullable'])) {
            $joinColumn['nullable'] = (bool) $joinColumnElement['nullable'];
        }

        if (isset($joinColumnElement['onDelete'])) {
            $joinColumn['onDelete'] = $joinColumnElement['onDelete'];
        }

        if (isset($joinColumnElement['onUpdate'])) {
            $joinColumn['onUpdate'] = $joinColumnElement['onUpdate'];
        }

        if (isset($joinColumnElement['columnDefinition'])) {
            $joinColumn['columnDefinition'] = $joinColumnElement['columnDefinition'];
        }

        return $joinColumn;
    }

    /**
     * {@inheritdoc}
     */
    protected function _loadMappingFile($file)
    {
        return \Symfony\Component\Yaml\Yaml::parse($file);
    }
}


text:
<?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 LGPL. For more information, see
 * <http://www.doctrine-project.org>.
*/

namespace Doctrine\ORM\Event;

/**
 * Lifecycle Events are triggered by the UnitOfWork during lifecycle transitions
 * of entities.
 *
 * @since 2.0
 * @author Roman Borschel <roman@code-factory.de>
 * @author Benjamin Eberlei <kontakt@beberlei.de>
 */
class LifecycleEventArgs extends \Doctrine\Common\EventArgs
{
    /**
     * @var EntityManager
     */
    private $_em;

    /**
     * @var object
     */
    private $_entity;

    public function __construct($entity, $em)
    {
        $this->_entity = $entity;
        $this->_em = $em;
    }

    public function getEntity()
    {
        return $this->_entity;
    }

    /**
     * @return EntityManager
     */
    public function getEntityManager()
    {
        return $this->_em;
    }
}

repo_name: michael-romer/zf-boilerplate

repo_language: PHP

mime_type: text/html


text:
<?php

namespace Doctrine\ORM\Event;

use Doctrine\Common\EventArgs;

use Doctrine\ORM\Mapping\ClassMetadataInfo;
use Doctrine\ORM\EntityManager;

/**
 * Class that holds event arguments for a loadMetadata event.
 *
 * @author Jonathan H. Wage <jonwage@gmail.com>
 * @since 2.0
 */
class LoadClassMetadataEventArgs extends EventArgs
{
    /**
     * @var ClassMetadata
     */
    private $classMetadata;

    /**
     * @var EntityManager
     */
    private $em;

    /**
     * @param ClassMetadataInfo $classMetadata
     * @param EntityManager $em
     */
    public function __construct(ClassMetadataInfo $classMetadata, EntityManager $em)
    {
        $this->classMetadata = $classMetadata;
        $this->em = $em;
    }

    /**
     * @return ClassMetadataInfo
     */
    public function getClassMetadata()
    {
        return $this->classMetadata;
    }

    /**
     * @return EntityManager
     */
    public function getEntityManager()
    {
        return $this->em;
    }
}


text:
<?php
/*
 *  $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>.
*/

namespace Doctrine\ORM\Event;

/**
 * Provides event arguments for the preFlush event.
 *
 * @license     http://www.opensource.org/licenses/lgpl-license.php LGPL
 * @link        www.doctrine-project.com
 * @since       2.0
 * @version     $Revision$
 * @author      Roman Borschel <roman@code-factory.de>
 * @author      Benjamin Eberlei <kontakt@beberlei.de>
 */
class OnFlushEventArgs extends \Doctrine\Common\EventArgs
{
    /**
     * @var EntityManager
     */
    private $_em;

    //private $_entitiesToPersist = array();
    //private $_entitiesToRemove = array();

    public function __construct($em)
    {
        $this->_em = $em;
    }

    /**
     * @return EntityManager
     */
    public function getEntityManager()
    {
        return $this->_em;
    }

    /*
    public function addEntityToPersist($entity)
    {

    }

    public function addEntityToRemove($entity)
    {

    }

    public function addEntityToUpdate($entity)
    {

    }

    public function getEntitiesToPersist()
    {
        return $this->_entitiesToPersist;
    }
    */
}


text:
<?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 LGPL. For more information, see
 * <http://www.doctrine-project.org>.
*/

namespace Doctrine\ORM\Event;

/**
 * Provides event arguments for the onClear event.
 *
 * @license     http://www.opensource.org/licenses/lgpl-license.php LGPL
 * @link        www.doctrine-project.com
 * @since       2.0
 * @version     $Revision$
 * @author      Roman Borschel <roman@code-factory.de>
 * @author      Benjamin Eberlei <kontakt@beberlei.de>
 */
class OnClearEventArgs extends \Doctrine\Common\EventArgs
{
    /**
     * @var \Doctrine\ORM\EntityManager
     */
    private $em;

    /**
     * @param \Doctrine\ORM\EntityManager $em
     */
    public function __construct($em)
    {
        $this->em = $em;
    }

    /**
     * @return \Doctrine\ORM\EntityManager
     */
    public function getEntityManager()
    {
        return $this->em;
    }
}


text:
<?php

namespace Doctrine\ORM\Event;

use Doctrine\Common\EventArgs,
    Doctrine\ORM\EntityManager;

/**
 * Class that holds event arguments for a preInsert/preUpdate event.
 *
 * @author Roman Borschel <roman@code-factory.org>
 * @author Benjamin Eberlei <kontakt@beberlei.de>
 * @since 2.0
 */
class PreUpdateEventArgs extends LifecycleEventArgs
{
    /**
     * @var array
     */
    private $_entityChangeSet;

    /**
     *
     * @param object $entity
     * @param EntityManager $em
     * @param array $changeSet
     */
    public function __construct($entity, $em, array &$changeSet)
    {
        parent::__construct($entity, $em);
        $this->_entityChangeSet = &$changeSet;
    }

    public function getEntityChangeSet()
    {
        return $this->_entityChangeSet;
    }

    /**
     * Field has a changeset?
     *
     * @return bool
     */
    public function hasChangedField($field)
    {
        return isset($this->_entityChangeSet[$field]);
    }

    /**
     * Get the old value of the changeset of the changed field.
     *
     * @param  string $field
     * @return mixed
     */
    public function getOldValue($field)
    {
    	$this->_assertValidField($field);

        return $this->_entityChangeSet[$field][0];
    }

    /**
     * Get the new value of the changeset of the changed field.
     *
     * @param  string $field
     * @return mixed
     */
    public function getNewValue($field)
    {
        $this->_assertValidField($field);

        return $this->_entityChangeSet[$field][1];
    }

    /**
     * Set the new value of this field.
     *
     * @param string $field
     * @param mixed $value
     */
    public function setNewValue($field, $value)
    {
        $this->_assertValidField($field);

        $this->_entityChangeSet[$field][1] = $value;
    }

    private function _assertValidField($field)
    {
    	if (!isset($this->_entityChangeSet[$field])) {
            throw new \InvalidArgumentException(
                "Field '".$field."' is not a valid field of the entity ".
                "'".get_class($this->getEntity())."' in PreInsertUpdateEventArgs."
            );
        }
    }
}


text:
<?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 LGPL. For more information, see
 * <http://www.doctrine-project.org>.
*/

namespace Doctrine\ORM\Tools;

use Doctrine\Common\ClassLoader;
use Doctrine\Common\Cache\Cache;
use Doctrine\Common\Cache\ArrayCache;
use Doctrine\ORM\Configuration;
use Doctrine\ORM\Mapping\Driver\XmlDriver;
use Doctrine\ORM\Mapping\Driver\YamlDriver;

/**
 * Convenience class for setting up Doctrine from different installations and configurations.
 *
 * @author Benjamin Eberlei <kontakt@beberlei.de>
 */
class Setup
{
    /**
     * Use this method to register all autoloaders for a setup where Doctrine is checked out from
     * its github repository at {@link http://github.com/doctrine/doctrine2}
     *
     * @param string $gitCheckoutRootPath
     * @return void
     */
    static public function registerAutoloadGit($gitCheckoutRootPath)
    {
        if (!class_exists('Doctrine\Common\ClassLoader', false)) {
            require_once $gitCheckoutRootPath . "/lib/vendor/doctrine-common/lib/Doctrine/Common/ClassLoader.php";
        }

        $loader = new ClassLoader("Doctrine\Common", $gitCheckoutRootPath . "/lib/vendor/doctrine-common/lib");
        $loader->register();

        $loader = new ClassLoader("Doctrine\DBAL", $gitCheckoutRootPath . "/lib/vendor/doctrine-dbal/lib");
        $loader->register();

        $loader = new ClassLoader("Doctrine\ORM", $gitCheckoutRootPath . "/lib");
        $loader->register();

        $loader = new ClassLoader("Symfony\Component", $gitCheckoutRootPath . "/lib/vendor");
        $loader->register();
    }

    /**
     * Use this method to register all autoloaders for a setup where Doctrine is installed
     * though {@link http://pear.doctrine-project.org}.
     *
     * @return void
     */
    static public function registerAutoloadPEAR()
    {
        if (!class_exists('Doctrine\Common\ClassLoader', false)) {
            require_once "Doctrine/Common/ClassLoader.php";
        }

        $loader = new ClassLoader("Doctrine");
        $loader->register();

        $parts = explode(PATH_SEPARATOR, get_include_path());

        foreach ($parts AS $includePath) {
            if ($includePath != "." && file_exists($includePath . "/Doctrine")) {
                $loader = new ClassLoader("Symfony\Component", $includePath . "/Doctrine");
                $loader->register();
                return;
            }
        }
    }

    /**
     * Use this method to register all autoloads for a downloaded Doctrine library.
     * Pick the directory the library was uncompressed into.
     *
     * @param string $directory
     */
    static public function registerAutoloadDirectory($directory)
    {
        if (!class_exists('Doctrine\Common\ClassLoader', false)) {
            require_once $directory . "/Doctrine/Common/ClassLoader.php";
        }

        $loader = new ClassLoader("Doctrine", $directory);
        $loader->register();

        $loader = new ClassLoader("Symfony\Component", $directory . "/Doctrine");
        $loader->register();
    }

    /**
     * Create a configuration with an annotation metadata driver.
     *
     * @param array $paths
     * @param boolean $isDevMode
     * @param string $proxyDir
     * @param Cache $cache
     * @return Configuration
     */
    static public function createAnnotationMetadataConfiguration(array $paths, $isDevMode = false, $proxyDir = null, Cache $cache = null)
    {
        $config = self::createConfiguration($isDevMode, $proxyDir, $cache);
        $config->setMetadataDriverImpl($config->newDefaultAnnotationDriver($paths));
        return $config;
    }

    /**
     * Create a configuration with an annotation metadata driver.
     *
     * @param array $paths
     * @param boolean $isDevMode
     * @param string $proxyDir
     * @param Cache $cache
     * @return Configuration
     */
    static public function createXMLMetadataConfiguration(array $paths, $isDevMode = false, $proxyDir = null, Cache $cache = null)
    {
        $config = self::createConfiguration($isDevMode, $proxyDir, $cache);
        $config->setMetadataDriverImpl(new XmlDriver($paths));
        return $config;
    }

    /**
     * Create a configuration with an annotation metadata driver.
     *
     * @param array $paths
     * @param boolean $isDevMode
     * @param string $proxyDir
     * @param Cache $cache
     * @return Configuration
     */
    static public function createYAMLMetadataConfiguration(array $paths, $isDevMode = false, $proxyDir = null, Cache $cache = null)
    {
        $config = self::createConfiguration($isDevMode, $proxyDir, $cache);
        $config->setMetadataDriverImpl(new YamlDriver($paths));
        return $config;
    }

    /**
     * Create a configuration without a metadata driver.
     *
     * @param bool $isDevMode
     * @param string $proxyDir
     * @param Cache $cache
     * @return Configuration
     */
    static public function createConfiguration($isDevMode = false, $proxyDir = null, Cache $cache = null)
    {
        $proxyDir = $proxyDir ?: sys_get_temp_dir();
        if ($isDevMode === false && $cache === null) {
            if (extension_loaded('apc')) {
                $cache = new \Doctrine\Common\Cache\ApcCache;
            } else if (extension_loaded('xcache')) {
                $cache = new \Doctrine\Common\Cache\XcacheCache;
            } else if (extension_loaded('memcache')) {
                $memcache = new \Memcache();
                $memcache->connect('127.0.0.1');
                $cache = new \Doctrine\Common\Cache\MemcacheCache();
                $cache->setMemcache($memcache);
            } else {
                $cache = new ArrayCache;
            }
        } else if ($cache === null) {
            $cache = new ArrayCache;
        }
        $cache->setNamespace("dc2_" . md5($proxyDir) . "_"); // to avoid collisions

        $config = new Configuration();
        $config->setMetadataCacheImpl($cache);
        $config->setQueryCacheImpl($cache);
        $config->setResultCacheImpl($cache);
        $config->setProxyDir( $proxyDir );
        $config->setProxyNamespace('DoctrineProxies');
        $config->setAutoGenerateProxyClasses($isDevMode);

        return $config;
    }
}


text:
<?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 LGPL. For more information, see
 * <http://www.doctrine-project.org>.
*/

namespace Doctrine\ORM\Tools;

use Doctrine\ORM\EntityManager;
use Doctrine\ORM\Mapping\ClassMetadataInfo;

/**
 * Performs strict validation of the mapping schema
 *
 * @license     http://www.opensource.org/licenses/lgpl-license.php LGPL
 * @link        www.doctrine-project.com
 * @since       1.0
 * @version     $Revision$
 * @author      Benjamin Eberlei <kontakt@beberlei.de>
 * @author      Guilherme Blanco <guilhermeblanco@hotmail.com>
 * @author      Jonathan Wage <jonwage@gmail.com>
 * @author      Roman Borschel <roman@code-factory.org>
 */
class SchemaValidator
{
    /**
     * @var EntityManager
     */
    private $em;

    /**
     * @param EntityManager $em
     */
    public function __construct(EntityManager $em)
    {
        $this->em = $em;
    }

    /**
     * Checks the internal consistency of mapping files.
     *
     * There are several checks that can't be done at runtime or are too expensive, which can be verified
     * with this command. For example:
     *
     * 1. Check if a relation with "mappedBy" is actually connected to that specified field.
     * 2. Check if "mappedBy" and "inversedBy" are consistent to each other.
     * 3. Check if "referencedColumnName" attributes are really pointing to primary key columns.
     * 4. Check if there are public properties that might cause problems with lazy loading.
     *
     * @return array
     */
    public function validateMapping()
    {
        $errors = array();
        $cmf = $this->em->getMetadataFactory();
        $classes = $cmf->getAllMetadata();

        foreach ($classes AS $class) {
            $ce = array();
            /* @var $class ClassMetadata */
            foreach ($class->associationMappings AS $fieldName => $assoc) {
                if (!$cmf->hasMetadataFor($assoc['targetEntity'])) {
                    $ce[] = "The target entity '" . $assoc['targetEntity'] . "' specified on " . $class->name . '#' . $fieldName . ' is unknown.';
                }

                if ($assoc['mappedBy'] && $assoc['inversedBy']) {
                    $ce[] = "The association " . $class . "#" . $fieldName . " cannot be defined as both inverse and owning.";
                }

                $targetMetadata = $cmf->getMetadataFor($assoc['targetEntity']);

                /* @var $assoc AssociationMapping */
                if ($assoc['mappedBy']) {
                    if ($targetMetadata->hasField($assoc['mappedBy'])) {
                        $ce[] = "The association " . $class->name . "#" . $fieldName . " refers to the owning side ".
                                "field " . $assoc['targetEntity'] . "#" . $assoc['mappedBy'] . " which is not defined as association.";
                    }
                    if (!$targetMetadata->hasAssociation($assoc['mappedBy'])) {
                        $ce[] = "The association " . $class->name . "#" . $fieldName . " refers to the owning side ".
                                "field " . $assoc['targetEntity'] . "#" . $assoc['mappedBy'] . " which does not exist.";
                    } else if ($targetMetadata->associationMappings[$assoc['mappedBy']]['inversedBy'] == null) {
                        $ce[] = "The field " . $class->name . "#" . $fieldName . " is on the inverse side of a ".
                                "bi-directional relationship, but the specified mappedBy association on the target-entity ".
                                $assoc['targetEntity'] . "#" . $assoc['mappedBy'] . " does not contain the required ".
                                "'inversedBy' attribute.";
                    } else  if ($targetMetadata->associationMappings[$assoc['mappedBy']]['inversedBy'] != $fieldName) {
                        $ce[] = "The mappings " . $class->name . "#" . $fieldName . " and " .
                                $assoc['targetEntity'] . "#" . $assoc['mappedBy'] . " are ".
                                "incosistent with each other.";
                    }
                }

                if ($assoc['inversedBy']) {
                    if ($targetMetadata->hasField($assoc['inversedBy'])) {
                        $ce[] = "The association " . $class->name . "#" . $fieldName . " refers to the inverse side ".
                                "field " . $assoc['targetEntity'] . "#" . $assoc['inversedBy'] . " which is not defined as association.";
                    }
                    if (!$targetMetadata->hasAssociation($assoc['inversedBy'])) {
                        $ce[] = "The association " . $class->name . "#" . $fieldName . " refers to the inverse side ".
                                "field " . $assoc['targetEntity'] . "#" . $assoc['inversedBy'] . " which does not exist.";
                    } else if ($targetMetadata->associationMappings[$assoc['inversedBy']]['mappedBy'] == null) {
                        $ce[] = "The field " . $class->name . "#" . $fieldName . " is on the owning side of a ".
                                "bi-directional relationship, but the specified mappedBy association on the target-entity ".
                                $assoc['targetEntity'] . "#" . $assoc['mappedBy'] . " does not contain the required ".
                                "'inversedBy' attribute.";
                    } else  if ($targetMetadata->associationMappings[$assoc['inversedBy']]['mappedBy'] != $fieldName) {
                        $ce[] = "The mappings " . $class->name . "#" . $fieldName . " and " .
                                $assoc['targetEntity'] . "#" . $assoc['inversedBy'] . " are ".
                                "incosistent with each other.";
                    }
                }

                if ($assoc['isOwningSide']) {
                    if ($assoc['type'] == ClassMetadataInfo::MANY_TO_MANY) {
                        foreach ($assoc['joinTable']['joinColumns'] AS $joinColumn) {
                            if (!isset($class->fieldNames[$joinColumn['referencedColumnName']])) {
                                $ce[] = "The referenced column name '" . $joinColumn['referencedColumnName'] . "' does not " .
                                        "have a corresponding field with this column name on the class '" . $class->name . "'.";
                                break;
                            }

                            $fieldName = $class->fieldNames[$joinColumn['referencedColumnName']];
                            if (!in_array($fieldName, $class->identifier)) {
                                $ce[] = "The referenced column name '" . $joinColumn['referencedColumnName'] . "' " .
                                        "has to be a primary key column.";
                            }
                        }
                        foreach ($assoc['joinTable']['inverseJoinColumns'] AS $inverseJoinColumn) {
                            $targetClass = $cmf->getMetadataFor($assoc['targetEntity']);
                            if (!isset($targetClass->fieldNames[$inverseJoinColumn['referencedColumnName']])) {
                                $ce[] = "The inverse referenced column name '" . $inverseJoinColumn['referencedColumnName'] . "' does not " .
                                        "have a corresponding field with this column name on the class '" . $targetClass->name . "'.";
                                break;
                            }

                            $fieldName = $targetClass->fieldNames[$inverseJoinColumn['referencedColumnName']];
                            if (!in_array($fieldName, $targetClass->identifier)) {
                                $ce[] = "The referenced column name '" . $inverseJoinColumn['referencedColumnName'] . "' " .
                                        "has to be a primary key column.";
                            }
                        }
                    } else if ($assoc['type'] & ClassMetadataInfo::TO_ONE) {
                        foreach ($assoc['joinColumns'] AS $joinColumn) {
                            $targetClass = $cmf->getMetadataFor($assoc['targetEntity']);
                            if (!isset($targetClass->fieldNames[$joinColumn['referencedColumnName']])) {
                                $ce[] = "The referenced column name '" . $joinColumn['referencedColumnName'] . "' does not " .
                                        "have a corresponding field with this column name on the class '" . $targetClass->name . "'.";
                                break;
                            }

                            $fieldName = $targetClass->fieldNames[$joinColumn['referencedColumnName']];
                            if (!in_array($fieldName, $targetClass->identifier)) {
                                $ce[] = "The referenced column name '" . $joinColumn['referencedColumnName'] . "' " .
                                        "has to be a primary key column.";
                            }
                        }
                    }
                }

                if (isset($assoc['orderBy']) && $assoc['orderBy'] !== null) {
                    $targetClass = $cmf->getMetadataFor($assoc['targetEntity']);
                    foreach ($assoc['orderBy'] AS $orderField => $orientation) {
                        if (!$targetClass->hasField($orderField)) {
                            $ce[] = "The association " . $class->name."#".$fieldName." is ordered by a foreign field " .
                                    $orderField . " that is not a field on the target entity " . $targetClass->name;
                        }
                    }
                }
            }

            foreach ($class->reflClass->getProperties(\ReflectionProperty::IS_PUBLIC) as $publicAttr) {
                if ($publicAttr->isStatic()) {
                    continue;
                }
                $ce[] = "Field '".$publicAttr->getName()."' in class '".$class->name."' must be private ".
                        "or protected. Public fields may break lazy-loading.";
            }

            foreach ($class->subClasses AS $subClass) {
                if (!in_array($class->name, class_parents($subClass))) {
                    $ce[] = "According to the discriminator map class '" . $subClass . "' has to be a child ".
                            "of '" . $class->name . "' but these entities are not related through inheritance.";
                }
            }

            if ($ce) {
                $errors[$class->name] = $ce;
            }
        }

        return $errors;
    }

    /**
     * Check if the Database Schema is in sync with the current metadata state.
     *
     * @return bool
     */
    public function schemaInSyncWithMetadata()
    {
        $schemaTool = new SchemaTool($this->em);

        $allMetadata = $this->em->getMetadataFactory()->getAllMetadata();
        return (count($schemaTool->getUpdateSchemaSql($allMetadata, false)) == 0);
    }
}


text:
<?php

namespace Doctrine\ORM\Tools;

use Doctrine\ORM\ORMException;

class ToolsException extends ORMException
{
    public static function couldNotMapDoctrine1Type($type)
    {
        return new self("Could not map doctrine 1 type '$type'!");
    }
}


text:
<?php
/*
 *  $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>.
 */

namespace Doctrine\ORM\Tools;

/**
 * Class to generate entity repository classes
 *
 * @license http://www.opensource.org/licenses/lgpl-license.php LGPL
 * @link    www.doctrine-project.org
 * @since   2.0
 * @version $Revision$
 * @author  Benjamin Eberlei <kontakt@beberlei.de>
 * @author  Guilherme Blanco <guilhermeblanco@hotmail.com>
 * @author  Jonathan Wage <jonwage@gmail.com>
 * @author  Roman Borschel <roman@code-factory.org>
 */
class EntityRepositoryGenerator
{
    protected static $_template =
'<?php

namespace <namespace>;

use Doctrine\ORM\EntityRepository;

/**
 * <className>
 *
 * This class was generated by the Doctrine ORM. Add your own custom
 * repository methods below.
 */
class <className> extends EntityRepository
{
}';

    public function generateEntityRepositoryClass($fullClassName)
    {
        $namespace = substr($fullClassName, 0, strrpos($fullClassName, '\\'));
        $className = substr($fullClassName, strrpos($fullClassName, '\\') + 1, strlen($fullClassName));

        $variables = array(
            '<namespace>' => $namespace,
            '<className>' => $className
        );
        return str_replace(array_keys($variables), array_values($variables), self::$_template);
    }

    public function writeEntityRepositoryClass($fullClassName, $outputDirectory)
    {
        $code = $this->generateEntityRepositoryClass($fullClassName);

        $path = $outputDirectory . DIRECTORY_SEPARATOR
              . str_replace('\\', \DIRECTORY_SEPARATOR, $fullClassName) . '.php';
        $dir = dirname($path);

        if ( ! is_dir($dir)) {
            mkdir($dir, 0777, true);
        }

        if ( ! file_exists($path)) {
            file_put_contents($path, $code);
        }
    }
}


text:
<?php
/*
 *  $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>.
 */

namespace Doctrine\ORM\Tools;

use Doctrine\ORM\Mapping\ClassMetadataInfo,
    Doctrine\ORM\Tools\Export\Driver\AbstractExporter,
    Doctrine\Common\Util\Inflector;

/**
 * Class to help with converting Doctrine 1 schema files to Doctrine 2 mapping files
 *
 * @license http://www.opensource.org/licenses/lgpl-license.php LGPL
 * @link    www.doctrine-project.org
 * @since   2.0
 * @version $Revision$
 * @author  Guilherme Blanco <guilhermeblanco@hotmail.com>
 * @author  Jonathan Wage <jonwage@gmail.com>
 * @author  Roman Borschel <roman@code-factory.org>
 */
class ConvertDoctrine1Schema
{
    private $_legacyTypeMap = array(
        // TODO: This list may need to be updated
        'clob' => 'text',
        'timestamp' => 'datetime',
        'enum' => 'string'
    );

    /**
     * Constructor passes the directory or array of directories
     * to convert the Doctrine 1 schema files from
     *
     * @param array $from
     * @author Jonathan Wage
     */
    public function __construct($from)
    {
        $this->_from = (array) $from;
    }

    /**
     * Get an array of ClassMetadataInfo instances from the passed
     * Doctrine 1 schema
     *
     * @return array $metadatas  An array of ClassMetadataInfo instances
     */
    public function getMetadata()
    {
        $schema = array();
        foreach ($this->_from as $path) {
            if (is_dir($path)) {
                $files = glob($path . '/*.yml');
                foreach ($files as $file) {
                    $schema = array_merge($schema, (array) \Symfony\Component\Yaml\Yaml::parse($file));
                }
            } else {
                $schema = array_merge($schema, (array) \Symfony\Component\Yaml\Yaml::parse($path));
            }
        }

        $metadatas = array();
        foreach ($schema as $className => $mappingInformation) {
            $metadatas[] = $this->_convertToClassMetadataInfo($className, $mappingInformation);
        }

        return $metadatas;
    }

    private function _convertToClassMetadataInfo($className, $mappingInformation)
    {
        $metadata = new ClassMetadataInfo($className);

        $this->_convertTableName($className, $mappingInformation, $metadata);
        $this->_convertColumns($className, $mappingInformation, $metadata);
        $this->_convertIndexes($className, $mappingInformation, $metadata);
        $this->_convertRelations($className, $mappingInformation, $metadata);

        return $metadata;
    }

    private function _convertTableName($className, array $model, ClassMetadataInfo $metadata)
    {
        if (isset($model['tableName']) && $model['tableName']) {
            $e = explode('.', $model['tableName']);
            if (count($e) > 1) {
                $metadata->table['schema'] = $e[0];
                $metadata->table['name'] = $e[1];
            } else {
                $metadata->table['name'] = $e[0];
            }
        }
    }

    private function _convertColumns($className, array $model, ClassMetadataInfo $metadata)
    {
        $id = false;

        if (isset($model['columns']) && $model['columns']) {
            foreach ($model['columns'] as $name => $column) {
                $fieldMapping = $this->_convertColumn($className, $name, $column, $metadata);

                if (isset($fieldMapping['id']) && $fieldMapping['id']) {
                    $id = true;
                }
            }
        }

        if ( ! $id) {
            $fieldMapping = array(
                'fieldName' => 'id',
                'columnName' => 'id',
                'type' => 'integer',
                'id' => true
            );
            $metadata->mapField($fieldMapping);
            $metadata->setIdGeneratorType(ClassMetadataInfo::GENERATOR_TYPE_AUTO);
        }
    }

    private function _convertColumn($className, $name, $column, ClassMetadataInfo $metadata)
    {
        if (is_string($column)) {
            $string = $column;
            $column = array();
            $column['type'] = $string;
        }
        if ( ! isset($column['name'])) {
            $column['name'] = $name;
        }
        // check if a column alias was used (column_name as field_name)
        if (preg_match("/(\w+)\sas\s(\w+)/i", $column['name'], $matches)) {
            $name = $matches[1];
            $column['name'] = $name;
            $column['alias'] = $matches[2];
        }
        if (preg_match("/([a-zA-Z]+)\(([0-9]+)\)/", $column['type'], $matches)) {
            $column['type'] = $matches[1];
            $column['length'] = $matches[2];
        }
        $column['type'] = strtolower($column['type']);
        // check if legacy column type (1.x) needs to be mapped to a 2.0 one
        if (isset($this->_legacyTypeMap[$column['type']])) {
            $column['type'] = $this->_legacyTypeMap[$column['type']];
        }
        if ( ! \Doctrine\DBAL\Types\Type::hasType($column['type'])) {
            throw ToolsException::couldNotMapDoctrine1Type($column['type']);
        }

        $fieldMapping = array();
        if (isset($column['primary'])) {
            $fieldMapping['id'] = true;
        }
        $fieldMapping['fieldName'] = isset($column['alias']) ? $column['alias'] : $name;
        $fieldMapping['columnName'] = $column['name'];
        $fieldMapping['type'] = $column['type'];
        if (isset($column['length'])) {
            $fieldMapping['length'] = $column['length'];
        }
        $allowed = array('precision', 'scale', 'unique', 'options', 'notnull', 'version');
        foreach ($column as $key => $value) {
            if (in_array($key, $allowed)) {
                $fieldMapping[$key] = $value;
            }
        }

        $metadata->mapField($fieldMapping);

        if (isset($column['autoincrement'])) {
            $metadata->setIdGeneratorType(ClassMetadataInfo::GENERATOR_TYPE_AUTO);
        } else if (isset($column['sequence'])) {
            $metadata->setIdGeneratorType(ClassMetadataInfo::GENERATOR_TYPE_SEQUENCE);
            $definition = array(
                'sequenceName' => is_array($column['sequence']) ? $column['sequence']['name']:$column['sequence']
            );
            if (isset($column['sequence']['size'])) {
                $definition['allocationSize'] = $column['sequence']['size'];
            }
            if (isset($column['sequence']['value'])) {
                $definition['initialValue'] = $column['sequence']['value'];
            }
            $metadata->setSequenceGeneratorDefinition($definition);
        }
        return $fieldMapping;
    }

    private function _convertIndexes($className, array $model, ClassMetadataInfo $metadata)
    {
        if (isset($model['indexes']) && $model['indexes']) {
            foreach ($model['indexes'] as $name => $index) {
                $type = (isset($index['type']) && $index['type'] == 'unique')
                    ? 'uniqueConstraints' : 'indexes';

                $metadata->table[$type][$name] = array(
                    'columns' => $index['fields']
                );
            }
        }
    }

    private function _convertRelations($className, array $model, ClassMetadataInfo $metadata)
    {
        if (isset($model['relations']) && $model['relations']) {
            foreach ($model['relations'] as $name => $relation) {
                if ( ! isset($relation['alias'])) {
                    $relation['alias'] = $name;
                }
                if ( ! isset($relation['class'])) {
                    $relation['class'] = $name;
                }
                if ( ! isset($relation['local'])) {
                    $relation['local'] = Inflector::tableize($relation['class']);
                }
                if ( ! isset($relation['foreign'])) {
                    $relation['foreign'] = 'id';
                }
                if ( ! isset($relation['foreignAlias'])) {
                    $relation['foreignAlias'] = $className;
                }

                if (isset($relation['refClass'])) {
                    $type = 'many';
                    $foreignType = 'many';
                    $joinColumns = array();
                } else {
                    $type = isset($relation['type']) ? $relation['type'] : 'one';
                    $foreignType = isset($relation['foreignType']) ? $relation['foreignType'] : 'many';
                    $joinColumns = array(
                        array(
                            'name' => $relation['local'],
                            'referencedColumnName' => $relation['foreign'],
                            'onDelete' => isset($relation['onDelete']) ? $relation['onDelete'] : null,
                            'onUpdate' => isset($relation['onUpdate']) ? $relation['onUpdate'] : null,
                        )
                    );
                }

                if ($type == 'one' && $foreignType == 'one') {
                    $method = 'mapOneToOne';
                } else if ($type == 'many' && $foreignType == 'many') {
                    $method = 'mapManyToMany';
                } else {
                    $method = 'mapOneToMany';
                }

                $associationMapping = array();
                $associationMapping['fieldName'] = $relation['alias'];
                $associationMapping['targetEntity'] = $relation['class'];
                $associationMapping['mappedBy'] = $relation['foreignAlias'];
                $associationMapping['joinColumns'] = $joinColumns;

                $metadata->$method($associationMapping);
            }
        }
    }
}


text:
<?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 LGPL. For more information, see
 * <http://www.doctrine-project.org>.
 */

namespace Doctrine\ORM\Tools;

use Doctrine\ORM\ORMException,
    Doctrine\DBAL\Types\Type,
    Doctrine\ORM\EntityManager,
    Doctrine\ORM\Mapping\ClassMetadata,
    Doctrine\ORM\Internal\CommitOrderCalculator,
    Doctrine\ORM\Tools\Event\GenerateSchemaTableEventArgs,
    Doctrine\ORM\Tools\Event\GenerateSchemaEventArgs;

/**
 * The SchemaTool is a tool to create/drop/update database schemas based on
 * <tt>ClassMetadata</tt> class descriptors.
 *
 * @license http://www.opensource.org/licenses/lgpl-license.php LGPL
 * @link    www.doctrine-project.org
 * @since   2.0
 * @version $Revision$
 * @author  Guilherme Blanco <guilhermeblanco@hotmail.com>
 * @author  Jonathan Wage <jonwage@gmail.com>
 * @author  Roman Borschel <roman@code-factory.org>
 * @author  Benjamin Eberlei <kontakt@beberlei.de>
 */
class SchemaTool
{
    /**
     * @var \Doctrine\ORM\EntityManager
     */
    private $_em;

    /**
     * @var \Doctrine\DBAL\Platforms\AbstractPlatform
     */
    private $_platform;

    /**
     * Initializes a new SchemaTool instance that uses the connection of the
     * provided EntityManager.
     *
     * @param Doctrine\ORM\EntityManager $em
     */
    public function __construct(EntityManager $em)
    {
        $this->_em = $em;
        $this->_platform = $em->getConnection()->getDatabasePlatform();
    }

    /**
     * Creates the database schema for the given array of ClassMetadata instances.
     *
     * @param array $classes
     */
    public function createSchema(array $classes)
    {
        $createSchemaSql = $this->getCreateSchemaSql($classes);
        $conn = $this->_em->getConnection();

        foreach ($createSchemaSql as $sql) {
            $conn->executeQuery($sql);
        }
    }

    /**
     * Gets the list of DDL statements that are required to create the database schema for
     * the given list of ClassMetadata instances.
     *
     * @param array $classes
     * @return array $sql The SQL statements needed to create the schema for the classes.
     */
    public function getCreateSchemaSql(array $classes)
    {
        $schema = $this->getSchemaFromMetadata($classes);
        return $schema->toSql($this->_platform);
    }

    /**
     * Some instances of ClassMetadata don't need to be processed in the SchemaTool context. This method detects them.
     *
     * @param ClassMetadata $class
     * @param array $processedClasses
     * @return bool
     */
    private function processingNotRequired($class, array $processedClasses)
    {
        return (
            isset($processedClasses[$class->name]) ||
            $class->isMappedSuperclass ||
            ($class->isInheritanceTypeSingleTable() && $class->name != $class->rootEntityName)
        );
    }

    /**
     * From a given set of metadata classes this method creates a Schema instance.
     *
     * @param array $classes
     * @return Schema
     */
    public function getSchemaFromMetadata(array $classes)
    {
        $processedClasses = array(); // Reminder for processed classes, used for hierarchies

        $sm = $this->_em->getConnection()->getSchemaManager();
        $metadataSchemaConfig = $sm->createSchemaConfig();
        $metadataSchemaConfig->setExplicitForeignKeyIndexes(false);
        $schema = new \Doctrine\DBAL\Schema\Schema(array(), array(), $metadataSchemaConfig);

        $evm = $this->_em->getEventManager();

        foreach ($classes as $class) {
            if ($this->processingNotRequired($class, $processedClasses)) {
                continue;
            }

            $table = $schema->createTable($class->getQuotedTableName($this->_platform));

            $columns = array(); // table columns

            if ($class->isInheritanceTypeSingleTable()) {
                $columns = $this->_gatherColumns($class, $table);
                $this->_gatherRelationsSql($class, $table, $schema);

                // Add the discriminator column
                $discrColumnDef = $this->_getDiscriminatorColumnDefinition($class, $table);

                // Aggregate all the information from all classes in the hierarchy
                foreach ($class->parentClasses as $parentClassName) {
                    // Parent class information is already contained in this class
                    $processedClasses[$parentClassName] = true;
                }

                foreach ($class->subClasses as $subClassName) {
                    $subClass = $this->_em->getClassMetadata($subClassName);
                    $this->_gatherColumns($subClass, $table);
                    $this->_gatherRelationsSql($subClass, $table, $schema);
                    $processedClasses[$subClassName] = true;
                }
            } else if ($class->isInheritanceTypeJoined()) {
                // Add all non-inherited fields as columns
                $pkColumns = array();
                foreach ($class->fieldMappings as $fieldName => $mapping) {
                    if ( ! isset($mapping['inherited'])) {
                        $columnName = $class->getQuotedColumnName($mapping['fieldName'], $this->_platform);
                        $this->_gatherColumn($class, $mapping, $table);

                        if ($class->isIdentifier($fieldName)) {
                            $pkColumns[] = $columnName;
                        }
                    }
                }

                $this->_gatherRelationsSql($class, $table, $schema);

                // Add the discriminator column only to the root table
                if ($class->name == $class->rootEntityName) {
                    $discrColumnDef = $this->_getDiscriminatorColumnDefinition($class, $table);
                } else {
                    // Add an ID FK column to child tables
                    /* @var Doctrine\ORM\Mapping\ClassMetadata $class */
                    $idMapping = $class->fieldMappings[$class->identifier[0]];
                    $this->_gatherColumn($class, $idMapping, $table);
                    $columnName = $class->getQuotedColumnName($class->identifier[0], $this->_platform);
                    // TODO: This seems rather hackish, can we optimize it?
                    $table->getColumn($columnName)->setAutoincrement(false);

                    $pkColumns[] = $columnName;

                    // Add a FK constraint on the ID column
                    $table->addUnnamedForeignKeyConstraint(
                        $this->_em->getClassMetadata($class->rootEntityName)->getQuotedTableName($this->_platform),
                        array($columnName), array($columnName), array('onDelete' => 'CASCADE')
                    );
                }

                $table->setPrimaryKey($pkColumns);

            } else if ($class->isInheritanceTypeTablePerClass()) {
                throw ORMException::notSupported();
            } else {
                $this->_gatherColumns($class, $table);
                $this->_gatherRelationsSql($class, $table, $schema);
            }

            $pkColumns = array();
            foreach ($class->identifier AS $identifierField) {
                if (isset($class->fieldMappings[$identifierField])) {
                    $pkColumns[] = $class->getQuotedColumnName($identifierField, $this->_platform);
                } else if (isset($class->associationMappings[$identifierField])) {
                    /* @var $assoc \Doctrine\ORM\Mapping\OneToOne */
                    $assoc = $class->associationMappings[$identifierField];
                    foreach ($assoc['joinColumns'] AS $joinColumn) {
                        $pkColumns[] = $joinColumn['name'];
                    }
                }
            }
            if (!$table->hasIndex('primary')) {
                $table->setPrimaryKey($pkColumns);
            }

            if (isset($class->table['indexes'])) {
                foreach ($class->table['indexes'] AS $indexName => $indexData) {
                    $table->addIndex($indexData['columns'], $indexName);
                }
            }

            if (isset($class->table['uniqueConstraints'])) {
                foreach ($class->table['uniqueConstraints'] AS $indexName => $indexData) {
                    $table->addUniqueIndex($indexData['columns'], $indexName);
                }
            }

            $processedClasses[$class->name] = true;

            if ($class->isIdGeneratorSequence() && $class->name == $class->rootEntityName) {
                $seqDef = $class->sequenceGeneratorDefinition;

                if (!$schema->hasSequence($seqDef['sequenceName'])) {
                    $schema->createSequence(
                        $seqDef['sequenceName'],
                        $seqDef['allocationSize'],
                        $seqDef['initialValue']
                    );
                }
            }

            if ($evm->hasListeners(ToolEvents::postGenerateSchemaTable)) {
                $evm->dispatchEvent(ToolEvents::postGenerateSchemaTable, new GenerateSchemaTableEventArgs($class, $schema, $table));
            }
        }

        if ($evm->hasListeners(ToolEvents::postGenerateSchema)) {
            $evm->dispatchEvent(ToolEvents::postGenerateSchema, new GenerateSchemaEventArgs($this->_em, $schema));
        }

        return $schema;
    }

    /**
     * Gets a portable column definition as required by the DBAL for the discriminator
     * column of a class.
     *
     * @param ClassMetadata $class
     * @return array The portable column definition of the discriminator column as required by
     *              the DBAL.
     */
    private function _getDiscriminatorColumnDefinition($class, $table)
    {
        $discrColumn = $class->discriminatorColumn;

        if (!isset($discrColumn['type']) || (strtolower($discrColumn['type']) == 'string' && $discrColumn['length'] === null)) {
            $discrColumn['type'] = 'string';
            $discrColumn['length'] = 255;
        }

        $table->addColumn(
            $discrColumn['name'],
            $discrColumn['type'],
            array('length' => $discrColumn['length'], 'notnull' => true)
        );
    }

    /**
     * Gathers the column definitions as required by the DBAL of all field mappings
     * found in the given class.
     *
     * @param ClassMetadata $class
     * @param Table $table
     * @return array The list of portable column definitions as required by the DBAL.
     */
    private function _gatherColumns($class, $table)
    {
        $columns = array();
        $pkColumns = array();

        foreach ($class->fieldMappings as $fieldName => $mapping) {
            if ($class->isInheritanceTypeSingleTable() && isset($mapping['inherited'])) {
                continue;
            }

            $column = $this->_gatherColumn($class, $mapping, $table);

            if ($class->isIdentifier($mapping['fieldName'])) {
                $pkColumns[] = $class->getQuotedColumnName($mapping['fieldName'], $this->_platform);
            }
        }

        // For now, this is a hack required for single table inheritence, since this method is called
        // twice by single table inheritence relations
        if(!$table->hasIndex('primary')) {
            //$table->setPrimaryKey($pkColumns);
        }

        return $columns;
    }

    /**
     * Creates a column definition as required by the DBAL from an ORM field mapping definition.
     *
     * @param ClassMetadata $class The class that owns the field mapping.
     * @param array $mapping The field mapping.
     * @param Table $table
     * @return array The portable column definition as required by the DBAL.
     */
    private function _gatherColumn($class, array $mapping, $table)
    {
        $columnName = $class->getQuotedColumnName($mapping['fieldName'], $this->_platform);
        $columnType = $mapping['type'];

        $options = array();
        $options['length'] = isset($mapping['length']) ? $mapping['length'] : null;
        $options['notnull'] = isset($mapping['nullable']) ? ! $mapping['nullable'] : true;
        if ($class->isInheritanceTypeSingleTable() && count($class->parentClasses) > 0) {
            $options['notnull'] = false;
        }

        $options['platformOptions'] = array();
        $options['platformOptions']['version'] = $class->isVersioned && $class->versionField == $mapping['fieldName'] ? true : false;

        if(strtolower($columnType) == 'string' && $options['length'] === null) {
            $options['length'] = 255;
        }

        if (isset($mapping['precision'])) {
            $options['precision'] = $mapping['precision'];
        }

        if (isset($mapping['scale'])) {
            $options['scale'] = $mapping['scale'];
        }

        if (isset($mapping['default'])) {
            $options['default'] = $mapping['default'];
        }

        if (isset($mapping['columnDefinition'])) {
            $options['columnDefinition'] = $mapping['columnDefinition'];
        }

        if ($class->isIdGeneratorIdentity() && $class->getIdentifierFieldNames() == array($mapping['fieldName'])) {
            $options['autoincrement'] = true;
        }
        if ($class->isInheritanceTypeJoined() && $class->name != $class->rootEntityName) {
            $options['autoincrement'] = false;
        }

        if ($table->hasColumn($columnName)) {
            // required in some inheritance scenarios
            $table->changeColumn($columnName, $options);
        } else {
            $table->addColumn($columnName, $columnType, $options);
        }

        $isUnique = isset($mapping['unique']) ? $mapping['unique'] : false;
        if ($isUnique) {
            $table->addUniqueIndex(array($columnName));
        }
    }

    /**
     * Gathers the SQL for properly setting up the relations of the given class.
     * This includes the SQL for foreign key constraints and join tables.
     *
     * @param ClassMetadata $class
     * @param \Doctrine\DBAL\Schema\Table $table
     * @param \Doctrine\DBAL\Schema\Schema $schema
     * @return void
     */
    private function _gatherRelationsSql($class, $table, $schema)
    {
        foreach ($class->associationMappings as $fieldName => $mapping) {
            if (isset($mapping['inherited'])) {
                continue;
            }

            $foreignClass = $this->_em->getClassMetadata($mapping['targetEntity']);

            if ($mapping['type'] & ClassMetadata::TO_ONE && $mapping['isOwningSide']) {
                $primaryKeyColumns = $uniqueConstraints = array(); // PK is unnecessary for this relation-type

                $this->_gatherRelationJoinColumns($mapping['joinColumns'], $table, $foreignClass, $mapping, $primaryKeyColumns, $uniqueConstraints);

                foreach($uniqueConstraints AS $indexName => $unique) {
                    $table->addUniqueIndex($unique['columns'], is_numeric($indexName) ? null : $indexName);
                }
            } else if ($mapping['type'] == ClassMetadata::ONE_TO_MANY && $mapping['isOwningSide']) {
                //... create join table, one-many through join table supported later
                throw ORMException::notSupported();
            } else if ($mapping['type'] == ClassMetadata::MANY_TO_MANY && $mapping['isOwningSide']) {
                // create join table
                $joinTable = $mapping['joinTable'];

                $theJoinTable = $schema->createTable($foreignClass->getQuotedJoinTableName($mapping, $this->_platform));

                $primaryKeyColumns = $uniqueConstraints = array();

                // Build first FK constraint (relation table => source table)
                $this->_gatherRelationJoinColumns($joinTable['joinColumns'], $theJoinTable, $class, $mapping, $primaryKeyColumns, $uniqueConstraints);

                // Build second FK constraint (relation table => target table)
                $this->_gatherRelationJoinColumns($joinTable['inverseJoinColumns'], $theJoinTable, $foreignClass, $mapping, $primaryKeyColumns, $uniqueConstraints);

                $theJoinTable->setPrimaryKey($primaryKeyColumns);

                foreach($uniqueConstraints AS $indexName => $unique) {
                    $theJoinTable->addUniqueIndex($unique['columns'], is_numeric($indexName) ? null : $indexName);
                }
            }
        }
    }

    /**
     * Get the class metadata that is responsible for the definition of the referenced column name.
     *
     * Previously this was a simple task, but with DDC-117 this problem is actually recursive. If its
     * not a simple field, go through all identifier field names that are associations recursivly and
     * find that referenced column name.
     *
     * TODO: Is there any way to make this code more pleasing?
     *
     * @param ClassMetadata $class
     * @param string $referencedColumnName
     * @return array(ClassMetadata, referencedFieldName)
     */
    private function getDefiningClass($class, $referencedColumnName)
    {
        $referencedFieldName = $class->getFieldName($referencedColumnName);

        if ($class->hasField($referencedFieldName)) {
            return array($class, $referencedFieldName);
        } else if (in_array($referencedColumnName, $class->getIdentifierColumnNames())) {
            // it seems to be an entity as foreign key
            foreach ($class->getIdentifierFieldNames() AS $fieldName) {
                if ($class->hasAssociation($fieldName) && $class->getSingleAssociationJoinColumnName($fieldName) == $referencedColumnName) {
                    return $this->getDefiningClass(
                        $this->_em->getClassMetadata($class->associationMappings[$fieldName]['targetEntity']),
                        $class->getSingleAssociationReferencedJoinColumnName($fieldName)
                    );
                }
            }
        }

        return null;
    }

    /**
     * Gather columns and fk constraints that are required for one part of relationship.
     *
     * @param array $joinColumns
     * @param \Doctrine\DBAL\Schema\Table $theJoinTable
     * @param ClassMetadata $class
     * @param array $mapping
     * @param array $primaryKeyColumns
     * @param array $uniqueConstraints
     */
    private function _gatherRelationJoinColumns($joinColumns, $theJoinTable, $class, $mapping, &$primaryKeyColumns, &$uniqueConstraints)
    {
        $localColumns = array();
        $foreignColumns = array();
        $fkOptions = array();
        $foreignTableName = $class->getQuotedTableName($this->_platform);

        foreach ($joinColumns as $joinColumn) {
            $columnName = $joinColumn['name'];
            list($definingClass, $referencedFieldName) = $this->getDefiningClass($class, $joinColumn['referencedColumnName']);

            if (!$definingClass) {
                throw new \Doctrine\ORM\ORMException(
                    "Column name `".$joinColumn['referencedColumnName']."` referenced for relation from ".
                    $mapping['sourceEntity'] . " towards ". $mapping['targetEntity'] . " does not exist."
                );
            }

            $primaryKeyColumns[] = $columnName;
            $localColumns[] = $columnName;
            $foreignColumns[] = $joinColumn['referencedColumnName'];

            if ( ! $theJoinTable->hasColumn($joinColumn['name'])) {
                // Only add the column to the table if it does not exist already.
                // It might exist already if the foreign key is mapped into a regular
                // property as well.

                $fieldMapping = $definingClass->getFieldMapping($referencedFieldName);

                $columnDef = null;
                if (isset($joinColumn['columnDefinition'])) {
                    $columnDef = $joinColumn['columnDefinition'];
                } else if (isset($fieldMapping['columnDefinition'])) {
                    $columnDef = $fieldMapping['columnDefinition'];
                }
                $columnOptions = array('notnull' => false, 'columnDefinition' => $columnDef);
                if (isset($joinColumn['nullable'])) {
                    $columnOptions['notnull'] = !$joinColumn['nullable'];
                }
                if ($fieldMapping['type'] == "string" && isset($fieldMapping['length'])) {
                    $columnOptions['length'] = $fieldMapping['length'];
                } else if ($fieldMapping['type'] == "decimal") {
                    $columnOptions['scale'] = $fieldMapping['scale'];
                    $columnOptions['precision'] = $fieldMapping['precision'];
                }

                $theJoinTable->addColumn($columnName, $fieldMapping['type'], $columnOptions);
            }

            if (isset($joinColumn['unique']) && $joinColumn['unique'] == true) {
                $uniqueConstraints[] = array('columns' => array($columnName));
            }

            if (isset($joinColumn['onUpdate'])) {
                $fkOptions['onUpdate'] = $joinColumn['onUpdate'];
            }

            if (isset($joinColumn['onDelete'])) {
                $fkOptions['onDelete'] = $joinColumn['onDelete'];
            }
        }

        $theJoinTable->addUnnamedForeignKeyConstraint(
            $foreignTableName, $localColumns, $foreignColumns, $fkOptions
        );
    }

    /**
     * Drops the database schema for the given classes.
     *
     * In any way when an exception is thrown it is supressed since drop was
     * issued for all classes of the schema and some probably just don't exist.
     *
     * @param array $classes
     * @return void
     */
    public function dropSchema(array $classes)
    {
        $dropSchemaSql = $this->getDropSchemaSQL($classes);
        $conn = $this->_em->getConnection();

        foreach ($dropSchemaSql as $sql) {
            try {
                $conn->executeQuery($sql);
            } catch(\Exception $e) {

            }
        }
    }

    /**
     * Drops all elements in the database of the current connection.
     *
     * @return void
     */
    public function dropDatabase()
    {
        $dropSchemaSql = $this->getDropDatabaseSQL();
        $conn = $this->_em->getConnection();

        foreach ($dropSchemaSql as $sql) {
            $conn->executeQuery($sql);
        }
    }

    /**
     * Gets the SQL needed to drop the database schema for the connections database.
     *
     * @return array
     */
    public function getDropDatabaseSQL()
    {
        $sm = $this->_em->getConnection()->getSchemaManager();
        $schema = $sm->createSchema();

        $visitor = new \Doctrine\DBAL\Schema\Visitor\DropSchemaSqlCollector($this->_platform);
        /* @var $schema \Doctrine\DBAL\Schema\Schema */
        $schema->visit($visitor);
        return $visitor->getQueries();
    }

    /**
     * Get SQL to drop the tables defined by the passed classes.
     *
     * @param array $classes
     * @return array
     */
    public function getDropSchemaSQL(array $classes)
    {
        $visitor = new \Doctrine\DBAL\Schema\Visitor\DropSchemaSqlCollector($this->_platform);
        $schema = $this->getSchemaFromMetadata($classes);

        $sm = $this->_em->getConnection()->getSchemaManager();
        $fullSchema = $sm->createSchema();
        foreach ($fullSchema->getTables() AS $table) {
            if (!$schema->hasTable($table->getName())) {
                foreach ($table->getForeignKeys() AS $foreignKey) {
                    /* @var $foreignKey \Doctrine\DBAL\Schema\ForeignKeyConstraint */
                    if ($schema->hasTable($foreignKey->getForeignTableName())) {
                        $visitor->acceptForeignKey($table, $foreignKey);
                    }
                }
            } else {
                $visitor->acceptTable($table);
                foreach ($table->getForeignKeys() AS $foreignKey) {
                    $visitor->acceptForeignKey($table, $foreignKey);
                }
            }
        }

        if ($this->_platform->supportsSequences()) {
            foreach ($schema->getSequences() AS $sequence) {
                $visitor->acceptSequence($sequence);
            }
            foreach ($schema->getTables() AS $table) {
                /* @var $sequence Table */
                if ($table->hasPrimaryKey()) {
                    $columns = $table->getPrimaryKey()->getColumns();
                    if (count($columns) == 1) {
                        $checkSequence = $table->getName() . "_" . $columns[0] . "_seq";
                        if ($fullSchema->hasSequence($checkSequence)) {
                            $visitor->acceptSequence($fullSchema->getSequence($checkSequence));
                        }
                    }
                }
            }
        }

        return $visitor->getQueries();
    }

    /**
     * Updates the database schema of the given classes by comparing the ClassMetadata
     * instances to the current database schema that is inspected. If $saveMode is set
     * to true the command is executed in the Database, else SQL is returned.
     *
     * @param array $classes
     * @param boolean $saveMode
     * @return void
     */
    public function updateSchema(array $classes, $saveMode=false)
    {
        $updateSchemaSql = $this->getUpdateSchemaSql($classes, $saveMode);
        $conn = $this->_em->getConnection();

        foreach ($updateSchemaSql as $sql) {
            $conn->executeQuery($sql);
        }
    }

    /**
     * Gets the sequence of SQL statements that need to be performed in order
     * to bring the given class mappings in-synch with the relational schema.
     * If $saveMode is set to true the command is executed in the Database,
     * else SQL is returned.
     *
     * @param array $classes The classes to consider.
     * @param boolean $saveMode True for writing to DB, false for SQL string
     * @return array The sequence of SQL statements.
     */
    public function getUpdateSchemaSql(array $classes, $saveMode=false)
    {
        $sm = $this->_em->getConnection()->getSchemaManager();

        $fromSchema = $sm->createSchema();
        $toSchema = $this->getSchemaFromMetadata($classes);

        $comparator = new \Doctrine\DBAL\Schema\Comparator();
        $schemaDiff = $comparator->compare($fromSchema, $toSchema);

        if ($saveMode) {
            return $schemaDiff->toSaveSql($this->_platform);
        } else {
            return $schemaDiff->toSql($this->_platform);
        }
    }
}


text:
<?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 LGPL. For more information, see
 * <http://www.doctrine-project.org>.
 */

namespace Doctrine\ORM\Tools;

use Doctrine\ORM\Mapping\ClassMetadataFactory;
use Doctrine\ORM\Mapping\ClassMetadataInfo;

/**
 * The DisconnectedClassMetadataFactory is used to create ClassMetadataInfo objects
 * that do not require the entity class actually exist. This allows us to
 * load some mapping information and use it to do things like generate code
 * from the mapping information.
 *
 * @license http://www.opensource.org/licenses/lgpl-license.php LGPL
 * @link    www.doctrine-project.org
 * @since   2.0
 * @author  Benjamin Eberlei <kontakt@beberlei.de>
 * @author  Guilherme Blanco <guilhermeblanco@hotmail.com>
 * @author  Jonathan Wage <jonwage@gmail.com>
 * @author  Roman Borschel <roman@code-factory.org>
 */
class DisconnectedClassMetadataFactory extends ClassMetadataFactory
{
    /**
     * @override
     */
    protected function newClassMetadataInstance($className)
    {
        $metadata = new ClassMetadataInfo($className);
        if (strpos($className, "\\") !== false) {
            $metadata->namespace = strrev(substr( strrev($className), strpos(strrev($className), "\\")+1 ));
        } else {
            $metadata->namespace = "";
        }
        return $metadata;
    }

    /**
     * Validate runtime metadata is correctly defined.
     *
     * @param ClassMetadata $class
     * @param ClassMetadata $parent
     */
    protected function validateRuntimeMetadata($class, $parent)
    {
        // validate nothing
    }

    /**
     * @override
     */
    protected function getParentClasses($name)
    {
        return array();
    }
}


text:
<?php
/*
 *  $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>.
*/

namespace Doctrine\ORM\Tools;

class ToolEvents
{
    /**
     * The postGenerateSchemaTable event occurs in SchemaTool#getSchemaFromMetadata()
     * whenever an entity class is transformed into its table representation. It recieves
     * the current non-complete Schema instance, the Entity Metadata Class instance and
     * the Schema Table instance of this entity.
     *
     * @var string
     */
    const postGenerateSchemaTable = 'postGenerateSchemaTable';

    /**
     * The postGenerateSchema event is triggered in SchemaTool#getSchemaFromMetadata()
     * after all entity classes have been transformed into the related Schema structure.
     * The EventArgs contain the EntityManager and the created Schema instance.
     *
     * @var string
     */
    const postGenerateSchema = 'postGenerateSchema';
}