getMethodParameters() public method

Returns an array of parameters of the given method. Each entry contains additional information about the parameter position, type hint etc.
public getMethodParameters ( string $className, string $methodName ) : array
$className string Name of the class containing the method
$methodName string Name of the method to return parameter information of
return array An array of parameter names and additional information or an empty array of no parameters were found
 /**
  * Only convert if the given target class has a constructor with one argument being of type given type
  *
  * @param string $source
  * @param string $targetType
  * @return bool
  */
 public function canConvertFrom($source, $targetType)
 {
     $methodParameters = $this->reflectionService->getMethodParameters($targetType, '__construct');
     if (count($methodParameters) !== 1) {
         return false;
     }
     $methodParameter = array_shift($methodParameters);
     return $methodParameter['type'] === gettype($source);
 }
Ejemplo n.º 2
0
 /**
  * Only convert if the given target class has a constructor with one argument being of type given type
  *
  * @param string $source
  * @param string $targetType
  * @return bool
  */
 public function canConvertFrom($source, $targetType)
 {
     if (($this->reflectionService->isClassAnnotatedWith($targetType, Flow\Entity::class) || $this->reflectionService->isClassAnnotatedWith($targetType, Flow\ValueObject::class) || $this->reflectionService->isClassAnnotatedWith($targetType, Entity::class)) === true) {
         return false;
     }
     $methodParameters = $this->reflectionService->getMethodParameters($targetType, '__construct');
     if (count($methodParameters) !== 1) {
         return false;
     }
     $methodParameter = array_shift($methodParameters);
     return $methodParameter['type'] === gettype($source);
 }
 /**
  * @test
  */
 public function methodParametersGetNormalizedType()
 {
     $methodParameters = $this->reflectionService->getMethodParameters(Reflection\Fixtures\AnnotatedClass::class, 'intAndIntegerParameters');
     foreach ($methodParameters as $methodParameter) {
         $this->assertEquals('integer', $methodParameter['type']);
     }
 }
 /**
  * Checks if the specified method matches against the method name
  * expression.
  *
  * Returns TRUE if method name, visibility and arguments constraints match and the target
  * method is not final.
  *
  * @param string $className Ignored in this pointcut filter
  * @param string $methodName Name of the method to match against
  * @param string $methodDeclaringClassName Name of the class the method was originally declared in
  * @param mixed $pointcutQueryIdentifier Some identifier for this query - must at least differ from a previous identifier. Used for circular reference detection.
  * @return boolean TRUE if the class matches, otherwise FALSE
  * @throws Exception
  */
 public function matches($className, $methodName, $methodDeclaringClassName, $pointcutQueryIdentifier)
 {
     $matchResult = preg_match('/^' . $this->methodNameFilterExpression . '$/', $methodName);
     if ($matchResult === false) {
         throw new Exception('Error in regular expression', 1168876915);
     } elseif ($matchResult !== 1) {
         return false;
     }
     switch ($this->methodVisibility) {
         case 'public':
             if (!($methodDeclaringClassName !== null && $this->reflectionService->isMethodPublic($methodDeclaringClassName, $methodName))) {
                 return false;
             }
             break;
         case 'protected':
             if (!($methodDeclaringClassName !== null && $this->reflectionService->isMethodProtected($methodDeclaringClassName, $methodName))) {
                 return false;
             }
             break;
     }
     if ($methodDeclaringClassName !== null && $this->reflectionService->isMethodFinal($methodDeclaringClassName, $methodName)) {
         return false;
     }
     $methodArguments = $methodDeclaringClassName === null ? [] : $this->reflectionService->getMethodParameters($methodDeclaringClassName, $methodName);
     foreach (array_keys($this->methodArgumentConstraints) as $argumentName) {
         $objectAccess = explode('.', $argumentName, 2);
         $argumentName = $objectAccess[0];
         if (!array_key_exists($argumentName, $methodArguments)) {
             $this->systemLogger->log('The argument "' . $argumentName . '" declared in pointcut does not exist in method ' . $methodDeclaringClassName . '->' . $methodName, LOG_NOTICE);
             return false;
         }
     }
     return true;
 }
 /**
  * Get the constructor argument reflection for the given object type.
  *
  * @param string $className
  * @return array<array>
  */
 protected function getConstructorArgumentsForClass($className)
 {
     if (!isset($this->constructorReflectionFirstLevelCache[$className])) {
         $constructorSignature = [];
         // TODO: Check if we can get rid of this reflection service usage, directly reflecting doesn't work as the proxy class __construct has no arguments.
         if ($this->reflectionService->hasMethod($className, '__construct')) {
             $constructorSignature = $this->reflectionService->getMethodParameters($className, '__construct');
         }
         $this->constructorReflectionFirstLevelCache[$className] = $constructorSignature;
     }
     return $this->constructorReflectionFirstLevelCache[$className];
 }
 /**
  * Generates the parameters code needed to call the constructor with the saved parameters.
  *
  * @param string $className Name of the class the method is declared in
  * @return string The generated parameters code
  */
 protected function buildSavedConstructorParametersCode($className)
 {
     if ($className === null) {
         return '';
     }
     $parametersCode = '';
     $methodParameters = $this->reflectionService->getMethodParameters($className, '__construct');
     $methodParametersCount = count($methodParameters);
     if ($methodParametersCount > 0) {
         foreach ($methodParameters as $methodParameterName => $methodParameterInfo) {
             $methodParametersCount--;
             $parametersCode .= '$this->Flow_Aop_Proxy_originalConstructorArguments[\'' . $methodParameterName . '\']' . ($methodParametersCount > 0 ? ', ' : '');
         }
     }
     return $parametersCode;
 }
 /**
  * Detects and registers any validators for arguments:
  * - by the data type specified in the param annotations
  * - additional validators specified in the validate annotations of a method
  *
  * @param string $className
  * @param string $methodName
  * @param array $methodParameters Optional pre-compiled array of method parameters
  * @param array $methodValidateAnnotations Optional pre-compiled array of validate annotations (as array)
  * @return array An Array of ValidatorConjunctions for each method parameters.
  * @throws Exception\InvalidValidationConfigurationException
  * @throws Exception\NoSuchValidatorException
  * @throws Exception\InvalidTypeHintException
  */
 public function buildMethodArgumentsValidatorConjunctions($className, $methodName, array $methodParameters = null, array $methodValidateAnnotations = null)
 {
     $validatorConjunctions = [];
     if ($methodParameters === null) {
         $methodParameters = $this->reflectionService->getMethodParameters($className, $methodName);
     }
     if (count($methodParameters) === 0) {
         return $validatorConjunctions;
     }
     foreach ($methodParameters as $parameterName => $methodParameter) {
         $validatorConjunction = $this->createValidator(ConjunctionValidator::class);
         if (!array_key_exists('type', $methodParameter)) {
             throw new Exception\InvalidTypeHintException('Missing type information, probably no @param annotation for parameter "$' . $parameterName . '" in ' . $className . '->' . $methodName . '()', 1281962564);
         }
         if (strpos($methodParameter['type'], '\\') === false) {
             $typeValidator = $this->createValidator($methodParameter['type']);
         } else {
             $typeValidator = null;
         }
         if ($typeValidator !== null) {
             $validatorConjunction->addValidator($typeValidator);
         }
         $validatorConjunctions[$parameterName] = $validatorConjunction;
     }
     if ($methodValidateAnnotations === null) {
         $validateAnnotations = $this->reflectionService->getMethodAnnotations($className, $methodName, Flow\Validate::class);
         $methodValidateAnnotations = array_map(function ($validateAnnotation) {
             return ['type' => $validateAnnotation->type, 'options' => $validateAnnotation->options, 'argumentName' => $validateAnnotation->argumentName];
         }, $validateAnnotations);
     }
     foreach ($methodValidateAnnotations as $annotationParameters) {
         $newValidator = $this->createValidator($annotationParameters['type'], $annotationParameters['options']);
         if ($newValidator === null) {
             throw new Exception\NoSuchValidatorException('Invalid validate annotation in ' . $className . '->' . $methodName . '(): Could not resolve class name for  validator "' . $annotationParameters['type'] . '".', 1239853109);
         }
         if (isset($validatorConjunctions[$annotationParameters['argumentName']])) {
             $validatorConjunctions[$annotationParameters['argumentName']]->addValidator($newValidator);
         } elseif (strpos($annotationParameters['argumentName'], '.') !== false) {
             $objectPath = explode('.', $annotationParameters['argumentName']);
             $argumentName = array_shift($objectPath);
             $validatorConjunctions[$argumentName]->addValidator($this->buildSubObjectValidator($objectPath, $newValidator));
         } else {
             throw new Exception\InvalidValidationConfigurationException('Invalid validate annotation in ' . $className . '->' . $methodName . '(): Validator specified for argument name "' . $annotationParameters['argumentName'] . '", but this argument does not exist.', 1253172726);
         }
     }
     return $validatorConjunctions;
 }
 /**
  * Builds the PHP code for the parameters of the specified method to be
  * used in a method interceptor in the proxy class
  *
  * @param string $fullClassName Name of the class the method is declared in
  * @param string $methodName Name of the method to create the parameters code for
  * @param boolean $addTypeAndDefaultValue If the type and default value for each parameters should be rendered
  * @return string A comma speparated list of parameters
  */
 public function buildMethodParametersCode($fullClassName, $methodName, $addTypeAndDefaultValue = true)
 {
     $methodParametersCode = '';
     $methodParameterTypeName = '';
     $defaultValue = '';
     $byReferenceSign = '';
     if ($fullClassName === null || $methodName === null) {
         return '';
     }
     $methodParameters = $this->reflectionService->getMethodParameters($fullClassName, $methodName);
     if (count($methodParameters) > 0) {
         $methodParametersCount = 0;
         foreach ($methodParameters as $methodParameterName => $methodParameterInfo) {
             if ($addTypeAndDefaultValue) {
                 if ($methodParameterInfo['array'] === true) {
                     $methodParameterTypeName = 'array';
                 } elseif ($methodParameterInfo['scalarDeclaration']) {
                     $methodParameterTypeName = $methodParameterInfo['type'];
                 } else {
                     $methodParameterTypeName = $methodParameterInfo['class'] === null ? '' : '\\' . $methodParameterInfo['class'];
                 }
                 if ($methodParameterInfo['optional'] === true) {
                     $rawDefaultValue = isset($methodParameterInfo['defaultValue']) ? $methodParameterInfo['defaultValue'] : null;
                     if ($rawDefaultValue === null) {
                         $defaultValue = ' = NULL';
                     } elseif (is_bool($rawDefaultValue)) {
                         $defaultValue = $rawDefaultValue ? ' = TRUE' : ' = FALSE';
                     } elseif (is_numeric($rawDefaultValue)) {
                         $defaultValue = ' = ' . $rawDefaultValue;
                     } elseif (is_string($rawDefaultValue)) {
                         $defaultValue = " = '" . $rawDefaultValue . "'";
                     } elseif (is_array($rawDefaultValue)) {
                         $defaultValue = ' = ' . $this->buildArraySetupCode($rawDefaultValue);
                     }
                 }
                 $byReferenceSign = $methodParameterInfo['byReference'] ? '&' : '';
             }
             $methodParametersCode .= ($methodParametersCount > 0 ? ', ' : '') . ($methodParameterTypeName ? $methodParameterTypeName . ' ' : '') . $byReferenceSign . '$' . $methodParameterName . $defaultValue;
             $methodParametersCount++;
         }
     }
     return $methodParametersCode;
 }
