Passed
Push — master ( 635436...706b38 )
by Jonathan
01:30
created

ConfigHashReplacer::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 5
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 4
CRAP Score 1

Importance

Changes 0
Metric Value
dl 0
loc 5
ccs 4
cts 4
cp 1
rs 9.4285
c 0
b 0
f 0
cc 1
eloc 3
nc 1
nop 2
crap 1
1
<?php
2
namespace Spekkionu\Assetcachebuster\HashReplacer;
3
4
use Spekkionu\Assetcachebuster\Writer\WriterInterface;
5
use Spekkionu\Assetcachebuster\Assetcachebuster as CacheBuster;
6
7
class ConfigHashReplacer implements HashReplacerInterface
8
{
9
    /**
10
     * @var WriterInterface
11
     */
12
    private $writer;
13
14
    /**
15
     * @var CacheBuster
16
     */
17
    private $cacheBuster;
18
19
    /**
20
     * HashReplacer constructor.
21
     * @param CacheBuster $cacheBuster
22
     * @param WriterInterface $writer
23
     */
24 2
    public function __construct(CacheBuster $cacheBuster, WriterInterface $writer)
25
    {
26 2
        $this->writer = $writer;
27 2
        $this->cacheBuster = $cacheBuster;
28 2
    }
29
30
    /**
31
     * Generate and save new hash
32
     * @return string New Hash
33
     * @throws \Exception
34
     */
35 2
    public function replaceHash()
36
    {
37 2
        $currentHash = $this->cacheBuster->getHash();
38 2
        $hash = $this->cacheBuster->generateHash();
39 2
        $this->writeHash($currentHash, $hash);
40 1
        $this->cacheBuster->setHash($hash);
41 1
        return $hash;
42
    }
43
44
    /**
45
     * @return string New hash
46
     * @throws \Exception
47
     */
48 2
    public function writeHash($currentHash, $hash)
49
    {
50 2
        $content = $this->writer->getCurrentConfig();
51 2
        $content = preg_replace(
52 2
            "/([\'\"]hash[\'\"].+?[\'\"])(" . preg_quote($currentHash, '/') . ")([\'\"].*)/",
53 2
            "'hash' => '" . $hash . "',",
54 2
            $content,
55 2
            1,
56 2
            $count
57
        );
58 2
        if ($count != 1) {
59 1
            throw new \RuntimeException("Could not find current hash key in config.");
60
        }
61
62 1
        $this->writer->setCurrentConfig($content);
63 1
        return $hash;
64
    }
65
}
66