Skip to content

Commit

Permalink
Added support for creating file on read and appending items to empty …
Browse files Browse the repository at this point in the history
…array
  • Loading branch information
jaxwilko committed Nov 23, 2021
1 parent cc439eb commit 71765a8
Showing 1 changed file with 19 additions and 4 deletions.
23 changes: 19 additions & 4 deletions src/Config/ConfigFile.php
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
<?php namespace Winter\Storm\Config;

use PhpParser\Node\Expr\ArrayItem;
use Winter\Storm\Config\ConfigFileInterface;
use PhpParser\Error;
use PhpParser\Node\Arg;
Expand Down Expand Up @@ -53,12 +54,18 @@ public function __construct(array $ast, string $file = null, PrettyPrinterAbstra
* Return a new instance of `ConfigFile` ready for modification of the file.
*
* @param string $file
* @param bool $createMissing
* @return ConfigFile|null
*/
public static function read(string $file): ?ConfigFile
public static function read(string $file, bool $createMissing = false): ?ConfigFile
{
if (!file_exists($file)) {
throw new \InvalidArgumentException('file not found');
if (!$createMissing) {
throw new \InvalidArgumentException('file not found');
}

// create the file with an empty array
file_put_contents($file, sprintf('<?php%1$s%1$sreturn [];%1$s', PHP_EOL));
}

$content = file_get_contents($file);
Expand Down Expand Up @@ -103,9 +110,17 @@ public function set($key, $value = null): ConfigFile
throw new ApplicationException('You must specify a value to set for the given key.');
}

$target = $this->seek(explode('.', $key), $this->ast[0]->expr->items);

$valueType = gettype($value);

if (!count($this->ast[0]->expr->items)) {
$this->ast[0]->expr->items[] = new ArrayItem(
$this->makeAstNode($valueType, $value),
$this->makeAstNode(gettype($key), $key)
);
return $this;
}

$target = $this->seek(explode('.', $key), $this->ast[0]->expr->items);
$class = get_class($target->value);

if ($class === FuncCall::class) {
Expand Down

0 comments on commit 71765a8

Please sign in to comment.