1:   2:   3:   4:   5:   6:   7:   8:   9:  10:  11:  12:  13:  14:  15:  16:  17:  18:  19:  20:  21:  22:  23:  24:  25:  26:  27:  28:  29:  30:  31:  32:  33:  34:  35:  36:  37:  38:  39:  40:  41:  42:  43:  44:  45:  46:  47:  48:  49:  50:  51:  52:  53:  54:  55:  56:  57:  58:  59:  60:  61:  62:  63:  64:  65:  66:  67:  68:  69:  70:  71:  72:  73:  74:  75:  76:  77:  78:  79:  80:  81:  82:  83:  84:  85:  86:  87:  88:  89:  90:  91:  92:  93:  94:  95:  96:  97:  98:  99: 100: 101: 102: 103: 104: 105: 106: 107: 108: 109: 110: 111: 112: 113: 114: 115: 116: 117: 118: 119: 120: 121: 122: 123: 124: 125: 126: 127: 128: 129: 130: 131: 132: 133: 134: 135: 136: 137: 138: 139: 140: 141: 142: 143: 144: 145: 146: 147: 148: 149: 150: 151: 152: 153: 154: 155: 156: 157: 158: 159: 160: 161: 162: 163: 164: 165: 166: 167: 168: 169: 170: 171: 172: 173: 174: 175: 176: 177: 178: 179: 180: 181: 182: 183: 184: 185: 186: 187: 188: 189: 190: 191: 192: 193: 194: 195: 196: 197: 198: 199: 200: 201: 202: 203: 204: 205: 206: 207: 208: 209: 210: 211: 212: 213: 214: 215: 216: 217: 218: 219: 220: 221: 222: 223: 224: 225: 226: 227: 228: 229: 230: 231: 232: 233: 234: 235: 236: 237: 238: 239: 240: 241: 242: 243: 244: 245: 246: 247: 248: 249: 250: 251: 252: 253: 254: 255: 256: 257: 258: 259: 260: 261: 262: 263: 264: 265: 266: 267: 268: 269: 270: 271: 272: 273: 274: 275: 276: 277: 278: 279: 280: 281: 282: 283: 284: 285: 286: 287: 288: 289: 290: 291: 292: 293: 294: 295: 296: 297: 298: 299: 300: 301: 302: 303: 304: 305: 306: 307: 308: 309: 310: 311: 312: 313: 314: 315: 316: 317: 318: 319: 320: 321: 322: 323: 324: 325: 326: 327: 328: 329: 330: 331: 332: 333: 334: 335: 336: 337: 338: 339: 340: 341: 342: 343: 344: 345: 346: 347: 348: 349: 350: 351: 352: 353: 354: 355: 356: 357: 358: 359: 360: 361: 362: 363: 364: 
<?php

namespace ClassConfig;

use ClassConfig\Annotation\Config;
use ClassConfig\Annotation\ConfigList;
use ClassConfig\Annotation\ConfigBoolean;
use ClassConfig\Annotation\ConfigEntryInterface;
use ClassConfig\Annotation\ConfigFloat;
use ClassConfig\Annotation\ConfigInteger;
use ClassConfig\Annotation\ConfigMap;
use ClassConfig\Annotation\ConfigObject;
use ClassConfig\Annotation\ConfigString;
use ClassConfig\Exceptions\ClassConfigAlreadyRegisteredException;
use ClassConfig\Exceptions\ClassConfigNotRegisteredException;
use Doctrine\Common\Annotations\AnnotationReader;

/**
 * Class ClassConfig
 * @package ClassConfig
 */
class ClassConfig
{
    /**
     * Config files are always re-generated when requested.
     */
    const CACHE_NEVER       = 0;

    /**
     * Config files are re-generated if older than the source (filemtime).
     */
    const CACHE_VALIDATE    = 1;

    /**
     * Config files are only generated once (or after being manually deleted).
     */
    const CACHE_ALWAYS      = 2;

    /**
     * Flag to determine whether the register() method has been called.
     *
     * @var bool
     */
    protected static $registered = false;

    /**
     * In-memory cache for the annotation reader.
     *
     * @var AnnotationReader
     */
    protected static $annotationReader;

    /**
     * The registered path to a cache folder.
     *
     * @var string
     */
    protected static $cachePath;

    /**
     * The registered caching strategy.
     *
     * @var int
     */
    protected static $cacheStrategy;

