Example #1
0
 /**
  * Create a parameter node.
  *
  * @param string $parameter_name
  *   Parameter name, eg. $parm
  * @return ParameterNode
  */
 public static function create($parameter_name)
 {
     $parameter_name = '$' . ltrim($parameter_name, '$');
     $parameter_node = new ParameterNode();
     $parameter_node->addChild(new VariableNode(T_VARIABLE, $parameter_name), 'name');
     return $parameter_node;
 }
 public function testGetValueNoArgument()
 {
     $this->parameter->setValue(StringNode::fromValue('har'));
     $path = new PathUtility('foo/%node');
     $binding = new ParameterBinding($path, $this->parameter);
     $this->assertEquals('har', $binding->getValue());
 }
 /**
  * {@inheritdoc}
  */
 public function convert(TargetInterface $target)
 {
     $this->writeService($target, 'boot_subscriber', ['class' => 'Drupal\\' . $target->id() . '\\EventSubscriber\\BootSubscriber', 'tags' => [['name' => 'event_subscriber']]]);
     $render = ['#theme' => 'dmu_event_subscriber', '#module' => $target->id(), '#class' => 'BootSubscriber', '#event' => 'KernelEvents::REQUEST'];
     $subscriber = $this->parse($render);
     $target->getIndexer('function')->get('hook_boot')->cloneAsMethodOf($subscriber)->setName('onEvent')->appendParameter(ParameterNode::create('event')->setTypeHint('\\Symfony\\Component\\HttpKernel\\Event\\GetResponseEvent'));
     $this->writeClass($target, $subscriber);
 }
 /**
  * @depends testHasParameter
  */
 public function testAppendParameter()
 {
     /** @var \Pharborist\Functions\FunctionDeclarationNode $function */
     $function = Parser::parseSnippet('function baz() {}');
     $function->appendParameter(ParameterNode::create('$neo'));
     $this->assertTrue($function->hasParameter('neo'));
     $function->appendParameter(function (FunctionDeclarationNode $function) {
         return ParameterNode::create('$trinity');
     });
     $this->assertTrue($function->hasParameter('trinity'));
 }
 /**
  * Create a function declaration.
  *
  * @param NameNode|string $function_name
  *   The function name.
  * @param array $parameters
  *   (Optional) List of parameters.
  *
  * @return FunctionDeclarationNode
  */
 public static function create($function_name, $parameters = NULL)
 {
     /** @var FunctionDeclarationNode $function */
     $function = Parser::parseSnippet("function {$function_name}() {}");
     if (is_array($parameters)) {
         foreach ($parameters as $parameter) {
             if (is_string($parameter)) {
                 $parameter = ParameterNode::create($parameter);
             }
             $function->appendParameter($parameter);
         }
     }
     return $function;
 }
 public function convert(TargetInterface $target)
 {
     $indexer = $target->getIndexer('function');
     $hooks = array_filter($this->pluginDefinition['hook'], [$indexer, 'has']);
     foreach ($hooks as $hook) {
         /** @var \Pharborist\Functions\FunctionDeclarationNode $function */
         $function = $indexer->get($hook);
         $function->prependParameter(ParameterNode::create('build')->setTypeHint('array')->setReference(TRUE));
         // Extract the entity type from the hook name (e.g. 'hook_node_view').
         preg_match('/^hook_(.+)_view$/', $hook, $matches);
         $entity_type = $matches[1];
         $rewriter = $this->rewriters->createInstance('_rewriter:' . $entity_type);
         $this->rewriteFunction($rewriter, $function->getParameterAtIndex(1), $target);
     }
 }
 /**
  * {@inheritdoc}
  */
 public function convert(TargetInterface $target)
 {
     /** @var \Pharborist\Functions\FunctionDeclarationNode $function */
     $function = $target->getIndexer('function')->get('hook_node_prepare');
     // foo_node_prepare() --> foo_node_prepare_form().
     $function->setName($function->getName() . '_form');
     // The first parameter is a node, so rewrite the function accordingly.
     $this->rewriters->createInstance('_entity:node')->rewrite($function->getParameterAtIndex(0));
     // Create the $operation parameter.
     $function->appendParameter(ParameterNode::create('operation'));
     // Create the $form_state parameter.
     $form_state = ParameterNode::create('form_state')->setTypeHint('\\Drupal\\Core\\Form\\FormStateInterface');
     $function->appendParameter($form_state);
     $target->save($function);
 }
 /**
  * {@inheritdoc}
  */
 public function convert(TargetInterface $target)
 {
     $target->getIndexer('function')->get($this->pluginDefinition['hook'])->setDocComment($this->buildFixMe(NULL, [], self::DOC_COMMENT));
     $render = ['#theme' => 'dmu_route_subscriber', '#module' => $target->id()];
     $this->writeClass($target, $this->parse($render));
     $alterable = ParameterNode::create('data');
     $alterable->setTypeHint('array')->setReference(TRUE);
     $parameter = clone $alterable;
     $this->implement($target, 'menu_links_discovered_alter')->appendParameter($parameter->setName('links'));
     $parameter = clone $alterable;
     $this->implement($target, 'menu_local_tasks_alter')->appendParameter($parameter->setName('data'))->appendParameter(ParameterNode::create('route_name'));
     $parameter = clone $alterable;
     $this->implement($target, 'menu_local_actions_alter')->appendParameter($parameter->setName('local_actions'));
     $parameter = clone $alterable;
     $items = clone $alterable;
     $function = $this->implement($target, 'contextual_links_view_alter')->appendParameter($parameter->setName('element'))->appendParameter($items->setName('items')->setReference(FALSE));
     $target->save($function);
 }
 /**
  * @return \Pharborist\Objects\ClassMethodNode
  */
 protected function addMethod(FunctionDeclarationNode $function, ClassNode $class, $alias = NULL)
 {
     $method = ClassMethodNode::fromFunction($function);
     if ($alias) {
         $method->setName($alias);
     }
     $class->appendMethod($method);
     // Add the parameters required for FormInterface conformance.
     $parameters = $method->getParameters()->toArray();
     if (empty($parameters)) {
         $parameters[0] = ParameterNode::create('$form');
         $method->appendParameter($parameters[0]);
     }
     if (sizeof($parameters) == 1) {
         $parameters[1] = ParameterNode::create('$form_state');
         $method->appendParameter($parameters[1]);
     }
     // The $form parameter must have the array type hint.
     $parameters[0]->setTypeHint('array');
     // The form state is never passed by reference.
     $parameters[1]->setReference(FALSE);
     // Additional parameters MUST have a default value of NULL in order to conform
     // to FormInterface.
     for ($i = 2; $i < sizeof($parameters); $i++) {
         $parameters[$i]->setValue(new TokenNode(T_STRING, 'NULL'));
     }
     $this->formStateRewriter->rewrite($parameters[1]);
     return $method;
 }
 /**
  * A helper function to ease exception catching in the __toString() method.
  *
  * @return string
  */
 protected function toString()
 {
     $doc = RootNode::create($this->getNamespace());
     $class = ClassNode::create($this->getName());
     $constructor = ClassMethodNode::create('__construct');
     $class->appendMethod($constructor);
     $constructorDocString = '';
     foreach ($this->getProperties() as $name => $info) {
         $class->createProperty($name, isset($info['default']) ? $info['default'] : NULL, 'protected');
         if (isset($info['description'])) {
             $propertyDocString = "@var {$info['type']} {$name}\n  {$info['description']}";
             $constructorDocString .= "@param {$info['type']} {$name}\n  {$info['description']}\n\n";
         } else {
             $propertyDocString = "@var {$info['type']} {$name}";
             $constructorDocString .= "@param {$info['type']} {$name}\n\n";
         }
         $class->getProperty($name)->closest(Filter::isInstanceOf('\\Pharborist\\Objects\\ClassMemberListNode'))->setDocComment(DocCommentNode::create($propertyDocString));
         $constructor->appendParameter(ParameterNode::create($name));
         $expression = Parser::parseSnippet("\$this->{$name} = \${$name};");
         $constructor->getBody()->lastChild()->before($expression);
         $getter = ClassMethodNode::create('get' . ucfirst($name));
         $class->appendMethod($getter);
         $class->getMethod('get' . ucfirst($name))->setDocComment(DocCommentNode::create("Gets the {$name} value."));
         $getter_expression = Parser::parseSnippet("return \$this->{$name};");
         $getter->getBody()->lastChild()->before($getter_expression);
     }
     $class->getMethod('__construct')->setDocComment(DocCommentNode::create($constructorDocString));
     $doc->getNamespace($this->getNamespace())->getBody()->append($class);
     /* @todo dispatch an event to allow subscribers to alter $doc */
     $formatter = FormatterFactory::getPsr2Formatter();
     $formatter->format($doc->getNamespace($this->getNamespace()));
     return $doc->getText();
 }
