ArgumentsReader.php 7.62 KB
Newer Older
Ketan's avatar
Ketan committed
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
<?php
/**
 * Copyright © Magento, Inc. All rights reserved.
 * See COPYING.txt for license details.
 */
namespace Magento\Framework\Code\Reader;

class ArgumentsReader
{
    const NO_DEFAULT_VALUE = 'NO-DEFAULT';

    /**
     * @var NamespaceResolver
     */
    private $namespaceResolver;

    /**
     * @var ScalarTypesProvider
     */
    private $scalarTypesProvider;

    /**
     * @param NamespaceResolver|null $namespaceResolver
     * @param ScalarTypesProvider|null $scalarTypesProvider
     */
    public function __construct(
        NamespaceResolver $namespaceResolver = null,
        ScalarTypesProvider $scalarTypesProvider = null
    ) {
        $this->namespaceResolver = $namespaceResolver ?: new NamespaceResolver();
        $this->scalarTypesProvider = $scalarTypesProvider ?: new ScalarTypesProvider();
    }

    /**
     * Get class constructor
     *
     * @param \ReflectionClass $class
     * @param bool $groupByPosition
     * @param bool $inherited
     * @return array
     * @SuppressWarnings(PHPMD.CyclomaticComplexity)
     * @SuppressWarnings(PHPMD.NPathComplexity)
     */
    public function getConstructorArguments(\ReflectionClass $class, $groupByPosition = false, $inherited = false)
    {
        $output = [];
        /**
         * Skip native PHP types, classes without constructor
         */
        if ($class->isInterface() || !$class->getFileName() || false == $class->hasMethod(
            '__construct'
        ) || !$inherited && $class->getConstructor()->class != $class->getName()
        ) {
            return $output;
        }

        $constructor = new \Zend\Code\Reflection\MethodReflection($class->getName(), '__construct');
        foreach ($constructor->getParameters() as $parameter) {
            $name = $parameter->getName();
            $position = $parameter->getPosition();
            $index = $groupByPosition ? $position : $name;
            $default = null;
            if ($parameter->isOptional()) {
                if ($parameter->isDefaultValueAvailable()) {
                    $value = $parameter->getDefaultValue();
                    if (true == is_array($value)) {
                        $default = $this->_varExportMin($value);
                    } elseif (true == is_int($value)) {
                        $default = $value;
                    } else {
                        $default = $parameter->getDefaultValue();
                    }
                } elseif ($parameter->allowsNull()) {
                    $default = null;
                }
            }

            $output[$index] = [
                'name' => $name,
                'position' => $position,
                'type' => $this->processType($class, $parameter),
                'isOptional' => $parameter->isOptional(),
                'default' => $default,
            ];
        }
        return $output;
    }

    /**
     * Process argument type.
     *
     * @param \ReflectionClass $class
     * @param \Zend\Code\Reflection\ParameterReflection $parameter
     * @return string
     */
    private function processType(\ReflectionClass $class, \Zend\Code\Reflection\ParameterReflection $parameter)
    {
        if ($parameter->getClass()) {
            return NamespaceResolver::NS_SEPARATOR . $parameter->getClass()->getName();
        }

        $type =  $parameter->detectType();

        if ($type === 'null') {
            return null;
        }

        if (strpos($type, '[]') !== false) {
            return 'array';
        }

        if (!in_array($type, $this->scalarTypesProvider->getTypes())) {
            $availableNamespaces = $this->namespaceResolver->getImportedNamespaces(file($class->getFileName()));
            $availableNamespaces[0] = $class->getNamespaceName();
            return $this->namespaceResolver->resolveNamespace($type, $availableNamespaces);
        }

        return $type;
    }

    /**
     * Get arguments of parent __construct call
     *
     * @param \ReflectionClass $class
     * @param array $classArguments
     * @return array|null
     */
    public function getParentCall(\ReflectionClass $class, array $classArguments)
    {
        /** Skip native PHP types */
        if (!$class->getFileName()) {
            return null;
        }

        $trimFunction = function (&$value) {
            $value = trim($value, PHP_EOL . ' $');
        };

        $method = $class->getMethod('__construct');
        $start = $method->getStartLine();
        $end = $method->getEndLine();
        $length = $end - $start;

        $source = file($class->getFileName());
        $content = implode('', array_slice($source, $start, $length));
        $pattern = '/parent::__construct\(([ ' .
            PHP_EOL .
            ']*[$]{1}[a-zA-Z0-9_]*,)*[ ' .
            PHP_EOL .
            ']*' .
            '([$]{1}[a-zA-Z0-9_]*){1}[' .
            PHP_EOL .
            ' ]*\);/';

        if (!preg_match($pattern, $content, $matches)) {
            return null;
        }

        $arguments = $matches[0];
        if (!trim($arguments)) {
            return null;
        }

        $arguments = substr(trim($arguments), 20, -2);
        $arguments = explode(',', $arguments);
        array_walk($arguments, $trimFunction);

        $output = [];
        foreach ($arguments as $argumentPosition => $argumentName) {
            $type = isset($classArguments[$argumentName]) ? $classArguments[$argumentName]['type'] : null;
            $output[$argumentPosition] = [
                'name' => $argumentName,
                'position' => $argumentPosition,
                'type' => $type,
            ];
        }
        return $output;
    }

    /**
     * Check argument type compatibility
     *
     * @param string $requiredType
     * @param string $actualType
     * @return bool
     */
    public function isCompatibleType($requiredType, $actualType)
    {
        /** Types are compatible if type names are equal */
        if ($requiredType === $actualType) {
            return true;
        }

        /** Types are 'semi-compatible' if one of them are undefined */
        if ($requiredType === null || $actualType === null) {
            return true;
        }

        /**
         * Special case for scalar arguments
         * Array type is compatible with array or null type. Both of these types are checked above
         */
        if ($requiredType === 'array' || $actualType === 'array') {
            return false;
        }

        if ($requiredType === 'mixed' || $actualType === 'mixed') {
            return true;
        }

        return is_subclass_of($actualType, $requiredType);
    }

    /**
     * Export variable value
     *
     * @param mixed $var
     * @return mixed|string
     */
    protected function _varExportMin($var)
    {
        if (is_array($var)) {
            $toImplode = [];
            foreach ($var as $key => $value) {
                $toImplode[] = var_export($key, true) . ' => ' . $this->_varExportMin($value);
            }
            $code = 'array(' . implode(', ', $toImplode) . ')';
            return $code;
        } else {
            return var_export($var, true);
        }
    }

    /**
     * Get constructor annotations
     *
     * @param \ReflectionClass $class
     * @return array
     */
    public function getAnnotations(\ReflectionClass $class)
    {
        $regexp = '(@([a-z_][a-z0-9_]+)\(([^\)]+)\))i';
        $docBlock = $class->getConstructor()->getDocComment();
        $annotations = [];
        preg_match_all($regexp, $docBlock, $matches);
        foreach (array_keys($matches[0]) as $index) {
            $name = $matches[1][$index];
            $value = trim($matches[2][$index], '" ');
            $annotations[$name] = $value;
        }

        return $annotations;
    }
}