<?php

namespace KupShop\KupShopBundle\DependencyInjection;

use KupShop\KupShopBundle\Util\System\BundleFinder;
use KupShop\KupShopBundle\Util\System\PathFinder;
use Symfony\Component\Config\Exception\FileLocatorFileNotFoundException;
use Symfony\Component\Config\FileLocator;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Loader;
use Symfony\Component\HttpKernel\DependencyInjection\Extension;

/**
 * This is the class that loads and manages your bundle configuration.
 *
 * @see http://symfony.com/doc/current/cookbook/bundles/extension.html
 */
class KupShopExtension extends Extension
{
    public function load(array $configs, ContainerBuilder $container)
    {
        $bundleFinder = new BundleFinder(new PathFinder());
        $bundleFinder->setContainer($container);

        foreach ($bundleFinder->getBundlesPath('Resources/config') as $bundle => $file) {
            $locator = new FileLocator($file);
            $loader = new Loader\YamlFileLoader($container, $locator);
            $loader->load('services.yml');

            // Avoid loading from KupShopBundle - contains global config
            if ($bundle == 'KupShopBundle') {
                continue;
            }

            try {
                $loader->load('config.yml');
            } catch (FileLocatorFileNotFoundException $e) {
                // ignore non-exiting config.yml file
            }
        }

        if (isDevelopment()) {
            // watch config.php to automatically regenerate container
            $container->fileExists('include/config.php');
            $container->fileExists('config/config.php');
        }
    }
}
