<commit_before><?php
/**
 * Created by PhpStorm.
 * User: kuroro2121
 * Date: 14/10/21
 * Time: 00:03
 */
namespace AutoMaid;

//use AppKernel;
use Doctrine\Common\Annotations\AnnotationReader as Reader;
use Monolog\Handler\StreamHandler;
use RecursiveDirectoryIterator;
use RecursiveIteratorIterator;
use Monolog\Logger;
use Symfony\Component\Yaml\Yaml;

class AutoMaid
{
    const SA                = 'AutoMaid\Annotation\ServiceAnnotation';
    const CA                = 'AutoMaid\Annotation\ControllerAnnotation';
    const DepA              = 'AutoMaid\Annotation\DepOn';
    const SERVICE_FILE_NAME = 'am_services.yml';

    /**
     * @var bool
     */
    public static $useTraits   = true;
    PUBLIC static $initSysConf = false;

    protected $projectDir;
    /**
     * @var Logger
     */
    protected $logger;

    /**
     * @var Service[]
     */
    protected $definedServices = array();

    /**
     * @var Service[]
     */
    protected $generateServices = array();

    /**
     * @var AMController[]
     */
    protected $controllers = array();
    /**
     * @var AppKernel
     */
    protected $kernel;
    /**
     * @var \Symfony\Component\DependencyInjection\ContainerInterface
     */
    protected $container;
    /**
     * @var Reader
     */
    protected $annotationReader;

    protected $amConfigFiles = array();

    function __construct()
    {
        $this->projectDir = __DIR__ . '/../../../../..';
        $this->logger     = new Logger('AutoMaid');
        $this->logger->pushHandler(
            new StreamHandler('php://stdin', Logger::INFO)
        );
    }

    public function init()
    {
        $this->amConfigFiles = $this->getConfigurationLocation();

        if (self::$initSysConf) {
            $this->initConfigurationFiles($this->amConfigFiles);
        }

        if (class_exists('AppKernel')) {
            $this->kernel = new \AppKernel('dev', true);
            //TODO Greg: below statement will cause a exception will booting kernel, a duplication raised. I may check it later
            $this->kernel->boot();
            $this->container = $this->kernel->getContainer();
            $this->getServices();
        }

        $this->annotationReader = new Reader();

    }

    /**
     * @return \string[]
     */
    public function getConfigurationLocation()
    {
        $filePathes = array();

        // Step 1. app/config/config.yml
        $filePathes[] = $this->projectDir . '/app/config/config.yml';

        // Step 2. any other service.yml under src
        foreach (new RecursiveIteratorIterator (
                     new RecursiveDirectoryIterator (
                         $this->projectDir . '/src'
                     ),
                     RecursiveIteratorIterator::CHILD_FIRST
                 ) as $x) {
            if ($x->getFileName() == 'services.yml') {
                $filePathes[] = $x->getPathName();
            }
        }

        return $filePathes;
    }

    /**
     * @param \string[] $locations
     */
    public function initConfigurationFiles(array $locations)
    {
        foreach ($locations as $location) {
            $config = Yaml::parse($location);
            if (isset($config['imports'])) {
                $imports = $config['imports'];
                foreach ($imports as $index => $import) {
                    if ($import['resource'] == self::SERVICE_FILE_NAME) {
                        unset($imports[$index]);
                    }
                }
            } else {
                $config['imports'] = array();
            }
            $config['imports'][] = array(
                'resource'      => self::SERVICE_FILE_NAME,
                'ignore_errors' => true,
            );

            // backup old service.yml and config.yml
            rename($location, $location . '.' . posix_getpid() . '.bak');
            // write back to yaml file
            file_put_contents($location, Yaml::dump($config));
            // backup old configuration if there is any
            $amService = dirname(
                    $location
                ) . DIRECTORY_SEPARATOR . self::SERVICE_FILE_NAME;
            if (file_exists($amService)) {
                rename($amService, $amService . '.' . posix_getpid() . '.bak');
            }
        }

    }

    /**
     * Get all already defined services
     */
    public function getServices()
    {
        if (!empty($this->container)) {
            // TODO Greg: below code is questionable as getServiceIds is not part of ContainerInterface
            // Use reflection to get services and alias of container
            $containerClazz    = new \ReflectionClass($this->container);
            $servicesProperty  = $containerClazz->getProperty('services');
            $aliasesProperty   = $containerClazz->getProperty('aliases');
            $methodMapProperty = $containerClazz->getProperty('methodMap');
            $servicesProperty->setAccessible(true);
            $aliasesProperty->setAccessible(true);
            $methodMapProperty->setAccessible(true);
            $services  = $servicesProperty->getValue($this->container);
            $aliases   = $aliasesProperty->getValue($this->container);
            $methodMap = $methodMapProperty->getValue($this->container);
            /*foreach ($services as $serviceName => $method) {
                $alias = '';
                foreach ($aliases as $a => $n) {
                    if ($n == $serviceName) {
                        $alias = $a;
                        break;
                    }
                }

                $this->definedServices[] = new Service(
                    $serviceName, '', $alias
                );
            }*/
            foreach ($methodMap as $serviceName => $method) {
                $alias = '';
                foreach ($aliases as $a => $n) {
                    if ($n == $serviceName) {
                        $alias = $a;
                        break;
                    }
                }
                $this->definedServices[] = new Service(
                    $serviceName, '', $alias
                );
            }

        }
    }

