1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
declare(strict_types = 1); |
4
|
|
|
|
5
|
|
|
namespace hanneskod\readmetester; |
6
|
|
|
|
7
|
|
|
use hanneskod\readmetester\Expectation\ExpectationFactory; |
8
|
|
|
|
9
|
|
|
/** |
10
|
|
|
* Create Examples objects from Definitions |
11
|
|
|
*/ |
12
|
|
|
class ExampleFactory |
13
|
|
|
{ |
14
|
|
|
/** |
15
|
|
|
* @var ExpectationFactory |
16
|
|
|
*/ |
17
|
|
|
private $expectationFactory; |
18
|
|
|
|
19
|
|
|
public function __construct(ExpectationFactory $expectationFactory) |
20
|
|
|
{ |
21
|
|
|
$this->expectationFactory = $expectationFactory; |
22
|
|
|
} |
23
|
|
|
|
24
|
|
|
/** |
25
|
|
|
* Create examples from definitions |
26
|
|
|
* |
27
|
|
|
* @return Example[] |
28
|
|
|
*/ |
29
|
|
|
public function createExamples(Definition ...$defs): array |
30
|
|
|
{ |
31
|
|
|
$examples = []; |
32
|
|
|
$context = null; |
33
|
|
|
|
34
|
|
|
foreach ($defs as $index => $def) { |
35
|
|
|
$name = (string)($index + 1); |
36
|
|
|
$code = $def->getCodeBlock(); |
37
|
|
|
$expectations = []; |
38
|
|
|
|
39
|
|
|
if ($context) { |
40
|
|
|
$code = $code->prepend($context); |
41
|
|
|
} |
42
|
|
|
|
43
|
|
|
foreach ($def->getAnnotations() as $annotation) { |
44
|
|
|
if ($annotation->isNamed('ignore')) { |
45
|
|
|
continue 2; |
46
|
|
|
} |
47
|
|
|
|
48
|
|
|
if ($annotation->isNamed('example')) { |
49
|
|
|
$name = $annotation->getArgument(); |
50
|
|
|
continue; |
51
|
|
|
} |
52
|
|
|
|
53
|
|
|
if ($annotation->isNamed('include')) { |
54
|
|
|
$toInclude = $annotation->getArgument(); |
55
|
|
|
|
56
|
|
|
if (!isset($examples[$toInclude])) { |
57
|
|
|
throw new \RuntimeException( |
58
|
|
|
"Example '$toInclude' does not exist and can not be included in definition ".($index + 1) |
59
|
|
|
); |
60
|
|
|
} |
61
|
|
|
|
62
|
|
|
$code = $code->prepend($examples[$toInclude]->getCodeBlock()); |
63
|
|
|
continue; |
64
|
|
|
} |
65
|
|
|
|
66
|
|
|
if ($expectation = $this->expectationFactory->createExpectation($annotation)) { |
67
|
|
|
$expectations[] = $expectation; |
68
|
|
|
continue; |
69
|
|
|
} |
70
|
|
|
|
71
|
|
|
if ($annotation->isNamed('exampleContext')) { |
72
|
|
|
$context = $code; |
73
|
|
|
continue; |
74
|
|
|
} |
75
|
|
|
|
76
|
|
|
throw new \RuntimeException("Unknown annotation @{$annotation->getName()}"); |
77
|
|
|
} |
78
|
|
|
|
79
|
|
|
if (empty($expectations)) { |
80
|
|
|
$expectations[] = $this->expectationFactory->createExpectation(new Annotation('expectNothing')); |
81
|
|
|
} |
82
|
|
|
|
83
|
|
|
if (isset($examples[$name])) { |
84
|
|
|
throw new \RuntimeException("Example '$name' already exists in definition ".($index + 1)); |
85
|
|
|
} |
86
|
|
|
|
87
|
|
|
$examples[$name] = new Example($name, $code, $expectations); |
88
|
|
|
} |
89
|
|
|
|
90
|
|
|
return $examples; |
91
|
|
|
} |
92
|
|
|
} |
93
|
|
|
|