Passed
Pull Request — master (#23)
by Dmitrij
02:57
created

AddJs   A

Complexity

Total Complexity 4

Size/Duplication

Total Lines 33
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
wmc 4
dl 0
loc 33
rs 10
c 0
b 0
f 0

3 Methods

Rating   Name   Duplication   Size   Complexity  
A addJs() 0 8 1
A __construct() 0 4 1
A handle() 0 9 2
1
<?php
2
3
namespace HotRodCli\Jobs\Js;
4
5
use HotRodCli\AppContainer;
6
use Symfony\Component\Filesystem\Filesystem;
7
8
class AddJs
9
{
10
    protected $container;
11
12
    /** @var Filesystem  */
13
    protected $filesystem;
14
15
    public function __construct(AppContainer $appContainer)
16
    {
17
        $this->container = $appContainer;
18
        $this->filesystem = $this->container->resolve(Filesystem::class);
19
    }
20
21
    public function handle(string $file, string $name, string $jsFile)
22
    {
23
        if (!$this->filesystem->exists($file)) {
24
            throw new \Exception('no such file');
25
        }
26
27
        $this->addJs($file, [
28
            'name' => $name,
29
            'js' => $jsFile
30
        ]);
31
    }
32
33
    protected function addJs(string $file, array $data)
34
    {
35
        $content = file_get_contents($file);
36
        preg_match('/=\s?((?:\r|\n|.)+(}))/', $content, $matches);
37
        $array = json_decode($matches[1], true);
38
        $array['*'][$data['name']] = $data['js'];
39
        $content = preg_replace('/=\s?((?:\r|\n|.)+(}))/', '= ' . json_encode($array, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES), $content);
40
        file_put_contents($file, $content);
41
    }
42
}
43