Completed
Pull Request — develop (#87)
by Jaap
03:38
created

File::create()   A

Complexity

Conditions 3
Paths 2

Size

Total Lines 16
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 9
CRAP Score 3

Importance

Changes 8
Bugs 0 Features 5
Metric Value
c 8
b 0
f 5
dl 0
loc 16
ccs 9
cts 9
cp 1
rs 9.4286
cc 3
eloc 9
nc 2
nop 3
crap 3
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\Fqsen;
18
use phpDocumentor\Reflection\Middleware\ChainFactory;
19
use phpDocumentor\Reflection\Middleware\Middleware;
20
use phpDocumentor\Reflection\Php\Factory\File\Adapter;
21
use phpDocumentor\Reflection\Php\Factory\File\CreateCommand;
22
use phpDocumentor\Reflection\Php\Factory\File\LocalAdapter;
23
use phpDocumentor\Reflection\Php\File as FileElement;
24
use phpDocumentor\Reflection\Php\NodesFactory;
25
use phpDocumentor\Reflection\Php\ProjectFactoryStrategy;
26
use phpDocumentor\Reflection\Php\StrategyContainer;
27
use phpDocumentor\Reflection\Types\Context;
28
use phpDocumentor\Reflection\Types\ContextFactory;
29
use PhpParser\Comment\Doc;
30
use PhpParser\Lexer;
31
use PhpParser\Node;
32
use PhpParser\Node\Stmt\Class_ as ClassNode;
33
use PhpParser\Node\Stmt\Function_ as FunctionNode;
34
use PhpParser\Node\Stmt\Interface_ as InterfaceNode;
35
use PhpParser\Node\Stmt\Namespace_ as NamespaceNode;
36
use PhpParser\Node\Stmt\Trait_ as TraitNode;
37
use PhpParser\NodeAbstract;
38
39
/**
40
 * Strategy to create File element from the provided filename.
41
 * This class supports extra middle wares to add extra steps to the creation process.
42
 */
43
final class File implements ProjectFactoryStrategy
0 ignored issues
show
Complexity introduced by
The class File has a coupling between objects value of 23. Consider to reduce the number of dependencies under 13.
Loading history...
44
{
45
    /**
46
     * @var NodesFactory
47
     */
48
    private $nodesFactory;
49
50
    /**
51
     * @var Adapter
52
     */
53
    private $adapter;
54
55
    /**
56
     * Initializes the object.
57
     *
58
     * @param NodesFactory $nodesFactory
59
     * @param Adapter $adapter
60
     * @param Middleware[] $middleware
61
     */
62 9
    public function __construct(NodesFactory $nodesFactory, Adapter $adapter = null, $middleware = array())
63
    {
64 9
        if ($adapter === null) {
65 9
            $adapter = new LocalAdapter();
66
        }
67
68 9
        $this->nodesFactory = $nodesFactory;
69 9
        $this->adapter = $adapter;
70
71 9
        $lastCallable = function ($command) {
72 5
            return $this->createFile($command);
73 9
        };
74
75 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...
76 9
    }
77
78
    /**
79
     * Returns true when the strategy is able to handle the object.
80
     *
81
     * @param string $filePath path to check.
82
     * @return boolean
83
     */
84 1
    public function matches($filePath)
85
    {
86 1
        return is_string($filePath) && $this->adapter->fileExists($filePath);
87
    }
88
89
    /**
90
     * Creates an File out of the given object.
91
     * Since an object might contain other objects that need to be converted the $factory is passed so it can be
92
     * used to create nested Elements.
93
     *
94
     * @param string $object path to the file to convert to an File object.
95
     * @param StrategyContainer $strategies used to convert nested objects.
96
     * @param Context $context
97
     * @return File
98
     */
99 7
    public function create($object, StrategyContainer $strategies, Context $context = null)
100
    {
101 7
        if (!$this->matches($object)) {
102 1
            throw new InvalidArgumentException(
103 1
                sprintf('%s cannot handle objects with the type %s',
104 1
                    __CLASS__,
105 1
                    is_object($object) ? get_class($object) : gettype($object)
106
                )
107
            );
108
        }
109
110 6
        $command = new CreateCommand($this->adapter, $object, $strategies);
111 6
        $middlewareChain = $this->middlewareChain;
112
113 6
        return $middlewareChain($command);
114
    }
115
116
    /**
117
     * @param $object
118
     * @param StrategyContainer $strategies
0 ignored issues
show
Bug introduced by
There is no parameter named $strategies. Was it maybe removed?

This check looks for PHPDoc comments describing methods or function parameters that do not exist on the corresponding method or function.

Consider the following example. The parameter $italy is not defined by the method finale(...).

/**
 * @param array $germany
 * @param array $island
 * @param array $italy
 */
function finale($germany, $island) {
    return "2:1";
}

The most likely cause is that the parameter was removed, but the annotation was not.

Loading history...
119
     * @return FileElement
120
     */
121 5
    private function createFile(CreateCommand $command)
122
    {
123 5
        $code = $this->adapter->getContents($command->getFilePath());
124 5
        $nodes = $this->nodesFactory->create($code);
125 5
        $docBlock = $this->createDocBlock($command->getStrategies(), $code, $nodes);
126
127 5
        $file = new FileElement(
128 5
            $this->adapter->md5($command->getFilePath()),
129 5
            $this->adapter->path($command->getFilePath()),
130
            $code,
131
            $docBlock
0 ignored issues
show
Bug introduced by
It seems like $docBlock defined by $this->createDocBlock($c...egies(), $code, $nodes) on line 125 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...
132
        );
133
134 5
        $this->createElements(new Fqsen('\\'), $nodes, $file, $command->getStrategies());
135
136 5
        return $file;
137
    }
138
139
    /**
140
     * @param Fqsen $namespace
141
     * @param Node[] $nodes
142
     * @param FileElement $file
143
     * @param StrategyContainer $strategies
144
     */
145 5
    private function createElements(Fqsen $namespace, $nodes, FileElement $file, StrategyContainer $strategies)
146
    {
147 5
        $contextFactory = new ContextFactory();
148 5
        $context = $contextFactory->createForNamespace((string)$namespace, $file->getSource());
149 5
        foreach ($nodes as $node) {
150 5
            switch (get_class($node)) {
151
                case ClassNode::class:
152 1
                    $strategy = $strategies->findMatching($node);
153 1
                    $class = $strategy->create($node, $strategies, $context);
154 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...
155 1
                    break;
156
                case FunctionNode::class:
157 1
                    $strategy = $strategies->findMatching($node);
158 1
                    $function = $strategy->create($node, $strategies, $context);
159 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...
160 1
                    break;
161
                case InterfaceNode::class:
162 1
                    $strategy = $strategies->findMatching($node);
163 1
                    $interface = $strategy->create($node, $strategies, $context);
164 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...
165 1
                    break;
166
                case NamespaceNode::class:
167 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...
168 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...
169 1
                    break;
170
                case TraitNode::class:
171 1
                    $strategy = $strategies->findMatching($node);
172 1
                    $trait = $strategy->create($node, $strategies, $context);
173 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...
174 5
                    break;
175
            }
176
        }
177 5
    }
178
    /**
179
     * @param StrategyContainer $strategies
180
     * @param $code
181
     * @param $nodes
182
     * @return null|\phpDocumentor\Reflection\Element
183
     * @internal param Context $context
184
     */
185 5
    private function createDocBlock(StrategyContainer $strategies, $code, $nodes)
186
    {
187 5
        $contextFactory = new ContextFactory();
188 5
        $context = $contextFactory->createForNamespace('\\', $code);
189 5
        $docBlock = null;
190
191
        /** @var NodeAbstract $node */
192 5
        $node = current($nodes);
193 5
        if ($node instanceof Node) {
194 5
            $comments = $node->getAttribute('comments');
195 5
            if (is_array($comments)) {
196
                if ($node instanceof NamespaceNode) {
197
                    $strategy = $strategies->findMatching(current($comments));
198
                    $docBlock = $strategy->create(current($comments), $strategies, $context);
199
                } elseif (count($comments) == 2) {
200
                    $strategy = $strategies->findMatching(current($comments));
201
                    $docBlock = $strategy->create(current($comments), $strategies, $context);
202
                }
203
            }
204
        }
205
206 5
        return $docBlock;
207
    }
208
}
209