Set up "squizlabs/php_codesniffer"

The tool we used to verify whether the code base has the correct coding
standard was removed [1].

This commit will set up one that works best for us and will also make
sure we have fully compliant to PS1 and PSR2.

[1]: ffec95acda

Signed-off-by: Henrique Moody <henriquemoody@gmail.com>
This commit is contained in:
Henrique Moody 2019-02-03 18:58:30 +01:00
parent 2b86e5443e
commit b7043b2652
No known key found for this signature in database
GPG key ID: 221E9281655813A6
237 changed files with 390 additions and 280 deletions

3
.gitignore vendored
View file

@ -1,7 +1,8 @@
.php_cs.cache
.couscous/
.phpcs.cache
composer.lock
Makefile
phpcs.xml
phpstan.neon
phpunit.xml
vendor/

View file

@ -34,6 +34,10 @@ script:
if [[ "${TRAVIS_PHP_VERSION}" == "7.2" ]]; then
vendor/bin/docheader check library tests
fi
- |
if [[ "${TRAVIS_PHP_VERSION}" == "7.2" ]]; then
vendor/bin/phpcs
fi
- |
if [[ "${TRAVIS_PHP_VERSION}" == "7.2" ]]; then
vendor/bin/phpstan analyze

View file

@ -11,6 +11,9 @@
"homepage": "https://github.com/Respect/Validation/graphs/contributors"
}
],
"config": {
"sort-packages": true
},
"require": {
"php": ">=7.1",
"respect/stringifier": "^0.2.0",
@ -22,6 +25,7 @@
"mikey179/vfsStream": "^1.6",
"phpstan/phpstan": "^0.10.3",
"phpunit/phpunit": "^7.3",
"squizlabs/php_codesniffer": "^3.4",
"symfony/validator": "^3.0||^4.0",
"zendframework/zend-validator": "^2.0"
},
@ -51,12 +55,14 @@
},
"scripts": {
"docheader": "vendor/bin/docheader check library/ tests/",
"phpcs": "vendor/bin/phpcs",
"phpstan": "vendor/bin/phpstan analyze",
"phpunit": "vendor/bin/phpunit",
"phpunit-integration": "vendor/bin/phpunit --testsuite=integration",
"phpunit-unit": "vendor/bin/phpunit --testsuite=unit",
"qa": [
"@docheader",
"@phpcs",
"@phpstan",
"@phpunit"
]

View file

@ -78,8 +78,14 @@ final class Factory
array $exceptionsNamespaces,
callable $translator
) {
$this->rulesNamespaces = $this->filterNamespaces($rulesNamespaces, self::DEFAULT_RULES_NAMESPACES);
$this->exceptionsNamespaces = $this->filterNamespaces($exceptionsNamespaces, self::DEFAULT_EXCEPTIONS_NAMESPACES);
$this->rulesNamespaces = $this->filterNamespaces(
$rulesNamespaces,
self::DEFAULT_RULES_NAMESPACES
);
$this->exceptionsNamespaces = $this->filterNamespaces(
$exceptionsNamespaces,
self::DEFAULT_EXCEPTIONS_NAMESPACES
);
$this->translator = $translator;
}
@ -233,8 +239,12 @@ final class Factory
*
* @return ValidationException
*/
private function createValidationException(string $exceptionName, string $id, $input, array $params): ValidationException
{
private function createValidationException(
string $exceptionName,
string $id,
$input,
array $params
): ValidationException {
/* @var ValidationException $exception */
$exception = $this->createReflectionClass($exceptionName, ValidationException::class)
->newInstance($input, $id, $params, $this->translator);

View file

@ -17,7 +17,9 @@ use ArrayAccess;
use SimpleXMLElement;
/**
* Validates if the input is an array or if the input can be used as an array (instance of `ArrayAccess` or `SimpleXMLElement`).
* Validates if the input is an array or if the input can be used as an array.
*
* Instance of `ArrayAccess` or `SimpleXMLElement` are also considered as valid.
*
* @author Alexandre Gomes Gaigalas <alexandre@gaigalas.net>
* @author Emmerson Siqueira <emmersonsiqueira@gmail.com>

View file

@ -50,13 +50,19 @@ final class Cnpj extends AbstractRule
return false;
}
for ($i = 0, $n = 0; $i < 12; $n += $cleanInput[$i] * $b[++$i]);
$n = 0;
for ($i = 0; $i < 12; ++$i) {
$n += $cleanInput[$i] * $b[$i+1];
}
if ($cleanInput[12] != ((($n %= 11) < 2) ? 0 : 11 - $n)) {
return false;
}
for ($i = 0, $n = 0; $i <= 12; $n += $cleanInput[$i] * $b[$i++]);
$n = 0;
for ($i = 0; $i <= 12; ++$i) {
$n += $cleanInput[$i] * $b[$i];
}
if ($cleanInput[13] != ((($n %= 11) < 2) ? 0 : 11 - $n)) {
return false;

View file

@ -41,13 +41,19 @@ final class Cpf extends AbstractRule
return false;
}
for ($s = 10, $n = 0, $i = 0; $s >= 2; $n += $c[$i++] * $s--);
$n = 0;
for ($s = 10, $i = 0; $s >= 2; ++$i, --$s) {
$n += $c[$i] * $s;
}
if ($c[9] != ((($n %= 11) < 2) ? 0 : 11 - $n)) {
return false;
}
for ($s = 11, $n = 0, $i = 0; $s >= 2; $n += $c[$i++] * $s--);
$n = 0;
for ($s = 11, $i = 0; $s >= 2; ++$i, --$s) {
$n += $c[$i] * $s;
}
if ($c[10] != ((($n %= 11) < 2) ? 0 : 11 - $n)) {
return false;

View file

@ -22,6 +22,7 @@ class PostalCode extends AbstractEnvelope
{
public const DEFAULT_PATTERN = '/^$/';
// phpcs:disable Generic.Files.LineLength.TooLong
/**
* @see http://download.geonames.org/export/dump/countryInfo.txt
*/
@ -187,6 +188,7 @@ class PostalCode extends AbstractEnvelope
'ZA' => '/^(\d{4})$/',
'ZM' => '/^(\d{5})$/',
];
// phpcs:enable Generic.Files.LineLength.TooLong
public function __construct($countryCode, CountryCode $countryCodeRule = null)
{

View file

@ -24,7 +24,9 @@ class Sorted extends AbstractRule
public function __construct(callable $fn = null, bool $ascending = true)
{
$this->fn = $fn ?? function ($x) { return $x; };
$this->fn = $fn ?? function ($x) {
return $x;
};
$this->ascending = $ascending;
}
@ -35,8 +37,7 @@ class Sorted extends AbstractRule
return true;
}
for ($i = 1; $i < $count; ++$i) {
if (
($this->ascending && ($this->fn)($input[$i]) < ($this->fn)($input[$i - 1]))
if (($this->ascending && ($this->fn)($input[$i]) < ($this->fn)($input[$i - 1]))
|| (!$this->ascending && ($this->fn)($input[$i]) > ($this->fn)($input[$i - 1]))
) {
return false;

View file

@ -35,6 +35,7 @@ final class VideoUrl extends AbstractRule
*/
private $service;
// phpcs:disable Generic.Files.LineLength.TooLong
/**
* @var array
*/
@ -43,6 +44,7 @@ final class VideoUrl extends AbstractRule
'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.

18
phpcs.xml.dist Normal file
View file

@ -0,0 +1,18 @@
<?xml version="1.0"?>
<ruleset
name="PHPCS Coding Standards for Respect"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="vendor/squizlabs/php_codesniffer/phpcs.xsd"
>
<arg name="basepath" value="." />
<arg name="cache" value=".phpcs.cache" />
<arg name="colors" />
<arg name="extensions" value="php,phpt" />
<arg value="p" />
<file>library/</file>
<file>tests/</file>
<rule ref="PSR1" />
<rule ref="PSR2" />
</ruleset>

View file

@ -10,9 +10,12 @@ use Respect\Validation\Validator;
Factory::setDefaultInstance(new Factory([], [], function (string $message): string {
$messages = [
'All of the required rules must pass for {{name}}' => 'Todas as regras requeridas devem passar para {{name}}',
'{{name}} must be of type string' => '{{name}} deve ser do tipo string',
'{{name}} must have a length between {{minValue}} and {{maxValue}}' => '{{name}} deve possuir de {{minValue}} a {{maxValue}} caracteres',
'All of the required rules must pass for {{name}}'
=> 'Todas as regras requeridas devem passar para {{name}}',
'{{name}} must be of type string'
=> '{{name}} deve ser do tipo string',
'{{name}} must have a length between {{minValue}} and {{maxValue}}'
=> '{{name}} deve possuir de {{minValue}} a {{maxValue}} caracteres',
];
return $messages[$message];

View file

@ -58,7 +58,8 @@ class AbstractRuleTest extends TestCase
$booleanResult,
// Invoking it to trigger __invoke
$abstractRuleMock($input),
'When invoking an instance of AbstractRule, the method validate should be called with the same input and return the same result.'
'When invoking an instance of AbstractRule, the method validate should'
. 'be called with the same input and return the same result.'
);
}

View file

@ -41,11 +41,17 @@ final class AttributeTest extends RuleTestCase
->willReturn(true);
return [
'Is valid when attribute is present without extra validator' => [new Attribute('bar'), $obj],
'Is valid when private attribute is present without extra validator' => [new Attribute('bar'), $this->objectWithPrivateProperty()],
'Is valid when attribute is present with extra validator' => [new Attribute('bar', $extraValidator), $obj],
'Is valid when non mandatory attribute is not present' => [new Attribute('foo', null, false), $obj],
'Is valid when non mandatory attribute is not present with extra validator' => [new Attribute('foo', $extraValidator, false), $obj],
'attribute is present without extra validator' => [new Attribute('bar'), $obj],
'private attribute is present without extra validator' => [
new Attribute('bar'),
$this->objectWithPrivateProperty()
],
'attribute is present with extra validator' => [new Attribute('bar', $extraValidator), $obj],
'non mandatory attribute is not present' => [new Attribute('foo', null, false), $obj],
'non mandatory attribute is not present with extra validator' => [
new Attribute('foo', $extraValidator, false),
$obj
],
];
}
@ -61,10 +67,13 @@ final class AttributeTest extends RuleTestCase
$extraValidatorMock->method('validate')->willReturn(false);
return [
'Is not valid when attribute is absent without extra validator' => [new Attribute('barr'), $obj],
'Is not valid when private attribute is not valid based on extra validator' => [new Attribute('bar', $extraValidatorMock), $this->objectWithPrivateProperty()],
'Is not valid when value provided is an empty string' => [new Attribute('barr'), ''],
'Is not valid when validator related to attribute does not validate' => [new Attribute('bar', $extraValidatorMock), $obj],
'attribute is absent without extra validator' => [new Attribute('barr'), $obj],
'private attribute is not valid based on extra validator' => [
new Attribute('bar', $extraValidatorMock),
$this->objectWithPrivateProperty()
],
'value provided is an empty string' => [new Attribute('barr'), ''],
'validator related to attribute does not validate' => [new Attribute('bar', $extraValidatorMock), $obj],
];
}

View file

@ -37,7 +37,9 @@ final class CallbackTest extends RuleTestCase
[new Callback('is_a', 'stdClass'), new \stdClass()],
[new Callback([$this, 'thisIsASampleCallbackUsedInsideThisTest']), 'test'],
[new Callback('is_string'), 'test'],
[new Callback(function () { return true; }), 'wpoiur'],
[new Callback(function () {
return true;
}), 'wpoiur'],
];
}
@ -52,8 +54,12 @@ final class CallbackTest extends RuleTestCase
public function providerForInvalidInput(): array
{
return [
[new Callback(function () { return false; }), 'w poiur'],
[new Callback(function () { return false; }), ''],
[new Callback(function () {
return false;
}), 'w poiur'],
[new Callback(function () {
return false;
}), ''],
];
}
}

