Increase PHPStan level to 2

Signed-off-by: Henrique Moody <henriquemoody@gmail.com>
This commit is contained in:
Henrique Moody 2019-02-04 00:29:13 +01:00
parent b7043b2652
commit f52097075b
No known key found for this signature in database
GPG key ID: 221E9281655813A6
27 changed files with 144 additions and 79 deletions

View file

@ -23,7 +23,8 @@
"egulias/email-validator": "^2.0",
"malukenho/docheader": "^0.1.4",
"mikey179/vfsStream": "^1.6",
"phpstan/phpstan": "^0.10.3",
"phpstan/phpstan": "^0.11",
"phpstan/phpstan-phpunit": "^0.11.0",
"phpunit/phpunit": "^7.3",
"squizlabs/php_codesniffer": "^3.4",
"symfony/validator": "^3.0||^4.0",

View file

@ -86,7 +86,7 @@ class NestedValidationException extends ValidationException implements IteratorA
}
/**
* @return SplObjectStorage
* @return SplObjectStorage|ValidationException[]
*/
public function getIterator(): SplObjectStorage
{
@ -210,6 +210,7 @@ class NestedValidationException extends ValidationException implements IteratorA
}
$exception->getChildren()->rewind();
/** @var ValidationException $childException */
$childException = $exception->getChildren()->current();
if ($childException->getMessage() === $exception->getMessage()) {
return true;

View file

@ -245,7 +245,7 @@ final class Factory
$input,
array $params
): ValidationException {
/* @var ValidationException $exception */
/** @var ValidationException $exception */
$exception = $this->createReflectionClass($exceptionName, ValidationException::class)
->newInstance($input, $id, $params, $this->translator);
if (isset($params['template'])) {

View file

@ -54,7 +54,7 @@ abstract class AbstractAge extends AbstractRule
{
$this->age = $age;
$this->format = $format;
$this->baseDate = date('Ymd') - $this->age * 10000;
$this->baseDate = (int) date('Ymd') - $this->age * 10000;
}
/**

View file

@ -13,6 +13,7 @@ declare(strict_types=1);
namespace Respect\Validation\Rules;
use Respect\Validation\Exceptions\NestedValidationException;
use Respect\Validation\Exceptions\ValidationException;
use Respect\Validation\Validatable;
use function is_scalar;
@ -67,10 +68,12 @@ abstract class AbstractRelated extends AbstractRule
try {
$this->decision('assert', $hasReference, $input);
} catch (ValidationException $e) {
throw $this
->reportError($this->reference, ['hasReference' => true])
->addChild($e);
} catch (ValidationException $validationException) {
/** @var NestedValidationException $nestedValidationException */
$nestedValidationException = $this->reportError($this->reference, ['hasReference' => true]);
$nestedValidationException->addChild($validationException);
throw $nestedValidationException;
}
}

View file

@ -13,6 +13,9 @@ declare(strict_types=1);
namespace Respect\Validation\Rules;
use Respect\Validation\Exceptions\AllOfException;
use Respect\Validation\Exceptions\GroupedValidationException;
/**
* @author Alexandre Gomes Gaigalas <alexandre@gaigalas.net>
* @author Henrique Moody <henriquemoody@gmail.com>
@ -30,7 +33,11 @@ class AllOf extends AbstractComposite
'passed' => $numRules - $numExceptions,
];
if (!empty($exceptions)) {
throw $this->reportError($input, $summary)->addChildren($exceptions);
/** @var AllOfException $allOfException */
$allOfException = $this->reportError($input, $summary);
$allOfException->addChildren($exceptions);
throw $allOfException;
}
}

View file

@ -13,6 +13,8 @@ declare(strict_types=1);
namespace Respect\Validation\Rules;
use Respect\Validation\Exceptions\AnyOfException;
use Respect\Validation\Exceptions\GroupedValidationException;
use Respect\Validation\Exceptions\ValidationException;
/**
@ -28,7 +30,11 @@ class AnyOf extends AbstractComposite
$numRules = count($validators);
$numExceptions = count($exceptions);
if ($numExceptions === $numRules) {
throw $this->reportError($input)->addChildren($exceptions);
/** @var AnyOfException $anyOfException */
$anyOfException = $this->reportError($input);
$anyOfException->addChildren($exceptions);
throw $anyOfException;
}
}

View file

@ -13,8 +13,10 @@ declare(strict_types=1);
namespace Respect\Validation\Rules;
use function array_map;
use function array_sum;
use function count;
use function is_scalar;
use function mb_strlen;
use function preg_replace;
/**
@ -39,35 +41,48 @@ final class Cnpj extends AbstractRule
}
// Code ported from jsfromhell.com
$cleanInput = preg_replace('/\D/', '', $input);
$b = [6, 5, 4, 3, 2, 9, 8, 7, 6, 5, 4, 3, 2];
$bases = [6, 5, 4, 3, 2, 9, 8, 7, 6, 5, 4, 3, 2];
$digits = $this->getDigits((string) $input);
if ($cleanInput < 1) {
if (array_sum($digits) < 1) {
return false;
}
if (14 != mb_strlen($cleanInput)) {
if (14 !== count($digits)) {
return false;
}
$n = 0;
for ($i = 0; $i < 12; ++$i) {
$n += $cleanInput[$i] * $b[$i+1];
$n += $digits[$i] * $bases[$i+1];
}
if ($cleanInput[12] != ((($n %= 11) < 2) ? 0 : 11 - $n)) {
if ($digits[12] != ((($n %= 11) < 2) ? 0 : 11 - $n)) {
return false;
}
$n = 0;
for ($i = 0; $i <= 12; ++$i) {
$n += $cleanInput[$i] * $b[$i];
$n += $digits[$i] * $bases[$i];
}
if ($cleanInput[13] != ((($n %= 11) < 2) ? 0 : 11 - $n)) {
if ($digits[13] != ((($n %= 11) < 2) ? 0 : 11 - $n)) {
return false;
}
return true;
}
/**
* @return int[]
*/
private function getDigits(string $input): array
{
return array_map(
'intval',
str_split(
preg_replace('/\D/', '', $input)
)
);
}
}

View file

@ -13,6 +13,7 @@ declare(strict_types=1);
namespace Respect\Validation\Rules;
use Respect\Validation\Exceptions\DomainException;
use Respect\Validation\Exceptions\ValidationException;
/**
@ -90,21 +91,25 @@ class Domain extends AbstractComposite
public function assert($input): void
{
$e = [];
$exceptions = [];
foreach ($this->checks as $chk) {
$this->collectAssertException($e, $chk, $input);
$this->collectAssertException($exceptions, $chk, $input);
}
if (count($parts = explode('.', (string) $input)) >= 2) {
$this->collectAssertException($e, $this->tld, array_pop($parts));
$this->collectAssertException($exceptions, $this->tld, array_pop($parts));
}
foreach ($parts as $p) {
$this->collectAssertException($e, $this->otherParts, $p);
$this->collectAssertException($exceptions, $this->otherParts, $p);
}
if (count($e)) {
throw $this->reportError($input)->addChildren($e);
if (count($exceptions)) {
/** @var DomainException $domainException */
$domainException = $this->reportError($input);
$domainException->addChildren($exceptions);
throw $domainException;
}
}

View file

@ -13,6 +13,7 @@ declare(strict_types=1);
namespace Respect\Validation\Rules;
use Respect\Validation\Exceptions\EachException;
use Respect\Validation\Exceptions\ValidationException;
use Respect\Validation\Helpers\CanValidateIterable;
use Respect\Validation\Validatable;
@ -37,7 +38,7 @@ final class Each extends AbstractRule
/**
* Initializes the constructor.
*
* @param mixed $rule
* @param Validatable $rule
*/
public function __construct(Validatable $rule)
{
@ -63,7 +64,11 @@ final class Each extends AbstractRule
}
if (!empty($exceptions)) {
throw $this->reportError($input)->addChildren($exceptions);
/** @var EachException $eachException */
$eachException = $this->reportError($input);
$eachException->addChildren($exceptions);
throw $eachException;
}
}

