Completed
Push — master ( 203341...1088a5 )
by Antoine
22s queued 13s
created

assertMatchesResourceCollectionJsonSchema()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 5
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 2
nc 1
nop 3
dl 0
loc 5
rs 10
c 0
b 0
f 0
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
namespace ApiPlatform\Core\Bridge\Symfony\Bundle\Test;
15
16
use ApiPlatform\Core\Api\OperationType;
17
use ApiPlatform\Core\Bridge\Symfony\Bundle\Test\Constraint\ArraySubset;
18
use ApiPlatform\Core\Bridge\Symfony\Bundle\Test\Constraint\MatchesJsonSchema;
19
use ApiPlatform\Core\JsonSchema\Schema;
20
use ApiPlatform\Core\JsonSchema\SchemaFactoryInterface;
21
use PHPUnit\Framework\ExpectationFailedException;
22
use Symfony\Component\DependencyInjection\Exception\ServiceNotFoundException;
23
use Symfony\Contracts\HttpClient\ResponseInterface;
24
25
/**
26
 * @see \Symfony\Bundle\FrameworkBundle\Test\WebTestAssertionsTrait
27
 *
28
 * @experimental
29
 */
30
trait ApiTestAssertionsTrait
31
{
32
    use BrowserKitAssertionsTrait;
33
34
    /**
35
     * Asserts that the retrieved JSON contains the specified subset.
36
     *
37
     * This method delegates to static::assertArraySubset().
38
     *
39
     * @param array|string $subset
40
     *
41
     * @throws \Symfony\Contracts\HttpClient\Exception\ClientExceptionInterface
42
     * @throws \Symfony\Contracts\HttpClient\Exception\DecodingExceptionInterface
43
     * @throws \Symfony\Contracts\HttpClient\Exception\RedirectionExceptionInterface
44
     * @throws \Symfony\Contracts\HttpClient\Exception\ServerExceptionInterface
45
     * @throws \Symfony\Contracts\HttpClient\Exception\TransportExceptionInterface
46
     */
47
    public static function assertJsonContains($subset, bool $checkForObjectIdentity = true, string $message = ''): void
48
    {
49
        if (\is_string($subset)) {
50
            $subset = json_decode($subset, true);
51
        }
52
        if (!\is_array($subset)) {
53
            throw new \InvalidArgumentException('$subset must be array or string (JSON array or JSON object)');
54
        }
55
56
        static::assertArraySubset($subset, self::getHttpResponse()->toArray(false), $checkForObjectIdentity, $message);
57
    }
58
59
    /**
60
     * Asserts that the retrieved JSON is equal to $json.
61
     *
62
     * Both values are canonicalized before the comparision.
63
     *
64
     * @param array|string $json
65
     */
66
    public static function assertJsonEquals($json, string $message = ''): void
67
    {
68
        if (\is_string($json)) {
69
            $json = json_decode($json, true);
70
        }
71
        if (!\is_array($json)) {
72
            throw new \InvalidArgumentException('$json must be array or string (JSON array or JSON object)');
73
        }
74
75
        static::assertEqualsCanonicalizing($json, self::getHttpResponse()->toArray(false), $message);
76
    }
77
78
    /**
79
     * Asserts that an array has a specified subset.
80
     *
81
     * Imported from dms/phpunit-arraysubset, because the original constraint has been deprecated.
82
     *
83
     * @copyright Sebastian Bergmann <[email protected]>
84
     * @copyright Rafael Dohms <[email protected]>
85
     *
86
     * @see https://github.com/sebastianbergmann/phpunit/issues/3494
87
     *
88
     * @param iterable $subset
89
     * @param iterable $array
90
     *
91
     * @throws ExpectationFailedException
92
     * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException
93
     * @throws \Exception
94
     */
95
    public static function assertArraySubset($subset, $array, bool $checkForObjectIdentity = false, string $message = ''): void
96
    {
97
        $constraint = new ArraySubset($subset, $checkForObjectIdentity);
98
99
        static::assertThat($array, $constraint, $message);
100
    }
101
102
    /**
103
     * @param object|array|string $jsonSchema
104
     */
105
    public static function assertMatchesJsonSchema($jsonSchema, ?int $checkMode = null, string $message = ''): void
106
    {
107
        $constraint = new MatchesJsonSchema($jsonSchema, $checkMode);
108
109
        static::assertThat(self::getHttpResponse()->toArray(false), $constraint, $message);
110
    }
111
112
    public static function assertMatchesResourceCollectionJsonSchema(string $resourceClass, ?string $operationName = null, string $format = 'jsonld'): void
113
    {
114
        $schema = self::getSchemaFactory()->buildSchema($resourceClass, $format, Schema::TYPE_OUTPUT, OperationType::COLLECTION, $operationName);
115
116
        static::assertMatchesJsonSchema($schema);
117
    }
118
119
    public static function assertMatchesResourceItemJsonSchema(string $resourceClass, ?string $operationName = null, string $format = 'jsonld'): void
120
    {
121
        $schema = self::getSchemaFactory()->buildSchema($resourceClass, $format, Schema::TYPE_OUTPUT, OperationType::ITEM, $operationName);
122
123
        static::assertMatchesJsonSchema($schema);
124
    }
125
126
    private static function getHttpClient(Client $newClient = null): ?Client
127
    {
128
        static $client;
129
130
        if (0 < \func_num_args()) {
131
            return $client = $newClient;
132
        }
133
134
        if (!$client instanceof Client) {
135
            static::fail(sprintf('A client must be set to make assertions on it. Did you forget to call "%s::createClient()"?', __CLASS__));
136
        }
137
138
        return $client;
139
    }
140
141
    private static function getHttpResponse(): ResponseInterface
142
    {
143
        if (!$response = self::getHttpClient()->getResponse()) {
0 ignored issues
show
Bug introduced by Kévin Dunglas
Are you sure the usage of self::getHttpClient() targeting ApiPlatform\Core\Bridge\...sTrait::getHttpClient() seems to always return null.

This check looks for function or method calls that always return null and whose return value is used.

class A
{
    function getObject()
    {
        return null;
    }

}

$a = new A();
if ($a->getObject()) {

The method getObject() can return nothing but null, so it makes no sense to use the return value.

The reason is most likely that a function or method is imcomplete or has been reduced for debug purposes.

Loading history...
144
            static::fail('A client must have an HTTP Response to make assertions. Did you forget to make an HTTP request?');
145
        }
146
147
        return $response;
148
    }
149
150
    private static function getSchemaFactory(): SchemaFactoryInterface
151
    {
152
        try {
153
            /** @var SchemaFactoryInterface $schemaFactory */
154
            $schemaFactory = static::$container->get('api_platform.json_schema.schema_factory');
155
        } catch (ServiceNotFoundException $e) {
156
            throw new \LogicException('You cannot use the resource JSON Schema assertions if the "api_platform.swagger.versions" config is null or empty.');
157
        }
158
159
        return $schemaFactory;
160
    }
161
}
162