/** * @param array $options */ public function setOptions(array $options) { if ($schema = $this->getOptionsSchema()) { try { $this->options = V::attempt($options, $schema); } catch (ValidationException $e) { throw new \InvalidArgumentException($e); } } else { $this->options = $options; } }
/** * @param InputValue $input * @throws ValidationException */ public function process(InputValue $input) { foreach ($this->getOption('options') as $schema) { try { $input->replace(function ($value) use($schema) { return V::attempt($value, $schema); }); return; } catch (ValidationException $e) { } } throw new ValidationException('none of the alternatives matched'); }
/** * @param InputValue $input * @param $key * @param AbstractSchema $schema * @throws ValidationException */ private function validateAndReplaceKey(InputValue $input, $key, AbstractSchema $schema) { try { $input->replace(function ($value) use($key, $schema) { $value[$key] = V::attempt($value[$key], $schema); return $value; }); if ($schema->getOption('strip')) { $input->replace(function ($value) use($key) { unset($value[$key]); return $value; }); } } catch (ValidationException $e) { throw new ValidationException(sprintf('key "%s" is invalid, because [ %s ]', $key, $e->getMessage())); } }
public function testAnyDefaultPreset() { $input = ['firstname' => 'Smok', 'lastname' => 'Wawelski', 'username' => 'foobar', 'created' => '2015-01-01', 'status' => 'foo']; $schema = V::arr()->keys(['username' => V::string()->defaultValue(function ($context) { return strtolower($context['firstname']) . '-' . strtolower($context['lastname']); }), 'firstname' => V::string(), 'lastname' => V::string(), 'created' => V::date()->dateTimeObject()->defaultValue(new \DateTime()), 'status' => V::string()->defaultValue('registered')]); $user = V::attempt($input, $schema); $this->assertEquals('foobar', $user['username']); $this->assertEquals('Smok', $user['firstname']); $this->assertEquals('Wawelski', $user['lastname']); $this->assertEquals('2015-01-01 00:00:00', $user['created']->format('Y-m-d H:i:s')); $this->assertEquals('foo', $user['status']); }