Completed
Push — master ( 476032...586917 )
by Dmitrij
9s
created

AddMageInit::addInit()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 8
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 8
rs 9.4285
c 0
b 0
f 0
cc 1
eloc 6
nc 1
nop 2
1
<?php
2
3
namespace HotRodCli\Jobs\Js;
4
5
use HotRodCli\AppContainer;
6
use Symfony\Component\Filesystem\Filesystem;
7
8
class AddMageInit
9
{
10
    protected $scriptTags = [
11
        'open' => '<script type="text/x-magento-init">',
12
        'close' => '</script>'
13
    ];
14
15
    protected $container;
16
17
    /** @var Filesystem  */
18
    protected $filesystem;
19
20
    public function __construct(AppContainer $appContainer)
21
    {
22
        $this->container = $appContainer;
23
        $this->filesystem = $this->container->resolve(Filesystem::class);
24
    }
25
26
    public function handle(string $file, array $data)
27
    {
28
        if (!$this->filesystem->exists($file)) {
29
            throw new \Exception('no such file');
30
        }
31
32
        $this->addInit($file, [
33
            'name' => $data['name'],
34
            'bind' => $data['bind'] ?? '*'
35
        ]);
36
    }
37
38
    protected function addInit($file, array $data)
39
    {
40
        $content = file_get_contents($file);
41
        $array = [];
42
        $array[$data['bind']][$data['name']]['text'] = 'HELLO WORLD';
43
        $content .= PHP_EOL . PHP_EOL. $this->scriptTags['open'] . PHP_EOL .
44
            json_encode($array, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES) . PHP_EOL . $this->scriptTags['close'] . PHP_EOL;
45
        file_put_contents($file, $content);
46
    }
47
}
48