Skip to content

Commit

Permalink
Add static constructor for readers (#5)
Browse files Browse the repository at this point in the history
  • Loading branch information
shadowhand authored and hkarlstrom committed Mar 14, 2019
1 parent c511cc8 commit 19ec897
Show file tree
Hide file tree
Showing 3 changed files with 49 additions and 17 deletions.
19 changes: 19 additions & 0 deletions src/AbstractReader.php
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,26 @@

abstract class AbstractReader
{
/**
* @throws \Exception If the OpenAPI file is not a supported type.
*/
public static function fromFile(string $openApiFilePath): AbstractReader
{
if (preg_match('/\.json$/', $openApiFilePath) === 1) {
return new JsonReader($openApiFilePath);
}

if (preg_match('/\.ya?ml$/', $openApiFilePath) === 1) {
return new YamlReader($openApiFilePath);
}

throw new \Exception('OpenAPI file name must have .json, .yaml or .yml extension');
}

/** @var array */
protected $raw;

/** @var array */
protected $cache;

public function get($path)
Expand Down
21 changes: 4 additions & 17 deletions src/OpenApiReader.php
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@

class OpenApiReader
{
/** @var string[] */
private static $methods = [
'get',
'put',
Expand All @@ -25,27 +26,13 @@ class OpenApiReader
'patch',
'trace',
];

/** @var AbstractReader */
private $reader;

/**
* OpenApiReader constructor.
*
* @param string $openApiFilePath
*
* @throws \Exception
*/
public function __construct(string $openApiFilePath)
{
if (preg_match('/\.json$/', $openApiFilePath) === 1) {
$this->reader = new JsonReader($openApiFilePath);
return;
}
if (preg_match('/\.ya?ml$/', $openApiFilePath) === 1) {
$this->reader = new YamlReader($openApiFilePath);
return;
}

throw new \Exception('OpenAPI file name must have .json, .yaml or .yml extension');
$this->reader = AbstractReader::fromFile($openApiFilePath);
}

public function getVersion() : string
Expand Down
26 changes: 26 additions & 0 deletions tests/AbstractReaderFromFileTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
<?php
declare(strict_types=1);

namespace HKarlstrom\OpenApiReader\Tests;

use HKarlstrom\OpenApiReader\AbstractReader;
use HKarlstrom\OpenApiReader\JsonReader;
use HKarlstrom\OpenApiReader\YamlReader;
use PHPUnit\Framework\TestCase;

class AbstractReaderFromFileTest extends TestCase
{
public function testCreateFromJson(): void
{
$reader = AbstractReader::fromFile(__DIR__ . '/testopenapi.json');

$this->assertInstanceOf(JsonReader::class, $reader);
}

public function testCreateFromYaml(): void
{
$reader = AbstractReader::fromFile(__DIR__ . '/testopenapi.yaml');

$this->assertInstanceOf(YamlReader::class, $reader);
}
}

0 comments on commit 19ec897

Please sign in to comment.