Skip to content

Plugin-System for Validation of formats? #266

Closed
@steffkes

Description

@steffkes

i'm using this library again for one of my projects, never had to extend it in any way since the included features were always enough - until this time ;>

there is already a part of FormatConstraint that validates format=phone but it only does a very, very simple check on US phone numbers. i did need to perform a check on a larger range including internal numbers. libphonenumber-for-php is a perfect fit for it, integrating that into json-schema and extending the FormatConstraint feels a bit ugly.

just for reference, one could or would probably:

class FormatConstraint extends \JsonSchema\Constraints\FormatConstraint
{
  public function check($element, $schema = null, $path = null, $i = null)
  {
    if($schema->format && $schema->format === 'phone') {
      try {
        PhoneNumberUtil::getInstance()->parse($element, NULL);
      } catch(NumberParseException $e) {
        $this->addError(
          $path,
          sprintf('Invalid phone number: %s', $e->getMessage()),
          'format',
          ['format' => $schema->format]
        );
      }
    }
  }

  protected function validatePhone($phoneNumber) {
    return true;
  }
}

since we extend FormatConstraint we'd have to give validatePhone a pass since it will be called from the original FormatConstraint#check method which is executed anyway since we have to ensure that all the other/existing format constraints still work.

the other thing is, since i'd like to include additional information in the response i need access to the exception - not a thing that all the existing validate* methods do right now. obviously a personal choice, but nevertheless.

before i start digging in such a plugin-system, i'm curious WDYT? is it even worth it? am i the only one that needed something like this? is it probably the only extension one could ever want?

let me know!

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions