<commit_before><?php

namespace Auryn;

class Injector {
    const A_RAW = ':';
    const A_DELEGATE = '+';
    const A_DEFINE = '@';
    const I_BINDINGS = 1;
    const I_DELEGATES = 2;
    const I_PREPARES = 4;
    const I_ALIASES = 8;
    const I_SHARES = 16;
    const I_ALL = 17;
    
    const E_NON_EMPTY_STRING_ALIAS = 1;
    const M_NON_EMPTY_STRING_ALIAS = "Invalid alias: non-empty string required at arguments 1 and 2";
    const E_SHARED_CANNOT_ALIAS = 2;
    const M_SHARED_CANNOT_ALIAS = "Cannot alias class %s to %s because it is currently shared";
    const E_SHARE_ARGUMENT = 3;
    const M_SHARE_ARGUMENT = "%s::share() requires a string class name or object instance at Argument 1; %s specified";
    const E_ALIASED_CANNOT_SHARE = 4;
    const M_ALIASED_CANNOT_SHARE = "Cannot share class %s because it is currently aliased to %s";
    const E_INVOKABLE = 5;
    const M_INVOKABLE = "Invalid invokable: callable or provisional string required";
    const E_NON_PUBLIC_CONSTRUCTOR = 6;
    const M_NON_PUBLIC_CONSTRUCTOR = "Cannot instantiate protected/private constructor in class %s";
    const E_NEEDS_DEFINITION = 7;
    const M_NEEDS_DEFINITION = "Injection definition required for non-concrete parameter $%s of type %s";
    const E_MAKE_FAILURE = 8;
    const M_MAKE_FAILURE = "Could not make %s: %s";
    const E_UNDEFINED_PARAM = 9;
    const M_UNDEFINED_PARAM = "No definition available to provision typeless parameter \$%s at position %d in %s()";
    const E_DELEGATE_ARGUMENT = 10;
    const M_DELEGATE_ARGUMENT = "%s::delegate expects a valid callable or executable class::method string at Argument 2";
    const E_CYCLIC_DEPENDENCY = 11;
    const M_CYCLIC_DEPENDENCY = "Detected a cyclic dependency while provisioning %s";

    private $reflector;
    private $classDefinitions = array();
    private $paramDefinitions = array();
    private $aliases = array();
    private $shares = array();
    private $prepares = array();
    private $delegates = array();
    private $inProgressMakes = array();

    public function __construct(Reflector $reflector = null) {
        $this->reflector = $reflector ?: new CachingReflector;
    }

    /**
     * Define instantiation directives for the specified class
     *
     * @param string $name The class (or alias) whose constructor arguments we wish to define
     * @param array $args An array mapping parameter names to values/instructions
     * @return self
     */
    public function define($name, array $args) {
        list(,$normalizedName) = $this->resolveAlias($name);
        $this->classDefinitions[$normalizedName] = $args;

        return $this;
    }

    /**
     * Assign a global default value for all parameters named $paramName
     *
     * Global parameter definitions are only used for parameters with no typehint, pre-defined or
     * call-time definition.
     *
     * @param string $paramName The parameter name for which this value applies
     * @param mixed $value The value to inject for this parameter name
     * @return self
     */
    public function defineParam($paramName, $value) {
        $this->paramDefinitions[$paramName] = $value;

        return $this;
    }

    /**
     * Define an alias for all occurrences of a given typehint
     *
     * Use this method to specify implementation classes for interface and abstract class typehints.
     *
     * @param string $original The typehint to replace
     * @param string $alias The implementation name
     * @return self
     */
    public function alias($original, $alias) {
        if (empty($original) || !is_string($original)) {
            throw new InjectorException(
                self::M_NON_EMPTY_STRING_ALIAS,
                self::E_NON_EMPTY_STRING_ALIAS
            );
        }
        if (empty($alias) || !is_string($alias)) {
            throw new InjectorException(
                self::M_NON_EMPTY_STRING_ALIAS,
                self::E_NON_EMPTY_STRING_ALIAS
            );
        }

        $originalNormalized = $this->normalizeName($original);

        if (isset($this->shares[$originalNormalized])) {
            throw new InjectorException(
                sprintf(
                    self::M_SHARED_CANNOT_ALIAS,
                    $this->normalizeName(get_class($this->shares[$originalNormalized])),
                    $alias
                ),
                self::E_SHARED_CANNOT_ALIAS
            );
        }

        if (array_key_exists($originalNormalized, $this->shares)) {
            $aliasNormalized = $this->normalizeName($alias);
            $this->shares[$aliasNormalized] = null;
            unset($this->shares[$originalNormalized]);
        }

        $this->aliases[$originalNormalized] = $alias;

        return $this;
    }

