Update version of "respect/coding-standard"

Signed-off-by: Henrique Moody <henriquemoody@gmail.com>
This commit is contained in:
Henrique Moody 2020-08-27 15:29:46 +02:00
parent 966c510559
commit 72dd88144e
No known key found for this signature in database
GPG key ID: 221E9281655813A6
21 changed files with 165 additions and 209 deletions

42
.php_cs
View file

@ -1,42 +0,0 @@
<?php
return PhpCsFixer\Config::create()
->setRiskyAllowed(true)
->setRules([
'@Symfony' => true,
'@PHP71Migration:risky' => true,
'phpdoc_align' => false,
'phpdoc_summary' => false,
'mb_str_functions' => true,
'no_multiline_whitespace_before_semicolons' => true,
'no_useless_else' => true,
'no_useless_return' => true,
'ordered_imports' => true,
'phpdoc_order' => true,
'array_syntax' => ['syntax' => 'short'],
'no_short_echo_tag' => true,
'php_unit_construct' => true,
'php_unit_dedicate_assert' => true,
'php_unit_expectation' => true,
'php_unit_mock' => true,
'php_unit_namespaced' => true,
'php_unit_ordered_covers' => true,
'php_unit_set_up_tear_down_visibility' => true,
'php_unit_test_annotation' => [
'style' => 'annotation',
],
'php_unit_test_case_static_method_calls' => ['call_type' => 'self'],
'php_unit_test_class_requires_covers' => true,
])
->setCacheFile(
sprintf(
'%s/.php_cs.cache',
getenv('TRAVIS') ? getenv('HOME').'/.php-cs-fixer' : __DIR__
)
)
->setFinder(
PhpCsFixer\Finder::create()
->in(['library', 'tests'])
->name('*.php')
->name('*.phpt')
);

View file

@ -27,7 +27,7 @@
"phpstan/phpstan-deprecation-rules": "^0.12", "phpstan/phpstan-deprecation-rules": "^0.12",
"phpstan/phpstan-phpunit": "^0.12", "phpstan/phpstan-phpunit": "^0.12",
"phpunit/phpunit": "^9.3", "phpunit/phpunit": "^9.3",
"respect/coding-standard": "^2.1", "respect/coding-standard": "^3.0",
"squizlabs/php_codesniffer": "^3.5", "squizlabs/php_codesniffer": "^3.5",
"symfony/validator": "^3.0||^4.0", "symfony/validator": "^3.0||^4.0",
"zendframework/zend-validator": "^2.1" "zendframework/zend-validator": "^2.1"

View file

@ -136,11 +136,6 @@ class ValidationException extends InvalidArgumentException implements Exception
return isset($this->defaultTemplates[$this->mode][$this->template]) === false; return isset($this->defaultTemplates[$this->mode][$this->template]) === false;
} }
public function __toString(): string
{
return $this->getMessage();
}
protected function chooseTemplate(): string protected function chooseTemplate(): string
{ {
return (string) key($this->defaultTemplates[$this->mode]); return (string) key($this->defaultTemplates[$this->mode]);
@ -154,4 +149,9 @@ class ValidationException extends InvalidArgumentException implements Exception
$this->params $this->params
); );
} }
public function __toString(): string
{
return $this->getMessage();
}
} }

View file

@ -36,13 +36,6 @@ use function ucfirst;
*/ */
final class Factory final class Factory
{ {
/**
* Default instance of the Factory.
*
* @var Factory
*/
private static $defaultInstance;
/** /**
* @var string[] * @var string[]
*/ */
@ -63,11 +56,30 @@ final class Factory
*/ */
private $parameterStringifier; private $parameterStringifier;
/**
* Default instance of the Factory.
*
* @var Factory
*/
private static $defaultInstance;
public function __construct() public function __construct()
{ {
$this->parameterStringifier = new KeepOriginalStringName(); $this->parameterStringifier = new KeepOriginalStringName();
} }
/**
* Returns the default instance of the Factory.
*/
public static function getDefaultInstance(): self
{
if (self::$defaultInstance === null) {
self::$defaultInstance = new self();
}
return self::$defaultInstance;
}
public function withRuleNamespace(string $rulesNamespace): self public function withRuleNamespace(string $rulesNamespace): self
{ {
$clone = clone $this; $clone = clone $this;
@ -100,26 +112,6 @@ final class Factory
return $clone; return $clone;
} }
/**
* Define the default instance of the Factory.
*/
public static function setDefaultInstance(self $defaultInstance): void
{
self::$defaultInstance = $defaultInstance;
}
/**
* Returns the default instance of the Factory.
*/
public static function getDefaultInstance(): self
{
if (self::$defaultInstance === null) {
self::$defaultInstance = new self();
}
return self::$defaultInstance;
}
/** /**
* Creates a rule. * Creates a rule.
* *
@ -185,6 +177,14 @@ final class Factory
return new ValidationException($input, $id, $params, $formatter); return new ValidationException($input, $id, $params, $formatter);
} }
/**
* Define the default instance of the Factory.
*/
public static function setDefaultInstance(self $defaultInstance): void
{
self::$defaultInstance = $defaultInstance;
}
/** /**
* Creates a reflection based on class name. * Creates a reflection based on class name.
* *

View file

@ -45,6 +45,13 @@ abstract class AbstractAge extends AbstractRule
*/ */
private $baseDate; private $baseDate;
/**
* Should compare the current base date with the given one.
*
* The dates are represented as integers in the format "Ymd".
*/
abstract protected function compare(int $baseDate, int $givenDate): bool;
/** /**
* Initializes the rule. * Initializes the rule.
*/ */
@ -71,13 +78,6 @@ abstract class AbstractAge extends AbstractRule
return $this->isValidWithFormat($this->format, (string) $input); return $this->isValidWithFormat($this->format, (string) $input);
} }
/**
* Should compare the current base date with the given one.
*
* The dates are represented as integers in the format "Ymd".
*/
abstract protected function compare(int $baseDate, int $givenDate): bool;
private function isValidWithoutFormat(string $dateTime): bool private function isValidWithoutFormat(string $dateTime): bool
{ {
$timestamp = strtotime($dateTime); $timestamp = strtotime($dateTime);

View file

@ -29,6 +29,14 @@ abstract class AbstractComparison extends AbstractRule
*/ */
private $compareTo; private $compareTo;
/**
* Compare both values and return whether the comparison is valid or not.
*
* @param mixed $left
* @param mixed $right
*/
abstract protected function compare($left, $right): bool;
/** /**
* Initializes the rule by setting the value to be compared to the input. * Initializes the rule by setting the value to be compared to the input.
* *
@ -53,12 +61,4 @@ abstract class AbstractComparison extends AbstractRule
return $this->compare($left, $right); return $this->compare($left, $right);
} }
/**
* Compare both values and return whether the comparison is valid or not.
*
* @param mixed $left
* @param mixed $right
*/
abstract protected function compare($left, $right): bool;
} }

View file

@ -29,6 +29,8 @@ abstract class AbstractFilterRule extends AbstractRule
*/ */
private $additionalChars; private $additionalChars;
abstract protected function validateFilteredInput(string $input): bool;
/** /**
* Initializes the rule with a list of characters to be ignored by the validation. * Initializes the rule with a list of characters to be ignored by the validation.
*/ */
@ -56,8 +58,6 @@ abstract class AbstractFilterRule extends AbstractRule
return $filteredInput === '' || $this->validateFilteredInput($filteredInput); return $filteredInput === '' || $this->validateFilteredInput($filteredInput);
} }
abstract protected function validateFilteredInput(string $input): bool;
private function filter(string $input): string private function filter(string $input): string
{ {
return str_replace(str_split($this->additionalChars), '', $input); return str_replace(str_split($this->additionalChars), '', $input);

View file

@ -35,14 +35,6 @@ abstract class AbstractRule implements Validatable
*/ */
protected $template; protected $template;
/**
* @param mixed$input
*/
public function __invoke($input): bool
{
return $this->validate($input);
}
/** /**
* {@inheritDoc} * {@inheritDoc}
*/ */
@ -98,4 +90,12 @@ abstract class AbstractRule implements Validatable
return $this; return $this;
} }
/**
* @param mixed$input
*/
public function __invoke($input): bool
{
return $this->validate($input);
}
} }

View file

@ -26,6 +26,11 @@ abstract class AbstractSearcher extends AbstractRule
{ {
use CanValidateUndefined; use CanValidateUndefined;
/**
* @return mixed[]
*/
abstract protected function getDataSource(): array;
/** /**
* {@inheritDoc} * {@inheritDoc}
*/ */
@ -38,9 +43,4 @@ abstract class AbstractSearcher extends AbstractRule
return in_array($input, $dataSource, true); return in_array($input, $dataSource, true);
} }
/**
* @return mixed[]
*/
abstract protected function getDataSource(): array;
} }

View file

@ -110,11 +110,10 @@ final class KeyNested extends AbstractRelated
/** /**
* @phpcsSuppress SlevomatCodingStandard.TypeHints.TypeHintDeclaration.MissingParameterTypeHint * @phpcsSuppress SlevomatCodingStandard.TypeHints.TypeHintDeclaration.MissingParameterTypeHint
* *
* @param object $object
* *
* @return mixed * @return mixed
*/ */
private function getValueFromObject($object, string $property) private function getValueFromObject(object $object, string $property)
{ {
if (empty($property) || !property_exists($object, $property)) { if (empty($property) || !property_exists($object, $property)) {
$message = sprintf('Cannot select the property %s from the given object', $this->getReference()); $message = sprintf('Cannot select the property %s from the given object', $this->getReference());

View file

@ -48,7 +48,7 @@ final class Luhn extends AbstractRule
$parity = $numDigits % 2; $parity = $numDigits % 2;
for ($i = 0; $i < $numDigits; ++$i) { for ($i = 0; $i < $numDigits; ++$i) {
$digit = $digits[$i]; $digit = $digits[$i];
if ($parity == ($i % 2)) { if ($parity == $i % 2) {
$digit <<= 1; $digit <<= 1;
if (9 < $digit) { if (9 < $digit) {
$digit = $digit - 9; $digit = $digit - 9;
@ -57,6 +57,6 @@ final class Luhn extends AbstractRule
$sum += $digit; $sum += $digit;
} }
return ($sum % 10) == 0; return $sum % 10 == 0;
} }
} }

View file

@ -44,7 +44,7 @@ final class NfeAccessKey extends AbstractRule
$digits = array_map('intval', str_split($input)); $digits = array_map('intval', str_split($input));
$w = []; $w = [];
for ($i = 0, $z = 5, $m = 43; $i <= $m; ++$i) { for ($i = 0, $z = 5, $m = 43; $i <= $m; ++$i) {
$z = $i < $m ? ($z - 1) == 1 ? 9 : ($z - 1) : 0; $z = $i < $m ? $z - 1 == 1 ? 9 : $z - 1 : 0;
$w[] = $z; $w[] = $z;
} }
@ -53,7 +53,7 @@ final class NfeAccessKey extends AbstractRule
} }
$s -= 11 * floor($s / 11); $s -= 11 * floor($s / 11);
$v = $s == 0 || $s == 1 ? 0 : (11 - $s); $v = $s == 0 || $s == 1 ? 0 : 11 - $s;
return $v == $digits[43]; return $v == $digits[43];
} }

View file