View file

@ -96,7 +96,10 @@ final class FactorTest extends RuleTestCase
'mt_rand is not factor -1.5' => [new Factor(mt_rand()), -1.5],
'mt_rand is not factor PHP_INT_MAX + 1' => [new Factor(mt_rand()), PHP_INT_MAX + 1],
'mt_rand is not factor calc' => [new Factor(mt_rand()), mt_rand(1, mt_getrandmax() - 1) / mt_getrandmax()],
'mt_rand is not factor -calc' => [new Factor(mt_rand()), -(mt_rand(1, mt_getrandmax() - 1) / mt_getrandmax())],
'mt_rand is not factor -calc' => [
new Factor(mt_rand()),
-(mt_rand(1, mt_getrandmax() - 1) / mt_getrandmax())
],
'mt_rand is not factor \'a\'' => [new Factor(mt_rand()), 'a'],
'mt_rand is not factor \'foo\'' => [new Factor(mt_rand()), 'foo'],
'mt_rand is not factor uniqid(\'a\')' => [new Factor(mt_rand()), uniqid('a')],

View file

@ -61,7 +61,8 @@ final class MacAddressTest extends RuleTestCase
'float' => [$sut, random_int(1, 9) / 10],
'null' => [$sut, null],
'resource' => [$sut, tmpfile()],
'callable' => [$sut, function (): void {}],
'callable' => [$sut, function (): void {
}],
];
}
}

