Moved check for URL validation config option to the UrlValidator itself

This commit is contained in:
Alejandro Celaya
2020-03-22 16:58:28 +01:00
parent d29ebb706e
commit 682a0768b7
5 changed files with 34 additions and 43 deletions

View File

@@ -11,7 +11,6 @@ use Shlinkio\Shlink\Core\Entity\ShortUrl;
use Shlinkio\Shlink\Core\Exception\InvalidUrlException;
use Shlinkio\Shlink\Core\Exception\NonUniqueSlugException;
use Shlinkio\Shlink\Core\Model\ShortUrlMeta;
use Shlinkio\Shlink\Core\Options\UrlShortenerOptions;
use Shlinkio\Shlink\Core\Repository\ShortUrlRepository;
use Shlinkio\Shlink\Core\Util\TagManagerTrait;
use Shlinkio\Shlink\Core\Util\UrlValidatorInterface;
@@ -24,17 +23,14 @@ class UrlShortener implements UrlShortenerInterface
use TagManagerTrait;
private EntityManagerInterface $em;
private UrlShortenerOptions $options;
private UrlValidatorInterface $urlValidator;
public function __construct(
UrlValidatorInterface $urlValidator,
EntityManagerInterface $em,
UrlShortenerOptions $options
EntityManagerInterface $em
) {
$this->urlValidator = $urlValidator;
$this->em = $em;
$this->options = $options;
}
/**
@@ -53,11 +49,7 @@ class UrlShortener implements UrlShortenerInterface
return $existingShortUrl;
}
// If the URL validation is enabled, check that the URL actually exists
if ($this->options->isUrlValidationEnabled()) {
$this->urlValidator->validateUrl($url);
}
$this->urlValidator->validateUrl($url);
$this->em->beginTransaction();
$shortUrl = new ShortUrl($url, $meta, new PersistenceDomainResolver($this->em));
$shortUrl->setTags($this->tagNamesToEntities($this->em, $tags));

View File

@@ -9,16 +9,19 @@ use GuzzleHttp\ClientInterface;
use GuzzleHttp\Exception\GuzzleException;
use GuzzleHttp\RequestOptions;
use Shlinkio\Shlink\Core\Exception\InvalidUrlException;
use Shlinkio\Shlink\Core\Options\UrlShortenerOptions;
class UrlValidator implements UrlValidatorInterface, RequestMethodInterface
{
private const MAX_REDIRECTS = 15;
private ClientInterface $httpClient;
private UrlShortenerOptions $options;
public function __construct(ClientInterface $httpClient)
public function __construct(ClientInterface $httpClient, UrlShortenerOptions $options)
{
$this->httpClient = $httpClient;
$this->options = $options;
}
/**
@@ -26,6 +29,11 @@ class UrlValidator implements UrlValidatorInterface, RequestMethodInterface
*/
public function validateUrl(string $url): void
{
// If the URL validation is not enabled, skip check
if (! $this->options->isUrlValidationEnabled()) {
return;
}
try {
$this->httpClient->request(self::METHOD_GET, $url, [
RequestOptions::ALLOW_REDIRECTS => ['max' => self::MAX_REDIRECTS],