Example #1
0
 /**
  * Creates a new, blank PHP source file.
  *
  * @param string|NULL $ns
  *  If provided, the new document will have this namespace added to it.
  *
  * @return static
  */
 public static function create($ns = NULL)
 {
     $node = new RootNode();
     $node->addChild(Token::openTag());
     if (is_string($ns) && $ns) {
         NamespaceNode::create($ns)->appendTo($node)->after(Token::newline());
     }
     return $node;
 }
Example #2
0
 /**
  * Utility method to PSR4-ify a class. It'll move the class into its own file
  * in the given module's namespace. The class is modified in-place, so you
  * should clone it before calling this function if you want to make a PSR-4
  * *copy* of it.
  *
  * @param \Drupal\drupalmoduleupgrader\TargetInterface $target
  *  The module which will own the class.
  * @param \Pharborist\ClassNode $class
  *  The class to modify.
  *
  * @return \Pharborist\ClassNode
  *  The modified class, returned for convenience.
  */
 public static function toPSR4(TargetInterface $target, ClassNode $class)
 {
     $ns = 'Drupal\\' . $target->id();
     RootNode::create($ns)->getNamespace($ns)->append($class->remove());
     WhitespaceNode::create("\n\n")->insertBefore($class);
     return $class;
 }
 public function execute()
 {
     $ns = $this->extractNS($this->configuration['class']);
     $class = $this->extractLocal($this->configuration['class']);
     $doc = RootNode::create($ns);
     $ns = $doc->getNamespace($ns);
     Token::newline()->insertBefore($ns);
     Token::newline()->appendTo($ns);
     $class = ClassNode::create($class);
     if ($parent = $this->configuration['parent']) {
         Parser::parseSnippet('use ' . ltrim($parent, '\\') . ';')->appendTo($ns)->after(Token::newline());
         $class->setExtends($this->extractLocal($parent));
     }
     $interfaces = (array) $this->configuration['interfaces'];
     foreach ($interfaces as $interface) {
         Parser::parseSnippet('use ' . ltrim($interface, '\\') . ';')->appendTo($ns)->after(Token::newline());
     }
     $class->setImplements(array_map([$this, 'extractLocal'], $interfaces));
     if (isset($this->configuration['doc'])) {
         $class->setDocComment(DocCommentNode::create($this->configuration['doc']));
     }
     $class->appendTo($ns)->before(Token::newline());
     $destination = $this->getUnaliasedPath($this->configuration['destination']);
     $dir = subStr($destination, 0, strrPos($destination, '/'));
     $this->fs->mkdir($dir);
     file_put_contents($destination, $doc->getText());
     // Need to store the class' local name as its index identifier because
     // \Pharborist\Filter::isClass() doesn't support lookup by qualified path.
     $this->target->getIndexer('class')->addFile($destination);
 }
    /**
     * {@inheritdoc}
     */
    public function convert(TargetInterface $target)
    {
        $unit_tests = [];
        $test_files = $target->getIndexer('class')->getQuery(['file'])->condition('parent', 'DrupalUnitTestCase')->execute()->fetchCol();
        foreach ($test_files as $test_file) {
            /** @var \Pharborist\Objects\Classnode[] $tests */
            $tests = $target->open($test_file)->find(Filter::isInstanceOf('\\Pharborist\\Objects\\SingleInheritanceNode'))->toArray();
            foreach ($tests as $test) {
                if ((string) $test->getExtends() === 'DrupalUnitTestCase') {
                    $unit_tests[] = $test;
                }
            }
        }
        /** @var \Pharborist\Objects\ClassNode $unit_test */
        foreach ($unit_tests as $unit_test) {
            $unit_test->setExtends('\\Drupal\\Tests\\UnitTestCase');
            $comment_text = <<<END
@FIXME
Unit tests are now written for the PHPUnit framework. You will need to refactor
this test in order for it to work properly.
END;
            $comment = DocCommentNode::create($comment_text);
            $unit_test->setDocComment($comment);
            $ns = 'Drupal\\Tests\\' . $target->id() . '\\Unit';
            $doc = RootNode::create($ns)->getNamespace($ns)->append($unit_test->remove());
            WhitespaceNode::create("\n\n")->insertBefore($unit_test);
            $this->write($target, 'tests/src/Unit/' . $unit_test->getName() . '.php', "<?php\n\n{$doc}");
        }
    }