Example #11
0
 public function visitParameterNode(ParameterNode $node)
 {
     if ($node->getValue()) {
         $assign = $node->getValue()->previousUntil(Filter::isTokenType('='), TRUE)->get(0);
         $this->spaceBefore($assign);
         $this->spaceAfter($assign);
     }
 }
Example #12
0
 public function matchReflector(\ReflectionFunctionAbstract $reflector)
 {
     $this->setReference($reflector->returnsReference());
     foreach ($reflector->getParameters() as $i => $parameter) {
         try {
             $this->getParameterAtIndex($i)->matchReflector($parameter);
         } catch (\OutOfBoundsException $e) {
             $this->appendParameter(ParameterNode::fromReflector($parameter));
         }
     }
     return $this;
 }
 /**
  * {@inheritdoc}
  */
 public function buildRoute(TargetInterface $target, Drupal7Route $route)
 {
     $definition = $this->buildRouteDefinition($target, $route);
     $map = $this->buildParameterMap($target, $route);
     $map->applyRoute($definition->unwrap());
     $indexer = $target->getIndexer('function');
     foreach ($map->toArray() as $function_name => $parameters) {
         if ($parameters && $indexer->has($function_name)) {
             /** @var \Pharborist\Functions\FunctionDeclarationNode $function */
             $function = $indexer->get($function_name);
             foreach ($parameters as $parameter_name => $info) {
                 $parameter = $function->getParameterByName($parameter_name)->setName($info['name'], TRUE);
                 if (isset($info['type'])) {
                     $plugin_id = '_rewriter:' . $info['type'];
                     if ($this->rewriters->hasDefinition($plugin_id)) {
                         $this->rewriters->createInstance($plugin_id)->rewrite($parameter);
                     }
                 }
             }
         }
     }
     $class_indexer = $target->getIndexer('class');
     if ($class_indexer->has('DefaultController')) {
         $controller = $class_indexer->get('DefaultController');
     } else {
         $controller = $this->getController($target, $route);
         $class_indexer->addFile($this->writeClass($target, $controller));
     }
     if ($indexer->has($route['title callback'])) {
         if (!$controller->hasMethod($route['title callback'])) {
             $indexer->get($route['title callback'])->cloneAsMethodOf($controller);
         }
     }
     if ($indexer->has($route['access callback'])) {
         $func = $indexer->get($route['access callback']);
         $returns = $func->find(Filter::isInstanceOf('\\Pharborist\\ReturnStatementNode'));
         foreach ($returns as $ret) {
             $call = ClassMethodCallNode::create('\\Drupal\\Core\\Access\\AccessResult', 'allowedIf')->appendArgument($ret->getExpression());
             $ret->replaceWith(ReturnStatementNode::create($call));
         }
         // The access callback always receives an $account parameter.
         if ($func->hasParameter('account')) {
             $func->getParameter('account')->setTypeHint('Drupal\\Core\\Session\\AccountInterface');
         } else {
             $account = ParameterNode::create('account')->setTypeHint('Drupal\\Core\\Session\\AccountInterface');
             $func->appendParameter($account);
         }
         if (!$controller->hasMethod($route['access callback'])) {
             $func->cloneAsMethodOf($controller);
         }
     }
     if ($indexer->has($route['page callback'])) {
         if (!$controller->hasMethod($route['page callback'])) {
             $indexer->get($route['page callback'])->cloneAsMethodOf($controller);
         }
     }
     $this->writeClass($target, $controller);
 }
 /**
  * Returns if the parameter is fully reassigned anywhere in the function.
  *
  * @param \Pharborist\Functions\ParameterNode $parameter
  *  The parameter to check.
  *
  * @return boolean
  */
 protected function isReassigned(ParameterNode $parameter)
 {
     return (bool) $parameter->getFunction()->find(Filter::isInstanceOf('\\Pharborist\\Variables\\VariableNode'))->filter(function (VariableNode $variable) use($parameter) {
         return $variable->getName() == $parameter->getName();
     })->filter($this->isAssigned)->count();
 }
Example #15
0
 /**
  * Parse parameter.
  * @return ParameterNode
  */
 private function parameter()
 {
     $node = new ParameterNode();
     if ($type = $this->optionalTypeHint()) {
         $node->addChild($type, 'typeHint');
     }
     $this->tryMatch('&', $node, 'reference');
     $this->tryMatch(T_ELLIPSIS, $node, 'variadic');
     $this->mustMatch(T_VARIABLE, $node, 'name', TRUE);
     if ($this->tryMatch('=', $node)) {
         $node->addChild($this->staticScalar(), 'value');
     }
     return $node;
 }
 public function testMatchReflector()
 {
     // @TODO Reflect on a function we define so we can more fully test this
     $reflector = (new \ReflectionFunction('array_walk'))->getParameters()[0];
     $node = ParameterNode::create('array')->matchReflector($reflector);
     $this->assertInstanceOf('\\Pharborist\\TokenNode', $node->getReference());
     $this->assertSame('&', $node->getReference()->getText());
     $this->assertNull($node->getValue());
 }
 public function testFunctionDeclaration()
 {
     $expected = 'function test($a, $b) {}';
     $function = FunctionDeclarationNode::create('test', ['$a', '$b']);
     $this->assertEquals($expected, $function->getText());
     $function = FunctionDeclarationNode::create('badoink');
     $function->appendParameter(ParameterNode::create('badonk'));
     $this->assertEquals('function badoink($badonk) {}', $function->getText());
 }