View file

@ -26,6 +26,7 @@ use function sprintf;
use function str_repeat;
use function str_replace;
use function strtr;
use function var_dump;
/**
* Validates whether the input is a valid IP address.
@ -181,7 +182,7 @@ final class Ip extends AbstractRule
throw new ComponentException('Invalid network mask');
}
$this->mask = sprintf('%032b', ip2long(long2ip(~(2 ** (32 - $parts[1]) - 1))));
$this->mask = sprintf('%032b', ip2long(long2ip(~(2 ** (32 - (int) $parts[1]) - 1))));
}
private function verifyAddress(string $address): bool
@ -199,6 +200,10 @@ final class Ip extends AbstractRule
private function belongsToSubnet(string $input): bool
{
if (null === $this->mask) {
return false;
}
$min = sprintf('%032b', ip2long($this->startAddress));
$input = sprintf('%032b', ip2long($input));

View file

@ -13,7 +13,9 @@ declare(strict_types=1);
namespace Respect\Validation\Rules\Locale;
use function array_map;
use Respect\Validation\Rules\AbstractRule;
use function str_split;
/**
* Validator for Polish VAT identification number (NIP).
@ -36,12 +38,13 @@ final class PlVatin extends AbstractRule
}
$weights = [6, 5, 7, 2, 3, 4, 5, 6, 7];
$digits = array_map('intval', str_split($input));
$targetControlNumber = $input[9];
$targetControlNumber = $digits[9];
$calculateControlNumber = 0;
for ($i = 0; $i < 9; ++$i) {
$calculateControlNumber += $input[$i] * $weights[$i];
$calculateControlNumber += $digits[$i] * $weights[$i];
}
$calculateControlNumber = $calculateControlNumber % 11;

View file

@ -13,8 +13,9 @@ declare(strict_types=1);
namespace Respect\Validation\Rules;
use function mb_strlen;
use function mb_substr;
use function array_map;
use function count;
use function str_split;
/**
* Validate whether a given input is a Luhn number.
@ -42,10 +43,11 @@ final class Luhn extends AbstractRule
private function isValid(string $input): bool
{
$sum = 0;
$numDigits = mb_strlen($input);
$digits = array_map('intval', str_split($input));
$numDigits = count($digits);
$parity = $numDigits % 2;
for ($i = 0; $i < $numDigits; ++$i) {
$digit = mb_substr($input, $i, 1);
$digit = $digits[$i];
if ($parity == ($i % 2)) {
$digit <<= 1;
if (9 < $digit) {

View file

@ -13,6 +13,9 @@ declare(strict_types=1);
namespace Respect\Validation\Rules;
use function array_map;
use function str_split;
/**
* Rule restrict to Brasil.
*
@ -27,16 +30,17 @@ class NfeAccessKey extends AbstractRule
/**
* @see Manual de Integração do Contribuinte v4.0.1 (http://www.nfe.fazenda.gov.br)
*
* @param string $aK access key
* @param string $input access key
*
* @return bool
*/
public function validate($aK): bool
public function validate($input): bool
{
if (44 !== mb_strlen($aK)) {
if (44 !== mb_strlen($input)) {
return false;
}
$digits = array_map('intval', str_split($input));
$w = [];
for ($i = 0, $z = 5, $m = 43; $i <= $m; ++$i) {
$z = ($i < $m) ? 1 == ($z - 1) ? 9 : ($z - 1) : 0;
@ -44,13 +48,12 @@ class NfeAccessKey extends AbstractRule
}
for ($i = 0, $s = 0, $k = 44; $i < $k; ++$i) {
$s += $aK[$i]
* $w[$i];
$s += $digits[$i] * $w[$i];
}
$s -= (11 * floor($s / 11));
$v = (0 == $s || 1 == $s) ? 0 : (11 - $s);
return $v == $aK[43];
return $v == $digits[43];
}
}

