public function LinkToFileConstraint::validate in File Link 2.0.x
Same name and namespace in other branches
- 8 src/Plugin/Validation/Constraint/LinkToFileConstraint.php \Drupal\file_link\Plugin\Validation\Constraint\LinkToFileConstraint::validate()
File
- src/
Plugin/ Validation/ Constraint/ LinkToFileConstraint.php, line 51
Class
- LinkToFileConstraint
- Validation constraint for file_link, checking that URI points to a file.
Namespace
Drupal\file_link\Plugin\Validation\ConstraintCode
public function validate($link, Constraint $constraint) {
/** @var \Drupal\file_link\Plugin\Field\FieldType\FileLinkItem $link */
if ($link
->isEmpty()) {
return;
}
$is_valid = TRUE;
$uri = $link
->get('uri')
->getValue();
// Try to resolve the given URI to a URL. It may fail if it's schemeless.
try {
$url = Url::fromUri($uri, [
'absolute' => TRUE,
])
->toString();
} catch (\InvalidArgumentException $e) {
$this->context
->addViolation("The following error occurred while getting the link URL: @error", [
'@error' => $e
->getMessage(),
]);
$is_valid = FALSE;
}
if ($is_valid) {
// If URL has no path but it still needs an extension then it's not valid.
if (!$this
->hasPath($url) && $this
->needsExtension($link)) {
$this->context
->addViolation("Provided file URL has no path nor extension: @uri", [
'@uri' => $uri,
]);
$is_valid = FALSE;
}
if ($is_valid && !$this
->hasDeferredRequest($link)) {
// Check for redirect response and get effective URL if any.
$url = $this
->getEffectiveUrl($url);
if ($this
->needsExtension($link) && !$this
->hasExtension($url)) {
$this->context
->addViolation("Provided file URL has no extension: @uri", [
'@uri' => $uri,
]);
$is_valid = FALSE;
}
if ($is_valid && $this
->hasExtension($url)) {
$is_valid = $this
->hasValidExtension($url, $link);
}
}
}
// If not valid construct error message.
if (!$is_valid) {
$this->context
->addViolation("Provided file URL has no valid extension: @uri", [
'@uri' => $uri,
]);
}
}