<?php
/*
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 * This software consists of voluntary contributions made by many individuals
 * and is licensed under the MIT license. For more information, see
 * <http://www.doctrine-project.org>.
 */

namespace Doctrine\ODM\MongoDB;

use Doctrine\Common\Annotations\AnnotationReader;
use Doctrine\Common\Cache\Cache;
use Doctrine\Common\Persistence\Mapping\Driver\MappingDriver;
use Doctrine\Common\Persistence\ObjectRepository;
use Doctrine\Common\Proxy\AbstractProxyFactory;
use Doctrine\ODM\MongoDB\Mapping\ClassMetadataFactory;
use Doctrine\ODM\MongoDB\Mapping\Driver\AnnotationDriver;
use Doctrine\ODM\MongoDB\PersistentCollection\DefaultPersistentCollectionFactory;
use Doctrine\ODM\MongoDB\PersistentCollection\DefaultPersistentCollectionGenerator;
use Doctrine\ODM\MongoDB\PersistentCollection\PersistentCollectionFactory;
use Doctrine\ODM\MongoDB\PersistentCollection\PersistentCollectionGenerator;
use Doctrine\ODM\MongoDB\Repository\DefaultRepositoryFactory;
use Doctrine\ODM\MongoDB\Repository\DocumentRepository as NewDocumentRepository;
use Doctrine\ODM\MongoDB\Repository\RepositoryFactory;

/**
 * Configuration class for the DocumentManager. When setting up your DocumentManager
 * you can optionally specify an instance of this class as the second argument.
 * If you do not pass a configuration object, a blank one will be created for you.
 *
 *     <?php
 *
 *     $config = new Configuration();
 *     $dm = DocumentManager::create(new Connection(), $config);
 *
 * @since       1.0
 */
class Configuration extends \Doctrine\MongoDB\Configuration
{
    /**
     * Never autogenerate a proxy/hydrator/persistent collection and rely that
     * it was generated by some process before deployment. Copied from
     * \Doctrine\Common\Proxy\AbstractProxyFactory.
     *
     * @var integer
     */
    const AUTOGENERATE_NEVER = 0;

    /**
     * Always generates a new proxy/hydrator/persistent collection in every request.
     *
     * This is only sane during development.
     * Copied from \Doctrine\Common\Proxy\AbstractProxyFactory.
     *
     * @var integer
     */
    const AUTOGENERATE_ALWAYS = 1;

    /**
     * Autogenerate the proxy/hydrator/persistent collection class when the file does not exist.
     *
     * This strategy causes a file exists call whenever any proxy/hydrator is used the
     * first time in a request. Copied from \Doctrine\Common\Proxy\AbstractProxyFactory.
     *
     * @var integer
     */
    const AUTOGENERATE_FILE_NOT_EXISTS = 2;

    /**
     * Generate the proxy/hydrator/persistent collection classes using eval().
     *
     * This strategy is only sane for development.
     * Copied from \Doctrine\Common\Proxy\AbstractProxyFactory.
     *
     * @var integer
     */
    const AUTOGENERATE_EVAL = 3;

    /**
     * Array of attributes for this configuration instance.
     *
     * @var array
     * @deprecated This property will be private in MongoDB ODM 2.0.
     */
    protected $attributes = [
        'mongoCmd' => '$',
        'retryConnect' => 0,
        'retryQuery' => 0,
    ];

    /**
     * Adds a namespace under a certain alias.
     *
     * @param string $alias
     * @param string $namespace
     */
    public function addDocumentNamespace($alias, $namespace)
    {
        $this->attributes['documentNamespaces'][$alias] = $namespace;
    }

    /**
     * Resolves a registered namespace alias to the full namespace.
     *
     * @param string $documentNamespaceAlias
     * @return string
     * @throws MongoDBException
     */
    public function getDocumentNamespace($documentNamespaceAlias)
    {
        if ( ! isset($this->attributes['documentNamespaces'][$documentNamespaceAlias])) {
            throw MongoDBException::unknownDocumentNamespace($documentNamespaceAlias);
        }

        return trim($this->attributes['documentNamespaces'][$documentNamespaceAlias], '\\');
    }

    /**
     * Retrieves the list of registered document namespace aliases.
     *
     * @return array
     */
    public function getDocumentNamespaces()
    {
        return $this->attributes['documentNamespaces'];
    }

    /**
     * Set the document alias map
     *
     * @param array $documentNamespaces
     * @return void
     */
    public function setDocumentNamespaces(array $documentNamespaces)
    {
        $this->attributes['documentNamespaces'] = $documentNamespaces;
    }