Example #5
0
 /**
  * {@inheritdoc}
  */
 public function execute()
 {
     /** @var \Pharborist\Objects\ClassNode $class */
     $class = $this->target->getIndexer('class')->get($this->configuration['source']);
     $ns = substr($this->configuration['destination'], 0, strrpos($this->configuration['destination'], '\\'));
     $doc = RootNode::create($ns);
     $ns = $doc->getNamespace($ns);
     WhitespaceNode::create("\n")->appendTo($ns);
     $import = [];
     if ($parent = $class->getExtends()) {
         $import[] = $parent->getAbsolutePath();
     }
     $interfaces = $class->getImplementList();
     if ($interfaces) {
         foreach ($interfaces->getItems() as $interface) {
             $import[] = $interface->getAbsolutePath();
         }
     }
     foreach ($class->getMethods() as $method) {
         foreach ($method->getParameters() as $parameter) {
             $type_hint = $parameter->getTypeHint();
             if ($type_hint instanceof NameNode) {
                 $import[] = $type_hint->getAbsolutePath();
             }
         }
     }
     foreach (array_unique($import) as $i) {
         Parser::parseSnippet('use ' . ltrim($i, '\\') . ';')->appendTo($ns);
         WhitespaceNode::create("\n")->appendTo($ns);
     }
     WhitespaceNode::create("\n")->appendTo($ns);
     $class->remove()->appendTo($ns);
     $search_for = ['Drupal\\' . $this->target->id(), '\\'];
     $replace_with = ['src', '/'];
     $path = str_replace($search_for, $replace_with, $this->configuration['destination']) . '.php';
     file_put_contents($this->target->getPath($path), $doc->getText());
 }
Example #6
0
 public function endRootNode(RootNode $node)
 {
     /** @var $open_tag TokenNode */
     foreach ($node->children(Filter::isTokenType(T_OPEN_TAG)) as $open_tag) {
         $this->removeSpaceAfter($open_tag);
         if ($open_tag !== "<?php\n") {
             $open_tag->setText("<?php\n");
         }
     }
 }
 public function move(ClassNode $test)
 {
     $ns = 'Drupal\\' . $this->target->id() . '\\Tests';
     RootNode::create($ns)->getNamespace($ns)->append($test->remove());
     WhitespaceNode::create("\n\n")->insertBefore($test);
     $this->writeClass($this->target, $test);
 }
 /**
  * {@inheritdoc}
  */
 public function create($file, $ns = NULL)
 {
     $this->documents[$file] = RootNode::create($ns);
     return $this->documents[$file];
 }
 public function testSort()
 {
     $root = new RootNode();
     $parent = $this->createParentNode();
     $root->append($parent);
     $children = [];
     for ($i = 0; $i <= 21; $i++) {
         $children[] = $this->createNode();
     }
     $parent->append($children);
     $collection = new NodeCollection($children, TRUE);
     foreach ($collection as $k => $child) {
         $this->assertSame($children[$k], $child);
     }
 }
Example #10
0
 /**
  * Build a syntax tree from the token iterator.
  * @param TokenIterator $iterator
  * @return RootNode Root node of the tree
  */
 public function buildTree(TokenIterator $iterator)
 {
     $this->skipped = [];
     $this->skipParent = NULL;
     $this->docComment = NULL;
     $this->skippedDocComment = [];
     $this->iterator = $iterator;
     $this->current = $this->iterator->current();
     $this->currentType = $this->current ? $this->current->getType() : NULL;
     $top = new RootNode();
     $this->top = $top;
     if ($this->currentType && $this->currentType !== T_OPEN_TAG) {
         $node = new TemplateNode();
         // Parse any template statements that proceed the opening PHP tag.
         $this->templateStatementList($node);
         $top->addChild($node);
     }
     if ($this->tryMatch(T_OPEN_TAG, $top, NULL, TRUE, TRUE)) {
         $this->topStatementList($top);
     }
     return $top;
 }
 /**
  * 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();
 }