CollisionHandler   A
last analyzed

Complexity

Total Complexity 7

Size/Duplication

Total Lines 35
Duplicated Lines 0 %

Importance

Changes 2
Bugs 1 Features 0
Metric Value
eloc 13
c 2
b 1
f 0
dl 0
loc 35
rs 10
wmc 7

4 Methods

Rating   Name   Duplication   Size   Complexity  
A appendFile() 0 3 1
A mergeJson() 0 7 1
A handle() 0 11 3
A __construct() 0 3 2
1
<?php
2
3
/*
4
 * This file is part of the PHINT package.
5
 *
6
 * (c) Jitendra Adhikari <[email protected]>
7
 *     <https://github.com/adhocore>
8
 *
9
 * Licensed under MIT license.
10
 */
11
12
namespace Ahc\Phint\Generator;
13
14
use Ahc\Phint\Util\Arr;
15
use Ahc\Phint\Util\Path;
16
17
class CollisionHandler implements CollisionHandlerInterface
18
{
19
    public function __construct(Path $pathUtil = null)
20
    {
21
        $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...
22
    }
23
24
    /**
25
     * {@inheritdoc}
26
     */
27
    public function handle(string $targetFile, string $newContent, array $parameters = null): bool
28
    {
29
        switch ($this->pathUtil->getExtension($targetFile)) {
30
            case 'json':
31
                return $this->mergeJson($targetFile, $newContent);
32
33
            case 'md':
34
                return $this->appendFile($targetFile, "\n---\n" . $newContent);
35
        }
36
37
        return false;
38
    }
39
40
    protected function mergeJson(string $targetFile, string $newContent): bool
41
    {
42
        $oldJson = $this->pathUtil->readAsJson($targetFile);
43
        $newJson = \json_decode($newContent, true);
44
        $merged  = Arr::mergeRecursive($oldJson, $newJson);
45
46
        return $this->pathUtil->writeFile($targetFile, $merged);
47
    }
48
49
    protected function appendFile(string $targetFile, string $newContent): bool
50
    {
51
        return $this->pathUtil->writeFile($targetFile, $newContent, \FILE_APPEND);
52
    }
53
}
54