Manifest::__construct()   A
last analyzed

Complexity

Conditions 2
Paths 2

Size

Total Lines 8

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 6

Importance

Changes 0
Metric Value
dl 0
loc 8
ccs 0
cts 7
cp 0
rs 10
c 0
b 0
f 0
cc 2
nc 2
nop 1
crap 6
1
<?php
2
/**
3
 * This file is part of Railt package.
4
 *
5
 * For the full copyright and license information, please view the LICENSE
6
 * file that was distributed with this source code.
7
 */
8
declare(strict_types=1);
9
10
namespace Railt\Console;
11
12
use Composer\Composer;
13
use Composer\Package\RootPackageInterface;
14
use Composer\Script\Event;
15
16
/**
17
 * Class Manifest
18
 */
19
class Manifest implements \JsonSerializable
20
{
21
    /**
22
     * @var array
23
     */
24
    private $manifest;
25
26
    /**
27
     * Composer constructor.
28
     * @param Composer $app
29
     */
30
    public function __construct(Composer $app)
31
    {
32
        $this->manifest = $this->loadRootExtras($app->getPackage());
33
34
        foreach ($this->loadDependencyExtras($app) as $extra) {
35
            $this->manifest = \array_merge_recursive($this->manifest, $extra);
36
        }
37
    }
38
39
    /**
40
     * @param Composer $app
41
     * @return iterable
42
     * @throws \InvalidArgumentException
43
     */
44
    private function loadDependencyExtras(Composer $app): iterable
45
    {
46
        $manager    = $app->getInstallationManager();
47
        $repository = $app->getRepositoryManager()->getLocalRepository();
48
49
        foreach ($repository->getPackages() as $package) {
50
            if ($manager->isPackageInstalled($repository, $package)) {
51
                $path = $manager->getInstallPath($package) . '/composer.json';
52
53
                yield $this->readExtra(\json_decode(\file_get_contents($path), true));
54
            }
55
        }
56
    }
57
58
    /**
59
     * @param array $dep
60
     * @return array
61
     */
62
    private function readExtra(array $dep): array
63
    {
64
        return $dep['extra']['railt'] ?? [];
65
    }
66
67
    /**
68
     * @return array
69
     */
70
    public function jsonSerialize(): array
71
    {
72
        return $this->manifest;
73
    }
74
75
    /**
76
     * @param RootPackageInterface $app
77
     * @return array
78
     */
79
    private function loadRootExtras(RootPackageInterface $app): array
80
    {
81
        return (array)($app->getExtra()['railt'] ?? []);
82
    }
83
84
    /**
85
     * @param Event $event
86
     * @throws \InvalidArgumentException
87
     * @throws \RuntimeException
88
     */
89
    public static function discover(Event $event): void
90
    {
91
        $composer = $event->getComposer();
92
        $manifest = new static($composer);
93
94
        $dir = $composer->getConfig()->get('bin-dir');
95
96
        \file_put_contents($dir . '/railt.json', \json_encode($manifest));
97
    }
98
}
99