protected function assertErrorCodeLocalization(Result $result) { $localizer = new ValidatorErrorLocalizer(); $errors = $result->getErrors(); $this->assertGreaterThanOrEqual(1, $errors); foreach ($errors as $error) { $msg = $localizer->getErrorMessage($error); $this->assertTrue($msg->exists(), 'message: ' . $msg); } }
/** * Returns a Status representing the given validation result. * * @param Result $result * * @return Status */ public function getResultStatus(Result $result) { $status = Status::newGood(); $status->setResult($result->isValid()); foreach ($result->getErrors() as $error) { $msg = $this->getErrorMessage($error); $status->fatal($msg); } return $status; }
/** * @param Result $result * @param Error[] $expectedErrors */ protected function assertResult(Result $result, array $expectedErrors) { $this->assertEquals(empty($expectedErrors), $result->isValid(), 'isValid()'); $errors = $result->getErrors(); $this->assertSameSize($expectedErrors, $errors, 'Number of errors:'); foreach ($expectedErrors as $i => $expectedError) { $error = $errors[$i]; $this->assertEquals($expectedError->getCode(), $error->getCode(), 'Error code:'); $this->assertEquals($expectedError->getParameters(), $error->getParameters(), 'Error parameters:'); $this->assertInstanceOf('Wikibase\\Repo\\Validators\\UniquenessViolation', $error); $this->assertEquals($expectedError->getConflictingEntity(), $error->getConflictingEntity()); } }
public function provideGetExceptionMessage() { $result0 = Result::newError(array()); $result1 = Result::newError(array(Error::newError('Eeek!', null, 'too-long', array(8)))); $result2 = Result::newError(array(Error::newError('Eeek!', null, 'too-long', array(array('eekwiki', 'Eek'))), Error::newError('Foo!', null, 'too-short', array(array('foowiki', 'Foo'))))); return array('ChangeOpValidationException(0)' => array(new ChangeOpValidationException($result0), 'wikibase-validator-invalid', array()), 'ChangeOpValidationException(1)' => array(new ChangeOpValidationException($result1), 'wikibase-validator-too-long', array('8')), 'ChangeOpValidationException(2)' => array(new ChangeOpValidationException($result2), 'wikibase-validator-too-long', array('eekwiki|Eek'))); }
/** * @see ValueValidator::validate() * * @param mixed $value The value to validate * * @return Result */ public function validate($value) { $isValid = is_int($value) || is_float($value); if ($isValid) { return Result::newSuccess(); } return Result::newError(array(Error::newError('Bad type, expected an integer or float value', null, 'bad-type', array('number', gettype($value))))); }
public function validEntityProvider() { $success = Result::newSuccess(); $failure = Result::newError(array(Error::newError('Foo!'))); $good = $this->getMock('Wikibase\\Repo\\Validators\\EntityValidator'); $good->expects($this->any())->method('validateEntity')->will($this->returnValue($success)); $bad = $this->getMock('Wikibase\\Repo\\Validators\\EntityValidator'); $bad->expects($this->any())->method('validateEntity')->will($this->returnValue($failure)); return array(array(array($good, $bad), false), array(array($bad, $good), false), array(array($good, $good), true), array(array(), true)); }
/** * Validate a fingerprint by applying each of the validators supplied to the constructor. * * @see FingerprintValidator::validateFingerprint * * @param Fingerprint $fingerprint * @param EntityId $entityId * @param string[]|null $languageCodes * * @return Result */ public function validateFingerprint(Fingerprint $fingerprint, EntityId $entityId, array $languageCodes = null) { foreach ($this->validators as $validator) { $result = $validator->validateFingerprint($fingerprint, $entityId, $languageCodes); if (!$result->isValid()) { return $result; } } return Result::newSuccess(); }
/** * @see ValueValidator::validate * * @param string $value The value to validate * * @return Result */ public function validate($value) { if ($this->normalizer !== null) { $value = call_user_func($this->normalizer, $value); } if (!in_array($value, $this->allowed, true)) { return Result::newError(array(Error::newError('Not a legal value: ' . $value, null, $this->errorCode, array($value)))); } return Result::newSuccess(); }
/** * Validate an entity by applying each of the validators supplied to the constructor. * * @see EntityValidator::validateEntity * * @since 0.5 * * @param EntityDocument $entity * * @return Result */ public function validateEntity(EntityDocument $entity) { foreach ($this->validators as $validator) { $result = $validator->validateEntity($entity); if (!$result->isValid()) { return $result; } } return Result::newSuccess(); }
/** * @param string|DataValue $value * * @return Result */ public function validate($value) { if ($value instanceof DataValue) { $value = $value->getArrayValue(); } if (preg_match($this->regex, $value)) { return Result::newSuccess(); } else { return Result::newError(array(Error::newError("doesn't match " . $this->regex))); } }
/** * @see ValueValidator::validate() * * @param int|float $value The numeric value to validate * * @return Result */ public function validate($value) { if ($value < $this->min) { // XXX: having to provide an array is quite inconvenient return Result::newError(array(Error::newError('Value out of range, the minimum value is ' . $this->min, null, 'too-low', array($this->min, $value)))); } if ($value > $this->max) { return Result::newError(array(Error::newError('Value out of range, the maximum value is ' . $this->max, null, 'too-high', array($this->max, $value)))); } return Result::newSuccess(); }
/** * @see ValueValidator::validate() * * @param string $value The value to validate * * @return Result */ public function validate($value) { $length = call_user_func($this->measure, $value); if ($length < $this->minLength) { // XXX: having to provide an array is quite inconvenient return Result::newError(array(Error::newError('Too short, minimum length is ' . $this->minLength, null, 'too-short', array($this->minLength, $value)))); } if ($length > $this->maxLength) { return Result::newError(array(Error::newError('Too long, maximum length is ' . $this->maxLength, null, 'too-long', array($this->maxLength, $this->truncateValue($value))))); } return Result::newSuccess(); }
/** * @see ValueValidator::validate() * * @param string $value The value to validate * * @return Result */ public function validate($value) { $match = preg_match($this->expression, $value); if ($match === 0 && !$this->inverse) { // XXX: having to provide an array is quite inconvenient return Result::newError(array(Error::newError('Pattern match failed: ' . $this->expression, null, $this->errorCode, array($value)))); } if ($match === 1 && $this->inverse) { // XXX: having to provide an array is quite inconvenient return Result::newError(array(Error::newError('Negative pattern matched: ' . $this->expression, null, $this->errorCode, array($value)))); } return Result::newSuccess(); }
/** * @return LabelDescriptionDuplicateDetector */ private function getLabelDescriptionDuplicateDetector() { $detector = $this->getMockBuilder('Wikibase\\LabelDescriptionDuplicateDetector')->disableOriginalConstructor()->getMock(); $self = $this; $detector->expects($this->any())->method('detectLabelDescriptionConflicts')->will($this->returnCallback(function ($entityType, array $labels, array $descriptions, EntityId $ignoreEntityId = null) use($self) { $errors = array(); $errors = array_merge($errors, $self->detectDupes($labels)); $errors = array_merge($errors, $self->detectDupes($descriptions)); $result = empty($errors) ? Result::newSuccess() : Result::newError($errors); return $result; })); return $detector; }
/** * @see ValueValidator::validate() * * @param array $data The data array to validate * * @return Result * @throws InvalidArgumentException */ public function validate($data) { if (!is_array($data)) { //XXX: or should this just be reported as invalid? throw new InvalidArgumentException('DataValue is not represented as an array'); } if (!isset($data[$this->field])) { return Result::newError(array(Error::newError('Required field ' . $this->field . ' not set', $this->field, 'missing-field', array($this->field)))); } $fieldValue = $data[$this->field]; $result = $this->validator->validate($fieldValue); // TODO: include the field name in the error report return $result; }
/** * @see ValueValidator::validate() * * @param mixed $value The value to validate * * @return Result */ public function validate($value) { $type = gettype($value); if ($type === $this->type) { return Result::newSuccess(); } if (is_object($value)) { $type = get_class($value); if (is_a($value, $this->type)) { return Result::newSuccess(); } } return Result::newError(array(Error::newError('Bad type, expected ' . $this->type, null, 'bad-type', array($this->type, $type)))); }
/** * @see EntityValidator::validate() * * @param EntityDocument $entity * * @return Result */ public function validateEntity(EntityDocument $entity) { $errors = array(); if ($entity instanceof Item) { // TODO: do not use global state $db = wfGetDB(DB_MASTER); $conflicts = $this->siteLinkConflictLookup->getConflictsForItem($entity, $db); /* @var ItemId $ignoreConflictsWith */ foreach ($conflicts as $conflict) { $errors[] = $this->getConflictError($conflict); } } return empty($errors) ? Result::newSuccess() : Result::newError($errors); }
/** * @see FingerprintValidator::validateFingerprint() * * @param Fingerprint $fingerprint * @param EntityId $entityId * @param string[]|null $languageCodes * * @return Result */ public function validateFingerprint(Fingerprint $fingerprint, EntityId $entityId, array $languageCodes = null) { $labels = $fingerprint->getLabels()->toTextArray(); $aliases = $fingerprint->getAliasGroups()->toTextArray(); if ($languageCodes !== null) { $languageKeys = array_flip($languageCodes); $labels = array_intersect_key($labels, $languageKeys); $aliases = array_intersect_key($aliases, $languageKeys); } // Nothing to do if there are no labels AND no aliases. if (empty($labels) && empty($aliases)) { return Result::newSuccess(); } return $this->duplicateDetector->detectLabelConflicts($entityId->getEntityType(), $labels, null, $entityId); }
/** * @see ValueValidator::validate() * * @param string $value The value to validate * * @return Result */ public function validate($value) { $result = Result::newSuccess(); try { $entityId = $this->idParser->parse($value); if ($this->forbiddenTypes === null || in_array($entityId->getEntityType(), $this->forbiddenTypes)) { // The label looks like a valid ID - we don't like that! $error = Error::newError('Looks like an Entity ID: ' . $value, null, $this->errorCode, array($value)); $result = Result::newError(array($error)); } } catch (EntityIdParsingException $parseException) { // All fine, the parsing did not work, so there is no entity id :) } return $result; }
/** * @see ValueValidator::validate() * * @param mixed $value The value to validate * * @return Result */ public function validate($value) { $result = Result::newSuccess(); foreach ($this->validators as $validator) { $subResult = $validator->validate($value); if (!$subResult->isValid()) { if ($this->failFast) { return $subResult; } else { $result = Result::merge($result, $subResult); } } } return $result; }
/** * @see FingerprintValidator::validateFingerprint() * * @param Fingerprint $fingerprint * @param EntityId $entityId * @param string[]|null $languageCodes * * @return Result */ public function validateFingerprint(Fingerprint $fingerprint, EntityId $entityId, array $languageCodes = null) { $labels = $fingerprint->getLabels()->toTextArray(); $descriptions = $fingerprint->getDescriptions()->toTextArray(); if ($languageCodes !== null) { $languageKeys = array_flip($languageCodes); $labels = array_intersect_key($labels, $languageKeys); $descriptions = array_intersect_key($descriptions, $languageKeys); } // Nothing to do if there are no labels OR no descriptions, since // a conflict requires a label AND a description. if (empty($labels) || empty($descriptions)) { return Result::newSuccess(); } return $this->duplicateDetector->detectLabelDescriptionConflicts($entityId->getEntityType(), $labels, $descriptions, $entityId); }
/** * @see ValueValidator::validate() * * @param mixed $value The value to validate * * @return Result */ public function validate($value) { $result = null; foreach ($this->validators as $validator) { $subResult = $validator->validate($value); if ($subResult->isValid()) { return $subResult; } else { $result = $result ? Result::merge($result, $subResult) : $subResult; } } if (!$result) { $result = Result::newError(array(Error::newError("No validators", null, 'no-validators'))); } return $result; }
/** * @see ValueValidator::validate() * * @param EntityIdValue|EntityId $value The ID to validate * * @return Result * @throws InvalidArgumentException */ public function validate($value) { if ($value instanceof EntityIdValue) { $value = $value->getEntityId(); } if (!$value instanceof EntityId) { throw new InvalidArgumentException("Expected an EntityId object"); } $actualType = $value->getEntityType(); $errors = array(); if ($this->entityType !== null && $actualType !== $this->entityType) { $errors[] = Error::newError("Wrong entity type: " . $actualType, null, 'bad-entity-type', array($actualType)); } if (!$this->entityLookup->hasEntity($value)) { $errors[] = Error::newError("Entity not found: " . $value, null, 'no-such-entity', array($value)); } return empty($errors) ? Result::newSuccess() : Result::newError($errors); }
protected function assertValidation($expected, array $validators, $value, $message) { $result = Result::newSuccess(); foreach ($validators as $validator) { $result = $validator->validate($value); if (!$result->isValid()) { break; } } if ($expected) { $errors = $result->getErrors(); if (!empty($errors)) { $this->fail($message . "\n" . $errors[0]->getText()); } $this->assertEquals($expected, $result->isValid(), $message); } else { $this->assertEquals($expected, $result->isValid(), $message); } }
/** * @see ValueValidator::validate() * * @param string $url * * @throws InvalidArgumentException * @return Result */ public function validate($url) { if (!is_string($url)) { throw new InvalidArgumentException('$url must be a string.'); } // See RFC 3986, section-3.1. if (!preg_match('/^([-+.a-z\\d]+):/i', $url, $matches)) { return Result::newError(array(Error::newError('Malformed URL, can\'t find scheme name.', null, 'bad-url', array($url)))); } // Should we also check for and fail on whitespace in $value? $scheme = strtolower($matches[1]); if (isset($this->validators[$scheme])) { $validator = $this->validators[$scheme]; } elseif (isset($this->validators['*'])) { $validator = $this->validators['*']; } else { return Result::newError(array(Error::newError('Unsupported URL scheme', null, 'bad-url-scheme', array($scheme)))); } return $validator->validate($url); }
protected function makeChangeOpsMerge(Item $fromItem, Item $toItem, array $ignoreConflicts = array(), $siteLookup = null) { if ($siteLookup === null) { $siteLookup = MockSiteStore::newFromTestSites(); } // A validator which makes sure that no site link is for page 'DUPE' $siteLinkUniquenessValidator = $this->getMock('Wikibase\\Repo\\Validators\\EntityValidator'); $siteLinkUniquenessValidator->expects($this->any())->method('validateEntity')->will($this->returnCallback(function (Item $item) { $siteLinks = $item->getSiteLinkList(); foreach ($siteLinks as $siteLink) { if ($siteLink->getPageName() === 'DUPE') { return Result::newError(array(Error::newError('SiteLink conflict'))); } } return Result::newSuccess(); })); $constraintProvider = $this->getMockBuilder('Wikibase\\Repo\\Validators\\EntityConstraintProvider')->disableOriginalConstructor()->getMock(); $constraintProvider->expects($this->any())->method('getUpdateValidators')->will($this->returnValue(array($siteLinkUniquenessValidator))); $changeOpFactoryProvider = new ChangeOpFactoryProvider($constraintProvider, $this->mockProvider->getMockGuidGenerator(), $this->mockProvider->getMockGuidValidator(), $this->mockProvider->getMockGuidParser($toItem->getId()), $this->mockProvider->getMockSnakValidator(), $this->mockProvider->getMockTermValidatorFactory(), $siteLookup); return new ChangeOpsMerge($fromItem, $toItem, $ignoreConflicts, $constraintProvider, $changeOpFactoryProvider, $siteLookup); }
/** * @param Result $result * @param Exception|null $previous * * @throws InvalidArgumentException */ public function __construct(Result $result, Exception $previous = null) { $messages = $this->composeErrorMessage($result->getErrors()); parent::__construct('Validation failed: ' . $messages, 0, $previous); $this->result = $result; }
/** * Throws an exception if it would not be possible to save the updated items * @throws ChangeOpException */ private function applyConstraintChecks(Item $item, ItemId $fromId) { $constraintValidator = new CompositeEntityValidator($this->constraintProvider->getUpdateValidators($item->getType())); $result = $constraintValidator->validateEntity($item); $errors = $result->getErrors(); $errors = $this->removeConflictsWithEntity($errors, $fromId); if (!empty($errors)) { $result = Result::newError($errors); throw new ChangeOpValidationException($result); } }
/** * @see ChangeOp::validate() * * @since 0.5 * * @param Entity $entity * * @throws ChangeOpException * * @return Result */ public function validate(Entity $entity) { $result = Result::newSuccess(); // deep clone of $entity to avoid side-effects $entity = unserialize(serialize($entity)); foreach ($this->changeOps as $changeOp) { $result = $changeOp->validate($entity); if (!$result->isValid()) { // XXX: alternatively, we could collect all the errors. break; } $changeOp->apply($entity); } return $result; }
/** * @see ChangeOp::validate() * * This default implementation always returns Result::newSuccess(). * * @since 0.5 * * @param Entity $entity * * @throws ChangeOpException * * @return Result */ public function validate(Entity $entity) { return Result::newSuccess(); }