    /**
     * Sets the cache driver implementation that is used for metadata caching.
     *
     * @param MappingDriver $driverImpl
     * @todo Force parameter to be a Closure to ensure lazy evaluation
     *       (as soon as a metadata cache is in effect, the driver never needs to initialize).
     */
    public function setMetadataDriverImpl(MappingDriver $driverImpl)
    {
        $this->attributes['metadataDriverImpl'] = $driverImpl;
    }

    /**
     * Add a new default annotation driver with a correctly configured annotation reader.
     *
     * @param array $paths
     * @return Mapping\Driver\AnnotationDriver
     */
    public function newDefaultAnnotationDriver($paths = array())
    {
        $reader = new AnnotationReader();

        return new AnnotationDriver($reader, (array)$paths);
    }

    /**
     * Gets the cache driver implementation that is used for the mapping metadata.
     *
     * @return MappingDriver
     */
    public function getMetadataDriverImpl()
    {
        return isset($this->attributes['metadataDriverImpl']) ?
            $this->attributes['metadataDriverImpl'] : null;
    }

    /**
     * Gets the cache driver implementation that is used for metadata caching.
     *
     * @return \Doctrine\Common\Cache\Cache
     */
    public function getMetadataCacheImpl()
    {
        return isset($this->attributes['metadataCacheImpl']) ?
            $this->attributes['metadataCacheImpl'] : null;
    }

    /**
     * Sets the cache driver implementation that is used for metadata caching.
     *
     * @param \Doctrine\Common\Cache\Cache $cacheImpl
     */
    public function setMetadataCacheImpl(Cache $cacheImpl)
    {
        $this->attributes['metadataCacheImpl'] = $cacheImpl;
    }

    /**
     * Sets the directory where Doctrine generates any necessary proxy class files.
     *
     * @param string $dir
     */
    public function setProxyDir($dir)
    {
        $this->attributes['proxyDir'] = $dir;
    }

    /**
     * Gets the directory where Doctrine generates any necessary proxy class files.
     *
     * @return string
     */
    public function getProxyDir()
    {
        return isset($this->attributes['proxyDir']) ?
            $this->attributes['proxyDir'] : null;
    }

    /**
     * Gets a boolean flag that indicates whether proxy classes should always be regenerated
     * during each script execution.
     *
     * @return boolean|integer
     */
    public function getAutoGenerateProxyClasses()
    {
        return isset($this->attributes['autoGenerateProxyClasses']) ?
            $this->attributes['autoGenerateProxyClasses'] : true;
    }

    /**
     * Sets a boolean flag that indicates whether proxy classes should always be regenerated
     * during each script execution.
     *
     * @param boolean|int $autoGenerateProxyClasses Possible values are constants of Doctrine\Common\Proxy\AbstractProxyFactory
     */
    public function setAutoGenerateProxyClasses($autoGenerateProxyClasses)
    {
        if (is_bool($autoGenerateProxyClasses)) {
            @trigger_error(
                sprintf('Passing boolean value to "%s" is deprecated, please use constants of "%s" instead.', __METHOD__, AbstractProxyFactory::class),
                E_USER_DEPRECATED
            );
        }

        if ($autoGenerateProxyClasses === AbstractProxyFactory::AUTOGENERATE_ALWAYS || $autoGenerateProxyClasses === AbstractProxyFactory::AUTOGENERATE_NEVER) {
            @trigger_error(
                sprintf('The "AUTOGENERATE_ALWAYS" and "AUTOGENERATE_NEVER" strategies for proxy generation are deprecated and will be dropped in doctrine/mongodb-odm 2.0. Please use "AUTOGENERATE_FILE_NOT_EXISTS" and "AUTOGENERATE_EVAL".'),
                E_USER_DEPRECATED
            );
        }

        $this->attributes['autoGenerateProxyClasses'] = $autoGenerateProxyClasses;
    }

    /**
     * Gets the namespace where proxy classes reside.
     *
     * @return string
     */
    public function getProxyNamespace()
    {
        return isset($this->attributes['proxyNamespace']) ?
            $this->attributes['proxyNamespace'] : null;
    }

    /**
     * Sets the namespace where proxy classes reside.
     *
     * @param string $ns
     */
    public function setProxyNamespace($ns)
    {
        $this->attributes['proxyNamespace'] = $ns;
    }

    /**
     * Sets the directory where Doctrine generates hydrator class files.
     *
     * @param string $dir
     */
    public function setHydratorDir($dir)
    {
        $this->attributes['hydratorDir'] = $dir;
    }

