Completed
Push — master ( 279d4e...5d09e0 )
by Elf
02:49
created

AssetsVersion::revisionAssets()   B

Complexity

Conditions 5
Paths 2

Size

Total Lines 25
Code Lines 14

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 30

Importance

Changes 0
Metric Value
cc 5
eloc 14
nc 2
nop 1
dl 0
loc 25
ccs 0
cts 20
cp 0
crap 30
rs 8.439
c 0
b 0
f 0
1
<?php
2
3
namespace ElfSundae\Laravel\Support\Console\Commands;
4
5
use Illuminate\Console\Command;
6
7
class AssetsVersion extends Command
8
{
9
    /**
10
     * The name and signature of the console command.
11
     *
12
     * @var string
13
     */
14
    protected $signature = 'assets:version {--config=assets : The filename of the assets configuration}';
15
16
    /**
17
     * The console command description.
18
     *
19
     * @var string
20
     */
21
    protected $description = 'Update assets version configuration';
22
23
    /**
24
     * Execute the console command.
25
     *
26
     * @return mixed
27
     */
28
    public function handle()
29
    {
30
        $config = (string) $this->option('config');
31
32
        $assets = $this->laravel['config']->get($config);
33
34
        $revisioned = $this->revisionAssets($assets);
35
36
        if ($assets !== $revisioned) {
37
            $this->updateAssetsConfigFile($config, $revisioned);
38
39
            $this->laravel['config'][$config] = $revisioned;
40
        }
41
42
        $this->info('Assets configuration '.(is_null($assets) ? 'created!' : 'updated!'));
43
    }
44
45
    /**
46
     * Revision assets.
47
     *
48
     * @param  array|null  $assets
49
     * @return array
50
     */
51
    protected function revisionAssets($assets)
52
    {
53
        $newAssets = [];
54
55
        if (is_array($assets)) {
56
            foreach ($assets as $file => $value) {
57
                if (is_numeric($file)) {
58
                    $file = $value;
59
                    $value = '0';
60
                }
61
62
                $path = public_path($file);
63
64
                if (is_file($path)) {
65
                    $value = substr(md5_file($path), 0, 10);
66
                } else {
67
                    $this->error("Revisioning file [{$file}] failed.");
68
                }
69
70
                $newAssets[$file] = $value;
71
            }
72
        }
73
74
        return $newAssets;
75
    }
76
77
    /**
78
     * Update assets config file.
79
     *
80
     * @param  string  $config
81
     * @param  mixed  $assets
82
     */
83
    protected function updateAssetsConfigFile($config, $assets)
84
    {
85
        file_put_contents(
86
            config_path($config.'.php'),
87
            sprintf("<?php\n\nreturn %s;\n", var_export($assets, true))
88
        );
89
    }
90
}
91