Skip to content

Commit

Permalink
Refactor Json class constructor and file handling
Browse files Browse the repository at this point in the history
  • Loading branch information
ewilan-riviere committed Nov 26, 2023
1 parent c1c7b7f commit 4debbfc
Showing 1 changed file with 16 additions and 22 deletions.
38 changes: 16 additions & 22 deletions src/Utils/Json.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@

namespace Kiwilan\Steward\Utils;

use Illuminate\Support\Facades\File;
use Kiwilan\HttpPool\Utils\PrintConsole;

class Json
Expand All @@ -17,28 +16,20 @@ class Json
public function __construct(
readonly protected mixed $data,
) {
if (is_file($this->data)) {
$this->path = $this->data;
$this->contents = file_get_contents($this->data);
} elseif (is_string($this->data)) {
$this->contents = json_decode($this->data, true);
} else {
if (is_array($data)) {
$this->contents = $this->data;
} elseif (is_string($data)) {
if (file_exists($data)) {
$this->path = $data;
$this->contents = file_get_contents($data);
} else {
$this->contents = json_decode($data, true);
}
} else {
$this->contents = $data;
}
}

public function load(string $path): mixed
{
$this->path = $path;
$this->contents = file_get_contents($path);

if (! $this->contents) {
$this->contents = [];
}

return $this->contents;
}

/**
* @return string Pretty json string
*/
Expand All @@ -55,11 +46,14 @@ public function save(string $saveTo, bool $console = true): void
{
$pretty = $this->pretty();

if (! is_dir($saveTo)) {
mkdir($saveTo, recursive: true);
if (file_exists($saveTo)) {
unlink($saveTo);
}

if (! is_dir(dirname($saveTo))) {
mkdir(dirname($saveTo), recursive: true);
}

unlink($saveTo);
file_put_contents($saveTo, $pretty);

if ($console) {
Expand Down

0 comments on commit 4debbfc

Please sign in to comment.