Test Failed
Push — master ( bdaab5...176ee2 )
by Vladimir
06:36
created

Assets   A

Complexity

Total Complexity 7

Size/Duplication

Total Lines 81
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 2

Importance

Changes 0
Metric Value
dl 0
loc 81
rs 10
c 0
b 0
f 0
wmc 7
lcom 1
cbo 2

3 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 4 1
A all() 0 18 2
B discover() 0 40 4
1
<?php
2
3
declare(strict_types=1);
4
5
namespace FondBot\Foundation;
6
7
use League\Flysystem\Filesystem;
8
9
class Assets
10
{
11
    public const TYPE_DRIVER = 'driver';
12
13
    private $filesystem;
14
15
    public function __construct(Filesystem $filesystem)
16
    {
17
        $this->filesystem = $filesystem;
18
    }
19
20
    /**
21
     * Get all assets.
22
     *
23
     * @param string|null $type
24
     *
25
     * @return array
26
     */
27
    public function all(string $type = null): array
28
    {
29
        $file = resolve('bootstrap_path').'/assets.json';
30
31
        $contents = $this->filesystem->get($file)->read();
32
        $assets = json_decode($contents, true);
33
34
        if ($type !== null) {
35
            return collect($assets)
36
                ->filter(function ($_, $key) use ($type) {
37
                    return $key === $type;
38
                })
39
                ->flatten()
40
                ->toArray();
41
        }
42
43
        return $assets;
44
    }
45
46
    /**
47
     * Discover assets.
48
     */
49
    public function discover(): void
50
    {
51
        $file = resolve('bootstrap_path').'/assets.json';
52
53
        // Flush cached assets
54
        if ($this->filesystem->has($file)) {
55
            $this->filesystem->delete($file);
56
        }
57
58
        $files = $this->filesystem->listContents('vendor', true);
59
60
        // Find all composer.json files
61
        // Then find suitable assets
62
        $assets = [];
63
64
        collect($files)
65
            ->filter(function (array $file) {
66
                return $file['type'] === 'file' && $file['basename'] === 'composer.json';
67
            })
68
            ->transform(function ($file) {
69
                $contents = $this->filesystem->get($file['path'])->read();
70
                $manifest = json_decode($contents, true);
71
72
                if (isset($manifest['extra'], $manifest['extra']['fondbot'])) {
73
                    return $manifest['extra']['fondbot'];
74
                }
75
76
                return null;
77
            })
78
            ->filter(function ($item) {
79
                return $item !== null;
80
            })
81
            ->each(function ($item) use (&$assets) {
82
                $type = key($item);
83
84
                $assets[$type][] = $item[$type];
85
            });
86
87
        $this->filesystem->put($file, json_encode($assets));
88
    }
89
}
90