View file

@ -40,7 +40,7 @@ final class MimetypeTest extends RuleTestCase
public function itShouldValidateWithDefinedFinfoInstance(): void
{
$mimetype = 'application/octet-stream';
$filename = $this->getFixtureDirectory().'/valid-image.png';
$filename = 'tests/fixtures/valid-image.png';
$fileInfoMock = $this
->getMockBuilder(finfo::class)
@ -65,12 +65,12 @@ final class MimetypeTest extends RuleTestCase
public function providerForValidInput(): array
{
return [
'image/png' => [new Mimetype('image/png'), $this->getFixtureDirectory().'/valid-image.png'],
'image/gif' => [new Mimetype('image/gif'), $this->getFixtureDirectory().'/valid-image.gif'],
'image/jpeg' => [new Mimetype('image/jpeg'), $this->getFixtureDirectory().'/valid-image.jpg'],
'text/plain' => [new Mimetype('text/plain'), $this->getFixtureDirectory().'/executable'],
'SplFileInfo' => [new Mimetype('image/png'), new SplFileInfo($this->getFixtureDirectory().'/valid-image.png')],
'SplFileObject' => [new Mimetype('image/png'), new SplFileObject($this->getFixtureDirectory().'/valid-image.png')],
'image/png' => [new Mimetype('image/png'), 'tests/fixtures/valid-image.png'],
'image/gif' => [new Mimetype('image/gif'), 'tests/fixtures/valid-image.gif'],
'image/jpeg' => [new Mimetype('image/jpeg'), 'tests/fixtures/valid-image.jpg'],
'text/plain' => [new Mimetype('text/plain'), 'tests/fixtures/executable'],
'SplFileInfo' => [new Mimetype('image/png'), new SplFileInfo('tests/fixtures/valid-image.png')],
'SplFileObject' => [new Mimetype('image/png'), new SplFileObject('tests/fixtures/valid-image.png')],
];
}
@ -80,8 +80,8 @@ final class MimetypeTest extends RuleTestCase
public function providerForInvalidInput(): array
{
return [
'invalid file' => [new Mimetype('image/png'), $this->getFixtureDirectory().'/invalid-image.png'],
'mismatch' => [new Mimetype('image/gif'), $this->getFixtureDirectory().'/valid-image.png'],
'invalid file' => [new Mimetype('image/png'), 'tests/fixtures/invalid-image.png'],
'mismatch' => [new Mimetype('image/gif'), 'tests/fixtures/valid-image.png'],
'directory' => [new Mimetype('application/octet-stream'), __DIR__],
'boolean' => [new Mimetype('application/octet-stream'), true],
'array' => [new Mimetype('application/octet-stream'), [__FILE__]],

View file

@ -37,9 +37,9 @@ final class SymbolicLinkTest extends RuleTestCase
$sut = new SymbolicLink();
return [
'filename' => [$sut, $this->getFixtureDirectory().'/symbolic-link'],
'SplFileInfo' => [$sut, new SplFileInfo($this->getFixtureDirectory().'/symbolic-link')],
'SplFileObject' => [$sut, new SplFileObject($this->getFixtureDirectory().'/symbolic-link')],
'filename' => [$sut, 'tests/fixtures/symbolic-link'],
'SplFileInfo' => [$sut, new SplFileInfo('tests/fixtures/symbolic-link')],
'SplFileObject' => [$sut, new SplFileObject('tests/fixtures/symbolic-link')],
];
}
@ -51,8 +51,8 @@ final class SymbolicLinkTest extends RuleTestCase
$sut = new SymbolicLink();
return [
'no existing filename' => [$sut, $this->getFixtureDirectory().'/non-existing-symbolic-link'],
'no existing SplFileInfo' => [$sut, new SplFileInfo($this->getFixtureDirectory().'/non-existing-symbolic-link')],
'no existing filename' => [$sut, 'tests/fixtures/non-existing-symbolic-link'],
'no existing SplFileInfo' => [$sut, new SplFileInfo('tests/fixtures/non-existing-symbolic-link')],
'bool true' => [$sut, true],
'bool false' => [$sut, false],
'empty string' => [$sut, ''],

View file

@ -29,7 +29,7 @@ class TypeTest extends RuleTestCase
{
/**
* @expectedException \Respect\Validation\Exceptions\ComponentException
* @expectedExceptionMessage "whatever" is not a valid type (Available: array, bool, boolean, callable, double, float, int, integer, null, object, resource, string)
* @expectedExceptionMessageRegExp /"whatever" is not a valid type \(Available: .+\)/
*
* @test
*/

View file

@ -34,23 +34,43 @@ final class WhenTest extends RuleTestCase
{
return [
'all true' => [
new When($this->createValidatableMock(true), $this->createValidatableMock(true), $this->createValidatableMock(true)),
new When(
$this->createValidatableMock(true),
$this->createValidatableMock(true),
$this->createValidatableMock(true)
),
true,
],
'bool (when = true, then = true, else = false)' => [
new When($this->createValidatableMock(true), $this->createValidatableMock(true), $this->createValidatableMock(false)),
new When(
$this->createValidatableMock(true),
$this->createValidatableMock(true),
$this->createValidatableMock(false)
),
true,
],
'bool (when = false, then = true, else = true)' => [
new When($this->createValidatableMock(false), $this->createValidatableMock(true), $this->createValidatableMock(true)),
new When(
$this->createValidatableMock(false),
$this->createValidatableMock(true),
$this->createValidatableMock(true)
),
true,
],
'bool (when = false, then = false, else = true)' => [
new When($this->createValidatableMock(false), $this->createValidatableMock(false), $this->createValidatableMock(true)),
new When(
$this->createValidatableMock(false),
$this->createValidatableMock(false),
$this->createValidatableMock(true)
),
true,
],
'bool (when = false, then = true, else = null)' => [
new When($this->createValidatableMock(true), $this->createValidatableMock(true), null),
new When(
$this->createValidatableMock(true),
$this->createValidatableMock(true),
null
),
true,
],
];
@ -63,19 +83,35 @@ final class WhenTest extends RuleTestCase
{
return [
'bool (when = true, then = false, else = false)' => [
new When($this->createValidatableMock(true), $this->createValidatableMock(false), $this->createValidatableMock(false)),
new When(
$this->createValidatableMock(true),
$this->createValidatableMock(false),
$this->createValidatableMock(false)
),
false,
],
'bool (when = true, then = false, else = true)' => [
new When($this->createValidatableMock(true), $this->createValidatableMock(false), $this->createValidatableMock(true)),
new When(
$this->createValidatableMock(true),
$this->createValidatableMock(false),
$this->createValidatableMock(true)
),
false,
],
'bool (when = false, then = false, else = false)' => [
new When($this->createValidatableMock(false), $this->createValidatableMock(false), $this->createValidatableMock(false)),
new When(
$this->createValidatableMock(false),
$this->createValidatableMock(false),
$this->createValidatableMock(false)
),
false,
],
'bool (when = true, then = false, else = null)' => [
new When($this->createValidatableMock(true), $this->createValidatableMock(false), null),
new When(
$this->createValidatableMock(true),
$this->createValidatableMock(false),
null
),
false,
],
];

View file

@ -80,7 +80,7 @@ class ZendTest extends TestCase
*/
public function userlandValidatorExtendingZendInterface(): void
{
$v = new Zend(new MyValidator());
$v = new Zend(new ZendDate());
self::assertAttributeInstanceOf(
$instanceOf = ValidatorInterface::class,
$attribute = 'zendValidator',
@ -107,7 +107,7 @@ class ZendTest extends TestCase
*
* @test
*/
public function constructorWithValidatorName_and_params(): void
public function constructorWithValidatorNameAndParams(): void
{
$zendValidatorName = 'StringLength';
$zendValidatorParams = ['min' => 10, 'max' => 25];
@ -153,7 +153,7 @@ class ZendTest extends TestCase
/**
* @depends constructorWithValidatorName
* @depends constructorWithValidatorName_and_params
* @depends constructorWithValidatorNameAndParams
* @depends zendDateValidatorWithRespectMethods
* @expectedException \Respect\Validation\Exceptions\ZendException
*
@ -165,10 +165,3 @@ class ZendTest extends TestCase
$v->assert('aw');
}
}
// Stubs
if (class_exists(ZendDate::class)) {
class MyValidator extends ZendDate
{
}
}