|
| 1 | +<?php |
| 2 | + |
| 3 | +/* |
| 4 | + * This file is part of the API Platform project. |
| 5 | + * |
| 6 | + * (c) Kévin Dunglas <[email protected]> |
| 7 | + * |
| 8 | + * For the full copyright and license information, please view the LICENSE |
| 9 | + * file that was distributed with this source code. |
| 10 | + */ |
| 11 | + |
| 12 | +declare(strict_types=1); |
| 13 | + |
| 14 | +use Behat\Behat\Context\Context; |
| 15 | +use Behat\Behat\Context\Environment\InitializedContextEnvironment; |
| 16 | +use Behat\Behat\Hook\Scope\BeforeScenarioScope; |
| 17 | +use Behatch\Context\RestContext; |
| 18 | +use Behatch\Json\Json; |
| 19 | +use JsonSchema\Validator; |
| 20 | +use PHPUnit\Framework\ExpectationFailedException; |
| 21 | + |
| 22 | +final class JsonHalContext implements Context |
| 23 | +{ |
| 24 | + /** |
| 25 | + * @var RestContext |
| 26 | + */ |
| 27 | + private $restContext; |
| 28 | + private $validator; |
| 29 | + private $schemaFile; |
| 30 | + |
| 31 | + public function __construct(string $schemaFile) |
| 32 | + { |
| 33 | + if (!is_file($schemaFile)) { |
| 34 | + throw new \InvalidArgumentException('The JSON HAL schema doesn\'t exist.'); |
| 35 | + } |
| 36 | + |
| 37 | + $this->validator = new Validator(); |
| 38 | + $this->schemaFile = $schemaFile; |
| 39 | + } |
| 40 | + |
| 41 | + /** |
| 42 | + * Gives access to the Behatch context. |
| 43 | + * |
| 44 | + * @BeforeScenario |
| 45 | + */ |
| 46 | + public function gatherContexts(BeforeScenarioScope $scope) |
| 47 | + { |
| 48 | + /** @var InitializedContextEnvironment $environment */ |
| 49 | + $environment = $scope->getEnvironment(); |
| 50 | + $this->restContext = $environment->getContext(RestContext::class); |
| 51 | + } |
| 52 | + |
| 53 | + /** |
| 54 | + * @Then the JSON should be valid according to the JSON HAL schema |
| 55 | + */ |
| 56 | + public function theJsonShouldBeValidAccordingToTheJsonHALSchema() |
| 57 | + { |
| 58 | + $json = $this->getJson()->getContent(); |
| 59 | + $this->validator->validate($json, (object) ['$ref' => 'file://'.__DIR__.'/../../'.$this->schemaFile]); |
| 60 | + |
| 61 | + if (!$this->validator->isValid()) { |
| 62 | + throw new ExpectationFailedException(sprintf('The JSON is not valid according to the HAL+JSON schema.')); |
| 63 | + } |
| 64 | + } |
| 65 | + |
| 66 | + private function getJson() |
| 67 | + { |
| 68 | + return new Json($this->getContent()); |
| 69 | + } |
| 70 | + |
| 71 | + private function getContent() |
| 72 | + { |
| 73 | + return $this->restContext->getMink()->getSession()->getDriver()->getContent(); |
| 74 | + } |
| 75 | +} |
0 commit comments