View file

@ -35,7 +35,7 @@ final class Nif extends AbstractRule
}
if (preg_match('/^(\d{8})([A-Z])$/', $input, $matches)) {
return $this->validateDni($matches[1], $matches[2]);
return $this->validateDni((int) $matches[1], $matches[2]);
}
if (preg_match('/^([KLMXYZ])(\d{7})([A-Z])$/', $input, $matches)) {
@ -49,41 +49,29 @@ final class Nif extends AbstractRule
return false;
}
/**
* @param int $number
* @param int $control
*/
private function validateDni($number, $control)
private function validateDni(int $number, string $control): bool
{
return mb_substr('TRWAGMYFPDXBNJZSQVHLCKE', ($number % 23), 1) === $control;
}
/**
* @param string $prefix
* @param int $number
* @param int $control
*/
private function validateNie($prefix, $number, $control)
private function validateNie(string $prefix, string $number, string $control): bool
{
if ('Y' === $prefix) {
return $this->validateDni('1'.$number, $control);
return $this->validateDni((int) ('1'.$number), $control);
}
if ('Z' === $prefix) {
return $this->validateDni('2'.$number, $control);
return $this->validateDni((int) ('2'.$number), $control);
}
return $this->validateDni($number, $control);
return $this->validateDni((int) $number, $control);
}
/**
* @param int $number
* @param string $control
*/
private function validateCif(string $number, $control)
private function validateCif(string $number, string $control)
{
$code = 0;
$position = 1;
/** @var int $digit */
foreach (str_split($number) as $digit) {
$increaser = $digit;
if (0 !== $position % 2) {

View file

@ -13,6 +13,8 @@ declare(strict_types=1);
namespace Respect\Validation\Rules;
use Respect\Validation\Exceptions\NoneOfException;
/**
* @author Alexandre Gomes Gaigalas <alexandre@gaigalas.net>
* @author Henrique Moody <henriquemoody@gmail.com>
@ -25,7 +27,11 @@ class NoneOf extends AbstractComposite
$numRules = count($this->getRules());
$numExceptions = count($exceptions);
if ($numRules !== $numExceptions) {
throw $this->reportError($input)->addChildren($exceptions);
/** @var NoneOfException $noneOfException */
$noneOfException = $this->reportError($input);
$noneOfException->addChildren($exceptions);
throw $noneOfException;
}
}

View file

@ -13,6 +13,7 @@ declare(strict_types=1);
namespace Respect\Validation\Rules;
use Respect\Validation\Exceptions\OneOfException;
use Respect\Validation\Exceptions\ValidationException;
/**
@ -28,7 +29,11 @@ class OneOf extends AbstractComposite
$numRules = count($validators);
$numExceptions = count($exceptions);
if ($numExceptions !== $numRules - 1) {
throw $this->reportError($input)->addChildren($exceptions);
/** @var OneOfException $oneOfException */
$oneOfException = $this->reportError($input);
$oneOfException->addChildren($exceptions);
throw $oneOfException;
}
}

View file

@ -45,7 +45,7 @@ final class Pis extends AbstractRule
$summation = 0;
for ($position = 0; $position < 10; ++$position) {
$summation += $digits[$position] * $multipliers[$position];
$summation += (int) $digits[$position] * $multipliers[$position];
}
$checkDigit = (int) $digits[10];

View file