    /**
     * Gets the directory where Doctrine generates hydrator class files.
     *
     * @return string
     */
    public function getHydratorDir()
    {
        return isset($this->attributes['hydratorDir']) ?
            $this->attributes['hydratorDir'] : null;
    }

    /**
     * Gets a boolean flag that indicates whether hydrator classes should always be regenerated
     * during each script execution.
     *
     * @return boolean|integer Possible values are defined constants
     */
    public function getAutoGenerateHydratorClasses()
    {
        return isset($this->attributes['autoGenerateHydratorClasses']) ?
            $this->attributes['autoGenerateHydratorClasses'] : true;
    }

    /**
     * Sets a boolean flag that indicates whether hydrator classes should always be regenerated
     * during each script execution.
     *
     * @param boolean|integer $bool
     */
    public function setAutoGenerateHydratorClasses($bool)
    {
        if (is_bool($bool)) {
            @trigger_error(
                sprintf('Passing boolean value to "%s" is deprecated, please use "AUTOGENERATE_*" constants of "%s" instead.', __METHOD__, self::class),
                E_USER_DEPRECATED
            );
        }
        $this->attributes['autoGenerateHydratorClasses'] = $bool;
    }

    /**
     * Gets the namespace where hydrator classes reside.
     *
     * @return string
     */
    public function getHydratorNamespace()
    {
        return isset($this->attributes['hydratorNamespace']) ?
            $this->attributes['hydratorNamespace'] : null;
    }

    /**
     * Sets the namespace where hydrator classes reside.
     *
     * @param string $ns
     */
    public function setHydratorNamespace($ns)
    {
        $this->attributes['hydratorNamespace'] = $ns;
    }

    /**
     * Sets the directory where Doctrine generates persistent collection class files.
     *
     * @param string $dir
     */
    public function setPersistentCollectionDir($dir)
    {
        $this->attributes['persistentCollectionDir'] = $dir;
    }

    /**
     * Gets the directory where Doctrine generates persistent collection class files.
     *
     * @return string
     */
    public function getPersistentCollectionDir()
    {
        return isset($this->attributes['persistentCollectionDir']) ?
            $this->attributes['persistentCollectionDir'] : null;
    }

    /**
     * Gets a integer flag that indicates how and when persistent collection
     * classes should be generated.
     *
     * @return integer Possible values are defined constants
     */
    public function getAutoGeneratePersistentCollectionClasses()
    {
        return isset($this->attributes['autoGeneratePersistentCollectionClasses']) ?
            $this->attributes['autoGeneratePersistentCollectionClasses'] : self::AUTOGENERATE_ALWAYS;
    }

    /**
     * Sets a integer flag that indicates how and when persistent collection
     * classes should be generated.
     *
     * @param integer $mode Possible values are defined constants
     */
    public function setAutoGeneratePersistentCollectionClasses($mode)
    {
        $this->attributes['autoGeneratePersistentCollectionClasses'] = $mode;
    }

    /**
     * Gets the namespace where persistent collection classes reside.
     *
     * @return string
     */
    public function getPersistentCollectionNamespace()
    {
        return isset($this->attributes['persistentCollectionNamespace']) ?
            $this->attributes['persistentCollectionNamespace'] : null;
    }

    /**
     * Sets the namespace where persistent collection classes reside.
     *
     * @param string $ns
     */
    public function setPersistentCollectionNamespace($ns)
    {
        $this->attributes['persistentCollectionNamespace'] = $ns;
    }

    /**
     * Sets the default DB to use for all Documents that do not specify
     * a database.
     *
     * @param string $defaultDB
     */
    public function setDefaultDB($defaultDB)
    {
        $this->attributes['defaultDB'] = $defaultDB;
    }

    /**
     * Gets the default DB to use for all Documents that do not specify a database.
     *
     * @return string $defaultDB
     */
    public function getDefaultDB()
    {
        return isset($this->attributes['defaultDB']) ?
            $this->attributes['defaultDB'] : null;
    }

    /**
     * Set the class metadata factory class name.
     *
     * @param string $cmfName
     */
    public function setClassMetadataFactoryName($cmfName)
    {
        $this->attributes['classMetadataFactoryName'] = $cmfName;
    }

    /**
     * Gets the class metadata factory class name.
     *
     * @return string
     */
    public function getClassMetadataFactoryName()
    {
        if ( ! isset($this->attributes['classMetadataFactoryName'])) {
            $this->attributes['classMetadataFactoryName'] = ClassMetadataFactory::class;
        }
        return $this->attributes['classMetadataFactoryName'];
    }

