/** * @param FormField $formField * @param KForm $form */ public function instanceMapFrom(FormField $formField, KForm $form) { $attribute = $formField->getFieldName(); $method = 'mappingFromFormField' . ucfirst($attribute); if ($this->instanceReflector->hasMethod($method)) { $methodReflector = $this->instanceReflector->getMethod($method); $parameters = array(); foreach ($methodReflector->getParameters() as $paramReflector) { switch (true) { case $paramReflector->getClass()->isSubclassOf(KForm::class): $parameters[] = $form; break; case $paramReflector->getClass()->isSubclassOf(FormField::class): $parameters[] = $formField; break; default: $parameters[] = $formField; break; } } call_user_func_array(array($this->instance, $method), $parameters); } else { $this->instance->{$attribute} = $formField->getValue(); } }
public function runController($cName, $aName, $params) { $theController = new $cName(); $reflection_object = new ReflectionObject($theController); if ($reflection_object->hasMethod('before_action')) { $reflection_object->getMethod('before_action')->invoke($theController); } call_user_func_array(array($theController, $aName), $params); if ($reflection_object->hasMethod('after_action')) { $reflection_object->getMethod('after_action')->invoke($theController); } }
/** * Checks to call the method. * * Throws exceptions if the method doesn't exist, is not public or if there are mandatory parameters. * * @param \ReflectionObject $reflector * @throws \BadMethodCallException */ private static function _processObjectMethod(\ReflectionObject $reflector) { // check for method name if (!$reflector->hasMethod(self::$part)) { throw new \BadMethodCallException(sprintf('Method %s doesn\'t exist at path "%s"', self::$part, self::$actPath)); } // check that method is public $methodReclector = $reflector->getMethod(self::$part); if (!$methodReclector->isPublic()) { throw new \BadMethodCallException(sprintf('Method %s is not public at path "%s"', self::$part, self::$actPath)); } // check that method has no mandatory parameters $parameters = $methodReclector->getParameters(); if (!empty($parameters)) { foreach ($parameters as $parameter) { // If has no default value, throw exception, can't call the method without parameters try { $parameter->getDefaultValue(); } catch (\ReflectionException $e) { throw new \BadMethodCallException(sprintf('Method %s has mandatory parameter at path "%s", can\'t call it', self::$part, self::$actPath)); } } } $method = self::$part; self::$reference = self::$reference->{$method}(); }
/** * Recursively traverses and wraps all Closure objects within the value. * * NOTE: THIS MAY NOT WORK IN ALL USE CASES, SO USE AT YOUR OWN RISK. * * @param mixed $data Any variable that contains closures. * @param SerializerInterface $serializer The serializer to use. */ public static function wrapClosures(&$data, SerializerInterface $serializer) { if ($data instanceof \Closure) { // Handle and wrap closure objects. $reflection = new \ReflectionFunction($data); if ($binding = $reflection->getClosureThis()) { self::wrapClosures($binding, $serializer); $scope = $reflection->getClosureScopeClass(); $scope = $scope ? $scope->getName() : 'static'; $data = $data->bindTo($binding, $scope); } $data = new SerializableClosure($data, $serializer); } elseif (is_array($data) || $data instanceof \stdClass || $data instanceof \Traversable) { // Handle members of traversable values. foreach ($data as &$value) { self::wrapClosures($value, $serializer); } } elseif (is_object($data) && !$data instanceof \Serializable) { // Handle objects that are not already explicitly serializable. $reflection = new \ReflectionObject($data); if (!$reflection->hasMethod('__sleep')) { foreach ($reflection->getProperties() as $property) { if ($property->isPrivate() || $property->isProtected()) { $property->setAccessible(true); } $value = $property->getValue($data); self::wrapClosures($value, $serializer); $property->setValue($data, $value); } } } }
/** * Provides functionality for getters and setters of the customer * @see Varien_Object::__call() */ public function __call($method, $args) { if ($this->_customer instanceof Mage_Customer_Model_Customer) { $key = $this->_underscore(substr($method, 3)); switch (substr($method, 0, 3)) { case 'get': return $this->_customer->getData($key, isset($args[0]) ? $args[0] : null); case 'set': return $this->_customer->setData($key, isset($args[0]) ? $args[0] : null); case 'uns': return $this->_customer->unsetData($key); case 'has': $data = $this->_customer->getData(); return isset($data[$key]); } try { $_reflectionObject = new ReflectionObject($this->_customer); if ($_reflectionObject->hasMethod($method)) { $_reflectionMethod = new ReflectionMethod(get_class($this->_customer), $method); return $_reflectionMethod->invokeArgs($this->_customer, $args); } } catch (Exception $e) { return parent::__call($method, $args); } } return parent::__call($method, $args); }
public function callRPCMethod() { $sRawMethod = $this->oRequest->method; @(list($sNameSpace, $sMethod) = explode('.', $sRawMethod)); if (is_null($sMethod)) { $sMethod = $sNameSpace; $sNameSpace = 'wp'; } $oInterface = $this->getRPCInterface($sNameSpace); if (!$this->hasRPCMethod($oInterface, $sMethod)) { $this->oResponse->error = 'Invalid RPC request: method [' . var_export($sMethod, true) . '] does not exist'; } else { if (is_null($this->oRequest->params) || !is_array($this->oRequest->params)) { throw new ExceptionResponseError('Invalid RPC request: missing parameters'); } $oReflectedInterface = new \ReflectionObject($oInterface); if ($oReflectedInterface->hasMethod($sMethod)) { /* @var $oReflectedMethod \ReflectionMethod */ $oReflectedMethod = $oReflectedInterface->getMethod($sMethod); if ($oReflectedMethod->isPublic()) { return $oReflectedMethod->invokeArgs($oInterface, $this->oRequest->params); } } } return null; }
public static function inflater(array $objects, $invokeName, $invokeArgs = null) { if (!is_array($objects) || count($objects) == 0) { return null; } $ref = new \ReflectionObject($objects[0]); $mode = $ref->hasMethod($invokeName) ? self::MODE_METHOD : self::MODE_PROPERTY; if ($mode == self::MODE_METHOD) { $values = array(); $methodRef = $ref->getMethod($invokeName); $argsCount = count($methodRef->getParameters()); unset($methodRef); if ($argsCount > 0) { foreach ($objects as $object) { array_push($values, call_user_func_array(array($object, $invokeName), $invokeArgs)); } } else { foreach ($objects as $object) { array_push($values, $object->{$invokeName}()); } } return $values; } elseif ($mode == self::MODE_PROPERTY) { $values = array(); foreach ($objects as $object) { $value = $object->{$invokeName}; array_push($values, $value); } return $values; } else { throw new \InvalidArgumentException('not found invoker'); } }
public function __call($method, $args) { $ro = new \ReflectionObject($this->runtimeCollection); if ($ro->hasMethod($method)) { call_user_func_array([$this->runtimeCollection, $method], $args); } else { throw new \RuntimeException("Attempted to call a non-existent proxy method on runtime collection: {$method}"); } }
function __call($method, $args) { $this_reflection = new ReflectionObject($this); if (in_array($method, $this->resource_methods) && $this_reflection->hasMethod("resource_{$method}")) { return call_user_func_array(array($this, "resource_{$method}"), $args); } else { throw new ShopifyResourceException("Method {$method} is unsupported for " . get_class($this)); } }
/** * @param array $data * @param $object */ public function hydrate(array $data, $object) { $reflection = new \ReflectionObject($object); foreach ($data as $name => $value) { $methodName = $this->getMethodName($name, self::METHOD_SETTER); if ($reflection->hasMethod($methodName)) { $reflection->getMethod($methodName)->invoke($object, $value); } } }
protected function createObject(\FS\Components\Factory\ConfigurationInterface $configuration, $class) { $reflected = new \ReflectionObject($configuration); $targets = explode('\\', $class); $configurationMethod = 'get' . end($targets); if ($reflected->hasMethod($configurationMethod)) { return $configuration->{$configurationMethod}(); } return new $class(); }
/** * Loads definitions and translations from provided context. * * @param ContextInterface $context * @param StepNode $step * * @return DefinitionSnippet */ public function propose(ContextInterface $context, StepNode $step) { $contextRefl = new \ReflectionObject($context); $contextClass = $contextRefl->getName(); $replacePatterns = array("/(?<= |^)\\\\'(?:((?!\\').)*)\\\\'(?= |\$)/", '/(?<= |^)\\"(?:[^\\"]*)\\"(?= |$)/', '/(\\d+)/'); $text = $step->getText(); $text = preg_replace('/([\\/\\[\\]\\(\\)\\\\^\\$\\.\\|\\?\\*\\+\'])/', '\\\\$1', $text); $regex = preg_replace($replacePatterns, array("\\'([^\\']*)\\'", "\"([^\"]*)\"", "(\\d+)"), $text); preg_match('/' . $regex . '/', $step->getText(), $matches); $count = count($matches) - 1; $methodName = preg_replace($replacePatterns, '', $text); $methodName = Transliterator::transliterate($methodName, ' '); $methodName = preg_replace('/[^a-zA-Z\\_\\ ]/', '', $methodName); $methodName = str_replace(' ', '', ucwords($methodName)); if (0 !== strlen($methodName)) { $methodName[0] = strtolower($methodName[0]); } else { $methodName = 'stepDefinition1'; } // get method number from method name $methodNumber = 2; if (preg_match('/(\\d+)$/', $methodName, $matches)) { $methodNumber = intval($matches[1]); } // check that proposed method name isn't arelady defined in context while ($contextRefl->hasMethod($methodName)) { $methodName = preg_replace('/\\d+$/', '', $methodName); $methodName .= $methodNumber++; } // check that proposed method name haven't been proposed earlier if (isset(self::$proposedMethods[$contextClass])) { foreach (self::$proposedMethods[$contextClass] as $proposedRegex => $proposedMethod) { if ($proposedRegex !== $regex) { while ($proposedMethod === $methodName) { $methodName = preg_replace('/\\d+$/', '', $methodName); $methodName .= $methodNumber++; } } } } self::$proposedMethods[$contextClass][$regex] = $methodName; $args = array(); for ($i = 0; $i < $count; $i++) { $args[] = "\$arg" . ($i + 1); } foreach ($step->getArguments() as $argument) { if ($argument instanceof PyStringNode) { $args[] = "PyStringNode \$string"; } elseif ($argument instanceof TableNode) { $args[] = "TableNode \$table"; } } $description = $this->generateSnippet($regex, $methodName, $args); return new DefinitionSnippet($step, $description); }
/** * @param object $object * @param string $methodName * * @return \Donquixote\CallbackReflection\Callback\CallbackReflection_ObjectMethod */ static function create($object, $methodName) { if (!is_object($object)) { throw new \InvalidArgumentException("First parameter must be an object."); } $reflObject = new \ReflectionObject($object); if (!$reflObject->hasMethod($methodName)) { throw new \InvalidArgumentException("Object has no such method."); } $reflMethod = $reflObject->getMethod($methodName); return new self($object, $reflMethod); }
/** * Get the child controller object. * * Gets the new child controller object from the child controller class * method. If the method does not exist, or the returned value is not a * controller object, a \RuntimeException is thrown. * * @throws \RuntimeException * @param $controllerName * @return Controller */ public function getChildController($controllerName) { $methodName = $this->parseControllerName($controllerName); if (!$this->reflection->hasMethod($methodName)) { throw new \RuntimeException("{$this->reflection->getName()}::{$methodName} does not exist"); } $controller = $this->reflection->getMethod($methodName)->invokeArgs($this->controller, []); if (!is_object($controller) || !$controller instanceof Controller) { throw new \RuntimeException("{$this->reflection->getName()}::{$methodName} did not return a Controller"); } return $controller; }
/** * Injects $dependency into property $name of $target * * This is a convenience method for setting a protected or private property in * a test subject for the purpose of injecting a dependency. * * @param object $target The instance which needs the dependency * @param string $name Name of the property to be injected * @param mixed $dependency The dependency to inject – usually an object but can also be any other type * @return void * @throws \RuntimeException * @throws \InvalidArgumentException */ protected function inject($target, $name, $dependency) { if (!is_object($target)) { throw new \InvalidArgumentException('Wrong type for argument $target, must be object.'); } $objectReflection = new \ReflectionObject($target); $methodNamePart = strtoupper($name[0]) . substr($name, 1); if ($objectReflection->hasMethod('set' . $methodNamePart)) { $methodName = 'set' . $methodNamePart; $target->{$methodName}($dependency); } elseif ($objectReflection->hasMethod('inject' . $methodNamePart)) { $methodName = 'inject' . $methodNamePart; $target->{$methodName}($dependency); } elseif ($objectReflection->hasProperty($name)) { $property = $objectReflection->getProperty($name); $property->setAccessible(true); $property->setValue($target, $dependency); } else { throw new \RuntimeException('Could not inject ' . $name . ' into object of type ' . get_class($target)); } }
public function __call($method, array $args) { try { $ro = new ReflectionObject($this->smarty); if ($ro->hasMethod($method)) { $rm = $ro->getMethod($method); return $rm->invokeArgs($this->smarty, $args); } } catch (Exception $ex) { throw new Hayate_View_Exception($ex->getMessage()); } }
public function remap() { $ci =& get_instance(); $method = $ci->uri->rsegment(2); $parameters = array_slice($ci->uri->rsegment_array(), 2); $reflection = new ReflectionObject($ci); if ($reflection->hasMethod($method)) { $reflection->getMethod($method)->invokeArgs($ci, $parameters); } else { array_splice($parameters, 0, 0, $method); $reflection->getMethod("index")->invokeArgs($ci, $parameters); } }
/** * {@inheritdoc} */ protected function tryReadOption($name, &$out, $default = null) { $success = false; $name = $this->prefix . $name; $out = $default; if (!$this->classOrObj) { return false; } if (isset($this->cache[$name]) || array_key_exists($name, $this->cache)) { $out = $this->cache[$name]; $success = true; } elseif ($this->reflector->hasProperty($name)) { $out = $this->readFromProperty($name); $success = true; $this->cache[$name] = $out; } elseif ($this->reflector->hasMethod($name)) { $out = $this->readFromMethod($name); $success = true; $this->cache[$name] = $out; } return $success; }
/** * @param object $voter * @param string $method */ public function __construct($voter, $method) { // We use some duck typing here so voters won't depend on this library in any way if (!is_object($voter)) { throw new \InvalidArgumentException('$voter has to be an object.'); } $reflection = new \ReflectionObject($voter); if (!$reflection->hasMethod($method) || !$reflection->getMethod($method)->isPublic()) { throw new \InvalidArgumentException('$voter has to be an object which has a public method called ' . $method); } $this->voter = $voter; $this->method = $method; }
/** * Internal helper function for mass-assignment of values to a doctrie object * * If the function declares a method named set */ protected function assignValuesToInst($oi, array $values = [], $checkIfDeclared = true) { $reflection = new \ReflectionObject($oi); foreach ($values as $p => $v) { $setter = 'set' . ucfirst($p); if ($reflection->hasMethod($setter)) { $oi->{$setter}($v); } elseif ($reflection->hasProperty($p) || !$checkIfDeclared) { $oi->{$p} = $v; } else { throw new \yii\base\InvalidConfigException('Doctrine object of class ' . get_class($oi) . ' does not declare ' . $setter . ' or $' . $p); } } }
public function __construct(array $values) { $this->values = $values; $child = new \ReflectionObject($this); if (!$child->hasMethod("create")) { throw new \Exception("create method is required"); } $create = $child->getMethod("create"); if (!$create->isProtected()) { throw new \Exception("create method must be protected"); } $create->setAccessible(true); $create->invokeArgs($this, $values); }
/** * Search for public methods on an Object for display in template * @author Fabien Potencier * @author Hélio Costa e Silva <*****@*****.**> * @param stdObject $object * @param mixed $item * @param array $arguments * @param boolean $arrayOnly */ protected function getAttribute($object, $item, array $arguments = array(), $arrayOnly = false) { if (is_object($object)) { $arrAllowedPrefixes = array('get', 'has', 'is', 'match', 'contain'); $reflection = new ReflectionObject($object); foreach ($arrAllowedPrefixes as $prefix) { if (strpos($item, $prefix) !== 0) { /* if isn't at first position, try next */ continue; } if ($reflection->hasMethod($item)) { $reflectionMethod = new ReflectionMethod($object, $item); if ($reflectionMethod->isPublic()) { if ($reflectionMethod->getNumberOfParameters() > 0) { return $reflectionMethod->invokeArgs($object, $arguments); } else { return $object->{$item}(); } } else { return null; } } } } $item = (string) $item; if ((is_array($object) || is_object($object) && $object instanceof ArrayAccess) && isset($object[$item])) { return $object[$item]; } if ($arrayOnly) { return null; } if (is_object($object) && isset($object->{$item})) { if ($this->env->hasExtension('sandbox')) { $this->env->getExtension('sandbox')->checkPropertyAllowed($object, $item); } return $object->{$item}; } /* @todo helio.costa __get __isset * __get() __isset() support. Still here for a while */ if (!is_object($object) || !method_exists($object, $method = $item) && !method_exists($object, $method = 'get' . $item)) { return null; } if ($this->env->hasExtension('sandbox')) { $this->env->getExtension('sandbox')->checkMethodAllowed($object, $method); } $reflection = new ReflectionObject($object); if ($reflection->hasMethod('__get')) { return call_user_func_array(array($object, $method), $arguments); } }
public function configure($oldObj, $newObject) { $ref = new \ReflectionObject($newObject); if (!$ref->hasMethod('setDelegateCallQueue')) { return $newObject; } $delegateQueue = $this->r['delegateCallQueue']; foreach ($this->propertyBuffer as $prop) { $delegateQueue->addProperty($prop); } $this->propertyBuffer = array(); $newObject->setDelegateCallQueue($delegateQueue); $newObject->setAnnotatedObject($oldObj); return $newObject; }
public function register_task($key, $obj) { if (array_key_exists($key, $this->tasks)) { trigger_error(sprintf("Task key '%s' is already defined!", $key)); return false; } //Reflect on the object and make sure it has an "execute()" method $refl = new ReflectionObject($obj); if (!$refl->hasMethod('execute')) { trigger_error(sprintf("Task '%s' does not have an 'execute' method defined", $key)); return false; } $this->tasks[$key] = $obj; return true; }
function handle(Trace $trace) { $this->trace = $trace; $action = isset($trace[self::PARAMETER_ACTION]) ? $trace[self::PARAMETER_ACTION] : null; $actionMethod = $this->getMethodName($action); $reflectedController = new ReflectionObject($this); if ($action && $reflectedController->hasMethod($actionMethod)) { $this->action = $action; $result = $this->processAction($action, $reflectedController->getMethod($actionMethod)); } else { $result = $this->handleUnknownAction($action); } $result = $this->makeActionResult($result); $this->processResult($result); $this->trace = null; }
function handle(RouteData $routeData, WebRequest $request) { $this->routeData = $routeData; $this->request = $request; $action = isset($this->routeData[self::ROUTE_DATA_ACTION]) ? $this->routeData[self::ROUTE_DATA_ACTION] : null; $actionMethod = $this->getMethodName($action); $reflectedController = new ReflectionObject($this); if ($action && $reflectedController->hasMethod($actionMethod)) { $result = $this->processAction($action, $reflectedController->getMethod($actionMethod)); } else { $result = $this->handleUnknownAction($action); } $result = $this->makeActionResult($result); if ($result) { $this->processResult($result); } }
/** * @param $object * @param string $injectMethodName Method which will be invoked with resolved dependencies as its arguments * @throws InjectionException */ public function injectDependencies($object, $injectMethodName = self::DEFAULT_INJECT_METHOD_NAME, $defaults = []) { if (!is_object($object)) { return; } $reflectedObject = new \ReflectionObject($object); if (!$reflectedObject->hasMethod($injectMethodName)) { return; } $reflectedMethod = $reflectedObject->getMethod($injectMethodName); try { $args = $this->prepareArgs($reflectedMethod, $defaults); } catch (\Exception $e) { throw new InjectionException("Failed to inject dependencies in instance of '{$reflectedObject->name}'. " . $e->getMessage()); } if (!$reflectedMethod->isPublic()) { $reflectedMethod->setAccessible(true); } $reflectedMethod->invokeArgs($object, $args); }
/** * Constructor for invoking a reflection object * Initiates the object as a service * @param class $object * @access private * @return class instance */ private function runAsService($object) { if (!isset($_GET['class'])) { throw new Exception('Method name not specified.'); } $reflObject = new ReflectionObject($object); if (!$reflObject->hasMethod($_GET['class'])) { throw new Exception('There is no method with this name.'); } $reflMethod = $reflObject->getMethod($_GET['class']); if (!$reflMethod->isPublic() || $reflMethod->isStatic() || $reflMethod->isInternal()) { throw new Exception('Invalid method name specified.'); } $reflParameters = $reflMethod->getParameters(); $args = array(); foreach ($reflParameters as $param) { $paramName = $param->getName(); if (!isset($_GET[$paramName])) { if ($param->isDefaultValueAvailable()) { $paramValue = $param->getDefaultValue(); } else { throw new Exception('Required parameter "' . $paramName . '" is not specified.'); } } else { $paramValue = $_GET[$paramName]; } if ($param->getClass()) { throw new Exception('The method contains unsupported parameter type: class object.'); } if ($param->isArray() && !is_array($paramValue)) { throw new Exception('Array expected for parameter "' . $paramName . '", but scalar found.'); } $args[$param->getPosition()] = $paramValue; } return $reflMethod->invokeArgs($object, $args); }
/** * @param mixed $data * @return string * @since Method available since Release 3.2.1 */ protected function dataToString($data) { $result = array(); foreach ($data as $_data) { if (is_array($_data)) { $result[] = 'array(' . $this->dataToString($_data) . ')'; } else { if (is_object($_data)) { $object = new ReflectionObject($_data); if ($object->hasMethod('__toString')) { $result[] = (string) $_data; } else { $result[] = get_class($_data); } } else { if (is_resource($_data)) { $result[] = '<resource>'; } else { $result[] = var_export($_data, TRUE); } } } } return join(', ', $result); }
public function get_admin_database_selection_html_table($order_by, $direction, $offset, $limit, $url = NULL, $sortable_fields_str = NULL, $caption = NULL, $actions_method_name = NULL, $actions_methods_args = NULL) { if (!isset($url)) { $url = $this->get_admin_page_url(); } $table = $this->get_element(); $field_objs = array(); if (isset($sortable_fields_str)) { foreach (explode(' ', $sortable_fields_str) as $field_str) { $field_objs[] = $table->get_field($field_str); } } else { $field_objs = $table->get_fields(); } $fields = array(); foreach ($field_objs as $field_obj) { $field['sortable'] = TRUE; $field['name'] = $field_obj->get_name(); $field['method'] = 'get_data_html_table_td'; $method_args = array(); $method_args[] = $field_obj; $field['method_args'] = $method_args; $fields[] = $field; } if (isset($actions_method_name)) { $renderer_reflection_object = new ReflectionObject($this); if ($renderer_reflection_object->hasMethod($actions_method_name)) { $actions_reflection_method = $renderer_reflection_object->getMethod($actions_method_name); if (isset($actions_methods_args)) { $actions = $actions_reflection_method->invokeArgs($this, $actions_methods_args); } else { $actions = $actions_reflection_method->invoke($this); } } else { throw new Exception(sprintf('No method called "%s" in class "%s"!', $actions_method_name, $renderer_reflection_object->getName())); } } else { $actions = array(); $edit_action['th'] = new HTMLTags_TH('Edit'); $edit_action['method'] = 'get_admin_database_tr_action_edit_td'; $actions[] = $edit_action; $delete_action['th'] = new HTMLTags_TH('Delete'); $delete_action['method'] = 'get_admin_database_tr_action_delete_td'; $actions[] = $delete_action; } #print_r($actions); if (!isset($caption)) { $caption = 'Data in the ' . $table->get_name() . ' table'; } return new Database_SelectionHTMLDiv($url, $table, $order_by, $direction, $offset, $limit, $limit_str = '10 20 50', $caption, 'table_pages_div', 'table_pages', $fields, $actions); }