Skip to content

Commit 11704f2

Browse files
innocenzibrendt
andauthored
refactor(core): consistently use json and filesystem utils (#1330)
Co-authored-by: Brent Roose <[email protected]>
1 parent d30ddcf commit 11704f2

File tree

52 files changed

+823
-490
lines changed

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

52 files changed

+823
-490
lines changed

packages/command-bus/src/AsyncCommandRepositories/FileCommandRepository.php

Lines changed: 7 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@
66

77
use Tempest\CommandBus\CommandRepository;
88
use Tempest\CommandBus\Exceptions\PendingCommandCouldNotBeResolved;
9+
use Tempest\Support\Filesystem;
910

1011
use function Tempest\Support\arr;
1112

@@ -15,32 +16,30 @@ public function store(string $uuid, object $command): void
1516
{
1617
$payload = serialize($command);
1718

18-
file_put_contents(__DIR__ . "/../stored-commands/{$uuid}.pending.txt", $payload);
19+
Filesystem\write_file(__DIR__ . "/../stored-commands/{$uuid}.pending.txt", $payload);
1920
}
2021

2122
public function findPendingCommand(string $uuid): object
2223
{
2324
$path = __DIR__ . "/../stored-commands/{$uuid}.pending.txt";
2425

25-
if (! file_exists($path)) {
26+
if (! Filesystem\is_file($path)) {
2627
throw new PendingCommandCouldNotBeResolved($uuid);
2728
}
2829

29-
$payload = file_get_contents($path);
30+
$payload = Filesystem\read_file($path);
3031

3132
return unserialize($payload);
3233
}
3334

3435
public function markAsDone(string $uuid): void
3536
{
36-
$path = __DIR__ . "/../stored-commands/{$uuid}.pending.txt";
37-
38-
unlink($path);
37+
Filesystem\delete_file(__DIR__ . "/../stored-commands/{$uuid}.pending.txt");
3938
}
4039

4140
public function markAsFailed(string $uuid): void
4241
{
43-
if (! is_file(__DIR__ . "/../stored-commands/{$uuid}.pending.txt")) {
42+
if (! Filesystem\is_file(__DIR__ . "/../stored-commands/{$uuid}.pending.txt")) {
4443
return;
4544
}
4645

@@ -55,7 +54,7 @@ public function getPendingCommands(): array
5554
return arr(glob(__DIR__ . '/../stored-commands/*.pending.txt'))
5655
->mapWithKeys(function (string $path) {
5756
$uuid = str_replace('.pending.txt', '', pathinfo($path, PATHINFO_BASENAME));
58-
$payload = file_get_contents($path);
57+
$payload = Filesystem\read_file($path);
5958

6059
yield $uuid => unserialize($payload);
6160
})

packages/console/src/Components/Concerns/OpensInEditor.php

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@
77
use Tempest\Console\CanOpenInEditor;
88
use Tempest\Console\Components\ComponentState;
99
use Tempest\Console\InteractiveConsoleComponent;
10+
use Tempest\Support\Filesystem;
1011

1112
use function Tempest\env;
1213

@@ -39,14 +40,14 @@ public function openInEditor(?string $text): string
3940
$editor = $this->getEditorCommand();
4041
$tempFile = tempnam(sys_get_temp_dir(), '.TEMPEST_INPUT');
4142

42-
file_put_contents($tempFile, $text ?? '');
43+
Filesystem\write_file($tempFile, $text ?? '');
4344

4445
if (passthru(escapeshellcmd("{$editor} " . escapeshellarg($tempFile))) === false) {
4546
// TODO: failed. handle that
4647
return $text;
4748
}
4849

49-
$updatedText = file_get_contents($tempFile);
50+
$updatedText = Filesystem\read_file($tempFile);
5051
unlink($tempFile);
5152

5253
$this->setState($previousState);

packages/console/src/Exceptions/ConsoleExceptionHandler.php

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,7 @@
1616
use Tempest\Core\Kernel;
1717
use Tempest\Highlight\Escape;
1818
use Tempest\Highlight\Highlighter;
19+
use Tempest\Support\Filesystem;
1920
use Throwable;
2021

2122
use function Tempest\Support\str;
@@ -76,7 +77,7 @@ public function handle(Throwable $throwable): void
7677
private function getSnippet(string $file, int $lineNumber): string
7778
{
7879
$highlighter = $this->highlighter->withGutter();
79-
$code = Escape::terminal($highlighter->parse(file_get_contents($file), language: 'php'));
80+
$code = Escape::terminal($highlighter->parse(Filesystem\read_file($file), language: 'php'));
8081
$lines = explode(PHP_EOL, $code);
8182

8283
$lines[$lineNumber - 1] = str($lines[$lineNumber - 1])

packages/console/src/Output/LogOutputBuffer.php

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@
55
namespace Tempest\Console\Output;
66

77
use Tempest\Console\OutputBuffer;
8+
use Tempest\Support\Filesystem;
89

910
final readonly class LogOutputBuffer implements OutputBuffer
1011
{
@@ -14,14 +15,14 @@ public function __construct(
1415

1516
public function clear(): self
1617
{
17-
file_put_contents($this->path, '');
18+
Filesystem\write_file($this->path, '');
1819

1920
return $this;
2021
}
2122

2223
public function read(): string
2324
{
24-
return file_get_contents($this->path);
25+
return Filesystem\read_file($this->path);
2526
}
2627

2728
public function write(string $contents): void

packages/console/src/Scheduler/GenericScheduler.php

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@
88
use Tempest\Console\Input\ConsoleArgumentBag;
99
use Tempest\Console\Scheduler;
1010
use Tempest\Core\ShellExecutor;
11+
use Tempest\Support\Filesystem;
1112

1213
use function Tempest\event;
1314
use function Tempest\internal_storage_path;
@@ -84,11 +85,11 @@ private function getInvocationsToRun(DateTime $date): array
8485
*/
8586
private function getPreviousRuns(): array
8687
{
87-
if (! file_exists(self::getCachePath())) {
88+
if (! Filesystem\is_file(self::getCachePath())) {
8889
return [];
8990
}
9091

91-
return unserialize(file_get_contents(self::getCachePath()), ['allowed_classes' => false]);
92+
return unserialize(Filesystem\read_file(self::getCachePath()), ['allowed_classes' => false]);
9293
}
9394

9495
/** @param ScheduledInvocation[] $ranInvocations */
@@ -106,6 +107,6 @@ private function markInvocationsAsRun(array $ranInvocations, DateTime $ranAt): v
106107
mkdir(directory: $directory, recursive: true);
107108
}
108109

109-
file_put_contents(self::getCachePath(), serialize($lastRuns));
110+
Filesystem\write_file(self::getCachePath(), serialize($lastRuns));
110111
}
111112
}

packages/core/src/Composer.php

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,8 @@
44

55
namespace Tempest\Core;
66

7+
use Tempest\Support\Filesystem;
8+
use Tempest\Support\Json;
79
use Tempest\Support\Namespace\Psr4Namespace;
810

911
use function Tempest\Support\arr;
@@ -94,7 +96,7 @@ public function addNamespace(string $namespace, string $path): self
9496

9597
public function save(): self
9698
{
97-
file_put_contents($this->composerPath, json_encode($this->composer, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES));
99+
Filesystem\write_json($this->composerPath, $this->composer, pretty: true);
98100

99101
return $this;
100102
}
@@ -108,10 +110,10 @@ public function executeUpdate(): self
108110

109111
private function loadComposerFile(string $path): array
110112
{
111-
if (! file_exists($path)) {
113+
if (! Filesystem\is_file($path)) {
112114
throw new ComposerJsonCouldNotBeLocated('Could not locate composer.json.');
113115
}
114116

115-
return json_decode(file_get_contents($path), associative: true);
117+
return Filesystem\read_json($path);
116118
}
117119
}

packages/core/src/Kernel/LoadDiscoveryLocations.php

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@
88
use Tempest\Core\Kernel;
99
use Tempest\Discovery\DiscoveryLocation;
1010
use Tempest\Discovery\DiscoveryLocationCouldNotBeLoaded;
11+
use Tempest\Support\Filesystem;
1112

1213
use function Tempest\Support\Path\normalize;
1314

@@ -115,10 +116,10 @@ private function discoverVendorPackages(): array
115116

116117
private function loadJsonFile(string $path): array
117118
{
118-
if (! file_exists($path)) {
119+
if (! Filesystem\is_file($path)) {
119120
throw new DiscoveryLocationCouldNotBeLoaded($path);
120121
}
121122

122-
return json_decode(file_get_contents($path), true);
123+
return Filesystem\read_json($path);
123124
}
124125
}

packages/core/src/PublishesFiles.php

Lines changed: 10 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,8 @@
1717
use Tempest\Generation\Exceptions\FileGenerationWasAborted;
1818
use Tempest\Generation\StubFileGenerator;
1919
use Tempest\Reflection\FunctionReflector;
20+
use Tempest\Support\Filesystem;
21+
use Tempest\Support\Json;
2022
use Tempest\Support\Str\ImmutableString;
2123
use Tempest\Validation\Rules\EndsWith;
2224
use Tempest\Validation\Rules\NotEmpty;
@@ -32,9 +34,6 @@
3234
use function Tempest\Support\str;
3335
use function Tempest\Support\Str\class_basename;
3436

35-
use const JSON_PRETTY_PRINT;
36-
use const JSON_UNESCAPED_SLASHES;
37-
3837
/**
3938
* Provides a bunch of methods to publish and generate files and work with common user input.
4039
*/
@@ -129,13 +128,13 @@ public function publish(string $source, string $destination, ?Closure $callback
129128
public function publishImports(): void
130129
{
131130
foreach ($this->publishedFiles as $file) {
132-
$contents = str(file_get_contents($file));
131+
$contents = str(Filesystem\read_file($file));
133132

134133
foreach ($this->publishedClasses as $old => $new) {
135134
$contents = $contents->replace($old, $new);
136135
}
137136

138-
file_put_contents($file, $contents);
137+
Filesystem\write_file($file, $contents);
139138
}
140139
}
141140

@@ -188,7 +187,7 @@ public function promptTargetPath(string $suggestedPath, ?array $rules = null): s
188187
*/
189188
public function askForOverride(string $targetPath): bool
190189
{
191-
if (! file_exists($targetPath)) {
190+
if (! Filesystem\is_file($targetPath)) {
192191
return true;
193192
}
194193

@@ -206,15 +205,15 @@ public function askForOverride(string $targetPath): bool
206205
*/
207206
public function update(string $path, Closure $callback, bool $ignoreNonExisting = false): void
208207
{
209-
if (! is_file($path)) {
208+
if (! Filesystem\is_file($path)) {
210209
if ($ignoreNonExisting) {
211210
return;
212211
}
213212

214213
throw new Exception("The file at path [{$path}] does not exist.");
215214
}
216215

217-
$contents = file_get_contents($path);
216+
$contents = Filesystem\read_file($path);
218217

219218
$reflector = new FunctionReflector($callback);
220219
$type = $reflector->getParameters()->current()->getType();
@@ -225,7 +224,7 @@ public function update(string $path, Closure $callback, bool $ignoreNonExisting
225224
default => throw new Exception('The callback must accept a string or ImmutableString.'),
226225
};
227226

228-
file_put_contents($path, $contents);
227+
Filesystem\write_file($path, $contents);
229228
}
230229

231230
/**
@@ -242,7 +241,7 @@ public function updateJson(string $path, Closure $callback, bool $ignoreNonExist
242241
function (string $content) use ($callback) {
243242
$indent = $this->detectIndent($content);
244243

245-
$json = json_decode($content, associative: true);
244+
$json = Json\decode($content);
246245
$json = $callback($json);
247246

248247
// PHP will output empty arrays for empty dependencies,
@@ -256,7 +255,7 @@ function (string $content) use ($callback) {
256255
$content = preg_replace_callback(
257256
'/^ +/m',
258257
fn ($m) => str_repeat($indent, strlen($m[0]) / 4),
259-
json_encode($json, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES),
258+
Json\encode($json, pretty: true),
260259
);
261260

262261
return "{$content}\n";

packages/database/src/Exceptions/QueryWasInvalid.php

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@
77
use Exception;
88
use PDOException;
99
use Tempest\Database\Query;
10+
use Tempest\Support\Json;
1011

1112
final class QueryWasInvalid extends Exception
1213
{
@@ -16,7 +17,7 @@ public function __construct(Query $query, array $bindings, PDOException $previou
1617

1718
$message .= PHP_EOL . PHP_EOL . $query->toSql() . PHP_EOL;
1819

19-
$message .= PHP_EOL . 'bindings: ' . json_encode($bindings, JSON_PRETTY_PRINT);
20+
$message .= PHP_EOL . 'bindings: ' . Json\encode($bindings, pretty: true);
2021

2122
parent::__construct(
2223
message: $message,

packages/database/src/MigrationDiscovery.php

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@
1111
use Tempest\Discovery\DiscoveryLocation;
1212
use Tempest\Discovery\IsDiscovery;
1313
use Tempest\Reflection\ClassReflector;
14+
use Tempest\Support\Filesystem;
1415

1516
final class MigrationDiscovery implements Discovery, DiscoversPath
1617
{
@@ -45,7 +46,7 @@ public function discoverPath(DiscoveryLocation $location, string $path): void
4546

4647
$fileName = pathinfo($path, PATHINFO_FILENAME);
4748

48-
$contents = explode(';', file_get_contents($path));
49+
$contents = explode(';', Filesystem\read_file($path));
4950

5051
foreach ($contents as $i => $content) {
5152
if (! $content) {

0 commit comments

Comments
 (0)