    /**
     * Gets array of default commit options.
     *
     * @return array
     */
    public function getDefaultCommitOptions()
    {
        if (isset($this->attributes['defaultCommitOptions'])) {
            return $this->attributes['defaultCommitOptions'];
        }

        return array('w' => 1);
    }

    /**
     * Sets array of default commit options.
     *
     * @param array $defaultCommitOptions
     */
    public function setDefaultCommitOptions($defaultCommitOptions)
    {
        $this->attributes['defaultCommitOptions'] = $defaultCommitOptions;
    }

    /**
     * Add a filter to the list of possible filters.
     *
     * @param string $name       The name of the filter.
     * @param string $className  The class name of the filter.
     * @param array  $parameters The parameters for the filter.
     */
    public function addFilter($name, $className, array $parameters = array())
    {
        $this->attributes['filters'][$name] = array(
            'class' => $className,
            'parameters' => $parameters
        );
    }

    /**
     * Gets the class name for a given filter name.
     *
     * @param string $name The name of the filter.
     *
     * @return string|null The filter class name, or null if it is undefined
     */
    public function getFilterClassName($name)
    {
        return isset($this->attributes['filters'][$name])
            ? $this->attributes['filters'][$name]['class']
            : null;
    }

    /**
     * Gets the parameters for a given filter name.
     *
     * @param string $name The name of the filter.
     *
     * @return array|null The filter parameters, or null if it is undefined
     */
    public function getFilterParameters($name)
    {
        return isset($this->attributes['filters'][$name])
            ? $this->attributes['filters'][$name]['parameters']
            : null;
    }

    /**
     * Sets default repository class.
     *
     * @param string $className
     *
     * @return void
     *
     * @throws MongoDBException If not is a ObjectRepository
     *
     * @deprecated in version 1.2 and will be removed in 2.0. Please use setDefaultDocumentRepositoryClassName instead.
     */
    public function setDefaultRepositoryClassName($className)
    {
        @trigger_error(
            sprintf('"%s" was deprecated in doctrine/mongodb-odm 1.2 and will be removed in 2.0. Please use "%s::setDefaultDocumentRepositoryClassName" instead.', __METHOD__, __CLASS__),
            E_USER_DEPRECATED
        );
        $this->setDefaultDocumentRepositoryClassName($className);
    }

    /**
     * Get default repository class.
     *
     * @return string
     *
     * @deprecated in version 1.2 and will be removed in 2.0. Please use getDefaultDocumentRepositoryClassName instead.
     */
    public function getDefaultRepositoryClassName()
    {
        @trigger_error(
            sprintf('"%s" was deprecated in doctrine/mongodb-odm 1.2 and will be removed in 2.0. Please use "%s::getDefaultDocumentRepositoryClassName" instead.', __METHOD__, __CLASS__),
            E_USER_DEPRECATED
        );
        return $this->getDefaultDocumentRepositoryClassName();
    }

    /**
     * @throws MongoDBException If not is a ObjectRepository.
     */
    public function setDefaultDocumentRepositoryClassName($className)
    {
        $reflectionClass = new \ReflectionClass($className);
        if (! $reflectionClass->implementsInterface(ObjectRepository::class)) {
            throw MongoDBException::invalidDocumentRepository($className);
        }
        $this->attributes['defaultDocumentRepositoryClassName'] = $className;
    }

    /**
     * Get default repository class.
     *
     * @return string
     */
    public function getDefaultDocumentRepositoryClassName()
    {
        return isset($this->attributes['defaultDocumentRepositoryClassName'])
            ? $this->attributes['defaultDocumentRepositoryClassName']
            : NewDocumentRepository::class;
    }

    /**
     * Set the document repository factory.
     *
     * @param RepositoryFactory $repositoryFactory
     */
    public function setRepositoryFactory(RepositoryFactory $repositoryFactory)
    {
        $this->attributes['repositoryFactory'] = $repositoryFactory;
    }

    /**
     * Get the document repository factory.
     *
     * @return RepositoryFactory
     */
    public function getRepositoryFactory()
    {
        return isset($this->attributes['repositoryFactory'])
            ? $this->attributes['repositoryFactory']
            : new DefaultRepositoryFactory();
    }

    /**
     * Set the persistent collection factory.
     *
     * @param PersistentCollectionFactory $persistentCollectionFactory
     */
    public function setPersistentCollectionFactory(PersistentCollectionFactory $persistentCollectionFactory)
    {
        $this->attributes['persistentCollectionFactory'] = $persistentCollectionFactory;
    }