    /**
     * The registered class namespace for config classes.
     * This will be used as prefix to source classes.
     *
     * @var string
     */
    protected static $classNamespace;

    /**
     * @param string $path
     */
    protected static function createDirectories(string $path)
    {
        if (!is_dir($path)) {
            static::createDirectories(dirname($path));
            mkdir($path);
        }
    }

    /**
     * Lazy getter for the annotation reader.
     *
     * @return AnnotationReader
     * @throws \Doctrine\Common\Annotations\AnnotationException
     */
    protected static function getAnnotationReader(): AnnotationReader
    {
        if (!isset(static::$annotationReader)) {
            static::$annotationReader = new AnnotationReader();
        }
        return static::$annotationReader;
    }

    /**
     * Getter for the registered cache path.
     * Throws a ClassConfigNotRegisteredException if register() wasn't called prior.
     *
     * @return string
     * @throws ClassConfigNotRegisteredException
     */
    protected static function getCachePath(): string
    {
        if (!static::$registered) {
            throw new ClassConfigNotRegisteredException();
        }
        return static::$cachePath;
    }

    /**
     * Getter for the registered class namespace.
     * Throws a ClassConfigNotRegisteredException if register() wasn't called prior.
     *
     * @return string
     * @throws ClassConfigNotRegisteredException
     */
    protected static function getClassNamespace(): string
    {
        if (!static::$registered) {
            throw new ClassConfigNotRegisteredException();
        }
        return self::$classNamespace;
    }

    /**
     * @param Config $annotation
     * @param string $className
     * @param string $classNamespace
     * @param string $canonicalClassName
     * @param string $targetClassNamespace
     * @param string $targetCanonicalClassName
     * @param int $time
     * @param int $subClassIteration
     * @return string
     */
    protected static function generate(
        Config $annotation,
        string $className,
        string $classNamespace,
        string $canonicalClassName,
        string $targetClassNamespace,
        string $targetCanonicalClassName,
        int $time,
        int &$subClassIteration = 0
    ): string {
        // a suffix of _0, _1, _2 etc. is added to generated sub-classes
        $suffix = 0 < $subClassIteration ? '_' . $subClassIteration : '';

        $effectiveClassName = $className . $suffix;
        $effectiveTargetCanonicalClassName = $targetCanonicalClassName . $suffix;

        $generator = new ClassGenerator($annotation, $effectiveClassName, $targetClassNamespace, $canonicalClassName);

        /**
         * @var string $key
         * @var ConfigEntryInterface $entry
         */
        foreach ($annotation->value as $key => $entry) {
            switch (true) {
                case $entry instanceof ConfigString:
                case $entry instanceof ConfigInteger:
                case $entry instanceof ConfigFloat:
                case $entry instanceof ConfigBoolean:
                case $entry instanceof ConfigObject:
                    $type = $entry->getType();
                    $generator
                        ->generateProperty($key, $type, isset($entry->default) ? $entry->default : null)
                        ->generateGet($key, $type)
                        ->generateSet($key, $type)
                        ->generateIsset($key)
                        ->generateUnset($key);
                    break;

                case $entry instanceof ConfigList:
                    $type = isset($entry->value) ? $entry->value->getType() : 'mixed';
                    $generator
                        ->generateProperty($key, $type . '[]', isset($entry->default) ?
                            array_values($entry->default) : null)
                        ->generateGet($key, $type . '[]')
                        ->generateListSet($key, $type . '[]')
                        ->generateListGetAt($key, $type)
                        ->generateListSetAt($key, $type)
                        ->generateListPush($key, $type)
                        ->generateListUnshift($key, $type)
                        ->generateArrayPop($key, $type)
                        ->generateArrayShift($key, $type)
                        ->generateArrayClear($key)
                        ->generateIsset($key)
                        ->generateUnset($key);
                    break;

                case $entry instanceof ConfigMap:
                    $type = isset($entry->value) ? $entry->value->getType() : 'mixed';
                    $generator
                        ->generateProperty($key, $type . '[]', $entry->default)
                        ->generateGet($key, $type . '[]')
                        ->generateMapSet($key, $type . '[]')
                        ->generateMapGetAt($key, $type)
                        ->generateMapSetAt($key, $type)
                        ->generateArrayPop($key, $type)
                        ->generateArrayShift($key, $type)
                        ->generateArrayClear($key)
                        ->generateIsset($key)
                        ->generateUnset($key);
                    break;

                case $entry instanceof Config:
                    $subClassIteration++;
                    $entryCanonicalClassName = static::generate(
                        $entry,
                        $className,
                        $classNamespace,
                        $canonicalClassName,
                        $targetClassNamespace,
                        $targetCanonicalClassName,
                        $time,
                        $subClassIteration
                    );
                    $generator
                        ->generateProperty($key, $entryCanonicalClassName)
                        ->generateConfigGet($key, $entryCanonicalClassName)
                        ->generateConfigSet($key)
                        ->generateConfigIsset($key)
                        ->generateConfigUnset($key);
                    break;

                default:
                    throw new \RuntimeException(sprintf(
                        'Invalid or unsupported configuration entry type: "%s".',
                        get_class($entry)
                    ));
            }
        }

        $generator
            ->generateMagicGet()
            ->generateMagicSet()
            ->generateMagicIsset()
            ->generateMagicUnset();

        $targetDir = static::getCachePath() . '/' . str_replace('\\', '/', $classNamespace);
        $targetPath = $targetDir . '/' . $effectiveClassName . '.php';

        static::createDirectories($targetDir);

        file_put_contents($targetPath, (string) $generator);
        touch($targetPath, $time);
        clearstatcache();

        // as optimization measure composer's autoloader remembers that a class does not exist on the first requested
        // it will refuse to autoload the class even if it subsequently becomes available
        // for this reason we need to manually load the newly generated class
        include_once $targetPath;

        return $effectiveTargetCanonicalClassName;
    }

    /**
     * Register the environment.
     * This must be called once and only once (on each request) before working with the library.
     *
     * @param string $cachePath
     * @param int $cacheStrategy
     * @param string $classNamespace
     */
    public static function register(
        string $cachePath,
        int $cacheStrategy = self::CACHE_VALIDATE,
        string $classNamespace = 'ClassConfig\Cache'
    ) {
        if (static::$registered) {
            throw new ClassConfigAlreadyRegisteredException();
        }

        // ensure the cache folder exists
        static::createDirectories($cachePath);

        static::$registered = true;
        static::$cachePath = $cachePath;
        static::$cacheStrategy = $cacheStrategy;
        static::$classNamespace = $classNamespace;
    }

    /**
     * @param string $canonicalClassName
     * @return string
     * @throws \Doctrine\Common\Annotations\AnnotationException
     * @throws \ReflectionException
     * @throws ClassConfigNotRegisteredException
     */
    public static function createClass(string $canonicalClassName): string
    {
        $parts = explode('\\', $canonicalClassName);

        $className = $parts[count($parts) - 1];
        $classNamespace = implode('\\', array_slice($parts, 0, -1));

        $targetClassNamespace = static::getClassNamespace() . '\\' . $classNamespace;
        $targetCanonicalClassName = $targetClassNamespace . '\\' . $className;

        switch (static::$cacheStrategy) {
            case static::CACHE_NEVER:
                // always regenerate
                $time = time();
                break;

            case static::CACHE_ALWAYS:
                // only generate if class does not exist
                if (class_exists($targetCanonicalClassName)) {
                    return $targetCanonicalClassName;
                }
                $time = time();
                break;

            case static::CACHE_VALIDATE:
            default:
                // validate by last modified time
                $time = filemtime((new \ReflectionClass($canonicalClassName))->getFileName());
                if (
                    class_exists($targetCanonicalClassName) &&
                    filemtime((new \ReflectionClass($canonicalClassName))->getFileName()) ===
                    filemtime((new \ReflectionClass($targetCanonicalClassName))->getFileName())
                ) {
                    return $targetCanonicalClassName;
                }
                break;
        }

        /** @var Config $annotation */
        $annotation = static::getAnnotationReader()->getClassAnnotation(
            new \ReflectionClass($canonicalClassName),
            Config::class
        );

        return static::generate(
            $annotation,
            $className,
            $classNamespace,
            $canonicalClassName,
            $targetClassNamespace,
            $targetCanonicalClassName,
            $time
        );
    }

    /**
     * @param string $class
     * @param object $owner
     * @return AbstractConfig
     * @throws \Doctrine\Common\Annotations\AnnotationException
     * @throws \ReflectionException
     * @throws ClassConfigNotRegisteredException
     */
    public static function createInstance(string $class, $owner): AbstractConfig
    {
        $canonicalClassName = static::createClass($class);
        return new $canonicalClassName($owner);
    }
}