<?php

namespace KupShop\ElninoBundle;

use KupShop\KupShopBundle\Config;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\HttpKernel\Bundle\Bundle;

class ElninoBundle extends Bundle
{
    private $cfg;

    public function boot()
    {
        $this->cfg = Config::get();
        spl_autoload_register(__NAMESPACE__.'\ElninoBundle::autoloadElnino', true, true);

        parent::boot();
    }

    public function build(ContainerBuilder $container)
    {
        $this->cfg = Config::get();
        spl_autoload_register(__NAMESPACE__.'\ElninoBundle::autoloadElnino', true, true);

        parent::build($container);
    }

    public function autoloadElnino($fqcn)
    {
        static $subclass = 1; // backward compatibility

        $length = strlen('Query');
        if (strpos($fqcn, '\\') && !(substr($fqcn, 0, $length) === 'Query')) {
            return;
        } else {
            if (strpos($fqcn, '\\')) {
                $fileName = str_replace('\\', '/', $fqcn).'.php';
                $prefix = '';
            } else {
                $fileName = "{$fqcn}.php";
                $prefix = 'class.';
            }
        }

        $shopFile = 'class.'.$fileName;
        $bundleFile = __DIR__.'/Old/'.$fileName;
        $engineFile = $this->cfg['Path']['shared_class'].$prefix.$fileName;

        if (file_exists($shopFile)) {
            return;
        }

        if (file_exists($engineFile)) {
            require_once $engineFile;
        }

        if (file_exists($bundleFile)) {
            require_once $bundleFile;
            list($namespace, $className) = parseClassName($fqcn);
            $namespace = !empty($namespace) ? 'namespace '.$namespace.' ' : '';
            $extendPrefix = !empty($namespace) ? '\\' : '';

            eval("{$namespace}{class {$className} extends {$extendPrefix}KupShop\\ElninoBundle\\Old\\{$fqcn} {}}");
        }
    }
}
