Skip to content

Commit

Permalink
Merge pull request #16 from nadar/array-file-input
Browse files Browse the repository at this point in the history
allow input from array
  • Loading branch information
nadar authored Nov 30, 2024
2 parents 9e3b684 + 4708ac9 commit 35d379a
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 2 deletions.
25 changes: 23 additions & 2 deletions src/ComposerReader.php
Original file line number Diff line number Diff line change
Expand Up @@ -18,17 +18,26 @@ class ComposerReader implements ComposerReaderInterface
*
* @param string $file The path to the composer.json file.
*/
public function __construct(public $file)
public function __construct(public string|array $file)
{
}

protected function isProvidedAsJsonArray(): bool
{
return is_array($this->file);
}

/**
* Whether current composer.json file is readable or not.
*
* @return boolean Whether current composer.json file is readable or not.
*/
public function canRead(): bool
{
if ($this->isProvidedAsJsonArray()) {
return true;
}

return is_file($this->file) && is_readable($this->file);
}

Expand All @@ -39,6 +48,10 @@ public function canRead(): bool
*/
public function canWrite(): bool
{
if ($this->isProvidedAsJsonArray()) {
return false;
}

return is_file($this->file) && is_writable($this->file);
}

Expand All @@ -60,8 +73,12 @@ public function canReadAndWrite()
* @throws Exception
* @return array The composer.json file as array.
*/
public function getContent()
public function getContent(): array
{
if ($this->isProvidedAsJsonArray()) {
return $this->file;
}

if ($this->_content === null) {
if (!$this->canRead()) {
throw new Exception(sprintf("Unable to read config file '%s'.", $this->file));
Expand All @@ -83,6 +100,10 @@ public function getContent()
*/
public function writeContent(array $content)
{
if ($this->isProvidedAsJsonArray()) {
throw new Exception("Unable to write content as file is provided as array.");
}

if (!$this->canWrite()) {
throw new Exception(sprintf("Unable to write config file '%s'.", $this->file));
}
Expand Down
12 changes: 12 additions & 0 deletions tests/ComposerReaderTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -129,4 +129,16 @@ public function testWriteContentException()
$this->expectException('\Exception');
$reader->writeContent(['foo' => 'bar']);
}

public function testUseArrayInputAsContent()
{
$json = $this->getValidJson();
$array = json_decode(file_get_contents($json), true);

$reader = new ComposerReader($array);
$this->assertTrue($reader->canRead());
$this->assertFalse($reader->canWrite());
$this->assertFalse($reader->canReadAndWrite());
$this->assertArrayHasKey('name', $reader->getContent());
}
}

0 comments on commit 35d379a

Please sign in to comment.