Completed
Push — master ( f0391e...085236 )
by Jitendra
9s
created

CollisionHandler   A

Complexity

Total Complexity 7

Size/Duplication

Total Lines 35
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
eloc 14
dl 0
loc 35
rs 10
c 0
b 0
f 0
wmc 7

4 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 3 2
A mergeJson() 0 7 1
A handle() 0 10 3
A appendFile() 0 3 1
1
<?php
2
3
namespace Ahc\Phint\Generator;
4
5
use Ahc\Phint\Util\Arr;
6
use Ahc\Phint\Util\Path;
7
8
class CollisionHandler implements CollisionHandlerInterface
9
{
10
    public function __construct(Path $pathUtil = null)
11
    {
12
        $this->pathUtil = $pathUtil ?: new Path;
0 ignored issues
show
Bug Best Practice introduced by
The property pathUtil does not exist. Although not strictly required by PHP, it is generally a best practice to declare properties explicitly.
Loading history...
13
    }
14
15
    /**
16
     * {@inheritdoc}
17
     */
18
    public function handle(string $targetFile, string $newContent, array $parameters = null)
19
    {
20
        switch ($this->pathUtil->getExtension($targetFile)) {
21
            case 'json':
22
                $this->mergeJson($targetFile, $newContent);
23
                break;
24
25
            case 'md':
26
                $this->appendFile($targetFile, "\n---\n" . $newContent);
27
                break;
28
        }
29
    }
30
31
    protected function mergeJson(string $targetFile, string $newContent)
32
    {
33
        $oldJson = $this->pathUtil->readAsJson($targetFile);
34
        $newJson = \json_decode($newContent, true);
35
        $merged  = Arr::mergeRecursive($oldJson, $newJson);
36
37
        $this->pathUtil->writeFile($targetFile, $merged);
38
    }
39
40
    protected function appendFile(string $targetFile, string $newContent)
41
    {
42
        $this->pathUtil->writeFile($targetFile, $newContent, \FILE_APPEND);
43
    }
44
}
45