    /**
     * Search a dir recursively and
     * @param string $path
     * @return int number of php files
     */<commit_msg>remove useless code<commit_after><?php
/**
 * Created by PhpStorm.
 * User: kuroro2121
 * Date: 14/10/21
 * Time: 00:03
 */
namespace AutoMaid;

//use AppKernel;
use Doctrine\Common\Annotations\AnnotationReader as Reader;
use Monolog\Handler\StreamHandler;
use RecursiveDirectoryIterator;
use RecursiveIteratorIterator;
use Monolog\Logger;
use Symfony\Component\Yaml\Yaml;

class AutoMaid
{
    const SA                = 'AutoMaid\Annotation\ServiceAnnotation';
    const CA                = 'AutoMaid\Annotation\ControllerAnnotation';
    const DepA              = 'AutoMaid\Annotation\DepOn';
    const SERVICE_FILE_NAME = 'am_services.yml';

    /**
     * @var bool
     */
    public static $useTraits   = true;
    PUBLIC static $initSysConf = false;

    protected $projectDir;
    /**
     * @var Logger
     */
    protected $logger;

    /**
     * @var Service[]
     */
    protected $definedServices = array();

    /**
     * @var Service[]
     */
    protected $generateServices = array();

    /**
     * @var AMController[]
     */
    protected $controllers = array();
    /**
     * @var AppKernel
     */
    protected $kernel;
    /**
     * @var \Symfony\Component\DependencyInjection\ContainerInterface
     */
    protected $container;
    /**
     * @var Reader
     */
    protected $annotationReader;

    protected $amConfigFiles = array();

    function __construct()
    {
        $this->projectDir = __DIR__ . '/../../../../..';
        $this->logger     = new Logger('AutoMaid');
        $this->logger->pushHandler(
            new StreamHandler('php://stdin', Logger::INFO)
        );
    }

    public function init()
    {
        $this->amConfigFiles = $this->getConfigurationLocation();

        if (self::$initSysConf) {
            $this->initConfigurationFiles($this->amConfigFiles);
        }

        if (class_exists('AppKernel')) {
            $this->kernel = new \AppKernel('dev', true);
            //TODO Greg: below statement will cause a exception will booting kernel, a duplication raised. I may check it later
            $this->kernel->boot();
            $this->container = $this->kernel->getContainer();
            $this->getServices();
        }

        $this->annotationReader = new Reader();

    }

    /**
     * @return \string[]
     */
    public function getConfigurationLocation()
    {
        $filePathes = array();

        // Step 1. app/config/config.yml
        $filePathes[] = $this->projectDir . '/app/config/config.yml';

        // Step 2. any other service.yml under src
        foreach (new RecursiveIteratorIterator (
                     new RecursiveDirectoryIterator (
                         $this->projectDir . '/src'
                     ),
                     RecursiveIteratorIterator::CHILD_FIRST
                 ) as $x) {
            if ($x->getFileName() == 'services.yml') {
                $filePathes[] = $x->getPathName();
            }
        }

        return $filePathes;
    }

    /**
     * @param \string[] $locations
     */
    public function initConfigurationFiles(array $locations)
    {
        foreach ($locations as $location) {
            $config = Yaml::parse($location);
            if (isset($config['imports'])) {
                $imports = $config['imports'];
                foreach ($imports as $index => $import) {
                    if ($import['resource'] == self::SERVICE_FILE_NAME) {
                        unset($imports[$index]);
                    }
                }
            } else {
                $config['imports'] = array();
            }
            $config['imports'][] = array(
                'resource'      => self::SERVICE_FILE_NAME,
                'ignore_errors' => true,
            );

            // backup old service.yml and config.yml
            rename($location, $location . '.' . posix_getpid() . '.bak');
            // write back to yaml file
            file_put_contents($location, Yaml::dump($config));
            // backup old configuration if there is any
            $amService = dirname(
                    $location
                ) . DIRECTORY_SEPARATOR . self::SERVICE_FILE_NAME;
            if (file_exists($amService)) {
                rename($amService, $amService . '.' . posix_getpid() . '.bak');
            }
        }

    }

    /**
     * Get all already defined services
     */
    public function getServices()
    {
        if (!empty($this->container)) {
            // TODO Greg: below code is questionable as getServiceIds is not part of ContainerInterface
            // Use reflection to get services and alias of container
            $containerClazz    = new \ReflectionClass($this->container);
            $servicesProperty  = $containerClazz->getProperty('services');
            $aliasesProperty   = $containerClazz->getProperty('aliases');
            $methodMapProperty = $containerClazz->getProperty('methodMap');
            $servicesProperty->setAccessible(true);
            $aliasesProperty->setAccessible(true);
            $methodMapProperty->setAccessible(true);
            $aliases   = $aliasesProperty->getValue($this->container);
            $methodMap = $methodMapProperty->getValue($this->container);

            foreach ($methodMap as $serviceName => $method) {
                $alias = '';
                foreach ($aliases as $a => $n) {
                    if ($n == $serviceName) {
                        $alias = $a;
                        break;
                    }
                }
                $this->definedServices[] = new Service(
                    $serviceName, '', $alias
                );
            }

        }
    }

    /**
     * Search a dir recursively and
     * @param string $path
     * @return int number of php files
     */
{'fraction_non_alphanumeric': 0.12861523162343583, 'fraction_numerical': 0.0026518604458440373, 'mean_word_length': 1.6447512601358756, 'pattern_counts': {'":': 0, '<': 5, '<?xml version=': 0, '>': 84, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '3679707', 'n_tokens_mistral': 3257, 'n_tokens_neox': 3098, 'n_words': 684}