@ -16,6 +16,7 @@ namespace Respect\Validation\Rules;
use Respect\Validation\Exceptions\SfException;
use Respect\Validation\Exceptions\ValidationException;
use Symfony\Component\Validator\Constraint;
use Symfony\Component\Validator\ConstraintViolationList;
use Symfony\Component\Validator\Validation;
use Symfony\Component\Validator\Validator\ValidatorInterface;
@ -58,6 +59,7 @@ final class Sf extends AbstractRule
*/
public function assert($input): void
{
/** @var ConstraintViolationList $violations */
$violations = $this->validator->validate($input, $this->constraint);
if (0 === $violations->count()) {
return;
@ -67,7 +69,7 @@ final class Sf extends AbstractRule
throw $this->reportError($input, ['violations' => $violations[0]->getMessage()]);
}
throw $this->reportError($input, ['violations' => trim((string) $violations)]);
throw $this->reportError($input, ['violations' => trim($violations->__toString())]);
}
/**

View file

@ -15,6 +15,7 @@ namespace Respect\Validation\Rules;
use ReflectionClass;
use Respect\Validation\Exceptions\ComponentException;
use Respect\Validation\Exceptions\ZendException;
/**
* @author Alexandre Gomes Gaigalas <alexandre@gaigalas.net>
@ -64,7 +65,11 @@ class Zend extends AbstractRule
$exceptions[] = $this->reportError($m, get_object_vars($this));
}
throw $this->reportError($input)->addChildren($exceptions);
/** @var ZendException $zendException */
$zendException = $this->reportError($input);
$zendException->addChildren($exceptions);
throw $zendException;
}
public function validate($input): bool

View file

@ -1,10 +1,13 @@
includes:
- vendor/phpstan/phpstan-phpunit/extension.neon
parameters:
fileExtensions:
- php
- phpt
ignoreErrors:
- '/Call to an undefined static method Respect\\Validation\\Validator::iDoNotExistSoIShouldThrowException/'
level: 1
level: 2
paths:
- library/
- tests/

View file

@ -14,12 +14,12 @@ $config = [
'schema' => 'my_schema',
];
$validator = v::arrayType()
->setName('Settings')
->key('host', v::stringType())
->key('user', v::stringType())
->key('password', v::stringType())
->key('schema', v::stringType());
$validator = v::arrayType();
$validator->setName('Settings');
$validator->key('host', v::stringType());
$validator->key('user', v::stringType());
$validator->key('password', v::stringType());
$validator->key('schema', v::stringType());
try {
$validator->assert($config);

View file

@ -70,8 +70,8 @@ abstract class RuleTestCase extends TestCase
*
* @api
*
* @param bool $expectedResult
* @param string[optional] $mockClassName
* @param bool $expectedResult
* @param string $mockClassName
*
* @return Validatable
*/

View file

@ -32,7 +32,7 @@ class NestedValidationExceptionTest extends TestCase
$composite = new AttributeException('input', 'id', [], 'trim');
$node = new IntValException('input', 'id', [], 'trim');
$composite->addChild($node);
self::assertCount(1, $composite->getChildren(true));
self::assertCount(1, $composite->getChildren());
self::assertContainsOnly(IntValException::class, $composite->getChildren());
}
@ -46,7 +46,7 @@ class NestedValidationExceptionTest extends TestCase
$composite->addChild($node);
$composite->addChild($node);
$composite->addChild($node);
self::assertCount(1, $composite->getChildren(true));
self::assertCount(1, $composite->getChildren());
self::assertContainsOnly(IntValException::class, $composite->getChildren());
}
}

View file

@ -64,6 +64,7 @@ final class FactoryTest extends TestCase
$constructorArguments = [true, false, true, false];
$factory = new Factory([self::TEST_RULES_NAMESPACE], [], 'trim');
/** @var Stub $rule */
$rule = $factory->rule('stub', $constructorArguments);
self::assertSame($constructorArguments, $rule->validations);

View file

@ -13,6 +13,7 @@ declare(strict_types=1);
namespace Respect\Validation\Rules;
use PHPUnit\Framework\MockObject\MockObject;
use Respect\Validation\Test\TestCase;
use Respect\Validation\Validatable;

View file

@ -146,9 +146,7 @@ class ZendTest extends TestCase
$v->validate($notValid),
'The validator returned true for an invalid value, this won\'t cause an exception later on.'
);
self::assertFalse(
$v->assert($notValid)
);
$v->assert($notValid);
}
/**