本文整理汇总了PHP中ReflectionClass::getConstructor方法的典型用法代码示例。如果您正苦于以下问题:PHP ReflectionClass::getConstructor方法的具体用法?PHP ReflectionClass::getConstructor怎么用?PHP ReflectionClass::getConstructor使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类ReflectionClass
的用法示例。
在下文中一共展示了ReflectionClass::getConstructor方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的PHP代码示例。
示例1: map
/**
* Maps two object together, a map should exist.
*
* @param $source
* @param $destination
*
* @return object
* @throws InvalidClassConstructorException
*/
public function map($source, $destination)
{
if (is_string($destination)) {
$destinationRef = new \ReflectionClass($destination);
if ($destinationRef->getConstructor() && $destinationRef->getConstructor()->getNumberOfRequiredParameters() > 0) {
throw new InvalidClassConstructorException($destination);
}
$destination = $destinationRef->newInstance();
}
$map = $this->getMap($this->guessType($source), $this->guessType($destination));
$fieldAccessors = $map->getFieldAccessors();
$fieldFilters = $map->getFieldFilters();
foreach ($fieldAccessors as $path => $fieldAccessor) {
$value = $fieldAccessor->getValue($source);
if (isset($fieldFilters[$path])) {
if (($filter = $fieldFilters[$path]) instanceof AbstractMappingFilter) {
$filter->setMapper($this);
}
$value = $filter->filter($value);
}
if ($map->getSkipNull() && is_null($value)) {
continue;
}
$propertyAccessor = PropertyAccess::createPropertyAccessor();
if ($map->getOverwriteIfSet()) {
$propertyAccessor->setValue($destination, $path, $value);
} else {
if ($propertyAccessor->getValue($destination, $path) == null) {
$propertyAccessor->setValue($destination, $path, $value);
}
}
}
return $destination;
}
示例2: testDateTime
/**
* Test handling of attributes of the DateTime type.
*/
public function testDateTime()
{
// Add a mostly dummy configuration. We are not going to read or write any files here.
// The important part is the accessors part.
$config = new Config(array('inputFile' => null, 'outputDir' => null, 'constructorParamsDefaultToNull' => true));
$complexType = new ComplexType($config, 'ComplexTypeTestClass');
$complexType->addMember('dateTime', 'dateTimeAttribute', false);
$this->generateClass($complexType);
$this->assertClassExists('ComplexTypeTestClass');
$this->assertClassHasAttribute('dateTimeAttribute', 'ComplexTypeTestClass');
$this->assertClassHasMethod('ComplexTypeTestClass', 'getDateTimeAttribute');
$this->assertClassHasMethod('ComplexTypeTestClass', 'setDateTimeAttribute');
$object = new \ComplexTypeTestClass(new \DateTime());
$class = new \ReflectionClass($object);
$this->assertMethodParameterHasType($class->getConstructor(), 'dateTimeAttribute', 'DateTime');
$this->assertMethodParameterDocBlockHasType($class->getConstructor(), 'dateTimeAttribute', '\\DateTime');
$this->assertMethodHasReturnType($class->getMethod('getDateTimeAttribute'), '\\DateTime');
$this->assertMethodParameterHasType($class->getMethod('setDateTimeAttribute'), 'dateTimeAttribute', 'DateTime');
$this->assertMethodParameterDocBlockHasType($class->getMethod('setDateTimeAttribute'), 'dateTimeAttribute', '\\DateTime');
// Using reflection to set up bad datetime value as like SoapClass does it
$property = 'dateTimeAttribute';
$badDateTime = 'noDate';
$this->setObjectProperty($object, $property, $badDateTime);
$this->assertFalse($object->getDateTimeAttribute());
// Test passing variable datetime formats available in SOAP, http://www.w3.org/TR/2001/REC-xmlschema-2-20010502/#dateTime
$now = new \DateTime();
foreach (array('Y-m-d\\TH:i:s', 'Y-m-d\\TH:i:sP', 'Y-m-d\\TH:i:s.u', 'Y-m-d\\TH:i:s.uP', 'Y-m-d\\TH:i:s\\Z', 'Y-m-d\\TH:i:s.u\\Z') as $format) {
$this->setObjectProperty($object, $property, $now->format($format));
$this->assertInstanceOf('\\DateTime', $object->getDateTimeAttribute());
}
}
示例3: execute
/**
* {@inheritdoc}
*/
public function execute(InputInterface $input, OutputInterface $output)
{
$class = $input->getArgument('factory');
$class = str_replace('/', '\\', $class);
if (false === class_exists($class)) {
throw new \Exception(sprintf('Class %s not found', $class));
}
$rfl = new \ReflectionClass($class);
if (null !== $rfl->getConstructor() && 0 < $rfl->getConstructor()->getNumberOfRequiredParameters()) {
throw new \Exception('Can\'t instanciate adapter factory %s, constructor shouldn\'t need required parameters');
}
$factory = new $class();
if (false === $factory instanceof AdapterFactory) {
throw new \Exception('Your adapter factory should implements Gaufrette\\TestSuite\\Adapter\\AdapterFactory');
}
$exit = 0;
foreach ($this->tests->all() as $test) {
$output->writeln('');
$adapter = $factory->create();
$result = $this->runTest($test, $adapter, $output);
$factory->destroy();
$exit = true === $result ? $exit : 1;
}
$output->writeln('');
return $exit;
}
示例4: resolve
/**
* @param null|string|CrudControllerInterface $controller
* @return CrudControllerInterface
* @throws ControllerNotFoundException
*/
public function resolve($controller)
{
if (null === $controller) {
$controller = $this->defaultController;
}
$name = $controller;
if (is_string($controller)) {
if (isset($this->resolved[$controller])) {
return $this->resolved[$controller];
}
if ($this->container->has($controller)) {
$controller = $this->container->get($controller);
} elseif (class_exists($controller, true)) {
$refl = new \ReflectionClass($controller);
if ($refl->implementsInterface('Bravesheep\\CrudifyBundle\\Controller\\CrudControllerInterface')) {
if ($refl->getConstructor() === null || $refl->getConstructor()->getNumberOfRequiredParameters() === 0) {
$controller = $refl->newInstance();
$controller->setContainer($this->container);
}
}
}
}
if (!$controller instanceof CrudControllerInterface) {
throw new ControllerNotFoundException("Could not resolve controller specification to controller");
}
if (is_string($name)) {
$this->resolved[$name] = $controller;
}
return $controller;
}
示例5: readInterface
/**
* Derives properties from constructor, public instance variables, getters and setters.
*
* @param object|null $object If provided, dynamic (run-time) variables are read as well
* @return \watoki\collections\Map|Property[] indexed by property name
*/
public function readInterface($object = null)
{
$properties = new Map();
if ($this->class->getConstructor()) {
foreach ($this->class->getConstructor()->getParameters() as $parameter) {
$this->accumulate($properties, new property\ConstructorProperty($this->factory, $this->class->getConstructor(), $parameter));
}
}
$declaredProperties = array();
foreach ($this->class->getProperties(\ReflectionProperty::IS_PUBLIC) as $property) {
if (!$property->isStatic()) {
$declaredProperties[] = $property->name;
$this->accumulate($properties, new property\InstanceVariableProperty($this->factory, $property));
}
}
if (is_object($object)) {
foreach ($object as $name => $value) {
if (!in_array($name, $declaredProperties)) {
$this->accumulate($properties, new property\DynamicProperty($this->factory, new \ReflectionClass($object), $name));
}
}
}
foreach ($this->class->getMethods(\ReflectionMethod::IS_PUBLIC) as $method) {
if (property\AccessorProperty::isAccessor($method) && !$method->isStatic()) {
$this->accumulate($properties, new property\AccessorProperty($this->factory, $method));
}
}
return $properties;
}
示例6: __construct
/**
* Constructor
*
* @param string|object $base_class Class name of the base class, or an instance
* @param array $constructor_args (Optional) Arguments to pass to the constructor of the base class
* @param array $constants (Optional) Constants to override
*/
public function __construct($base_class, array $constructor_args = array(), array $constants = array())
{
// @codeCoverageIgnoreStart
if (PHP_VERSION_ID < 50300) {
trigger_error(get_class() . ': This class requires PHP version 5.3 or higher.', E_USER_ERROR);
}
// @codeCoverageIgnoreEnd
if (is_object($base_class) && count($constructor_args)) {
throw new Mollie_Testing_Exception('Unused constructor arguments for passed instance of "' . get_class($base_class) . '".');
}
// If it's an instance, just accept it
if (is_object($base_class)) {
$this->_base_class = $base_class;
} elseif (!class_exists($base_class)) {
throw new Mollie_Testing_Exception("Base class '{$base_class}' does not exist.");
} else {
$ref = new ReflectionClass($base_class);
if ($ref->isAbstract()) {
$ref = new ReflectionClass($this->createDerivedClass($base_class));
}
if ($ref->getConstructor() && count($constructor_args) < $ref->getConstructor()->getNumberOfRequiredParameters()) {
throw new Mollie_Testing_Exception($ref->getConstructor()->getNumberOfRequiredParameters() . " constructor arguments required for '{$base_class}::__construct(...)'.");
}
$this->_base_class = sizeof($constructor_args) ? $ref->newInstanceArgs($constructor_args) : $ref->newInstance();
}
}
示例7: generateCode
private function generateCode($classes, $controllerName)
{
$methods = [];
$comments = [];
foreach ($classes as $item) {
if (false === class_exists($item)) {
$comments[] = sprintf('Class %s does not exist', $item);
continue;
}
$reflection = new \ReflectionClass($item);
if ($reflection->getConstructor() && 0 !== $reflection->getConstructor()->getNumberOfRequiredParameters()) {
$comments[] = sprintf('Class %s has a required constructor argument', $item);
continue;
}
if (false === $reflection->hasMethod('getDefaultView')) {
$comments[] = sprintf('Class %s has no default view', $item);
continue;
}
list($name) = array_reverse(explode("\\", $item));
$template = $reflection->newInstance()->getDefaultView();
$methods[] = ['name' => lcfirst($name), 'class' => $item, 'template' => $template];
}
$code = '<?php' . "\n\n" . '// THIS FILE IS GENERATED DURING THE CACHE WARMUP, DO NOT MODIFY' . "\n" . 'class %s extends \\Symfony\\Bundle\\FrameworkBundle\\Controller\\Controller' . "\n" . '{%s}';
$code = sprintf($code, $controllerName, "\n\n\t" . ($comments ? implode("\n\t", $comments) . "\n\n\t" : '') . implode("\n\t", array_map(function ($item) {
$key = false === strpos($item['class'], "PagePart") ? 'page' : 'resource';
return sprintf('public function %sAction()' . "\n\t" . '{' . "\n\t\t" . 'return $this->render("%s", [' . "\n\t\t\t" . '"%s" => new \\%s,' . "\n\t\t" . ']);' . "\n\t" . "}" . "\n", $item['name'], $item['template'], $key, $item['class']);
}, $methods)) . "\n");
$code = str_replace("\t", " ", $code);
return $code;
}
示例8: instantinate
private function instantinate($class_name)
{
if (array_key_exists($class_name, $this->class_dictionary)) {
$class_name = $this->class_dictionary[$class_name];
}
$class = new ReflectionClass($class_name);
$parameters = array();
$constructor = $class->getConstructor();
if ($constructor != null) {
$parameters = $class->getConstructor()->getParameters();
}
$dependencies = array();
foreach ($parameters as $value) {
$className = "";
if ($value->getClass() != null) {
$className = $value->getClass()->getName();
}
$parameterName = $value->getName();
if (array_key_exists($className, $this->instance_dictionary)) {
$dependencies[] = $this->instance_dictionary[$className];
} elseif (array_key_exists($parameterName, $this->var_dictionary)) {
if (!is_string($this->var_dictionary[$parameterName])) {
$dependencies[] = $this->var_dictionary[$parameterName];
} else {
$dependencies[] = $this->get($this->var_dictionary[$parameterName]);
}
} elseif (array_key_exists($className, $this->class_dictionary)) {
$dependencies[] = $this->get($className);
} else {
throw new IocClassNotFounException($class_name, $className, $parameterName);
}
}
return call_user_func_array(array(new ReflectionClass($class_name), 'newInstance'), $dependencies);
}
示例9: testGeneratedCode
public function testGeneratedCode()
{
// Test that enums are created correctly.
//
// the MS-SSNWS contains enumerations with names that collide with PHP
// keywords. This test ensures that they are created correctly.
//
// Load the code. This ensures that the syntax of the generated code is
// valid.
// We do not call the service here. It is not necessary for the check
// at hand and we do not have a valid endpoint for the service either.
// Create an instance of a class containing problematic constants. This also autoloads it.
$typeEnum = new \sqlDbTypeEnum();
// If we got this far and loaded the class without parse errors we should be good.
$this->assertTrue(true);
// Test that classes with datetimes are created correctly.
//
// This should be in a separate test method. This would however cause
// code generated to run twice and classes would be generated twice as
// setUp() is called twice. Since the first part of the test loads all
// the classes the second round would add a suffix to class names to
// avoid conflicts.
//
// This we test for multiple aspects in the same method. Going forward
// we should consider separating generated code between methods - e.g.
// by adding the test method as a namespace.
$this->assertGeneratedClassExists('DayAsNumber');
$object = new \DayAsNumber(new \DateTime());
$class = new \ReflectionClass($object);
$this->assertMethodParameterHasType($class->getConstructor(), 'day', 'DateTime');
$this->assertMethodParameterDocBlockHasType($class->getConstructor(), 'day', '\\DateTime');
}
示例10: make
/**
* Makes an instance of a class
*
* @param string $className Class name
* @return object Class instance
*/
public function make($className)
{
// Create a reflection to access the class properties
$reflection = new \ReflectionClass($className);
// If the class has no constructor, just return a new instance
$constructor = $reflection->getConstructor();
if (is_null($constructor)) {
return new $className();
}
// Or get the constructor parameters and instance dependencies
$dependencies = [];
$parameters = $reflection->getConstructor()->getParameters();
foreach ($parameters as $param) {
$class = $param->getClass();
if ($class && $class->getName() === 'Laito\\App') {
// If the dependency is the app itself, inject the current instance
$dependencies[] = $this;
} else {
// Otherwise, inject the instantiated dependency or a null value
$dependencies[] = $class ? $this->make($class->name) : 'NULL';
}
}
// Return the class instance
$instance = $reflection->newInstanceArgs($dependencies);
// If the class has a boot method, run it
if (method_exists($instance, 'boot')) {
$instance->boot();
}
// Return instance
return $instance;
}
示例11: getReflectionParameters
/**
* @return \ReflectionParameter[]
*/
function getReflectionParameters()
{
$reflConstructor = $this->reflClass->getConstructor();
if (NULL === $reflConstructor) {
return array();
}
return $reflConstructor->getParameters();
}
示例12: initConstructorArgs
/**
* Fetches constructor args (array of ReflectionParameter) from the reflected class
* and set them as an associative array
*/
public function initConstructorArgs()
{
$constructor = $this->reflected->getConstructor();
if (!is_null($constructor)) {
// Index parameters by their names
foreach ($constructor->getParameters() as $param) {
$this->constructorArgs[$param->getName()] = $param;
}
}
}
示例13: getClassDefinition
/**
* Get Class definition for constructor parameter.
*
* @param \ReflectionClass $parameterClass
*
* @return mixed|null|object
*/
private function getClassDefinition(\ReflectionClass $parameterClass)
{
$parameterClassName = $parameterClass->getName();
$entryReference = new \ReflectionClass($parameterClass->getName());
$argumentParams = false;
if ($entryReference->getConstructor()) {
$argumentParams = $entryReference->getConstructor()->getParameters();
}
return $argumentParams ? $this->get($parameterClassName) : new $parameterClassName();
}
示例14: initConstructorArgs
/**
* Fetches constructor args (array of ReflectionParameter) from the reflected class
* and set them as an associative array
*
* Convert the parameter names to camelCase for classes that have contructor
* params defined in snake_case for consistency with the options
*/
public function initConstructorArgs()
{
$constructor = $this->reflected->getConstructor();
if (!is_null($constructor)) {
// Index parameters by their names
foreach ($constructor->getParameters() as $param) {
$name = Util::snakeToCamelCase($param->getName());
$this->constructorArgs[$name] = $param;
}
}
}
示例15: initConstructorArgs
/**
* Fetches constructor args (array of ReflectionParameter) from the reflected class
* and set them as an associative array
*
* Convert the parameter names to camelCase for classes that have contructor
* params defined in snake_case for consistency with the options
*/
public function initConstructorArgs()
{
$constructor = $this->reflected->getConstructor();
$nameConverter = new CamelCaseToSnakeCaseNameConverter();
if (!is_null($constructor)) {
// Index parameters by their names
foreach ($constructor->getParameters() as $param) {
$this->constructorArgs[$nameConverter->denormalize($param->getName())] = $param;
}
}
}