    private function normalizeName($className) {
        return ltrim(strtolower($className), '\\');
    }

    /**
     * Share the specified class/instance across the Injector context
     *
     * @param mixed $nameOrInstance The class or object to share
     * @return self
     */
    public function share($nameOrInstance) {
        if (is_string($nameOrInstance)) {
            $this->shareClass($nameOrInstance);
        } elseif (is_object($nameOrInstance)) {
            $this->shareInstance($nameOrInstance);
        } else {
            throw new InjectorException(
                sprintf(
                    self::M_SHARE_ARGUMENT,
                    __CLASS__,
                    gettype($nameOrInstance)
                ),
                self::E_SHARE_ARGUMENT
            );
        }

        return $this;
    }

    private function shareClass($nameOrInstance) {
        list(, $normalizedName) = $this->resolveAlias($nameOrInstance);
        $this->shares[$normalizedName] = isset($this->shares[$normalizedName])
            ? $this->shares[$normalizedName]
            : null;
    }

    private function resolveAlias($name) {
        $normalizedName = $this->normalizeName($name);
        if (isset($this->aliases[$normalizedName])) {
            $name = $this->aliases[$normalizedName];
            $normalizedName = $this->normalizeName($name);
        }

        return array($name, $normalizedName);
    }

    private function shareInstance($obj) {
        $normalizedName = $this->normalizeName(get_class($obj));
        if (isset($this->aliases[$normalizedName])) {
            // You cannot share an instance of a class name that is already aliased
            throw new InjectorException(
                sprintf(
                    self::M_ALIASED_CANNOT_SHARE,
                    $normalizedName,
                    $this->aliases[$normalizedName]
                ),
                self::E_ALIASED_CANNOT_SHARE
            );
        }
        $this->shares[$normalizedName] = $obj;
    }

    /**
     * Register a prepare callable to modify/prepare objects of type $name after instantiation
     *
     * Any callable or provisionable invokable may be specified. Preparers are passed two
     * arguments: the instantiated object to be mutated and the current Injector instance.
     *
     * @param string $name
     * @param mixed $callableOrMethodStr Any callable or provisionable invokable method
     * @return self
     */
    public function prepare($name, $callableOrMethodStr) {
        if ($this->isExecutable($callableOrMethodStr) === false) {
            throw new InjectorException(
                self::M_INVOKABLE,
                self::E_INVOKABLE
            );
        }

        list(,$normalizedName) = $this->resolveAlias($name);
        $this->prepares[$normalizedName] = $callableOrMethodStr;

        return $this;
    }

    private function isExecutable($exe) {
        if (is_callable($exe)) {
            return true;
        }
        if (is_string($exe) && method_exists($exe, '__invoke')) {
            return true;
        }
        if (is_array($exe) && isset($exe[0], $exe[1]) && method_exists($exe[0], $exe[1])) {
            return true;
        }

        return false;
    }

    /**
     * Delegate the creation of $name instances to the specified callable
     *
     * @param string $name
     * @param mixed $callableOrMethodStr Any callable or provisionable invokable method
     * @return self
     */
    public function delegate($name, $callableOrMethodStr) {
        if ($this->isExecutable($callableOrMethodStr) === false) {
            throw new InjectorException(
                sprintf(self::M_DELEGATE_ARGUMENT, __CLASS__),
                self::E_DELEGATE_ARGUMENT
            );
        }

        $normalizedName = $this->normalizeName($name);
        $this->delegates[$normalizedName] = $callableOrMethodStr;

        return $this;
    }