Ejemplo n.º 9
0
 /**
  * Returns an array of CommandArgumentDefinition that contains
  * information about required/optional arguments of this command.
  * If the command does not expect any arguments, an empty array is returned
  *
  * @return array<CommandArgumentDefinition>
  */
 public function getArgumentDefinitions()
 {
     if (!$this->hasArguments()) {
         return [];
     }
     $commandArgumentDefinitions = [];
     $commandMethodReflection = $this->getCommandMethodReflection();
     $annotations = $commandMethodReflection->getTagsValues();
     $commandParameters = $this->reflectionService->getMethodParameters($this->controllerClassName, $this->controllerCommandName . 'Command');
     $i = 0;
     foreach ($commandParameters as $commandParameterName => $commandParameterDefinition) {
         $explodedAnnotation = explode(' ', $annotations['param'][$i]);
         array_shift($explodedAnnotation);
         array_shift($explodedAnnotation);
         $description = implode(' ', $explodedAnnotation);
         $required = $commandParameterDefinition['optional'] !== true;
         $commandArgumentDefinitions[] = new CommandArgumentDefinition($commandParameterName, $required, $description);
         $i++;
     }
     return $commandArgumentDefinitions;
 }
Ejemplo n.º 10
0
 /**
  * This function tries to find yet unmatched dependencies which need to be injected via "inject*" setter methods.
  *
  * @param array &$objectConfigurations
  * @return void
  * @throws ObjectException if an injected property is private
  */
 protected function autowireProperties(array &$objectConfigurations)
 {
     /** @var Configuration $objectConfiguration */
     foreach ($objectConfigurations as $objectConfiguration) {
         $className = $objectConfiguration->getClassName();
         $properties = $objectConfiguration->getProperties();
         if ($className === '') {
             continue;
         }
         $classMethodNames = get_class_methods($className);
         if (!is_array($classMethodNames)) {
             if (!class_exists($className)) {
                 throw new UnknownClassException(sprintf('The class "%s" defined in the object configuration for object "%s", defined in package: %s, does not exist.', $className, $objectConfiguration->getObjectName(), $objectConfiguration->getPackageKey()), 1352371371);
             } else {
                 throw new UnknownClassException(sprintf('Could not autowire properties of class "%s" because names of methods contained in that class could not be retrieved using get_class_methods().', $className), 1352386418);
             }
         }
         foreach ($classMethodNames as $methodName) {
             if (isset($methodName[6]) && strpos($methodName, 'inject') === 0 && $methodName[6] === strtoupper($methodName[6])) {
                 $propertyName = lcfirst(substr($methodName, 6));
                 $autowiringAnnotation = $this->reflectionService->getMethodAnnotation($className, $methodName, Flow\Autowiring::class);
                 if ($autowiringAnnotation !== null && $autowiringAnnotation->enabled === false) {
                     continue;
                 }
                 if ($methodName === 'injectSettings') {
                     $packageKey = $objectConfiguration->getPackageKey();
                     if ($packageKey !== null) {
                         $properties[$propertyName] = new ConfigurationProperty($propertyName, ['type' => ConfigurationManager::CONFIGURATION_TYPE_SETTINGS, 'path' => $packageKey], ConfigurationProperty::PROPERTY_TYPES_CONFIGURATION);
                     }
                 } else {
                     if (array_key_exists($propertyName, $properties)) {
                         continue;
                     }
                     $methodParameters = $this->reflectionService->getMethodParameters($className, $methodName);
                     if (count($methodParameters) !== 1) {
                         $this->systemLogger->log(sprintf('Could not autowire property %s because %s() expects %s instead of exactly 1 parameter.', $className . '::' . $propertyName, $methodName, count($methodParameters) ?: 'none'), LOG_DEBUG);
                         continue;
                     }
                     $methodParameter = array_pop($methodParameters);
                     if ($methodParameter['class'] === null) {
                         $this->systemLogger->log(sprintf('Could not autowire property %s because the method parameter in %s() contained no class type hint.', $className . '::' . $propertyName, $methodName), LOG_DEBUG);
                         continue;
                     }
                     $properties[$propertyName] = new ConfigurationProperty($propertyName, $methodParameter['class'], ConfigurationProperty::PROPERTY_TYPES_OBJECT);
                 }
             }
         }
         foreach ($this->reflectionService->getPropertyNamesByAnnotation($className, Inject::class) as $propertyName) {
             if ($this->reflectionService->isPropertyPrivate($className, $propertyName)) {
                 throw new ObjectException(sprintf('The property "%%s" in class "%s" must not be private when annotated for injection.', $propertyName, $className), 1328109641);
             }
             if (!array_key_exists($propertyName, $properties)) {
                 /** @var Inject $injectAnnotation */
                 $injectAnnotation = $this->reflectionService->getPropertyAnnotation($className, $propertyName, Inject::class);
                 $objectName = trim(implode('', $this->reflectionService->getPropertyTagValues($className, $propertyName, 'var')), ' \\');
                 $configurationProperty = new ConfigurationProperty($propertyName, $objectName, ConfigurationProperty::PROPERTY_TYPES_OBJECT, null, $injectAnnotation->lazy);
                 $properties[$propertyName] = $configurationProperty;
             }
         }
         foreach ($this->reflectionService->getPropertyNamesByAnnotation($className, InjectConfiguration::class) as $propertyName) {
             if ($this->reflectionService->isPropertyPrivate($className, $propertyName)) {
                 throw new ObjectException(sprintf('The property "%s" in class "%s" must not be private when annotated for configuration injection.', $propertyName, $className), 1416765599);
             }
             if (array_key_exists($propertyName, $properties)) {
                 continue;
             }
             /** @var InjectConfiguration $injectConfigurationAnnotation */
             $injectConfigurationAnnotation = $this->reflectionService->getPropertyAnnotation($className, $propertyName, InjectConfiguration::class);
             if ($injectConfigurationAnnotation->type === ConfigurationManager::CONFIGURATION_TYPE_SETTINGS) {
                 $packageKey = $injectConfigurationAnnotation->package !== null ? $injectConfigurationAnnotation->package : $objectConfiguration->getPackageKey();
                 $configurationPath = rtrim($packageKey . '.' . $injectConfigurationAnnotation->path, '.');
             } else {
                 if ($injectConfigurationAnnotation->package !== null) {
                     throw new ObjectException(sprintf('The InjectConfiguration annotation for property "%s" in class "%s" specifies a "package" key for configuration type "%s", but this is only supported for injection of "Settings".', $propertyName, $className, $injectConfigurationAnnotation->type), 1420811958);
                 }
                 $configurationPath = $injectConfigurationAnnotation->path;
             }
             $properties[$propertyName] = new ConfigurationProperty($propertyName, ['type' => $injectConfigurationAnnotation->type, 'path' => $configurationPath], ConfigurationProperty::PROPERTY_TYPES_CONFIGURATION);
         }
         $objectConfiguration->setProperties($properties);
     }
 }
 /**
  * Renders additional code for the __construct() method of the Proxy Class which realizes constructor injection.
  *
  * @param Configuration $objectConfiguration
  * @return string The built code
  * @throws ObjectException\UnknownObjectException
  */
 protected function buildConstructorInjectionCode(Configuration $objectConfiguration)
 {
     $assignments = [];
     $argumentConfigurations = $objectConfiguration->getArguments();
     $constructorParameterInfo = $this->reflectionService->getMethodParameters($objectConfiguration->getClassName(), '__construct');
     $argumentNumberToOptionalInfo = [];
     foreach ($constructorParameterInfo as $parameterInfo) {
         $argumentNumberToOptionalInfo[$parameterInfo['position'] + 1] = $parameterInfo['optional'];
     }
     $highestArgumentPositionWithAutowiringEnabled = -1;
     foreach ($argumentConfigurations as $argumentNumber => $argumentConfiguration) {
         if ($argumentConfiguration === null) {
             continue;
         }
         $argumentPosition = $argumentNumber - 1;
         if ($argumentConfiguration->getAutowiring() === Configuration::AUTOWIRING_MODE_ON) {
             $highestArgumentPositionWithAutowiringEnabled = $argumentPosition;
         }
         $argumentValue = $argumentConfiguration->getValue();
         $assignmentPrologue = 'if (!array_key_exists(' . ($argumentNumber - 1) . ', $arguments)) $arguments[' . ($argumentNumber - 1) . '] = ';
         if ($argumentValue === null && isset($argumentNumberToOptionalInfo[$argumentNumber]) && $argumentNumberToOptionalInfo[$argumentNumber] === true) {
             $assignments[$argumentPosition] = $assignmentPrologue . 'NULL';
         } else {
             switch ($argumentConfiguration->getType()) {
                 case ConfigurationArgument::ARGUMENT_TYPES_OBJECT:
                     if ($argumentValue instanceof Configuration) {
                         $argumentValueObjectName = $argumentValue->getObjectName();
                         $argumentValueClassName = $argumentValue->getClassName();
                         if ($argumentValueClassName === null) {
                             $preparedArgument = $this->buildCustomFactoryCall($argumentValue->getFactoryObjectName(), $argumentValue->getFactoryMethodName(), $argumentValue->getArguments());
                             $assignments[$argumentPosition] = $assignmentPrologue . $preparedArgument;
                         } else {
                             if ($this->objectConfigurations[$argumentValueObjectName]->getScope() === Configuration::SCOPE_PROTOTYPE) {
                                 $assignments[$argumentPosition] = $assignmentPrologue . 'new \\' . $argumentValueObjectName . '(' . $this->buildMethodParametersCode($argumentValue->getArguments()) . ')';
                             } else {
                                 $assignments[$argumentPosition] = $assignmentPrologue . '\\Neos\\Flow\\Core\\Bootstrap::$staticObjectManager->get(\'' . $argumentValueObjectName . '\')';
                             }
                         }
                     } else {
                         if (strpos($argumentValue, '.') !== false) {
                             $settingPath = explode('.', $argumentValue);
                             $settings = Arrays::getValueByPath($this->configurationManager->getConfiguration(ConfigurationManager::CONFIGURATION_TYPE_SETTINGS), array_shift($settingPath));
                             $argumentValue = Arrays::getValueByPath($settings, $settingPath);
                         }
                         if (!isset($this->objectConfigurations[$argumentValue])) {
                             throw new ObjectException\UnknownObjectException('The object "' . $argumentValue . '" which was specified as an argument in the object configuration of object "' . $objectConfiguration->getObjectName() . '" does not exist.', 1264669967);
                         }
                         $assignments[$argumentPosition] = $assignmentPrologue . '\\Neos\\Flow\\Core\\Bootstrap::$staticObjectManager->get(\'' . $argumentValue . '\')';
                     }
                     break;
                 case ConfigurationArgument::ARGUMENT_TYPES_STRAIGHTVALUE:
                     $assignments[$argumentPosition] = $assignmentPrologue . var_export($argumentValue, true);
                     break;
                 case ConfigurationArgument::ARGUMENT_TYPES_SETTING:
                     $assignments[$argumentPosition] = $assignmentPrologue . '\\Neos\\Flow\\Core\\Bootstrap::$staticObjectManager->getSettingsByPath(explode(\'.\', \'' . $argumentValue . '\'))';
                     break;
             }
         }
     }
     for ($argumentCounter = count($assignments) - 1; $argumentCounter > $highestArgumentPositionWithAutowiringEnabled; $argumentCounter--) {
         unset($assignments[$argumentCounter]);
     }
     $code = $argumentCounter >= 0 ? "\n        " . implode(";\n        ", $assignments) . ";\n" : '';
     $index = 0;
     foreach ($constructorParameterInfo as $parameterName => $parameterInfo) {
         if ($parameterInfo['optional'] === true) {
             break;
         }
         if ($objectConfiguration->getScope() === Configuration::SCOPE_SINGLETON) {
             $code .= '        if (!array_key_exists(' . $index . ', $arguments)) throw new \\Neos\\Flow\\ObjectManagement\\Exception\\UnresolvedDependenciesException(\'Missing required constructor argument $' . $parameterName . ' in class \' . __CLASS__ . \'. Please check your calling code and Dependency Injection configuration.\', 1296143787);' . "\n";
         } else {
             $code .= '        if (!array_key_exists(' . $index . ', $arguments)) throw new \\Neos\\Flow\\ObjectManagement\\Exception\\UnresolvedDependenciesException(\'Missing required constructor argument $' . $parameterName . ' in class \' . __CLASS__ . \'. Note that constructor injection is only support for objects of scope singleton (and this is not a singleton) – for other scopes you must pass each required argument to the constructor yourself.\', 1296143788);' . "\n";
         }
         $index++;
     }
     return $code;
 }