    /**
     * Get the persistent collection factory.
     *
     * @return DefaultPersistentCollectionFactory
     */
    public function getPersistentCollectionFactory()
    {
        if ( ! isset($this->attributes['persistentCollectionFactory'])) {
            $this->attributes['persistentCollectionFactory'] = new DefaultPersistentCollectionFactory();
        }
        return $this->attributes['persistentCollectionFactory'];
    }

    /**
     * Set the persistent collection generator.
     *
     * @param PersistentCollectionGenerator $persistentCollectionGenerator
     */
    public function setPersistentCollectionGenerator(PersistentCollectionGenerator $persistentCollectionGenerator)
    {
        $this->attributes['persistentCollectionGenerator'] = $persistentCollectionGenerator;
    }

    /**
     * Get the persistent collection generator.
     *
     * @return DefaultPersistentCollectionGenerator
     */
    public function getPersistentCollectionGenerator()
    {
        if ( ! isset($this->attributes['persistentCollectionGenerator'])) {
            $this->attributes['persistentCollectionGenerator'] = new DefaultPersistentCollectionGenerator(
                $this->getPersistentCollectionDir(),
                $this->getPersistentCollectionNamespace()
            );
        }
        return $this->attributes['persistentCollectionGenerator'];
    }

    /**
     * {@inheritdoc}
     *
     * @deprecated This method is deprecated and will be removed in MongoDB ODM 2.0.
     */
    public function getLoggerCallable()
    {
        @trigger_error(sprintf('The "%s" method is deprecated and will be removed in doctrine/mongodb-odm 2.0.', __METHOD__), E_USER_DEPRECATED);

        return parent::getLoggerCallable();
    }

    /**
     * {@inheritdoc}
     *
     * @deprecated This method is deprecated and will be removed in MongoDB ODM 2.0.
     */
    public function setLoggerCallable($loggerCallable)
    {
        @trigger_error(sprintf('The "%s" method is deprecated and will be removed in doctrine/mongodb-odm 2.0.', __METHOD__), E_USER_DEPRECATED);

        parent::setLoggerCallable($loggerCallable);
    }

    /**
     * {@inheritdoc}
     *
     * @deprecated This method is deprecated and will be removed in MongoDB ODM 2.0.
     */
    public function getMongoCmd()
    {
        @trigger_error(sprintf('The "%s" method is deprecated and will be removed in doctrine/mongodb-odm 2.0.', __METHOD__), E_USER_DEPRECATED);

        return parent::getMongoCmd();
    }

    /**
     * {@inheritdoc}
     *
     * @deprecated This method is deprecated and will be removed in MongoDB ODM 2.0.
     */
    public function setMongoCmd($cmd)
    {
        @trigger_error(sprintf('The "%s" method is deprecated and will be removed in doctrine/mongodb-odm 2.0.', __METHOD__), E_USER_DEPRECATED);

        parent::setMongoCmd($cmd);
    }

    /**
     * {@inheritdoc}
     *
     * @deprecated This method is deprecated and will be removed in MongoDB ODM 2.0.
     */
    public function getRetryConnect()
    {
        @trigger_error(sprintf('The "%s" method is deprecated and will be removed in doctrine/mongodb-odm 2.0.', __METHOD__), E_USER_DEPRECATED);

        return parent::getRetryConnect();
    }

    /**
     * {@inheritdoc}
     *
     * @deprecated This method is deprecated and will be removed in MongoDB ODM 2.0.
     */
    public function setRetryConnect($retryConnect)
    {
        @trigger_error(sprintf('The "%s" method is deprecated and will be removed in doctrine/mongodb-odm 2.0.', __METHOD__), E_USER_DEPRECATED);

        parent::setRetryConnect($retryConnect);
    }

    /**
     * {@inheritdoc}
     *
     * @deprecated This method is deprecated and will be removed in MongoDB ODM 2.0.
     */
    public function getRetryQuery()
    {
        @trigger_error(sprintf('The "%s" method is deprecated and will be removed in doctrine/mongodb-odm 2.0.', __METHOD__), E_USER_DEPRECATED);

        return parent::getRetryQuery();
    }

    /**
     * {@inheritdoc}
     *
     * @deprecated This method is deprecated and will be removed in MongoDB ODM 2.0.
     */
    public function setRetryQuery($retryQuery)
    {
        @trigger_error(sprintf('The "%s" method is deprecated and will be removed in doctrine/mongodb-odm 2.0.', __METHOD__), E_USER_DEPRECATED);

        parent::setRetryQuery($retryQuery);
    }
}