    /**
     * Retrieve stored data for the specified definition type
     *
     * Exposes introspection of existing binds/delegates/shares/etc for decoration and composition.
     *
     * @param string $nameFilter An optional class name filter
     * @param int $typeFilter A bitmask of Injector::* type constant flags
     * @return array
     */
    public function inspect($nameFilter = null, $typeFilter = null) {
        $result = array();
        $name = $nameFilter ? $this->normalizeName($nameFilter) : null;

        if (empty($typeFilter)) {
            $typeFilter = self::I_ALL;
        }

        if ($typeFilter & self::I_BINDINGS && ($elements = $this->filter($this->classDefinitions, $name))) {
            $result[self::I_BINDINGS] = $elements;
        }
        if ($typeFilter & self::I_DELEGATES && ($elements = $this->filter($this->delegates, $name))) {
            $result[self::I_DELEGATES] = $elements;
        }
        if ($typeFilter & self::I_PREPARES && ($elements = $this->filter($this->prepares, $name))) {
            $result[self::I_PREPARES] = $elements;
        }
        if ($typeFilter & self::I_ALIASES && ($elements = $this->filter($this->aliases, $name))) {
            $result[self::I_ALIASES] = $elements;
        }
        if ($typeFilter & self::I_SHARES && ($elements = $this->filter($this->shares, $name))) {
            $result[self::I_SHARES] = $elements;
        }

        return $result;
    }

    private function filter($source, $name) {
        if (empty($name)) {
            return $source;
        } elseif (isset($source[$name])) {
            return $source[$name];
        } else {
            return array();
        }
    }

