HighSpeaker/vendor/workerman/validation/library/Rules/VideoUrl.php

91 lines
2.4 KiB
PHP
Raw Normal View History

2022-12-24 22:10:40 +08:00
<?php
/*
2024-01-31 22:15:08 +08:00
* Copyright (c) Alexandre Gomes Gaigalas <alganet@gmail.com>
* SPDX-License-Identifier: MIT
2022-12-24 22:10:40 +08:00
*/
declare(strict_types=1);
namespace Respect\Validation\Rules;
use Respect\Validation\Exceptions\ComponentException;
use function array_keys;
use function is_string;
use function mb_strtolower;
use function preg_match;
use function sprintf;
/**
* Validates if the input is a video URL value.
*
* @author Danilo Correa <danilosilva87@gmail.com>
* @author Emmerson Siqueira <emmersonsiqueira@gmail.com>
* @author Henrique Moody <henriquemoody@gmail.com>
* @author Ricardo Gobbo <ricardo@clicknow.com.br>
*/
final class VideoUrl extends AbstractRule
{
private const SERVICES = [
2024-01-31 22:15:08 +08:00
// phpcs:disable Generic.Files.LineLength.TooLong
2022-12-24 22:10:40 +08:00
'youtube' => '@^https?://(www\.)?(?:youtube\.com/(?:[^/]+/.+/|(?:v|e(?:mbed)?)/|.*[?&]v=)|youtu\.be/)([^\"&?/]{11})@i',
'vimeo' => '@^https?://(www\.)?(player\.)?(vimeo\.com/)((channels/[A-z]+/)|(groups/[A-z]+/videos/)|(video/))?([0-9]+)@i',
'twitch' => '@^https?://(((www\.)?twitch\.tv/videos/[0-9]+)|clips\.twitch\.tv/[a-zA-Z]+)$@i',
2024-01-31 22:15:08 +08:00
// phpcs:enable Generic.Files.LineLength.TooLong
2022-12-24 22:10:40 +08:00
];
2024-01-31 22:15:08 +08:00
/**
* @var string|null
*/
private $service;
2022-12-24 22:10:40 +08:00
/**
* Create a new instance VideoUrl.
*
* @throws ComponentException when the given service is not supported
*/
public function __construct(?string $service = null)
{
if ($service !== null && !$this->isSupportedService($service)) {
throw new ComponentException(sprintf('"%s" is not a recognized video service.', $service));
}
$this->service = $service;
}
/**
* {@inheritDoc}
*/
public function validate($input): bool
{
if (!is_string($input)) {
return false;
}
if ($this->service !== null) {
return $this->isValid($this->service, $input);
}
foreach (array_keys(self::SERVICES) as $service) {
if (!$this->isValid($service, $input)) {
continue;
}
return true;
}
return false;
}
private function isSupportedService(string $service): bool
{
return isset(self::SERVICES[mb_strtolower($service)]);
}
private function isValid(string $service, string $input): bool
{
return preg_match(self::SERVICES[mb_strtolower($service)], $input) > 0;
}
}