|
7 | 7 | use Tobyz\JsonApiServer\Exception\JsonApiErrorsException; |
8 | 8 | use Tobyz\JsonApiServer\JsonApi; |
9 | 9 | use Tobyz\JsonApiServer\Schema\Field\Attribute; |
| 10 | +use Tobyz\JsonApiServer\Schema\Type\Arr; |
| 11 | +use Tobyz\JsonApiServer\Schema\Type\Str; |
10 | 12 | use Tobyz\Tests\JsonApiServer\AbstractTestCase; |
11 | 13 | use Tobyz\Tests\JsonApiServer\MockResource; |
12 | 14 |
|
@@ -65,4 +67,66 @@ public function test_validate_on_update() |
65 | 67 | ]), |
66 | 68 | ); |
67 | 69 | } |
| 70 | + |
| 71 | + public function test_validate_is_not_run_when_type_validation_fails() |
| 72 | + { |
| 73 | + $called = false; |
| 74 | + |
| 75 | + $this->api->resource( |
| 76 | + new MockResource( |
| 77 | + 'users', |
| 78 | + endpoints: [Create::make()], |
| 79 | + fields: [ |
| 80 | + Attribute::make('aliases') |
| 81 | + ->type(Arr::make()) |
| 82 | + ->writable() |
| 83 | + ->validate(function (array $value, callable $fail) use (&$called) { |
| 84 | + $called = true; |
| 85 | + }), |
| 86 | + ], |
| 87 | + ), |
| 88 | + ); |
| 89 | + |
| 90 | + try { |
| 91 | + $this->api->handle( |
| 92 | + $this->buildRequest('POST', '/users')->withParsedBody([ |
| 93 | + 'data' => ['type' => 'users', 'attributes' => ['aliases' => 1]], |
| 94 | + ]), |
| 95 | + ); |
| 96 | + $this->fail('Expected validation to fail.'); |
| 97 | + } catch (JsonApiErrorsException) { |
| 98 | + $this->assertFalse($called); |
| 99 | + } |
| 100 | + } |
| 101 | + |
| 102 | + public function test_validate_is_not_run_when_non_nullable_value_is_null() |
| 103 | + { |
| 104 | + $called = false; |
| 105 | + |
| 106 | + $this->api->resource( |
| 107 | + new MockResource( |
| 108 | + 'users', |
| 109 | + endpoints: [Create::make()], |
| 110 | + fields: [ |
| 111 | + Attribute::make('name') |
| 112 | + ->type(Str::make()) |
| 113 | + ->writable() |
| 114 | + ->validate(function (string $value, callable $fail) use (&$called) { |
| 115 | + $called = true; |
| 116 | + }), |
| 117 | + ], |
| 118 | + ), |
| 119 | + ); |
| 120 | + |
| 121 | + try { |
| 122 | + $this->api->handle( |
| 123 | + $this->buildRequest('POST', '/users')->withParsedBody([ |
| 124 | + 'data' => ['type' => 'users', 'attributes' => ['name' => null]], |
| 125 | + ]), |
| 126 | + ); |
| 127 | + $this->fail('Expected validation to fail.'); |
| 128 | + } catch (JsonApiErrorsException) { |
| 129 | + $this->assertFalse($called); |
| 130 | + } |
| 131 | + } |
68 | 132 | } |
0 commit comments