@ -59,7 +59,7 @@ final class Nif extends AbstractRule
private function validateDni(int $number, string $control): bool private function validateDni(int $number, string $control): bool
{ {
return mb_substr('TRWAGMYFPDXBNJZSQVHLCKE', ($number % 23), 1) === $control; return mb_substr('TRWAGMYFPDXBNJZSQVHLCKE', $number % 23, 1) === $control;
} }
private function validateNie(string $prefix, string $number, string $control): bool private function validateNie(string $prefix, string $number, string $control): bool
@ -92,12 +92,12 @@ final class Nif extends AbstractRule
$digits = str_split((string) $code); $digits = str_split((string) $code);
$lastDigit = (int) array_pop($digits); $lastDigit = (int) array_pop($digits);
$key = $lastDigit === 0 ? 0 : (10 - $lastDigit); $key = $lastDigit === 0 ? 0 : 10 - $lastDigit;
if (is_numeric($control)) { if (is_numeric($control)) {
return (int) $key === (int) $control; return (int) $key === (int) $control;
} }
return mb_substr('JABCDEFGHI', ($key % 10), 1) === $control; return mb_substr('JABCDEFGHI', $key % 10, 1) === $control;
} }
} }

View file

@ -42,7 +42,7 @@ final class PrimeNumber extends AbstractRule
} }
for ($i = 3; $i <= ceil(sqrt((float) $input)); $i += 2) { for ($i = 3; $i <= ceil(sqrt((float) $input)); $i += 2) {
if (($input % $i) == 0) { if ($input % $i == 0) {
return false; return false;
} }
} }

View file

@ -31,19 +31,19 @@ use function sprintf;
*/ */
final class VideoUrl extends AbstractRule final class VideoUrl extends AbstractRule
{ {
private const SERVICES = [
// phpcs:disable Generic.Files.LineLength.TooLong
'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',
// phpcs:enable Generic.Files.LineLength.TooLong
];
/** /**
* @var string|null * @var string|null
*/ */
private $service; private $service;
// phpcs:disable Generic.Files.LineLength.TooLong
private const SERVICES = [
'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',
];
// phpcs:enable Generic.Files.LineLength.TooLong
/** /**
* Create a new instance VideoUrl. * Create a new instance VideoUrl.
* *

View file

@ -181,6 +181,14 @@ use function count;
*/ */
final class Validator extends AllOf final class Validator extends AllOf
{ {
/**
* Create instance validator.
*/
public static function create(): self
{
return new self();
}
/** /**
* {@inheritDoc} * {@inheritDoc}
*/ */
@ -222,12 +230,4 @@ final class Validator extends AllOf
return $this; return $this;
} }
/**
* Create instance validator.
*/
public static function create(): self
{
return new self();
}
} }

View file

@ -1,17 +1,10 @@
--CREDITS-- --CREDITS--
Paul Karikari <paulkarikari1@gmail.com> Paul Karikari <paulkarikari1@gmail.com>
--SKIPIF-- --FILE--
<?php <?php
declare(strict_types=1); declare(strict_types=1);
if (!extension_loaded('uopz')) {
echo 'skip: Extension "uopz" is required to test "Uploaded" rule';
}
?>
--FILE--
<?php
require 'vendor/autoload.php'; require 'vendor/autoload.php';
use Respect\Validation\Exceptions\NestedValidationException; use Respect\Validation\Exceptions\NestedValidationException;
@ -46,6 +39,12 @@ try {
echo $exception->getFullMessage() . PHP_EOL; echo $exception->getFullMessage() . PHP_EOL;
} }
?> ?>
--SKIPIF--
<?php
if (!extension_loaded('uopz')) {
echo 'skip: Extension "uopz" is required to test "Uploaded" rule';
}
?>
--EXPECT-- --EXPECT--
"filename" must be an uploaded file "filename" must be an uploaded file
"filename" must not be an uploaded file "filename" must not be an uploaded file

View file

@ -41,26 +41,6 @@ final class CallTest extends TestCase
*/ */
private $errorException; private $errorException;
/**
* {@inheritDoc}
*/
protected function setUp(): void
{
$this->errorException = new ErrorException('This is a PHP error');
set_error_handler(function (): void {
throw $this->errorException;
});
}
/**
* {@inheritDoc}
*/
protected function tearDown(): void
{
restore_error_handler();
}
/** /**
* @test * @test
*/ */
@ -312,4 +292,24 @@ final class CallTest extends TestCase
trigger_error('Forcing PHP to trigger an error'); trigger_error('Forcing PHP to trigger an error');
} }
/**
* {@inheritDoc}
*/
protected function setUp(): void
{
$this->errorException = new ErrorException('This is a PHP error');
set_error_handler(function (): void {
throw $this->errorException;
});
}
/**
* {@inheritDoc}
*/
protected function tearDown(): void
{
restore_error_handler();
}
} }

View file

@ -35,22 +35,6 @@ final class NoTest extends RuleTestCase
*/ */
private $locale; private $locale;
/**
* {@inheritDoc}
*/
protected function setUp(): void
{
$this->locale = (string) setlocale(LC_ALL, '0');
}
/**
* {@inheritDoc}
*/
protected function tearDown(): void
{
setlocale(LC_ALL, $this->locale);
}
/** /**
* {@inheritDoc} * {@inheritDoc}
*/ */
@ -139,4 +123,20 @@ final class NoTest extends RuleTestCase
self::assertInvalidInput(new No(true), $input); self::assertInvalidInput(new No(true), $input);
} }
/**
* {@inheritDoc}
*/
protected function setUp(): void
{
$this->locale = (string) setlocale(LC_ALL, '0');
}
/**
* {@inheritDoc}
*/
protected function tearDown(): void
{
setlocale(LC_ALL, $this->locale);
}
} }

View file

@ -34,24 +34,6 @@ final class UploadedTest extends RuleTestCase
{ {
public const UPLOADED_FILENAME = 'uploaded.ext'; public const UPLOADED_FILENAME = 'uploaded.ext';
/**
* {@inheritDoc}
*/
protected function setUp(): void
{
if (!extension_loaded('uopz')) {
throw new SkippedTestError('Extension "uopz" is required to test "Uploaded" rule');
}
uopz_set_return(
'is_uploaded_file',
static function (string $filename): bool {
return $filename === UploadedTest::UPLOADED_FILENAME;
},
true
);
}
/** /**
* {@inheritDoc} * {@inheritDoc}
*/ */
@ -80,4 +62,22 @@ final class UploadedTest extends RuleTestCase
[$rule, new stdClass()], [$rule, new stdClass()],
]; ];
} }
/**
* {@inheritDoc}
*/
protected function setUp(): void
{
if (!extension_loaded('uopz')) {
throw new SkippedTestError('Extension "uopz" is required to test "Uploaded" rule');
}
uopz_set_return(
'is_uploaded_file',
static function (string $filename): bool {
return $filename === UploadedTest::UPLOADED_FILENAME;
},
true
);
}
} }

View file

@ -39,22 +39,6 @@ final class YesTest extends RuleTestCase
*/ */
private $locale; private $locale;
/**
* {@inheritDoc}
*/
protected function setUp(): void
{
$this->locale = (string) setlocale(LC_ALL, '0');
}
/**
* {@inheritDoc}
*/
protected function tearDown(): void
{
setlocale(LC_ALL, $this->locale);
}
/** /**
* {@inheritDoc} * {@inheritDoc}
*/ */
@ -146,4 +130,20 @@ final class YesTest extends RuleTestCase
self::assertInvalidInput(new Yes(true), $input); self::assertInvalidInput(new Yes(true), $input);
} }
/**
* {@inheritDoc}
*/
protected function setUp(): void
{
$this->locale = (string) setlocale(LC_ALL, '0');
}
/**
* {@inheritDoc}
*/
protected function tearDown(): void
{
setlocale(LC_ALL, $this->locale);
}
} }