Created
June 26, 2020 02:13
-
-
Save chx/e6cf5783b76e3e9637e9d6b756f99cf6 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
namespace Drupal\sd8\Plugin\Validation\Constraint; | |
use Symfony\Component\Validator\Constraint; | |
use Symfony\Component\Validator\Constraints\Url; | |
use Symfony\Component\Validator\Constraints\UrlValidator; | |
/** | |
* Validates the LinkUriValid constraint. | |
*/ | |
class LinkUriValidConstraintValidator extends UrlValidator { | |
/** | |
* {@inheritdoc} | |
*/ | |
public function validate($value, Constraint $constraint) { | |
if (isset($value)) { | |
try { | |
/** @var \Drupal\Core\Url $urlObject */ | |
$urlObject = $value->getUrl(); | |
$url = $urlObject->setAbsolute()->toString(); | |
// LinkExternalProtocolsConstraintValidator will deal with external | |
// URLs with invalid protocols. | |
/** @var \Drupal\sd8\Plugin\Validation\Constraint\LinkUriValidConstraint $constraint */ | |
$parts = parse_url($url); | |
if (!$urlObject->isExternal() || in_array($parts['scheme'], $constraint->protocols)) { | |
parent::validate($url, $constraint); | |
} | |
if ($parts['scheme'] === 'mailto' && !filter_var($parts['path'], FILTER_VALIDATE_EMAIL)) { | |
$this->context->buildViolation($constraint->message) | |
->setParameter('{{ value }}', $this->formatValue($value)) | |
->setCode(Url::INVALID_URL_ERROR) | |
->addViolation(); | |
} | |
} | |
catch (\Exception $e) { | |
// This is not our job, it can be invalid internal path and more. | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment