Completed
Push — develop ( ea714c...693449 )
by Jaap
9s
created

File::createFileDocBlock()   C

Complexity

Conditions 13
Paths 13

Size

Total Lines 47
Code Lines 30

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 23
CRAP Score 13.0864

Importance

Changes 0
Metric Value
cc 13
eloc 30
nc 13
nop 4
dl 0
loc 47
ccs 23
cts 25
cp 0.92
crap 13.0864
rs 5.0999
c 0
b 0
f 0

How to fix   Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

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-2018 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 extends AbstractFactory implements ProjectFactoryStrategy
0 ignored issues
show
Complexity introduced by
The class File has a coupling between objects value of 20. Consider to reduce the number of dependencies under 13.
Loading history...
43
{
44
    /**
45
     * @var NodesFactory
46
     */
47
    private $nodesFactory;
48
49
    /**
50
     * Initializes the object.
51
     *
52
     * @param NodesFactory $nodesFactory
53
     * @param Middleware[] $middleware
54
     */
55 12
    public function __construct(NodesFactory $nodesFactory, $middleware = array())
56
    {
57 12
        $this->nodesFactory = $nodesFactory;
58
59 12
        $lastCallable = function ($command) {
60 8
            return $this->createFile($command);
61 12
        };
62
63 12
        $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...
64 12
    }
65
66
    /**
67
     * Returns true when the strategy is able to handle the object.
68
     *
69
     * @param string $file path to check.
70
     * @return boolean
71
     */
72 1
    public function matches($file)
73
    {
74 1
        return $file instanceof FileSystemFile;
75
    }
76
77
    /**
78
     * Creates an File out of the given object.
79
     * Since an object might contain other objects that need to be converted the $factory is passed so it can be
80
     * used to create nested Elements.
81
     *
82
     * @param FileSystemFile $object path to the file to convert to an File object.
83
     * @param StrategyContainer $strategies used to convert nested objects.
84
     * @param Context $context
85
     * @return File
86
     */
87 9
    protected function doCreate($object, StrategyContainer $strategies, Context $context = null)
88
    {
89 9
        $command = new CreateCommand($object, $strategies);
90 9
        $middlewareChain = $this->middlewareChain;
91
92 9
        return $middlewareChain($command);
93
    }
94
95
    /**
96
     * @param CreateCommand $command
97
     * @return FileElement
98
     */
99 8
    private function createFile(CreateCommand $command)
100
    {
101 8
        $file = $command->getFile();
102 8
        $code = $file->getContents();
103 8
        $nodes = $this->nodesFactory->create($code);
104
105 8
        $contextFactory = new ContextFactory();
106 8
        $context = $contextFactory->createForNamespace('\\', $code);
107
108 8
        $docBlock = $this->createFileDocBlock(null, $command->getStrategies(), $context, $nodes);
109
110 8
        $result = new FileElement(
111 8
            $file->md5(),
112 8
            $file->path(),
113 8
            $code,
114 8
            $docBlock
0 ignored issues
show
Bug introduced by
It seems like $docBlock defined by $this->createFileDocBloc...es(), $context, $nodes) on line 108 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...
115
        );
116
117 8
        $this->createElements(new Fqsen('\\'), $nodes, $result, $command->getStrategies());
118
119 8
        return $result;
120
    }
121
122
    /**
123
     * @param Fqsen $namespace
124
     * @param Node[] $nodes
125
     * @param FileElement $file
126
     * @param StrategyContainer $strategies
127
     */
128 8
    private function createElements(Fqsen $namespace, $nodes, FileElement $file, StrategyContainer $strategies)
129
    {
130 8
        $contextFactory = new ContextFactory();
131 8
        $context = $contextFactory->createForNamespace((string)$namespace, $file->getSource());
132 8
        foreach ($nodes as $node) {
133 8
            switch (get_class($node)) {
134 8
                case ClassNode::class:
135 2
                    $strategy = $strategies->findMatching($node);
136 2
                    $class = $strategy->create($node, $strategies, $context);
137 2
                    $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...
138 2
                    break;
139 6
                case FunctionNode::class:
140 1
                    $strategy = $strategies->findMatching($node);
141 1
                    $function = $strategy->create($node, $strategies, $context);
142 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...
143 1
                    break;
144 5
                case InterfaceNode::class:
145 1
                    $strategy = $strategies->findMatching($node);
146 1
                    $interface = $strategy->create($node, $strategies, $context);
147 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...
148 1
                    break;
149 4
                case NamespaceNode::class:
150 3
                    $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...
151 3
                    $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...
152 3
                    break;
153 1
                case TraitNode::class:
154 1
                    $strategy = $strategies->findMatching($node);
155 1
                    $trait = $strategy->create($node, $strategies, $context);
156 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...
157 8
                    break;
158
            }
159
        }
160 8
    }
