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
/**
 * MIT License
 *
 * Copyright (c) 2018, ArrayIterator
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NON INFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */

declare(strict_types=1);

namespace ArrayIterator\Extension;

use FilesystemIterator;

/**
 * Class Loader
 * @package ArrayIterator\Extension
 *
 * Extension Loader for main extension object core.
 */
class Loader
{
    /**
     * Extension directory to check.
     *
     * @var string
     */
    protected $extensionsDirectory;

    /**
     * Extension Parser.
     *
     * @var ParserInterface
     */
    protected $parser;

    /**
     * Stored data about extension
     *
     * @var \SplFixedArray|ExtensionInfo[]|ExtensionInterface[]
     */
    protected $stack;

    /**
     * Determine if on strict mode.
     *
     * @var bool
     */
    protected $strictMode = false;

    /**
     * List of original identifiers.
     *
     * @var string[]
     */
    protected $keysNormal = null;

    /**
     * List of lower case identifier. Values as offset stack.
     *
     * @var int[]
     */
    protected $keysLower = null;

    /**
     * List of loaded extensions.
     *
     * @var string[]|null
     */
    protected $loaded = null;

    /**
     * List of class name duplication extension detect by parser.
     * Key name as original string identifier.
     *
     * @var array|array[]|string[][]
     */
    protected $duplications = [];

    /**
     * Loader constructor.
     * @param string $extensionsDirectory <p>
     * Extensions directory to crawl.
     * </p>
     * @param bool $strictMode [optional] <p>
     * Determine about use <b>Strict Mode</b> or not.
     * </p>
     * @param ParserInterface|null $parser [optional] <p>
     * Object parser to use as extension directory parser & crawler,
     * if <b>NULL</b> @uses Parser as default parser.
     * </p>
     */
    public function __construct(
        string $extensionsDirectory,
        bool $strictMode = false,
        ParserInterface $parser = null
    ) {
        $spl = new \SplFileInfo($extensionsDirectory);
        if (!$spl->isDir()) {
            throw new \RuntimeException(
                sprintf(
                    'Directory %s is not exists',
                    $extensionsDirectory
                )
            );
        }

        $this->stack = null;
        $this->strictMode = $strictMode;
        $this->parser = $parser ?: new Parser();
        $this->extensionsDirectory = (new \SplFileInfo($extensionsDirectory))->getRealPath();
    }

    /**
     * Get parser object instance.
     *
     * @return ParserInterface
     */
    public function getParser() : ParserInterface
    {
        return $this->parser;
    }

    /**
     * Get extensions directory.
     *
     * @return string realpath extensions directory.
     */
    public function getExtensionsDirectory() : string
    {
        return $this->extensionsDirectory;
    }

    /**
     * Get Strict Mode information.
     *
     * @return bool is on Strict Mode or not.
     */
    public function isStrictMode() : bool
    {
        return $this->strictMode;
    }

    /**
     * Start parsing extensions from given extensions directory.
     *
     * @uses FilesystemIterator <p>
     * To iterate scan of directory.
     * </p>
     * @return Loader
     */
    public function start() : Loader
    {
        // if stack is not empty, this is mean that
        // has been processed.
        if ($this->stack) {
            return $this;
        }

        // set default properties data
        $this->loaded = [];
        $this->stack = [];
        $this->keysLower = [];
        $this->keysNormal = [];

        $c = 0;
        $existingClass = [];
        /**
         * @var \SplFileInfo $item
         */
        foreach (new FilesystemIterator(
            $this->extensionsDirectory,
            FilesystemIterator::CURRENT_AS_FILEINFO
            | FilesystemIterator::KEY_AS_FILENAME
            | FilesystemIterator::SKIP_DOTS
        ) as $fileName => $item) {
            if ($item->isDir()) {
                $name = basename($fileName);
                $lowerName = strtolower($name);
                if (isset($this->keysLower[$lowerName])) {
                    continue;
                }
                $parsed = $this
                    ->parser
                    ->parse(
                        $this->extensionsDirectory
                        . DIRECTORY_SEPARATOR
                        . $fileName,
                        $this->strictMode,
                        $existingClass,
                        $this->duplications
                    );
                if ($parsed) {
                    array_push($existingClass, $parsed->getClassName());
                    $this->keysNormal[$c] = $name;
                    $this->keysLower[$lowerName] = $c;
                    $this->stack[$c] = $parsed;
                    $c++;
                }
            }
        }

        unset($parsed, $existingClass);
        $this->stack = \SplFixedArray::fromArray($this->stack);

        return $this;
    }

