Skip to content

Commit 465c341

Browse files
committed
Fixed issues related to jq clearing te composer.json when adding composer autoloads
1 parent 57b05dc commit 465c341

File tree

1 file changed

+41
-20
lines changed

1 file changed

+41
-20
lines changed

src/PHP/ComposerAutoload.php

Lines changed: 41 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -6,16 +6,14 @@
66

77
use Kiboko\Component\Dockerfile\Dockerfile;
88

9-
final class ComposerAutoload implements Dockerfile\LayerInterface
9+
final readonly class ComposerAutoload implements Dockerfile\LayerInterface, \Stringable
1010
{
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+
) {
1917
}
2018

2119
private static function command(string ...$command): string
@@ -50,22 +48,45 @@ private static function pipe(string ...$commands): string
5048
return implode(' | ', $commands);
5149
}
5250

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
5457
{
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)
6082
)
61-
}, array_keys($this->autoloads), array_values($this->autoloads)));
83+
);
6284

63-
$d = $commands;
6485
return (string) new Dockerfile\Run(
6586
<<<RUN
66-
set -ex \\
67-
&& {$commands}
68-
RUN
87+
set -ex \\
88+
&& {$commands}
89+
RUN
6990
);
7091
}
7192
}

0 commit comments

Comments
 (0)