<?php

/*
 * This file is part of the Doctrine MongoDBBundle
 *
 * The code was originally distributed inside the Symfony framework.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 * (c) Doctrine Project
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Doctrine\Bundle\MongoDBBundle\CacheWarmer;

use Doctrine\ODM\MongoDB\Configuration;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\HttpKernel\CacheWarmer\CacheWarmerInterface;

/**
 * The persistent collections generator cache warmer generates all custom persistent collections.
 *
 * In the process of generating persistent collections the cache for all the metadata is primed also,
 * since this information is necessary to build the persistent collections in the first place.
 *
 * @author Maciej Malarz <malarzm@gmail.com>
 */
class PersistentCollectionCacheWarmer implements CacheWarmerInterface
{
    /**
     * @var ContainerInterface
     */
    private $container;

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

    /**
     * This cache warmer is not optional, without persistent collections fatal error occurs!
     *
     * @return false
     */
    public function isOptional()
    {
        return false;
    }

    public function warmUp($cacheDir)
    {
        // we need the directory no matter the hydrator cache generation strategy.
        $collCacheDir = $this->container->getParameter('doctrine_mongodb.odm.persistent_collection_dir');
        if (! file_exists($collCacheDir)) {
            if (false === @mkdir($collCacheDir, 0775, true)) {
                throw new \RuntimeException(sprintf('Unable to create the Doctrine persistent collection directory (%s)', dirname($collCacheDir)));
            }
        } else if (! is_writable($collCacheDir)) {
            throw new \RuntimeException(sprintf('Doctrine persistent collection directory (%s) is not writable for the current system user.', $collCacheDir));
        }

        // if persistent collection are autogenerated we don't need to generate them in the cache warmer.
        if (Configuration::AUTOGENERATE_NEVER !== $this->container->getParameter('doctrine_mongodb.odm.auto_generate_persistent_collection_classes')) {
            return;
        }

        $generated = [];
        /* @var $registry \Doctrine\Common\Persistence\ManagerRegistry */
        $registry = $this->container->get('doctrine_mongodb');
        foreach ($registry->getManagers() as $dm) {
            /* @var $dm \Doctrine\ODM\MongoDB\DocumentManager */
            $collectionGenerator = $dm->getConfiguration()->getPersistentCollectionGenerator();
            $classes = $dm->getMetadataFactory()->getAllMetadata();
            foreach ($classes as $metadata) {
                foreach ($metadata->getAssociationNames() as $fieldName) {
                    $mapping = $metadata->getFieldMapping($fieldName);
                    if (empty($mapping['collectionClass']) || in_array($mapping['collectionClass'], $generated)) {
                        continue;
                    }
                    $generated[] = $mapping['collectionClass'];
                    $collectionGenerator->generateClass($mapping['collectionClass'], $collCacheDir);
                }
            }
        }
    }
}
