public function setForm(Form &$form, array $request) { $errors = array(); $form->befor_set(); $reflex = new ReflectionObject($form); $propts = $reflex->getParentClass()->getProperties(); foreach ($propts as $propt) { $name = $propt->getName(); $exis = method_exists($form, self::VALIDATE . $name); $value = isset($request[$name]) ? $request[$name] : null; $valid = self::VALIDATE . $name; $setvl = self::SET_METHOD . ucfirst($name); $respn = $exis ? $form->{$valid}($value) : true; if ($respn === true) { if (method_exists($form, $setvl)) { if ($value != null) { $form->{$setvl}($value); } } else { if ($value != null) { $propt->setAccessible(true); $propt->setValue($form, $value); $propt->setAccessible(false); } } } else { $errors[$name] = $respn; } } $form->after_set(); return count($errors) > 0 ? $errors : true; }
protected function getPropertyValue($object, $property) { $refl = new \ReflectionObject($object); $repoProp = $refl->getProperty($property); $repoProp->setAccessible(true); return $repoProp->getValue($object); }
public function invokeMethod($object, $methodName, array $args = array()) { $refObject = new \ReflectionObject($object); $method = $refObject->getMethod($methodName); $method->setAccessible(true); return $method->invokeArgs($object, $args); }
/** * @param object $object * @param string $propertyName * @param mixed $propertyValue */ public function setProtectedProperty($object, $propertyName, $propertyValue) { $class = new \ReflectionObject($object); $property = $class->getProperty($propertyName); $property->setAccessible(true); $property->setValue($object, $propertyValue); }
/** * Guesses the template name to render and its variables and adds them to * the request object. * * @param FilterControllerEvent $event A FilterControllerEvent instance */ public function onKernelController(FilterControllerEvent $event) { if (!is_array($controller = $event->getController())) { return; } $request = $event->getRequest(); if (!($configuration = $request->attributes->get('_template'))) { return; } if (!$configuration->getTemplate()) { $guesser = $this->container->get('sensio_framework_extra.view.guesser'); $configuration->setTemplate($guesser->guessTemplateName($controller, $request, $configuration->getEngine())); } $request->attributes->set('_template', $configuration->getTemplate()); $request->attributes->set('_template_vars', $configuration->getVars()); $request->attributes->set('_template_streamable', $configuration->isStreamable()); // all controller method arguments if (!$configuration->getVars()) { $r = new \ReflectionObject($controller[0]); $vars = array(); foreach ($r->getMethod($controller[1])->getParameters() as $param) { $vars[] = $param->getName(); } $request->attributes->set('_template_default_vars', $vars); } }
/** * Runs the test case. * @return void */ public function run($method = NULL) { $r = new \ReflectionObject($this); $methods = array_values(preg_grep(self::METHOD_PATTERN, array_map(function (\ReflectionMethod $rm) { return $rm->getName(); }, $r->getMethods()))); if (substr($method, 0, 2) === '--') { // back compatibility $method = NULL; } if ($method === NULL && isset($_SERVER['argv']) && ($tmp = preg_filter('#(--method=)?([\\w-]+)$#Ai', '$2', $_SERVER['argv']))) { $method = reset($tmp); if ($method === self::LIST_METHODS) { Environment::$checkAssertions = FALSE; header('Content-Type: text/plain'); echo '[' . implode(',', $methods) . ']'; return; } } if ($method === NULL) { foreach ($methods as $method) { $this->runMethod($method); } } elseif (in_array($method, $methods, TRUE)) { $this->runMethod($method); } else { throw new TestCaseException("Method '{$method}' does not exist or it is not a testing method."); } }
/** * {@inheritdoc} */ public function isValid(ProxyInterface $proxy) : bool { $asserted = true; $reflectionObject = new \ReflectionObject($proxy); //Browse properties assertion foreach ($this->propertiesAssertions as $property => $exceptedValue) { if (null !== $exceptedValue && \property_exists($proxy, $property)) { //If the property exists, get it's value via the Reflection api (properties are often not accessible for public) $reflectionProperty = $reflectionObject->getProperty($property); $reflectionProperty->setAccessible(true); $propertyValue = $reflectionProperty->getValue($proxy); if (!\is_callable($exceptedValue)) { //Not a callable, perform a equal test $asserted &= $exceptedValue == $propertyValue; } else { $asserted &= $exceptedValue($propertyValue); } } else { //If the property does not existn the assertion fail $asserted = false; } if (!$asserted) { //Stop at first fail break; } } return $asserted; }
public static function execute($commande, $params) { session_start(); $endpoint=new static(); $commande = "API_".$commande; $endpointReflx = new ReflectionObject($endpoint); $methodReflx = $endpointReflx->getMethod($commande); try{ $result =$methodReflx->invokeArgs($endpoint, $params); $result = [ 'status'=>'success', 'value'=>$result ]; } catch(ErrorException $ex) { $result = [ 'status'=>'error', 'value'=>$ex->getMessage() ]; } session_commit(); return $result; }
/** * @param $object * @param $propertyName * @param $value */ protected function setProtectedValue(&$object, $propertyName, $value) { $reflectionObject = new \ReflectionObject($object); $property = $reflectionObject->getProperty($propertyName); $property->setAccessible(true); $property->setValue($object, $value); }
* Marked only as protected to allow extension of the class. To extend, * simply override {@link getInstance()}. * * @var Zend_Controller_Front */ protected static $_instance = null; /** * Array of invocation parameters to use when instantiating action * controllers * @var array */ protected $_invokeParams = array(); /** * Subdirectory within a module containing controllers; defaults to 'controllers' * @var string */ protected $_moduleControllerDirectoryName = 'controllers'; /** * Instance of Zend_Controller_Plugin_Broker * @var Zend_Controller_Plugin_Broker */ protected $_plugins = null; /** * Instance of Zend_Controller_Request_Abstract * @var Zend_Controller_Request_Abstract */ protected $_request = null; /** * Instance of Zend_Controller_Response_Abstract * @var Zend_Controller_Response_Abstract
public function testFilterResponseConvertsCookies() { $client = new Client(new TestHttpKernel()); $r = new \ReflectionObject($client); $m = $r->getMethod('filterResponse'); $m->setAccessible(true); $expected = array( 'foo=bar; expires=Sun, 15 Feb 2009 20:00:00 GMT; domain=http://example.com; path=/foo; secure; httponly', 'foo1=bar1; expires=Sun, 15 Feb 2009 20:00:00 GMT; domain=http://example.com; path=/foo; secure; httponly' ); $response = new Response(); $response->headers->setCookie(new Cookie('foo', 'bar', \DateTime::createFromFormat('j-M-Y H:i:s T', '15-Feb-2009 20:00:00 GMT')->format('U'), '/foo', 'http://example.com', true, true)); $domResponse = $m->invoke($client, $response); $this->assertEquals($expected[0], $domResponse->getHeader('Set-Cookie')); $response = new Response(); $response->headers->setCookie(new Cookie('foo', 'bar', \DateTime::createFromFormat('j-M-Y H:i:s T', '15-Feb-2009 20:00:00 GMT')->format('U'), '/foo', 'http://example.com', true, true)); $response->headers->setCookie(new Cookie('foo1', 'bar1', \DateTime::createFromFormat('j-M-Y H:i:s T', '15-Feb-2009 20:00:00 GMT')->format('U'), '/foo', 'http://example.com', true, true)); $domResponse = $m->invoke($client, $response); $this->assertEquals($expected[0], $domResponse->getHeader('Set-Cookie')); $this->assertEquals($expected, $domResponse->getHeader('Set-Cookie', false)); }
public function testCommitNeedNotification() { $notifier = $this->getMock('Sismo\\Contrib\\CrossFingerNotifier'); $r = new \ReflectionObject($notifier); $m = $r->getMethod('commitNeedNotification'); $m->setAccessible(true); $project = new Project('Twig'); $commit = new Commit($project, '123456'); $commit->setAuthor('Fabien'); $commit->setMessage('Foo'); $commit2 = new Commit($project, '123455'); $commit2->setAuthor('Fabien'); $commit2->setMessage('Bar'); $commit2->setStatusCode('success'); $commit3 = clone $commit2; //a failed commit should be notified $this->assertTrue($m->invoke($notifier, $commit)); //a successful commit without predecessor should be notified $this->assertTrue($m->invoke($notifier, $commit2)); $project->setCommits(array($commit3)); //a successful commit with a successful predecessor should NOT be notified $this->assertFalse($m->invoke($notifier, $commit2)); $project->setCommits(array($commit2, $commit3)); //a failed commit with a successful predecessor should be notified $this->assertTrue($m->invoke($notifier, $commit)); }
/** * Test Clone */ public function testProtectedMethods() { $result = ConcreteSingleton::getInstance(); $reflection = new \ReflectionObject($result); $this->assertTrue($reflection->getMethod('__construct')->isProtected()); $this->assertTrue($reflection->getMethod('__clone')->isProtected()); }
public function reflect($object) { $reflection = new \ReflectionObject($object); $properties = $reflection->getProperties(); $fields = []; foreach ($properties as $property) { $name = $property->getName(); if ($name == 'bot_name') { continue; } if (!$property->isPrivate()) { if (is_object($object->{$name})) { $fields[$name] = $this->reflect($object->{$name}); } else { $property->setAccessible(true); $value = $property->getValue($object); if (is_null($value)) { continue; } $fields[$name] = $value; } } } return $fields; }
private function readRoutes($object) { $reflObj = new \ReflectionObject($object); $reflProp = $reflObj->getProperty('routes'); $reflProp->setAccessible(true); return $reflProp->getValue($object); }
/** * Test build path. */ public function testBuildPath() { $reflection_object = new \ReflectionObject($this->client); $reflection_method = $reflection_object->getMethod('buildPath'); $reflection_method->setAccessible(TRUE); $this->assertEquals($reflection_method->invoke($this->client), 'HNK2IC/F_jM8Zls30dL/guid/-/2849493'); }
/** * Defines all required functions and constants * * @see _define() * @return void */ public function checkAPI() { // The constants are defined. $this->_define('T_NAMESPACE'); $this->_define('T_NS_SEPARATOR'); $this->_define('E_USER_DEPRECATED', E_USER_WARNING); /* * Every static public method with an @implement annotation defines * a function. */ $reflectionObject = new ReflectionObject($this); $methods = $reflectionObject->getMethods(ReflectionMethod::IS_STATIC | ReflectionMethod::IS_PUBLIC); foreach ($methods as $method) { // The method comment is parsed for the @implement annotation $isAnnotated = preg_match('/\\s*\\*\\s*@implement\\s+(\\S+)/', $method->getDocComment(), $matches); if (!$isAnnotated) { continue; } $function = $matches[1]; // A function might already exist. if (function_exists($function)) { continue; } // The parameters are build. $parametersArray = array(); for ($i = 0; $i < $method->getNumberOfParameters(); $i++) { $parametersArray[] = '$parameter' . $i; } $parameters = implode(', ', $parametersArray); // The function is defined. $apiClass = get_class($this); $definition = "function {$function}({$parameters})\n {\n \$parameters = func_get_args();\n return call_user_func_array(\n array('{$apiClass}', '{$method->getName()}'),\n \$parameters\n );\n }\n "; eval($definition); } }
public function testNoConstructor() { $obj = Singleton::getInstance(); $refl = new \ReflectionObject($obj); $meth = $refl->getMethod('__construct'); $this->assertTrue($meth->isPrivate()); }
protected function getRepoProperty($container) { $refl = new \ReflectionObject($container); $repoProp = $refl->getProperty('items'); $repoProp->setAccessible(true); return $repoProp->getValue($container); }
static function get_eids($search_term, $prop_id, $type_id, $search_compare_op = 0) { $prop_name = Property::static_get_table_name($prop_id); $vptepte_class_name = "view_" . $prop_name . "_to_e_p_to_e"; // include_once (dirname(__FILE__) .'/../PropertyTypeEntity/'.$vptepte_class_name.'.php'); $theclass = new $vptepte_class_name(); $reflObject = new ReflectionObject($theclass); $reflMethod = $reflObject->getMethod("get_eids"); $reflParameters = $reflMethod->getParameters(); $args = array(); foreach ($reflParameters as $param) { //$paramName = $param->getName(); //$args[$param->getPosition()] = $paramName; $args[$param->getPosition()] = func_get_arg($param->getPosition()); //this way view_int_prop... will be passed the fourth argument. //Note: assumes get_eids signature matches order between here and the vptepte's } $eids = array(); if (!$type_id) { $type_hash = MixedQueries::get_type_list(); foreach ($type_hash as $_type_id => $type_name) { //$eids = array_merge($eids, $theclass->get_eids($search_term, $prop_id, $_type_id)); $args[2] = $_type_id; $eids = array_merge($eids, $reflMethod->invokeArgs($theclass, $args)); } } else { //$eids = $theclass->get_eids($search_term, $prop_id, $type_id); $eids = $reflMethod->invokeArgs($theclass, $args); } return $eids; }
/** * @param AdminInterface $admin * * @return mixed * @throws \RuntimeException */ public function load(AdminInterface $admin) { $filename = $this->cacheFolder . '/route_' . md5($admin->getCode()); $cache = new ConfigCache($filename, $this->debug); if (!$cache->isFresh()) { $resources = array(); $routes = array(); $reflection = new \ReflectionObject($admin); $resources[] = new FileResource($reflection->getFileName()); if (!$admin->getRoutes()) { throw new \RuntimeException('Invalid data type, Admin::getRoutes must return a RouteCollection'); } foreach ($admin->getRoutes()->getElements() as $code => $route) { $routes[$code] = $route->getDefault('_sonata_name'); } if (!is_array($admin->getExtensions())) { throw new \RuntimeException('extensions must be an array'); } foreach ($admin->getExtensions() as $extension) { $reflection = new \ReflectionObject($extension); $resources[] = new FileResource($reflection->getFileName()); } $cache->write(serialize($routes), $resources); } return unserialize(file_get_contents($filename)); }
public function execute($registry, $args = array()) { // Stop any magical methods being called if (substr($this->method, 0, 2) == '__') { return false; } // Initialize the class if (is_file($this->file)) { include_once $this->file; $controller = new $this->class($registry); } else { return false; } //print_r($args); // Now we have the controller we want to check if the corrasponding number of arguments matches the method being called. $reflection = new ReflectionObject($controller); $parameters = $reflection->getMethod($this->method)->getParameters(); foreach ($perameters as $perameter) { echo $perameter->name . "\n"; } if (count($perameters) != count($args)) { } print_r($perameters); // Call the method if set if (method_exists($controller, $this->method)) { return call_user_func_array(array($controller, $this->method), $args); } else { return false; } }
public function capture() { $shim = $this->getShim(); $event_manager = $shim->getApp(); if ($shim->isMage2()) { $shim->getObjectManager()->get('Magento\\Logger')->log('Work in ' . __FILE__); $shim->getObjectManager()->get('Magento\\Event\\Manager')->collectAllMage2(); return; } $r = new ReflectionObject($event_manager); $rp = $r->getProperty('_events'); if (method_exists($rp, 'setAccessible')) { $rp->setAccessible(true); $events = $rp->getValue($event_manager); } else { $events = $this->_phpFivePointTwoReflection($event_manager); } $collector = new Pzdgmailcom_Commercebug_Model_Collectorevents(); foreach ($events as $area => $event) { foreach ($event as $event_name => $configuration) { $o = new stdClass(); $o->area = $area; $o->event = $event_name; $o->data = array(); $collector->collectInformation($o); $collector->collectObservers($event_name, $configuration); } } }
protected function callProtectedMethod($object, $method, array $args = array()) { $reflectedObject = new \ReflectionObject($object); $reflectedMethod = $reflectedObject->getMethod($method); $reflectedMethod->setAccessible(true); return $reflectedMethod->invokeArgs($object, $args); }
private function actionCall($service, $actionName) { $refObject = new ReflectionObject($service); $refMethod = $refObject->getMethod($actionName); $values = $this->parameterValues($refMethod); return $refMethod->invokeArgs($service, $values); }
/** * Retrieves the base path from the CldrRepository's cldrBasePath attribute * @return string */ protected function retrieveCldrBasePath() { $reflectedCldrRepository = new \ReflectionObject($this->cldrRepository); $reflectedBasePathProperty = $reflectedCldrRepository->getProperty('cldrBasePath'); $reflectedBasePathProperty->setAccessible(true); return $reflectedBasePathProperty->getValue($this->cldrRepository); }
public function testLoadFile() { $loader = new YamlFileLoader(new ContainerBuilder(), new FileLocator(self::$fixturesPath . '/ini')); $r = new \ReflectionObject($loader); $m = $r->getMethod('loadFile'); $m->setAccessible(true); try { $m->invoke($loader, 'foo.yml'); $this->fail('->load() throws an InvalidArgumentException if the loaded file does not exist'); } catch (\Exception $e) { $this->assertInstanceOf('\\InvalidArgumentException', $e, '->load() throws an InvalidArgumentException if the loaded file does not exist'); $this->assertEquals('The service file "foo.yml" is not valid.', $e->getMessage(), '->load() throws an InvalidArgumentException if the loaded file does not exist'); } try { $m->invoke($loader, 'parameters.ini'); $this->fail('->load() throws an InvalidArgumentException if the loaded file is not a valid YAML file'); } catch (\Exception $e) { $this->assertInstanceOf('\\InvalidArgumentException', $e, '->load() throws an InvalidArgumentException if the loaded file is not a valid YAML file'); $this->assertEquals('The service file "parameters.ini" is not valid.', $e->getMessage(), '->load() throws an InvalidArgumentException if the loaded file is not a valid YAML file'); } $loader = new YamlFileLoader(new ContainerBuilder(), new FileLocator(self::$fixturesPath . '/yaml')); foreach (array('nonvalid1', 'nonvalid2') as $fixture) { try { $m->invoke($loader, $fixture . '.yml'); $this->fail('->load() throws an InvalidArgumentException if the loaded file does not validate'); } catch (\Exception $e) { $this->assertInstanceOf('\\InvalidArgumentException', $e, '->load() throws an InvalidArgumentException if the loaded file does not validate'); $this->assertStringMatchesFormat('The service file "nonvalid%d.yml" is not valid.', $e->getMessage(), '->load() throws an InvalidArgumentException if the loaded file does not validate'); } } }
/** * 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); } } } }
public function testParseFile() { $loader = new XmlFileLoader(new ContainerBuilder(), new FileLocator(self::$fixturesPath . '/ini')); $r = new \ReflectionObject($loader); $m = $r->getMethod('parseFileToDOM'); $m->setAccessible(true); try { $m->invoke($loader, self::$fixturesPath . '/ini/parameters.ini'); $this->fail('->parseFileToDOM() throws an InvalidArgumentException if the loaded file is not a valid XML file'); } catch (\Exception $e) { $this->assertInstanceOf('Symfony\\Component\\DependencyInjection\\Exception\\InvalidArgumentException', $e, '->parseFileToDOM() throws an InvalidArgumentException if the loaded file is not a valid XML file'); $this->assertRegExp(sprintf('#^Unable to parse file ".+%s".$#', 'parameters.ini'), $e->getMessage(), '->parseFileToDOM() throws an InvalidArgumentException if the loaded file is not a valid XML file'); $e = $e->getPrevious(); $this->assertInstanceOf('InvalidArgumentException', $e, '->parseFileToDOM() throws an InvalidArgumentException if the loaded file is not a valid XML file'); $this->assertStringStartsWith('[ERROR 4] Start tag expected, \'<\' not found (in', $e->getMessage(), '->parseFileToDOM() throws an InvalidArgumentException if the loaded file is not a valid XML file'); } $loader = new XmlFileLoader(new ContainerBuilder(), new FileLocator(self::$fixturesPath . '/xml')); try { $m->invoke($loader, self::$fixturesPath . '/xml/nonvalid.xml'); $this->fail('->parseFileToDOM() throws an InvalidArgumentException if the loaded file does not validate the XSD'); } catch (\Exception $e) { $this->assertInstanceOf('Symfony\\Component\\DependencyInjection\\Exception\\InvalidArgumentException', $e, '->parseFileToDOM() throws an InvalidArgumentException if the loaded file does not validate the XSD'); $this->assertRegExp(sprintf('#^Unable to parse file ".+%s".$#', 'nonvalid.xml'), $e->getMessage(), '->parseFileToDOM() throws an InvalidArgumentException if the loaded file is not a valid XML file'); $e = $e->getPrevious(); $this->assertInstanceOf('InvalidArgumentException', $e, '->parseFileToDOM() throws an InvalidArgumentException if the loaded file does not validate the XSD'); $this->assertStringStartsWith('[ERROR 1845] Element \'nonvalid\': No matching global declaration available for the validation root. (in', $e->getMessage(), '->parseFileToDOM() throws an InvalidArgumentException if the loaded file does not validate the XSD'); } $xml = $m->invoke($loader, self::$fixturesPath . '/xml/services1.xml'); $this->assertInstanceOf('DOMDocument', $xml, '->parseFileToDOM() returns an SimpleXMLElement object'); }
public function start($keyName, $lifetime = null) { static $reflector; if (!$this->_backend->getFrontend() instanceof Output) { return null; } if (!$reflector) { $reflector = new \ReflectionObject($this->_backend); } $existingCache = $this->get($keyName, $lifetime); if ($existingCache === null) { $fresh = true; $this->_backend->getFrontend()->start(); } else { $fresh = false; } $_fresh = $reflector->getProperty('_fresh'); $_fresh->setAccessible(true); $_fresh->setValue($this->_backend, $fresh); $_started = $reflector->getProperty('_started'); $_started->setAccessible(true); $_started->setValue($this->_backend, true); /** * Update the last lifetime to be used in save() */ if ($lifetime !== null) { $_lastLifetime = $reflector->getProperty('_lastLifetime'); $_lastLifetime->setAccessible(true); $_lastLifetime->setValue($this->_backend, $lifetime); } return $existingCache; }