161
162
    /**
163
     * @param Doc $docBlock
164
     * @param StrategyContainer $strategies
165
     * @param Context $context
166
     * @param Node[] $nodes
167
     * @return null|\phpDocumentor\Reflection\DocBlock
168
     */
169 8
    protected function createFileDocBlock(
0 ignored issues
show
Complexity introduced by
This operation has 372 execution paths which exceeds the configured maximum of 200.

A high number of execution paths generally suggests many nested conditional statements and make the code less readible. This can usually be fixed by splitting the method into several smaller methods.

You can also find more information in the “Code” section of your repository.

Loading history...
170
        Doc $docBlock = null,
0 ignored issues
show
Unused Code introduced by
The parameter $docBlock is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
171
        StrategyContainer $strategies = null,
172
        Context $context = null,
173
        $nodes = array()
174
    ) {
175 8
        $node = current($nodes);
176 8
        if (!$node instanceof Node) {
177
            return null;
178
        }
179
180 8
        $comments = $node->getAttribute('comments');
181 8
        if (!is_array($comments) || empty($comments)) {
182 5
            return null;
183
        }
184
185 3
        $found = 0;
186 3
        $firstDocBlock = null;
187 3
        foreach ($comments as $comment) {
188 3
            if (!$comment instanceof Doc) {
189 1
                continue;
190
            }
191
192
            //If current node cannot have a docblock return the first comment as docblock for the file.
193
            if (!(
194 3
                $node instanceof ClassNode ||
195 2
                $node instanceof FunctionNode ||
196 2
                $node instanceof InterfaceNode ||
197 3
                $node instanceof TraitNode
198
            )) {
199 2
                return $this->createDocBlock($strategies, $comment, $context);
0 ignored issues
show
Bug introduced by
It seems like $strategies defined by parameter $strategies on line 171 can be null; however, phpDocumentor\Reflection...ctory::createDocBlock() does not accept null, maybe add an additional type check?

It seems like you allow that null is being passed for a parameter, however the function which is called does not seem to accept null.

We recommend to add an additional type check (or disallow null for the parameter):

function notNullable(stdClass $x) { }

// Unsafe
function withoutCheck(stdClass $x = null) {
    notNullable($x);
}

// Safe - Alternative 1: Adding Additional Type-Check
function withCheck(stdClass $x = null) {
    if ($x instanceof stdClass) {
        notNullable($x);
    }
}

// Safe - Alternative 2: Changing Parameter
function withNonNullableParam(stdClass $x) {
    notNullable($x);
}
Loading history...
200
            }
201
202 1
            $found++;
203 1
            if ($firstDocBlock === null) {
204 1
                $firstDocBlock = $comment;
205 1
            } elseif ($found > 2) {
206 1
                break;
207
            }
208
        }
209
210 1
        if ($found === 2) {
211 1
            return $this->createDocBlock($strategies, $firstDocBlock, $context);
0 ignored issues
show
Bug introduced by
It seems like $strategies defined by parameter $strategies on line 171 can be null; however, phpDocumentor\Reflection...ctory::createDocBlock() does not accept null, maybe add an additional type check?

It seems like you allow that null is being passed for a parameter, however the function which is called does not seem to accept null.

We recommend to add an additional type check (or disallow null for the parameter):

function notNullable(stdClass $x) { }

// Unsafe
function withoutCheck(stdClass $x = null) {
    notNullable($x);
}

// Safe - Alternative 1: Adding Additional Type-Check
function withCheck(stdClass $x = null) {
    if ($x instanceof stdClass) {
        notNullable($x);
    }
}

// Safe - Alternative 2: Changing Parameter
function withNonNullableParam(stdClass $x) {
    notNullable($x);
}
Loading history...
212
        }
213
214
        return null;
215
    }
216
}
217