    /**
     * Instantiate/provision a class instance
     *
     * @param string $name
     * @param array $args
     * @return mixed
     */
    public function make($name, array $args = array()) {<commit_msg>Simplify Injector::inspect()<commit_after><?php

namespace Auryn;

class Injector {
    const A_RAW = ':';
    const A_DELEGATE = '+';
    const A_DEFINE = '@';
    const I_BINDINGS = 1;
    const I_DELEGATES = 2;
    const I_PREPARES = 4;
    const I_ALIASES = 8;
    const I_SHARES = 16;
    const I_ALL = 17;
    
    const E_NON_EMPTY_STRING_ALIAS = 1;
    const M_NON_EMPTY_STRING_ALIAS = "Invalid alias: non-empty string required at arguments 1 and 2";
    const E_SHARED_CANNOT_ALIAS = 2;
    const M_SHARED_CANNOT_ALIAS = "Cannot alias class %s to %s because it is currently shared";
    const E_SHARE_ARGUMENT = 3;
    const M_SHARE_ARGUMENT = "%s::share() requires a string class name or object instance at Argument 1; %s specified";
    const E_ALIASED_CANNOT_SHARE = 4;
    const M_ALIASED_CANNOT_SHARE = "Cannot share class %s because it is currently aliased to %s";
    const E_INVOKABLE = 5;
    const M_INVOKABLE = "Invalid invokable: callable or provisional string required";
    const E_NON_PUBLIC_CONSTRUCTOR = 6;
    const M_NON_PUBLIC_CONSTRUCTOR = "Cannot instantiate protected/private constructor in class %s";
    const E_NEEDS_DEFINITION = 7;
    const M_NEEDS_DEFINITION = "Injection definition required for non-concrete parameter $%s of type %s";
    const E_MAKE_FAILURE = 8;
    const M_MAKE_FAILURE = "Could not make %s: %s";
    const E_UNDEFINED_PARAM = 9;
    const M_UNDEFINED_PARAM = "No definition available to provision typeless parameter \$%s at position %d in %s()";
    const E_DELEGATE_ARGUMENT = 10;
    const M_DELEGATE_ARGUMENT = "%s::delegate expects a valid callable or executable class::method string at Argument 2";
    const E_CYCLIC_DEPENDENCY = 11;
    const M_CYCLIC_DEPENDENCY = "Detected a cyclic dependency while provisioning %s";

    private $reflector;
    private $classDefinitions = array();
    private $paramDefinitions = array();
    private $aliases = array();
    private $shares = array();
    private $prepares = array();
    private $delegates = array();
    private $inProgressMakes = array();

    public function __construct(Reflector $reflector = null) {
        $this->reflector = $reflector ?: new CachingReflector;
    }

    /**
     * Define instantiation directives for the specified class
     *
     * @param string $name The class (or alias) whose constructor arguments we wish to define
     * @param array $args An array mapping parameter names to values/instructions
     * @return self
     */
    public function define($name, array $args) {
        list(,$normalizedName) = $this->resolveAlias($name);
        $this->classDefinitions[$normalizedName] = $args;

        return $this;
    }

    /**
     * Assign a global default value for all parameters named $paramName
     *
     * Global parameter definitions are only used for parameters with no typehint, pre-defined or
     * call-time definition.
     *
     * @param string $paramName The parameter name for which this value applies
     * @param mixed $value The value to inject for this parameter name
     * @return self
     */
    public function defineParam($paramName, $value) {
        $this->paramDefinitions[$paramName] = $value;

        return $this;
    }

    /**
     * Define an alias for all occurrences of a given typehint
     *
     * Use this method to specify implementation classes for interface and abstract class typehints.
     *
     * @param string $original The typehint to replace
     * @param string $alias The implementation name
     * @return self
     */
    public function alias($original, $alias) {
        if (empty($original) || !is_string($original)) {
            throw new InjectorException(
                self::M_NON_EMPTY_STRING_ALIAS,
                self::E_NON_EMPTY_STRING_ALIAS
            );
        }
        if (empty($alias) || !is_string($alias)) {
            throw new InjectorException(
                self::M_NON_EMPTY_STRING_ALIAS,
                self::E_NON_EMPTY_STRING_ALIAS
            );
        }

        $originalNormalized = $this->normalizeName($original);

        if (isset($this->shares[$originalNormalized])) {
            throw new InjectorException(
                sprintf(
                    self::M_SHARED_CANNOT_ALIAS,
                    $this->normalizeName(get_class($this->shares[$originalNormalized])),
                    $alias
                ),
                self::E_SHARED_CANNOT_ALIAS
            );
        }

        if (array_key_exists($originalNormalized, $this->shares)) {
            $aliasNormalized = $this->normalizeName($alias);
            $this->shares[$aliasNormalized] = null;
            unset($this->shares[$originalNormalized]);
        }

        $this->aliases[$originalNormalized] = $alias;

        return $this;
    }

    private function normalizeName($className) {
        return ltrim(strtolower($className), '\\');
    }

    /**
     * Share the specified class/instance across the Injector context
     *
     * @param mixed $nameOrInstance The class or object to share
     * @return self
     */
    public function share($nameOrInstance) {
        if (is_string($nameOrInstance)) {
            $this->shareClass($nameOrInstance);
        } elseif (is_object($nameOrInstance)) {
            $this->shareInstance($nameOrInstance);
        } else {
            throw new InjectorException(
                sprintf(
                    self::M_SHARE_ARGUMENT,
                    __CLASS__,
                    gettype($nameOrInstance)
                ),
                self::E_SHARE_ARGUMENT
            );
        }

        return $this;
    }

    private function shareClass($nameOrInstance) {
        list(, $normalizedName) = $this->resolveAlias($nameOrInstance);
        $this->shares[$normalizedName] = isset($this->shares[$normalizedName])
            ? $this->shares[$normalizedName]
            : null;
    }

    private function resolveAlias($name) {
        $normalizedName = $this->normalizeName($name);
        if (isset($this->aliases[$normalizedName])) {
            $name = $this->aliases[$normalizedName];
            $normalizedName = $this->normalizeName($name);
        }

        return array($name, $normalizedName);
    }

    private function shareInstance($obj) {
        $normalizedName = $this->normalizeName(get_class($obj));
        if (isset($this->aliases[$normalizedName])) {
            // You cannot share an instance of a class name that is already aliased
            throw new InjectorException(
                sprintf(
                    self::M_ALIASED_CANNOT_SHARE,
                    $normalizedName,
                    $this->aliases[$normalizedName]
                ),
                self::E_ALIASED_CANNOT_SHARE
            );
        }
        $this->shares[$normalizedName] = $obj;
    }

    /**
     * Register a prepare callable to modify/prepare objects of type $name after instantiation
     *
     * Any callable or provisionable invokable may be specified. Preparers are passed two
     * arguments: the instantiated object to be mutated and the current Injector instance.
     *
     * @param string $name
     * @param mixed $callableOrMethodStr Any callable or provisionable invokable method
     * @return self
     */
    public function prepare($name, $callableOrMethodStr) {
        if ($this->isExecutable($callableOrMethodStr) === false) {
            throw new InjectorException(
                self::M_INVOKABLE,
                self::E_INVOKABLE
            );
        }

        list(,$normalizedName) = $this->resolveAlias($name);
        $this->prepares[$normalizedName] = $callableOrMethodStr;

        return $this;
    }

    private function isExecutable($exe) {
        if (is_callable($exe)) {
            return true;
        }
        if (is_string($exe) && method_exists($exe, '__invoke')) {
            return true;
        }
        if (is_array($exe) && isset($exe[0], $exe[1]) && method_exists($exe[0], $exe[1])) {
            return true;
        }

        return false;
    }

    /**
     * Delegate the creation of $name instances to the specified callable
     *
     * @param string $name
     * @param mixed $callableOrMethodStr Any callable or provisionable invokable method
     * @return self
     */
    public function delegate($name, $callableOrMethodStr) {
        if ($this->isExecutable($callableOrMethodStr) === false) {
            throw new InjectorException(
                sprintf(self::M_DELEGATE_ARGUMENT, __CLASS__),
                self::E_DELEGATE_ARGUMENT
            );
        }

        $normalizedName = $this->normalizeName($name);
        $this->delegates[$normalizedName] = $callableOrMethodStr;

        return $this;
    }

    /**
     * Retrieve stored data for the specified definition type
     *
     * Exposes introspection of existing binds/delegates/shares/etc for decoration and composition.
     *
     * @param string $nameFilter An optional class name filter
     * @param int $typeFilter A bitmask of Injector::* type constant flags
     * @return array
     */
    public function inspect($nameFilter = null, $typeFilter = null) {
        $result = array();
        $name = $nameFilter ? $this->normalizeName($nameFilter) : null;

        if (empty($typeFilter)) {
            $typeFilter = self::I_ALL;
        }

        if ($typeFilter & self::I_BINDINGS) {
            $result[self::I_BINDINGS] = $this->filter($this->classDefinitions, $name);
        }
        if ($typeFilter & self::I_DELEGATES) {
            $result[self::I_DELEGATES] = $this->filter($this->delegates, $name);
        }
        if ($typeFilter & self::I_PREPARES) {
            $result[self::I_PREPARES] = $this->filter($this->prepares, $name);
        }
        if ($typeFilter & self::I_ALIASES) {
            $result[self::I_ALIASES] = $this->filter($this->aliases, $name);
        }
        if ($typeFilter & self::I_SHARES) {
            $result[self::I_SHARES] = $this->filter($this->shares, $name);
        }

        return $result;
    }

    private function filter($source, $name) {
        if (empty($name)) {
            return $source;
        } elseif (isset($source[$name])) {
            return $source[$name];
        } else {
            return array();
        }
    }

    /**
     * Instantiate/provision a class instance
     *
     * @param string $name
     * @param array $args
     * @return mixed
     */
    public function make($name, array $args = array()) {
{'fraction_non_alphanumeric': 0.10798634164848715, 'fraction_numerical': 0.002750640235227165, 'mean_word_length': 2.341838351822504, 'pattern_counts': {'":': 0, '<': 5, '<?xml version=': 0, '>': 91, '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': '60727', 'n_tokens_mistral': 6250, 'n_tokens_neox': 6025, 'n_words': 1531}