Skip to content

Commit

Permalink
feat: Enhance ComposerReader to accept string or array input and upda…
Browse files Browse the repository at this point in the history
…te read/write logic
  • Loading branch information
nadar committed Nov 30, 2024
1 parent 9e3b684 commit f9a4ea1
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 2 deletions.
24 changes: 22 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,9 @@ 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 +72,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 +99,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 f9a4ea1

Please sign in to comment.