Skip to content

Instantly share code, notes, and snippets.

@Maks3w
Created October 8, 2015 12:37
Show Gist options
  • Save Maks3w/119477c754e5d4a8377e to your computer and use it in GitHub Desktop.
Save Maks3w/119477c754e5d4a8377e to your computer and use it in GitHub Desktop.
Conditional require fields on Apigility
<?php
namespace Application\Problem;
use ZF\ApiProblem\ApiProblem;
/**
* Represent a Failed Validation API Problem.
*
* This Problem must be used only when the failure is specific to one or many fields.
*/
class FailedValidation extends ApiProblem
{
/**
* @param array $additional
*/
public function __construct(array $additional)
{
$additional = array_map(
function ($item) {
return (is_string($item) ? [$item] : $item);
},
$additional
);
$additional = [
'validation_messages' => $additional,
];
parent::__construct(422, 'Failed Validation', null, null, $additional);
}
}
<?php
namespace Application\V1\Rest\Foo;
use Application\Problem\FailedValidation;
use ZF\Rest\AbstractResourceListener;
/**
* This assume the input filter has the following fields
*
* - type: Required. Possible values are Baz or Foo
* - baz_name: Optional. Required only if type is Baz
* - foo_name: Optional. Required only if type is Foo
* - foo_surnames: Optional. Required only if type is Foo
* - foo_email: Optional. Required only if type is Foo
*/
class FooResource extends AbstractResourceListener
{
/**
* {@inheritdoc}
*/
public function create($data)
{
// Revalidate using conditional rules.
$failedValidation = $this->validateInputs($data);
if ($failedValidation) {
// If not empty then return API validation failed response.
return $failedValidation;
}
// Perform resource creation logic.
// return $something;
}
/**
* @param \stdClass $data
*
* @return null|FailedValidation
*/
private function validateInputs($data)
{
$inputFilter = $this->getInputFilter();
$inputFilter->setData((array) $data);
$requireField = function ($fieldName) use ($inputFilter) {
$pcdName = $inputFilter->get($fieldName);
$pcdName->setAllowEmpty(false);
$pcdName->setRequired(true);
};
switch ($data->type) {
case 'Baz':
$requireField('baz_name');
break;
case 'Foo':
$requireField('foo_name');
$requireField('foo_surnames');
$requireField('foo_email');
break;
default:
$inputFilter->get('type')
->setErrorMessage('type invalid');
break;
}
if ($inputFilter->isValid()) {
return null;
}
return new FailedValidation($inputFilter->getMessages());
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment