ExpectationAnnotationParser::__construct()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 1
nc 1
nop 1
dl 0
loc 3
rs 10
c 0
b 0
f 0
1
<?php
2
3
/**
4
 * This file is part of phiremock-codeception-extension.
5
 *
6
 * phiremock-codeception-extension is free software: you can redistribute it and/or modify
7
 * it under the terms of the GNU Lesser General Public License as published by
8
 * the Free Software Foundation, either version 3 of the License, or
9
 * (at your option) any later version.
10
 *
11
 * phiremock-codeception-extension is distributed in the hope that it will be useful,
12
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14
 * GNU General Public License for more details.
15
 *
16
 * You should have received a copy of the GNU General Public License
17
 * along with phiremock-codeception-extension.  If not, see <http://www.gnu.org/licenses/>.
18
 */
19
20
namespace Mcustiel\Phiremock\Codeception\Util;
21
22
use Codeception\Exception\ParseException;
23
use Codeception\Test\Cest;
24
use Codeception\TestInterface;
25
use Codeception\Util\Annotation;
26
27
class ExpectationAnnotationParser
28
{
29
    /** @var string */
30
    private $expectationsPath;
31
32
    public function __construct(string $expectationsPath)
33
    {
34
        $this->expectationsPath = $expectationsPath;
35
    }
36
37
    /**
38
     * @param TestInterface|Cest $test
39
     *
40
     * @return array
41
     */
42
    public function getExpectations(TestInterface $test): array
43
    {
44
        if (!$test instanceof Cest) {
45
            return [];
46
        }
47
        $expectations = Annotation::forMethod(
48
            $test->getTestInstance(),
49
            $test->getTestMethod()
50
        )->fetchAll('expectation');
51
52
        return array_map([$this, 'parseExpectation'], $expectations);
53
    }
54
55
    /** @throws ParseException */
56
    public function parseExpectation(string $expectationAnnotation): string
57
    {
58
        $matches = [];
59
        $expectationRegex = '/\(?\"?(?<filePath>[a-zA-Z0-9_\\/]+)(.json)?\"?\)?/';
60
        preg_match($expectationRegex, $expectationAnnotation, $matches);
61
62
        if (empty($matches)) {
63
            throw new ParseException("The 'expectation' annotation could not be parsed (found: '$expectationAnnotation')");
64
        }
65
66
        $expectationPath = $this->getExpectationFullPath("{$matches['filePath']}.json");
67
        if (!file_exists($expectationPath)) {
68
            throw new ParseException("The expectation at $expectationPath could not be found ");
69
        }
70
71
        return $expectationPath;
72
    }
73
74
    private function getExpectationFullPath($path): string
75
    {
76
        return sprintf('%s/%s', $this->expectationsPath, $path);
77
    }
78
}
79