respect-validation/library/Rules/LanguageCode.php

80 lines
1.9 KiB
PHP
Raw Normal View History

2015-10-26 23:59:48 +01:00
<?php
/*
* This file is part of Respect/Validation.
*
* (c) Alexandre Gomes Gaigalas <alexandre@gaigalas.net>
*
* For the full copyright and license information, please view the LICENSE file
* that was distributed with this source code.
2015-10-26 23:59:48 +01:00
*/
declare(strict_types=1);
2015-10-26 23:59:48 +01:00
namespace Respect\Validation\Rules;
use Respect\Validation\Exceptions\ComponentException;
use Sokil\IsoCodes\IsoCodesFactory;
use Sokil\IsoCodes\TranslationDriver\DummyDriver;
use function in_array;
use function is_string;
use function sprintf;
2015-10-26 23:59:48 +01:00
/**
* Validates whether the input is language code based on ISO 639.
*
* @author Danilo Benevides <danilobenevides01@gmail.com>
* @author Emmerson Siqueira <emmersonsiqueira@gmail.com>
* @author Henrique Moody <henriquemoody@gmail.com>
2015-10-26 23:59:48 +01:00
*/
final class LanguageCode extends AbstractRule
2015-10-26 23:59:48 +01:00
{
public const ALPHA2 = 'alpha-2';
public const ALPHA3 = 'alpha-3';
public const AVAILABLE_SETS = [self::ALPHA2, self::ALPHA3];
2015-10-26 23:59:48 +01:00
/**
* @var string
2015-10-26 23:59:48 +01:00
*/
private $set;
/**
* @var IsoCodesFactory
*/
private $factory;
2015-10-26 23:59:48 +01:00
/**
* Initializes the rule defining the ISO 639 set.
*
* @throws ComponentException
*/
public function __construct(string $set = self::ALPHA2)
2015-10-26 23:59:48 +01:00
{
if (!in_array($set, self::AVAILABLE_SETS)) {
2015-10-26 23:59:48 +01:00
throw new ComponentException(sprintf('"%s" is not a valid language set for ISO 639', $set));
}
$this->set = $set;
$this->factory = new IsoCodesFactory(null, new DummyDriver());
2015-10-26 23:59:48 +01:00
}
/**
* {@inheritDoc}
*/
public function validate($input): bool
2015-10-26 23:59:48 +01:00
{
if (!is_string($input) || $input === '') {
return false;
}
$languages = $this->factory->getLanguages();
if ($this->set === self::ALPHA2) {
return $languages->getByAlpha2($input) !== null;
}
return $languages->getByAlpha3($input) !== null;
2015-10-26 23:59:48 +01:00
}
}