Completed
Push — master ( cc11ea...ef1f9a )
by Nils
02:07
created

MemoryExtension::init()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 8
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 8
rs 9.4285
cc 2
eloc 4
nc 2
nop 1
1
<?php
2
3
namespace whm\Smoke\Extensions\SmokeMemory;
4
5
use phm\HttpWebdriverClient\Http\Response\UriAwareResponse;
6
use Symfony\Component\Yaml\Yaml;
7
use whm\Html\Uri;
8
use whm\Smoke\Extensions\SmokeResponseRetriever\Retriever\CrawlingRetriever;
9
use whm\Smoke\Extensions\SmokeResponseRetriever\Retriever\Retriever;
10
use whm\Smoke\Rules\CheckResult;
11
12
class MemoryExtension
13
{
14
    private $memoryFile;
15
16
    private $memory = array();
17
    private $oldMemories = array();
18
19
    public function init($memoryFile)
20
    {
21
        $this->memoryFile = $memoryFile;
22
23
        if (file_exists($memoryFile)) {
24
            $this->oldMemories = Yaml::parse(file_get_contents($memoryFile));
25
        }
26
    }
27
28
    /**
29
     * @var CheckResult[] $results
30
     *
31
     * @Event("Scanner.Scan.Validate")
32
     */
33
    public function process($results, UriAwareResponse $response)
34
    {
35
        foreach ($results as $result) {
36
            /** @var UriAwareResponse $response */
37
            if ($result->getStatus() == CheckResult::STATUS_FAILURE) {
38
                $this->memory[] = (string)$response->getUri();
39
            }
40
        }
41
    }
42
43
    /**
44
     * @Event("Scanner.Scan.Finish")
45
     */
46
    public function finish()
47
    {
48
        $yaml = Yaml::dump($this->memory);
49
        file_put_contents($this->memoryFile, $yaml);
50
    }
51
52
53
    /**
54
     * @Event("Scanner.Init.ResponseRetriever")
55
     */
56
    public function initRetriever(Retriever $responseRetriever)
57
    {
58
        if ($responseRetriever instanceof CrawlingRetriever) {
59
            foreach ($this->oldMemories as $memory) {
60
                $responseRetriever->addPage(new Uri($memory));
61
            }
62
        } else {
63
            throw new \RuntimeException('The memory extension can only be used with a crawling retriever.');
64
        }
65
    }
66
}
67