Completed
Push — master ( 2ce63d...389baa )
by Luis
11:05 queued 03:24
created

MethodDocBlock::returnType()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 7
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 5
CRAP Score 2

Importance

Changes 0
Metric Value
cc 2
eloc 4
nc 2
nop 0
dl 0
loc 7
ccs 5
cts 5
cp 1
crap 2
rs 9.4285
c 0
b 0
f 0
1
<?php
2
/**
3
 * PHP version 7.1
4
 *
5
 * This source file is subject to the license that is bundled with this package in the file LICENSE.
6
 */
7
8
namespace PhUml\Code\Methods;
9
10
use PhUml\Code\DocBlock;
11
use PhUml\Code\TypeDeclaration;
12
13
/**
14
 * It used to extract the return type of a method
15
 */
16
class MethodDocBlock extends DocBlock
17
{
18
    private static $returnExpression = '/@return\s*([\w]+(\[\])?)/';
19
    private static $parameterExpression = '/@param\s*([\w]+(?:\[\])?)\s*(\$[\w]+)/';
20
21
    /** @var TypeDeclaration[] */
22
    private $parameters;
23
24 72
    public function __construct(?string $comment)
25
    {
26 72
        parent::__construct($comment);
27 72
        $this->setParameters();
28 72
    }
29
30
31 72
    public static function from(?string $text): MethodDocBlock
32
    {
33 72
        return new MethodDocBlock($text);
34
    }
35
36 66
    public function returnType(): TypeDeclaration
37
    {
38 66
        $type = null;
39 66
        if (preg_match(self::$returnExpression, $this->comment, $matches)) {
40 51
            $type = trim($matches[1]);
41
        }
42 66
        return TypeDeclaration::from($type);
43
    }
44
45 72
    public function typeOfParameter(string $parameterName): TypeDeclaration
46
    {
47 72
        return $this->parameters[$parameterName] ?? TypeDeclaration::absent();
48
    }
49
50 72
    private function setParameters(): void
51
    {
52 72
        if (!preg_match_all(self::$parameterExpression, $this->comment, $matches)) {
53 66
            return;
54
        }
55 69
        foreach ($matches[0] as $typeHint) {
56 69
            $this->extractDeclarationFrom($typeHint);
57
        }
58 69
    }
59
60 69
    private function extractDeclarationFrom(string $typeHint): void
61
    {
62 69
        if (preg_match(self::$parameterExpression, $typeHint, $match)) {
63 69
            [$_, $type, $parameterName] = $match;
64 69
            $this->parameters[$parameterName] = TypeDeclaration::from($type);
65
        }
66 69
    }
67
}
68