|
6 | 6 |
|
7 | 7 | use Kiboko\Component\Dockerfile\Dockerfile;
|
8 | 8 |
|
9 |
| -final class ComposerAutoload implements Dockerfile\LayerInterface |
| 9 | +final readonly class ComposerAutoload implements Dockerfile\LayerInterface, \Stringable |
10 | 10 | {
|
11 |
| - /** |
12 |
| - * @param array<string, array<string, string|list<string>>> $autoloads |
13 |
| - */ |
14 |
| - private array $autoloads; |
15 |
| - |
16 |
| - public function __construct(array $autoloads) |
17 |
| - { |
18 |
| - $this->autoloads = $autoloads; |
| 11 | + public function __construct( |
| 12 | + /** |
| 13 | + * @param array<string, array<string, string|list<string>>> $autoloads |
| 14 | + */ |
| 15 | + private array $autoloads |
| 16 | + ) { |
19 | 17 | }
|
20 | 18 |
|
21 | 19 | private static function command(string ...$command): string
|
@@ -50,22 +48,45 @@ private static function pipe(string ...$commands): string
|
50 | 48 | return implode(' | ', $commands);
|
51 | 49 | }
|
52 | 50 |
|
53 |
| - public function __toString() |
| 51 | + private static function indirection(string $command, string $destination): string |
| 52 | + { |
| 53 | + return $command . ' > ' . self::escapeArgument($destination); |
| 54 | + } |
| 55 | + |
| 56 | + private static function and(string ...$commands): string |
54 | 57 | {
|
55 |
| - $commands = implode(' \\' . PHP_EOL . ' && ', array_map(fn ($type, $autoload) => match ($type) { |
56 |
| - 'psr4' => self::pipe( |
57 |
| - self::command('cat', 'composer.json'), |
58 |
| - self::command('jq', '--indent', '4', sprintf('.autoload."psr-4" |= . + %s', json_encode($autoload))), |
59 |
| - self::command('tee', 'composer.json') |
| 58 | + return implode(' \\'.\PHP_EOL.' && ', $commands); |
| 59 | + } |
| 60 | + |
| 61 | + public function __toString(): string |
| 62 | + { |
| 63 | + if (\count($this->autoloads) <= 0) { |
| 64 | + return ''; |
| 65 | + } |
| 66 | + |
| 67 | + $commands = self::and( |
| 68 | + ...array_map( |
| 69 | + fn ($type, $autoload) => match ($type) { |
| 70 | + 'psr4' => self::and( |
| 71 | + self::pipe( |
| 72 | + self::command('cat', 'composer.json'), |
| 73 | + self::command('jq', '--indent', '4', sprintf('.autoload."psr-4" |= . + %s', json_encode($autoload, \JSON_THROW_ON_ERROR))), |
| 74 | + self::command('tee', 'composer.temp') |
| 75 | + ), |
| 76 | + self::indirection(self::command('cat', 'composer.temp'), 'composer.json'), |
| 77 | + self::command('rm', 'composer.temp'), |
| 78 | + ) |
| 79 | + }, |
| 80 | + array_keys($this->autoloads), |
| 81 | + array_values($this->autoloads) |
60 | 82 | )
|
61 |
| - }, array_keys($this->autoloads), array_values($this->autoloads))); |
| 83 | + ); |
62 | 84 |
|
63 |
| - $d = $commands; |
64 | 85 | return (string) new Dockerfile\Run(
|
65 | 86 | <<<RUN
|
66 |
| - set -ex \\ |
67 |
| - && {$commands} |
68 |
| - RUN |
| 87 | + set -ex \\ |
| 88 | + && {$commands} |
| 89 | + RUN |
69 | 90 | );
|
70 | 91 | }
|
71 | 92 | }
|
0 commit comments