diff --git a/src/ComposerReader.php b/src/ComposerReader.php index c71b1cf..9511bcb 100755 --- a/src/ComposerReader.php +++ b/src/ComposerReader.php @@ -18,10 +18,15 @@ 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. * @@ -29,6 +34,10 @@ public function __construct(public $file) */ public function canRead(): bool { + if ($this->isProvidedAsJsonArray()) { + return true; + } + return is_file($this->file) && is_readable($this->file); } @@ -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); } @@ -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)); @@ -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)); } diff --git a/tests/ComposerReaderTest.php b/tests/ComposerReaderTest.php index 2f42c7b..113f9c7 100755 --- a/tests/ComposerReaderTest.php +++ b/tests/ComposerReaderTest.php @@ -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()); + } }