    /**
     * Verify if extension is exist.
     *
     * @param string $selector <p>
     * Case insensitive selector, this use base name of extension directory.
     * </p>
     * @return bool TRUE if exist otherwise FALSE
     */
    public function exist(string $selector) : bool
    {
        // if has not been parsed returning false
        if (!$this->stack) {
            return false;
        }

        return isset($this->keysLower[strtolower($selector)]);
    }

    /**
     * Verify if extension loaded.
     *
     * @param string $selector <p>
     * Case insensitive selector, this use base name of extension directory.
     * </p>
     * @return bool TRUE if loaded otherwise FALSE.
     */
    public function isLoaded(string $selector) : bool
    {
        // if has not been parsed returning false
        if (!$this->stack) {
            return false;
        }

        return isset($this->loaded[strtolower($selector)]);
    }

    /**
     * Get available extensions selector.
     *
     * @return string[] list of selector / extensions base name.
     */
    public function getAllAvailableExtensions() : array
    {
        return $this->start()->keysNormal;
    }

    /**
     * Get list of duplicate classes while on parsing process
     * key name as base of directory.
     *
     * @return array|string[][] List of duplicate class name. Key name as original string identifier.
     */
    public function getDuplications() : array
    {
        return $this->duplications;
    }

    /**
     * Load the extension by selector.
     *
     * @param string $selector <p>Input string selector base name.</p>
     * @return ExtensionInterface instance of extension.
     * @throws ExtensionNotFoundException if extension does not exists.
     * @see Loader::instantiateExtension()
     */
    public function load(string $selector)
    {
        // if stack is empty, start the parsing process.
        if (!$this->stack) {
            $this->start();
        }
        if (!$this->exist($selector)) {
            throw new ExtensionNotFoundException($selector);
        }

        $selector = strtolower($selector);
        $offset = $this->keysLower[$selector];
        if (isset($this->loaded[$selector])) {
            return $this->stack[$offset];
        }

        $this->stack[$offset]    = $this->instantiateExtension(
            $this->stack[$offset]->getClassName(),
            $this->stack[$offset]
        );
        $this->loaded[$selector] = $this->keysNormal[$offset];
        return $this->stack[$offset];
    }

    /**
     * Instantiate extension.
     *
     * @param string $extensionClassName <p>
     * Extension class name.
     * </p>
     * @param ExtensionInfo $info <p>
     * ExtensionInfo as default object info representation.
     * </p>
     * @return ExtensionInterface instance of object.
     */
    protected function instantiateExtension(
        string $extensionClassName,
        ExtensionInfo $info
    ) : ExtensionInterface {
        return new $extensionClassName($info);
    }

    /**
     * Magic Method __sleep keep the data when object being serialize.
     *
     * @return array represent as object properties need to be keep.
     */
    public function __sleep() : array
    {
        return [
            'extensionsDirectory',
            'strictMode',
            'parser',
            'loaded'
        ];
    }

    /**
     * Magic Method __wakeup() process when serialized object being unserialize.
     *
     * @return void
     */
    public function __wakeup()
    {
        // check if stack if empty and extension as loaded
        if (!$this->stack && is_array($this->loaded)) {
            $this->start();
            foreach ($this->loaded as $key => $bool) {
                $this->load($key);
            }
        }
    }
}