Created
August 3, 2020 04:23
-
-
Save sogaoh/b138cc043caece1df1ea5fd776ab8b5a to your computer and use it in GitHub Desktop.
validateRequestCompliantForOpenApiSpec 実装例
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* @param array $requestBody | |
* @param string $uri | |
* @param string $method | |
* @return JsonResponse|null | |
*/ | |
public function validateRequestCompliantForOpenApiSpec( | |
array $requestBody, | |
string $uri, | |
string $method | |
): ?JsonResponse | |
{ | |
$validatorBase = OpenApiValidatorFactory::getInstance(); | |
$validator = $validatorBase->getValidatorYaml()->getServerRequestValidator(); | |
$psr17Factory = $validatorBase->getPsr17Factory(); | |
$stream = $psr17Factory->createStream( | |
\http_build_query($this->adjustBooleanInArray($requestBody)) | |
); | |
$stream->rewind(); | |
$request = $psr17Factory->createServerRequest( | |
\strtolower($method), $uri) | |
->withBody($stream) | |
->withHeader('Content-Type', 'application/x-www-form-urlencoded'); | |
//->withHeader('Content-Type', 'multipart/form-data'); | |
try { | |
Log::info('-- request validate : ['.$method.'] '.$uri); | |
$validator->validate($request); | |
} catch (ValidationFailed $ve) { | |
return (new ApiException( | |
$ve->getMessage(), | |
Response::HTTP_UNPROCESSABLE_ENTITY | |
))->toResponse(null); | |
} | |
return null; | |
} | |
/** | |
* OpenApiValidatorFactory constructor. | |
*/ | |
final private function __construct() | |
{ | |
$this->validatorYaml = (new ValidatorBuilder())->fromYamlFile(\base_path() . '/path/to/yaml.yml'); | |
$this->psr17Factory = new Psr17Factory(); | |
$this->psrHttpFactory = new PsrHttpFactory( | |
$this->psr17Factory, $this->psr17Factory, $this->psr17Factory, $this->psr17Factory | |
); | |
} | |
/** | |
* @param array $srcArray | |
* @return array | |
*/ | |
public function adjustBooleanInArray(array $srcArray): array | |
{ | |
$dstArray = []; | |
foreach ($srcArray as $srcKey => $srcValue) { | |
switch (\gettype($srcValue)) { | |
case 'boolean': | |
$dstArray = \array_merge( | |
$dstArray, | |
[$srcKey => ($srcValue) ? 'true' : 'false'] | |
); | |
break; | |
case 'array': | |
$dstArray = \array_merge( | |
$dstArray, | |
[$srcKey => $this->adjustBooleanInArray($srcValue)] | |
); | |
break; | |
default: | |
$dstArray = \array_merge( | |
$dstArray, | |
[$srcKey => $srcValue] | |
); | |
break; | |
} | |
} | |
return $dstArray; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment