Completed
Pull Request — develop (#89)
by Jaap
04:24
created

File::createDocBlock()   B

Complexity

Conditions 5
Paths 5

Size

Total Lines 23
Code Lines 15

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 10
CRAP Score 7.1941

Importance

Changes 2
Bugs 0 Features 0
Metric Value
c 2
b 0
f 0
dl 0
loc 23
ccs 10
cts 18
cp 0.5556
rs 8.5907
cc 5
eloc 15
nc 5
nop 3
crap 7.1941
1
<?php
2
/**
3
 * This file is part of phpDocumentor.
4
 *
5
 * For the full copyright and license information, please view the LICENSE
6
 * file that was distributed with this source code.
7
 *
8
 * @copyright 2010-2015 Mike van Riel<[email protected]>
9
 * @license   http://www.opensource.org/licenses/mit-license.php MIT
10
 * @link      http://phpdoc.org
11
 */
12
13
14
namespace phpDocumentor\Reflection\Php\Factory;
15
16
use InvalidArgumentException;
17
use phpDocumentor\Reflection\File as FileSystemFile;
18
use phpDocumentor\Reflection\Fqsen;
19
use phpDocumentor\Reflection\Middleware\ChainFactory;
20
use phpDocumentor\Reflection\Middleware\Middleware;
21
use phpDocumentor\Reflection\Php\Factory\File\CreateCommand;
22
use phpDocumentor\Reflection\Php\File as FileElement;
23
use phpDocumentor\Reflection\Php\NodesFactory;
24
use phpDocumentor\Reflection\Php\ProjectFactoryStrategy;
25
use phpDocumentor\Reflection\Php\StrategyContainer;
26
use phpDocumentor\Reflection\Types\Context;
27
use phpDocumentor\Reflection\Types\ContextFactory;
28
use PhpParser\Comment\Doc;
29
use PhpParser\Lexer;
30
use PhpParser\Node;
31
use PhpParser\Node\Stmt\Class_ as ClassNode;
32
use PhpParser\Node\Stmt\Function_ as FunctionNode;
33
use PhpParser\Node\Stmt\Interface_ as InterfaceNode;
34
use PhpParser\Node\Stmt\Namespace_ as NamespaceNode;
35
use PhpParser\Node\Stmt\Trait_ as TraitNode;
36
use PhpParser\NodeAbstract;
37
38
/**
39
 * Strategy to create File element from the provided filename.
40
 * This class supports extra middle wares to add extra steps to the creation process.
41
 */
42
final class File implements ProjectFactoryStrategy
0 ignored issues
show
Complexity introduced by
The class File has a coupling between objects value of 22. Consider to reduce the number of dependencies under 13.
Loading history...
43
{
44
    /**
45
     * @var NodesFactory
46
     */
47
    private $nodesFactory;
48
49
    /**
50
     * @var Adapter
51
     */
52
    private $adapter;
0 ignored issues
show
Unused Code introduced by
The property $adapter is not used and could be removed.

This check marks private properties in classes that are never used. Those properties can be removed.

Loading history...
53
54
    /**
55
     * Initializes the object.
56
     *
57
     * @param NodesFactory $nodesFactory
58
     * @param Middleware[] $middleware
59
     */
60 9
    public function __construct(NodesFactory $nodesFactory, $middleware = array())
61
    {
62 9
        $this->nodesFactory = $nodesFactory;
63
64 9
        $lastCallable = function ($command) {
65 5
            return $this->createFile($command);
66 9
        };
67
68 9
        $this->middlewareChain = ChainFactory::createExecutionChain($middleware, $lastCallable);
0 ignored issues
show
Bug introduced by
The property middlewareChain does not exist. Did you maybe forget to declare it?

In PHP it is possible to write to properties without declaring them. For example, the following is perfectly valid PHP code:

class MyClass { }

$x = new MyClass();
$x->foo = true;

Generally, it is a good practice to explictly declare properties to avoid accidental typos and provide IDE auto-completion:

class MyClass {
    public $foo;
}

$x = new MyClass();
$x->foo = true;
Loading history...
69 9
    }
70
71
    /**
72
     * Returns true when the strategy is able to handle the object.
73
     *
74
     * @param string $file path to check.
75
     * @return boolean
76
     */
77 1
    public function matches($file)
78
    {
79 1
        return $file instanceof FileSystemFile;
80
    }
81
82
    /**
83
     * Creates an File out of the given object.
84
     * Since an object might contain other objects that need to be converted the $factory is passed so it can be
85
     * used to create nested Elements.
86
     *
87
     * @param FileSystemFile $object path to the file to convert to an File object.
88
     * @param StrategyContainer $strategies used to convert nested objects.
89
     * @param Context $context
90
     * @return File
91
     */
92 7
    public function create($object, StrategyContainer $strategies, Context $context = null)
93
    {
94 7
        if (!$this->matches($object)) {
0 ignored issues
show
Documentation introduced by
$object is of type object<phpDocumentor\Reflection\File>, but the function expects a string.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
95 1
            throw new InvalidArgumentException(
96 1
                sprintf('%s cannot handle objects with the type %s',
97 1
                    __CLASS__,
98 1
                    is_object($object) ? get_class($object) : gettype($object)
99 1
                )
100 1
            );
101
        }
102
103 6
        $command = new CreateCommand($object, $strategies);
104 6
        $middlewareChain = $this->middlewareChain;
105
106 6
        return $middlewareChain($command);
107
    }
108
109
    /**
110
     * @param CreateCommand $command
111
     * @return FileElement
112
     */
113 5
    private function createFile(CreateCommand $command)
114
    {
115 5
        $file = $command->getFile();
116 5
        $code = $file->getContents();
117 5
        $nodes = $this->nodesFactory->create($code);
118 5
        $docBlock = $this->createDocBlock($command->getStrategies(), $code, $nodes);
119
120 5
        $result = new FileElement(
121 5
            $file->md5(),
122 5
            $file->path(),
123 5
            $code,
124
            $docBlock
0 ignored issues
show
Bug introduced by
It seems like $docBlock defined by $this->createDocBlock($c...egies(), $code, $nodes) on line 118 can also be of type object<phpDocumentor\Reflection\Element>; however, phpDocumentor\Reflection\Php\File::__construct() does only seem to accept null|object<phpDocumentor\Reflection\DocBlock>, maybe add an additional type check?

If a method or function can return multiple different values and unless you are sure that you only can receive a single value in this context, we recommend to add an additional type check:

/**
 * @return array|string
 */
function returnsDifferentValues($x) {
    if ($x) {
        return 'foo';
    }

    return array();
}

$x = returnsDifferentValues($y);
if (is_array($x)) {
    // $x is an array.
}

If this a common case that PHP Analyzer should handle natively, please let us know by opening an issue.

Loading history...
125 5
        );
126
127 5
        $this->createElements(new Fqsen('\\'), $nodes, $result, $command->getStrategies());
128
129 5
        return $result;
130
    }
131
132
    /**
133
     * @param Fqsen $namespace
134
     * @param Node[] $nodes
135
     * @param FileElement $file
136
     * @param StrategyContainer $strategies
137
     */
138 5
    private function createElements(Fqsen $namespace, $nodes, FileElement $file, StrategyContainer $strategies)
139
    {
140 5
        $contextFactory = new ContextFactory();
141 5
        $context = $contextFactory->createForNamespace((string)$namespace, $file->getSource());
142 5
        foreach ($nodes as $node) {
143 5
            switch (get_class($node)) {
144 5
                case ClassNode::class:
145 1
                    $strategy = $strategies->findMatching($node);
146 1
                    $class = $strategy->create($node, $strategies, $context);
147 1
                    $file->addClass($class);
0 ignored issues
show
Compatibility introduced by
$class of type object<phpDocumentor\Reflection\Element> is not a sub-type of object<phpDocumentor\Reflection\Php\Class_>. It seems like you assume a concrete implementation of the interface phpDocumentor\Reflection\Element to be always present.

This check looks for parameters that are defined as one type in their type hint or doc comment but seem to be used as a narrower type, i.e an implementation of an interface or a subclass.

Consider changing the type of the parameter or doing an instanceof check before assuming your parameter is of the expected type.

Loading history...
148 1
                    break;
149 4
                case FunctionNode::class:
150 1
                    $strategy = $strategies->findMatching($node);
151 1
                    $function = $strategy->create($node, $strategies, $context);
152 1
                    $file->addFunction($function);
0 ignored issues
show
Compatibility introduced by
$function of type object<phpDocumentor\Reflection\Element> is not a sub-type of object<phpDocumentor\Reflection\Php\Function_>. It seems like you assume a concrete implementation of the interface phpDocumentor\Reflection\Element to be always present.

This check looks for parameters that are defined as one type in their type hint or doc comment but seem to be used as a narrower type, i.e an implementation of an interface or a subclass.

Consider changing the type of the parameter or doing an instanceof check before assuming your parameter is of the expected type.

Loading history...
153 1
                    break;
154 3
                case InterfaceNode::class:
155 1
                    $strategy = $strategies->findMatching($node);
156 1
                    $interface = $strategy->create($node, $strategies, $context);
157 1
                    $file->addInterface($interface);
0 ignored issues
show
Compatibility introduced by
$interface of type object<phpDocumentor\Reflection\Element> is not a sub-type of object<phpDocumentor\Reflection\Php\Interface_>. It seems like you assume a concrete implementation of the interface phpDocumentor\Reflection\Element to be always present.

This check looks for parameters that are defined as one type in their type hint or doc comment but seem to be used as a narrower type, i.e an implementation of an interface or a subclass.

Consider changing the type of the parameter or doing an instanceof check before assuming your parameter is of the expected type.

Loading history...
158 1
                    break;
159 2
                case NamespaceNode::class:
160 1
                    $file->addNamespace($node->fqsen);
0 ignored issues
show
Bug introduced by
Accessing fqsen on the interface PhpParser\Node suggest that you code against a concrete implementation. How about adding an instanceof check?

If you access a property on an interface, you most likely code against a concrete implementation of the interface.

Available Fixes

  1. Adding an additional type check:

    interface SomeInterface { }
    class SomeClass implements SomeInterface {
        public $a;
    }
    
    function someFunction(SomeInterface $object) {
        if ($object instanceof SomeClass) {
            $a = $object->a;
        }
    }
    
  2. Changing the type hint:

    interface SomeInterface { }
    class SomeClass implements SomeInterface {
        public $a;
    }
    
    function someFunction(SomeClass $object) {
        $a = $object->a;
    }
    
Loading history...
161 1
                    $this->createElements($node->fqsen, $node->stmts, $file, $strategies);
0 ignored issues
show
Bug introduced by
Accessing fqsen on the interface PhpParser\Node suggest that you code against a concrete implementation. How about adding an instanceof check?

If you access a property on an interface, you most likely code against a concrete implementation of the interface.

Available Fixes

  1. Adding an additional type check:

    interface SomeInterface { }
    class SomeClass implements SomeInterface {
        public $a;
    }
    
    function someFunction(SomeInterface $object) {
        if ($object instanceof SomeClass) {
            $a = $object->a;
        }
    }
    
  2. Changing the type hint:

    interface SomeInterface { }
    class SomeClass implements SomeInterface {
        public $a;
    }
    
    function someFunction(SomeClass $object) {
        $a = $object->a;
    }
    
Loading history...
Bug introduced by
Accessing stmts on the interface PhpParser\Node suggest that you code against a concrete implementation. How about adding an instanceof check?

If you access a property on an interface, you most likely code against a concrete implementation of the interface.

Available Fixes

  1. Adding an additional type check:

    interface SomeInterface { }
    class SomeClass implements SomeInterface {
        public $a;
    }
    
    function someFunction(SomeInterface $object) {
        if ($object instanceof SomeClass) {
            $a = $object->a;
        }
    }
    
  2. Changing the type hint:

    interface SomeInterface { }
    class SomeClass implements SomeInterface {
        public $a;
    }
    
    function someFunction(SomeClass $object) {
        $a = $object->a;
    }
    
Loading history...
162 1
                    break;
163 1
                case TraitNode::class:
164 1
                    $strategy = $strategies->findMatching($node);
165 1
                    $trait = $strategy->create($node, $strategies, $context);
166 1
                    $file->addTrait($trait);
0 ignored issues
show
Compatibility introduced by
$trait of type object<phpDocumentor\Reflection\Element> is not a sub-type of object<phpDocumentor\Reflection\Php\Trait_>. It seems like you assume a concrete implementation of the interface phpDocumentor\Reflection\Element to be always present.

This check looks for parameters that are defined as one type in their type hint or doc comment but seem to be used as a narrower type, i.e an implementation of an interface or a subclass.

Consider changing the type of the parameter or doing an instanceof check before assuming your parameter is of the expected type.

Loading history...
167 1
                    break;
168 5
            }
169 5
        }
170 5
    }
171
    /**
172
     * @param StrategyContainer $strategies
173
     * @param $code
174
     * @param $nodes
175
     * @return null|\phpDocumentor\Reflection\Element
176
     * @internal param Context $context
177
     */
178 5
    private function createDocBlock(StrategyContainer $strategies, $code, $nodes)
179
    {
180 5
        $contextFactory = new ContextFactory();
181 5
        $context = $contextFactory->createForNamespace('\\', $code);
182 5
        $docBlock = null;
183
184
        /** @var NodeAbstract $node */
185 5
        $node = current($nodes);
186 5
        if ($node instanceof Node) {
187 5
            $comments = $node->getAttribute('comments');
188 5
            if (is_array($comments)) {
189
                if ($node instanceof NamespaceNode) {
190
                    $strategy = $strategies->findMatching(current($comments));
191
                    $docBlock = $strategy->create(current($comments), $strategies, $context);
192
                } elseif (count($comments) == 2) {
193
                    $strategy = $strategies->findMatching(current($comments));
194
                    $docBlock = $strategy->create(current($comments), $strategies, $context);
195
                }
196
            }
197 5
        }
198
199 5
        return $docBlock;
200
    }
201
}
202