Passed
Push — master ( 178b22...96b0ca )
by Mariano
04:20
created

ExpectationAnnotationParser   A

Complexity

Total Complexity 7

Size/Duplication

Total Lines 47
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
eloc 17
dl 0
loc 47
rs 10
c 0
b 0
f 0
wmc 7

4 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 3 1
A getExpectationFullPath() 0 3 1
A parseExpectation() 0 16 3
A getExpectations() 0 8 2
1
<?php
2
3
namespace Mcustiel\Phiremock\Codeception\Util;
4
5
use Codeception\Exception\ParseException;
6
use Codeception\Test\Cest;
7
use Codeception\TestInterface;
8
use Codeception\Util\Annotation;
9
10
class ExpectationAnnotationParser
11
{
12
    /** @var string */
13
    private $expectationsPath;
14
15
    public function __construct(string $expectationsPath)
16
    {
17
        $this->expectationsPath = $expectationsPath;
18
    }
19
20
    /**
21
     * @param TestInterface|Cest $test
22
     *
23
     * @return array
24
     */
25
    public function getExpectations(TestInterface $test): array
26
    {
27
        if (!$test instanceof Cest) {
28
            return [];
29
        }
30
        $expectations = Annotation::forMethod($test->getTestClass(), $test->getTestMethod())->fetchAll('expectation');
31
32
        return array_map([$this, 'parseExpectation'], $expectations);
33
    }
34
35
    /** @throws ParseException */
36
    public function parseExpectation(string $expectationAnnotation): string
37
    {
38
        $matches = [];
39
        $expectationRegex = '/\(?\"?(?<filePath>[a-zA-Z0-9_\\/]+)(.json)?\"?\)?/';
40
        preg_match($expectationRegex, $expectationAnnotation, $matches);
41
42
        if (empty($matches)) {
43
            throw new ParseException("The 'expectation' annotation could not be parsed (found: '$expectationAnnotation')");
44
        }
45
46
        $expectationPath = $this->getExpectationFullPath("{$matches['filePath']}.json");
47
        if (!file_exists($expectationPath)) {
48
            throw new ParseException("The expectation at $expectationPath could not be found ");
49
        }
50
51
        return $expectationPath;
52
    }
53
54
    private function getExpectationFullPath($path): string
55
    {
56
        return sprintf('%s/%s', $this->expectationsPath, $path);
57
    }
58
}
59