From dd5ac0f7e6d0b2fe994303554f67210b85cc22a5 Mon Sep 17 00:00:00 2001 From: Meritoo Date: Sun, 5 May 2019 09:49:03 +0200 Subject: [PATCH] Fix code pointed by Psalm --- src/Exception/Base/UnknownTypeException.php | 4 +- src/Exception/File/EmptyFilePathException.php | 4 +- .../CannotResolveClassNameException.php | 2 +- .../ClassWithoutConstructorException.php | 34 ++ .../MissingChildClassesException.php | 4 +- .../NotExistingPropertyException.php | 6 +- .../TooManyChildClassesException.php | 4 +- .../Type/UnknownDatePartTypeException.php | 2 +- .../UnknownOopVisibilityTypeException.php | 2 +- src/Traits/Test/Base/BaseTestCaseTrait.php | 80 ++-- .../Test/Base/BaseTypeTestCaseTrait.php | 14 +- src/Traits/ValueObject/HumanTrait.php | 35 +- src/Type/Base/BaseType.php | 8 +- src/Type/DatePeriod.php | 64 +-- src/Type/OopVisibilityType.php | 12 +- src/Utilities/Arrays.php | 314 ++++++------ src/Utilities/Miscellaneous.php | 23 +- src/Utilities/Reflection.php | 103 ++-- tests/Collection/CollectionTest.php | 14 +- .../IncorrectBundleNameExceptionTest.php | 13 +- .../CannotResolveClassNameExceptionTest.php | 19 +- .../ClassWithoutConstructorExceptionTest.php | 66 +++ .../MissingChildClassesExceptionTest.php | 14 +- .../NotExistingPropertyExceptionTest.php | 16 +- .../TooManyChildClassesExceptionTest.php | 14 +- .../UnknownOopVisibilityTypeExceptionTest.php | 14 +- tests/Type/DatePartTypeTest.php | 24 +- tests/Type/DatePeriodTest.php | 67 ++- tests/Type/OopVisibilityTypeTest.php | 16 +- tests/Utilities/ArraysTest.php | 450 +++++++++++++++--- tests/Utilities/DateTest.php | 82 ++-- tests/Utilities/MiscellaneousTest.php | 71 ++- tests/Utilities/ReflectionTest.php | 14 +- 33 files changed, 1085 insertions(+), 524 deletions(-) create mode 100644 src/Exception/Reflection/ClassWithoutConstructorException.php create mode 100644 tests/Exception/Reflection/ClassWithoutConstructorExceptionTest.php diff --git a/src/Exception/Base/UnknownTypeException.php b/src/Exception/Base/UnknownTypeException.php index 43abda2..d42571b 100644 --- a/src/Exception/Base/UnknownTypeException.php +++ b/src/Exception/Base/UnknownTypeException.php @@ -28,13 +28,13 @@ abstract class UnknownTypeException extends Exception * @param string $typeName Name of the something * @return UnknownTypeException */ - public static function create($unknownType, BaseType $typeInstance, $typeName) + public static function create($unknownType, BaseType $typeInstance, string $typeName): UnknownTypeException { $template = 'The \'%s\' type of %s is unknown. Probably doesn\'t exist or there is a typo. You should use one' . ' of these types: %s.'; $allTypes = $typeInstance->getAll(); - $types = Arrays::values2string($allTypes, '', ', '); + $types = Arrays::values2string($allTypes, '', ', ') ?? '[types not found]'; $message = sprintf($template, $unknownType, $typeName, $types); return new static($message); diff --git a/src/Exception/File/EmptyFilePathException.php b/src/Exception/File/EmptyFilePathException.php index 33333f5..f4386f7 100644 --- a/src/Exception/File/EmptyFilePathException.php +++ b/src/Exception/File/EmptyFilePathException.php @@ -18,8 +18,10 @@ class EmptyFilePathException extends \Exception { /** * Creates exception + * + * @return EmptyFilePathException */ - public static function create() + public static function create(): EmptyFilePathException { return new static('Path of the file is empty. Did you provide path of proper file?'); } diff --git a/src/Exception/Reflection/CannotResolveClassNameException.php b/src/Exception/Reflection/CannotResolveClassNameException.php index dee9dde..ff5191f 100644 --- a/src/Exception/Reflection/CannotResolveClassNameException.php +++ b/src/Exception/Reflection/CannotResolveClassNameException.php @@ -27,7 +27,7 @@ class CannotResolveClassNameException extends Exception * prepared. Otherwise - for trait. * @return CannotResolveClassNameException */ - public static function create($source, $forClass = true) + public static function create($source, bool $forClass = true): CannotResolveClassNameException { $forWho = 'trait'; $value = ''; diff --git a/src/Exception/Reflection/ClassWithoutConstructorException.php b/src/Exception/Reflection/ClassWithoutConstructorException.php new file mode 100644 index 0000000..b67a44a --- /dev/null +++ b/src/Exception/Reflection/ClassWithoutConstructorException.php @@ -0,0 +1,34 @@ + + * @copyright Meritoo + */ +class ClassWithoutConstructorException extends Exception +{ + /** + * Creates exception + * + * @param string $className Fully-qualified name of class that hasn't constructor + * @return ClassWithoutConstructorException + */ + public static function create(string $className): ClassWithoutConstructorException + { + $template = 'Oops, class \'%s\' hasn\'t constructor. Did you use proper class?'; + $message = sprintf($template, $className); + + return new static($message); + } +} diff --git a/src/Exception/Reflection/MissingChildClassesException.php b/src/Exception/Reflection/MissingChildClassesException.php index 27183ff..8a51e09 100644 --- a/src/Exception/Reflection/MissingChildClassesException.php +++ b/src/Exception/Reflection/MissingChildClassesException.php @@ -26,12 +26,12 @@ class MissingChildClassesException extends Exception * strings, object or string. * @return MissingChildClassesException */ - public static function create($parentClass) + public static function create($parentClass): MissingChildClassesException { $template = 'The \'%s\' class requires one child class at least who will extend her (maybe is an abstract' . ' class), but the child classes are missing. Did you forget to extend this class?'; - $parentClassName = Reflection::getClassName($parentClass); + $parentClassName = Reflection::getClassName($parentClass) ?? '[unknown class]'; $message = sprintf($template, $parentClassName); return new static($message); diff --git a/src/Exception/Reflection/NotExistingPropertyException.php b/src/Exception/Reflection/NotExistingPropertyException.php index 4b7484f..35723a4 100644 --- a/src/Exception/Reflection/NotExistingPropertyException.php +++ b/src/Exception/Reflection/NotExistingPropertyException.php @@ -19,11 +19,11 @@ class NotExistingPropertyException extends \Exception /** * Creates exception * - * @param mixed $object Object that should contains given property - * @param string $property Name of the property + * @param mixed $object Object that should contains given property + * @param null|string $property Name of the property * @return NotExistingPropertyException */ - public static function create($object, $property) + public static function create($object, ?string $property): NotExistingPropertyException { $template = 'Property \'%s\' does not exist in instance of class \'%s\'. Did you use proper name of property?'; $message = sprintf($template, $property, get_class($object)); diff --git a/src/Exception/Reflection/TooManyChildClassesException.php b/src/Exception/Reflection/TooManyChildClassesException.php index f06dab2..19967dc 100644 --- a/src/Exception/Reflection/TooManyChildClassesException.php +++ b/src/Exception/Reflection/TooManyChildClassesException.php @@ -27,12 +27,12 @@ class TooManyChildClassesException extends Exception * @param array $childClasses Child classes * @return TooManyChildClassesException */ - public static function create($parentClass, array $childClasses) + public static function create($parentClass, array $childClasses): TooManyChildClassesException { $template = "The '%s' class requires one child class at most who will extend her, but more than one child" . " class was found:\n- %s\n\nWhy did you create more than one classes that extend '%s' class?"; - $parentClassName = Reflection::getClassName($parentClass); + $parentClassName = Reflection::getClassName($parentClass) ?? '[unknown class]'; $message = sprintf($template, $parentClassName, implode("\n- ", $childClasses), $parentClassName); return new static($message); diff --git a/src/Exception/Type/UnknownDatePartTypeException.php b/src/Exception/Type/UnknownDatePartTypeException.php index 2a85b2b..29e1d5a 100644 --- a/src/Exception/Type/UnknownDatePartTypeException.php +++ b/src/Exception/Type/UnknownDatePartTypeException.php @@ -26,7 +26,7 @@ class UnknownDatePartTypeException extends UnknownTypeException * @param string $value Incorrect value * @return UnknownDatePartTypeException */ - public static function createException($unknownDatePart, $value) + public static function createException(string $unknownDatePart, string $value): UnknownDatePartTypeException { return parent::create($unknownDatePart, new DatePartType(), sprintf('date part (with value %s)', $value)); } diff --git a/src/Exception/Type/UnknownOopVisibilityTypeException.php b/src/Exception/Type/UnknownOopVisibilityTypeException.php index 6f4ef01..6463362 100644 --- a/src/Exception/Type/UnknownOopVisibilityTypeException.php +++ b/src/Exception/Type/UnknownOopVisibilityTypeException.php @@ -25,7 +25,7 @@ class UnknownOopVisibilityTypeException extends UnknownTypeException * @param string $unknownType Unknown visibility of a property, a method or (as of PHP 7.1.0) a constant * @return UnknownOopVisibilityTypeException */ - public static function createException($unknownType) + public static function createException(string $unknownType): UnknownOopVisibilityTypeException { return parent::create($unknownType, new OopVisibilityType(), 'OOP-related visibility'); } diff --git a/src/Traits/Test/Base/BaseTestCaseTrait.php b/src/Traits/Test/Base/BaseTestCaseTrait.php index 30bffcd..dfb5452 100644 --- a/src/Traits/Test/Base/BaseTestCaseTrait.php +++ b/src/Traits/Test/Base/BaseTestCaseTrait.php @@ -10,11 +10,13 @@ namespace Meritoo\Common\Traits\Test\Base; use DateTime; use Generator; +use Meritoo\Common\Exception\Reflection\ClassWithoutConstructorException; use Meritoo\Common\Exception\Type\UnknownOopVisibilityTypeException; use Meritoo\Common\Type\OopVisibilityType; use Meritoo\Common\Utilities\Miscellaneous; use ReflectionClass; use ReflectionMethod; +use RuntimeException; use stdClass; /** @@ -37,7 +39,7 @@ trait BaseTestCaseTrait * * @return Generator */ - public function provideEmptyValue() + public function provideEmptyValue(): ?Generator { yield['']; yield[' ']; @@ -52,7 +54,7 @@ trait BaseTestCaseTrait * * @return Generator */ - public function provideEmptyScalarValue() + public function provideEmptyScalarValue(): ?Generator { yield['']; yield[' ']; @@ -66,7 +68,7 @@ trait BaseTestCaseTrait * * @return Generator */ - public function provideBooleanValue() + public function provideBooleanValue(): ?Generator { yield[false]; yield[true]; @@ -77,7 +79,7 @@ trait BaseTestCaseTrait * * @return Generator */ - public function provideDateTimeInstance() + public function provideDateTimeInstance(): ?Generator { yield[new DateTime()]; yield[new DateTime('yesterday')]; @@ -90,7 +92,7 @@ trait BaseTestCaseTrait * * @return Generator */ - public function provideDateTimeRelativeFormat() + public function provideDateTimeRelativeFormat(): ?Generator { yield['now']; yield['yesterday']; @@ -110,7 +112,7 @@ trait BaseTestCaseTrait * * @return Generator */ - public function provideNotExistingFilePath() + public function provideNotExistingFilePath(): ?Generator { yield['lets-test.doc']; yield['lorem/ipsum.jpg']; @@ -122,7 +124,7 @@ trait BaseTestCaseTrait * * @return Generator */ - public function provideNonScalarValue() + public function provideNonScalarValue(): ?Generator { yield[ [], @@ -145,7 +147,7 @@ trait BaseTestCaseTrait * @param string $directoryPath (optional) Path of directory containing the file * @return string */ - public function getFilePathForTesting($fileName, $directoryPath = '') + public function getFilePathForTesting(string $fileName, string $directoryPath = ''): string { $rootPath = Miscellaneous::getProjectRootPath(); @@ -162,33 +164,34 @@ trait BaseTestCaseTrait /** * Verifies visibility and arguments of method * - * @param string $classNamespace Namespace of class that contains method to verify - * @param ReflectionMethod|string $method Name of method or just the method to verify - * @param string $visibilityType Expected visibility of verified method. One of - * OopVisibilityType class constants. - * @param int $argumentsCount (optional) Expected count/amount of arguments of the - * verified method - * @param int $requiredArgumentsCount (optional) Expected count/amount of required arguments - * of the verified method + * @param string $className Fully-qualified name of class that contains method to verify + * @param ReflectionMethod $method Name of method or just the method to verify + * @param string $visibilityType Expected visibility of verified method. One of OopVisibilityType + * class constants. + * @param int $argumentsCount (optional) Expected count/amount of arguments of the verified + * method + * @param int $requiredArgumentsCount (optional) Expected count/amount of required arguments of the + * verified method * @throws UnknownOopVisibilityTypeException + * @throws RuntimeException * * Attention. 2nd argument, the $method, may be: * - string - name of the method * - instance of ReflectionMethod - just the method (provided by ReflectionClass::getMethod() method) */ protected static function assertMethodVisibilityAndArguments( - $classNamespace, - $method, - $visibilityType, - $argumentsCount = 0, - $requiredArgumentsCount = 0 - ) { + string $className, + ReflectionMethod $method, + string $visibilityType, + int $argumentsCount = 0, + int $requiredArgumentsCount = 0 + ): void { // Type of visibility is not correct? if (!(new OopVisibilityType())->isCorrectType($visibilityType)) { - throw new UnknownOopVisibilityTypeException($visibilityType); + throw UnknownOopVisibilityTypeException::createException($visibilityType); } - $reflection = new ReflectionClass($classNamespace); + $reflection = new ReflectionClass($className); // Name of method provided only? // Let's find instance of the method (based on reflection) @@ -218,24 +221,29 @@ trait BaseTestCaseTrait /** * Verifies visibility and arguments of class constructor * - * @param string $classNamespace Namespace of class that contains constructor to verify + * @param string $className Fully-qualified name of class that contains constructor to verify * @param string $visibilityType Expected visibility of verified method. One of OopVisibilityType class * constants. * @param int $argumentsCount (optional) Expected count/amount of arguments of the verified method * @param int $requiredArgumentsCount (optional) Expected count/amount of required arguments of the verified * method + * @throws ClassWithoutConstructorException */ protected static function assertConstructorVisibilityAndArguments( - $classNamespace, - $visibilityType, - $argumentsCount = 0, - $requiredArgumentsCount = 0 - ) { - $reflection = new ReflectionClass($classNamespace); + string $className, + string $visibilityType, + int $argumentsCount = 0, + int $requiredArgumentsCount = 0 + ): void { + $reflection = new ReflectionClass($className); $method = $reflection->getConstructor(); + if (null === $method) { + throw ClassWithoutConstructorException::create($className); + } + static::assertMethodVisibilityAndArguments( - $classNamespace, + $className, $method, $visibilityType, $argumentsCount, @@ -246,11 +254,11 @@ trait BaseTestCaseTrait /** * Asserts that class with given namespace has no constructor * - * @param string $classNamespace Namespace of class that contains constructor to verify + * @param string $className Fully-qualified name of class that contains constructor to verify */ - protected static function assertHasNoConstructor($classNamespace) + protected static function assertHasNoConstructor(string $className): void { - $reflection = new ReflectionClass($classNamespace); + $reflection = new ReflectionClass($className); $constructor = $reflection->getConstructor(); static::assertNull($constructor); @@ -261,7 +269,7 @@ trait BaseTestCaseTrait * * @param string $testsDataDirPath Path of directory with data used by test cases */ - protected static function setTestsDataDirPath($testsDataDirPath) + protected static function setTestsDataDirPath(string $testsDataDirPath): void { static::$testsDataDirPath = $testsDataDirPath; } diff --git a/src/Traits/Test/Base/BaseTypeTestCaseTrait.php b/src/Traits/Test/Base/BaseTypeTestCaseTrait.php index 5633c8d..4fc2f1a 100644 --- a/src/Traits/Test/Base/BaseTypeTestCaseTrait.php +++ b/src/Traits/Test/Base/BaseTypeTestCaseTrait.php @@ -22,7 +22,7 @@ trait BaseTypeTestCaseTrait /** * Verifies availability of all types */ - public function testAvailabilityOfAllTypes() + public function testAvailabilityOfAllTypes(): void { $available = $this->getTestedTypeInstance()->getAll(); $all = $this->getAllExpectedTypes(); @@ -33,12 +33,12 @@ trait BaseTypeTestCaseTrait /** * Verifies whether given type is correct or not * - * @param string $type Type to verify - * @param bool $expected Information if given type is correct or not + * @param null|string $type Type to verify + * @param bool $expected Information if given type is correct or not * * @dataProvider provideTypeToVerify */ - public function testIfGivenTypeIsCorrect($type, $expected) + public function testIfGivenTypeIsCorrect(?string $type, bool $expected): void { static::assertEquals($expected, $this->getTestedTypeInstance()->isCorrectType($type)); } @@ -48,19 +48,19 @@ trait BaseTypeTestCaseTrait * * @return Generator */ - abstract public function provideTypeToVerify(); + abstract public function provideTypeToVerify(): Generator; /** * Returns instance of the tested type * * @return BaseType */ - abstract protected function getTestedTypeInstance(); + abstract protected function getTestedTypeInstance(): BaseType; /** * Returns all expected types of the tested type * * @return array */ - abstract protected function getAllExpectedTypes(); + abstract protected function getAllExpectedTypes(): array; } diff --git a/src/Traits/ValueObject/HumanTrait.php b/src/Traits/ValueObject/HumanTrait.php index e0eb795..a75bfa6 100644 --- a/src/Traits/ValueObject/HumanTrait.php +++ b/src/Traits/ValueObject/HumanTrait.php @@ -8,6 +8,8 @@ namespace Meritoo\Common\Traits\ValueObject; +use DateTime; + /** * Methods and properties related to human * @@ -33,26 +35,26 @@ trait HumanTrait /** * Email address * - * @var string + * @var null|string */ protected $email; /** * Birth date * - * @var \DateTime + * @var null|DateTime */ protected $birthDate; /** * Class constructor * - * @param string $firstName First name - * @param string $lastName Last name - * @param string $email (optional) Email address - * @param \DateTime $birthDate (optional) Birth date + * @param string $firstName First name + * @param string $lastName Last name + * @param null|string $email (optional) Email address. Default: null. + * @param null|DateTime $birthDate (optional) Birth date. Default: null. */ - public function __construct($firstName, $lastName, $email = null, \DateTime $birthDate = null) + public function __construct(string $firstName, string $lastName, ?string $email = null, ?DateTime $birthDate = null) { $this->firstName = $firstName; $this->lastName = $lastName; @@ -68,12 +70,14 @@ trait HumanTrait public function __toString() { $template = '%s'; + $email = ''; if ('' !== $this->email && null !== $this->email) { $template .= ' <%s>'; + $email = $this->email; } - return sprintf($template, $this->getFullName(), $this->email); + return sprintf($template, $this->getFullName(), $email); } /** @@ -81,7 +85,7 @@ trait HumanTrait * * @return string */ - public function getFirstName() + public function getFirstName(): string { return $this->firstName; } @@ -91,7 +95,7 @@ trait HumanTrait * * @return string */ - public function getLastName() + public function getLastName(): string { return $this->lastName; } @@ -101,7 +105,7 @@ trait HumanTrait * * @return null|string */ - public function getEmail() + public function getEmail(): ?string { return $this->email; } @@ -109,9 +113,9 @@ trait HumanTrait /** * Returns birth date * - * @return null|\DateTime + * @return null|DateTime */ - public function getBirthDate() + public function getBirthDate(): ?DateTime { return $this->birthDate; } @@ -119,10 +123,11 @@ trait HumanTrait /** * Returns the full name * - * @param bool $firstNameFirst (optional) If is set to true, first name is the first part. Otherwise - last name. + * @param bool $firstNameFirst (optional) If is set to true, first name is the first part (default behaviour). + * Otherwise - name. * @return string */ - public function getFullName($firstNameFirst = true) + public function getFullName(bool $firstNameFirst = true): string { $beginning = $this->lastName; $finish = $this->firstName; diff --git a/src/Type/Base/BaseType.php b/src/Type/Base/BaseType.php index ec8dafa..fa3f6c7 100644 --- a/src/Type/Base/BaseType.php +++ b/src/Type/Base/BaseType.php @@ -22,7 +22,7 @@ abstract class BaseType /** * All types * - * @var array + * @var null|array */ private $all; @@ -31,7 +31,7 @@ abstract class BaseType * * @return array */ - public function getAll() + public function getAll(): array { if (null === $this->all) { $this->all = Reflection::getConstants($this); @@ -43,10 +43,10 @@ abstract class BaseType /** * Returns information if given type is correct * - * @param mixed $type The type to check + * @param null|string $type The type to check * @return bool */ - public function isCorrectType($type) + public function isCorrectType(?string $type): bool { return in_array($type, $this->getAll(), true); } diff --git a/src/Type/DatePeriod.php b/src/Type/DatePeriod.php index 590e8ff..d25985c 100644 --- a/src/Type/DatePeriod.php +++ b/src/Type/DatePeriod.php @@ -24,87 +24,87 @@ class DatePeriod extends BaseType /** * The period constant: last month * - * @var int + * @var string */ - public const LAST_MONTH = 4; + public const LAST_MONTH = '4'; /** * The period constant: last week * - * @var int + * @var string */ - public const LAST_WEEK = 1; + public const LAST_WEEK = '1'; /** * The period constant: last year * - * @var int + * @var string */ - public const LAST_YEAR = 7; + public const LAST_YEAR = '7'; /** * The period constant: next month * - * @var int + * @var string */ - public const NEXT_MONTH = 6; + public const NEXT_MONTH = '6'; /** * The period constant: next week * - * @var int + * @var string */ - public const NEXT_WEEK = 3; + public const NEXT_WEEK = '3'; /** * The period constant: next year * - * @var int + * @var string */ - public const NEXT_YEAR = 9; + public const NEXT_YEAR = '9'; /** * The period constant: this month * - * @var int + * @var string */ - public const THIS_MONTH = 5; + public const THIS_MONTH = '5'; /** * The period constant: this week * - * @var int + * @var string */ - public const THIS_WEEK = 2; + public const THIS_WEEK = '2'; /** * The period constant: this year * - * @var int + * @var string */ - public const THIS_YEAR = 8; + public const THIS_YEAR = '8'; /** * The start date of period * - * @var DateTime + * @var null|DateTime */ private $startDate; /** * The end date of period * - * @var DateTime + * @var null|DateTime */ private $endDate; /** * Class constructor * - * @param DateTime $startDate (optional) The start date of period - * @param DateTime $endDate (optional) The end date of period + * @param null|DateTime $startDate (optional) The start date of period + * @param null|DateTime $endDate (optional) The end date of period */ - public function __construct(DateTime $startDate = null, DateTime $endDate = null) + public function __construct(?DateTime $startDate = null, ?DateTime $endDate = null) { $this->startDate = $startDate; $this->endDate = $endDate; @@ -117,7 +117,7 @@ class DatePeriod extends BaseType * @param bool $startDate (optional) If is set to true, start date will be formatted. Otherwise - end date. * @return string */ - public function getFormattedDate($format, $startDate = true) + public function getFormattedDate(string $format, bool $startDate = true): string { $date = $this->getEndDate(); @@ -138,9 +138,9 @@ class DatePeriod extends BaseType /** * Returns the end date of period * - * @return DateTime + * @return null|DateTime */ - public function getEndDate() + public function getEndDate(): ?DateTime { return $this->endDate; } @@ -148,10 +148,10 @@ class DatePeriod extends BaseType /** * Sets the end date of period * - * @param DateTime $endDate (optional) The end date of period + * @param null|DateTime $endDate (optional) The end date of period. Default: null. * @return $this */ - public function setEndDate(DateTime $endDate = null) + public function setEndDate(?DateTime $endDate = null): self { $this->endDate = $endDate; @@ -161,9 +161,9 @@ class DatePeriod extends BaseType /** * Returns the start date of period * - * @return DateTime + * @return null|DateTime */ - public function getStartDate() + public function getStartDate(): ?DateTime { return $this->startDate; } @@ -171,10 +171,10 @@ class DatePeriod extends BaseType /** * Sets the start date of period * - * @param DateTime $startDate (optional) The start date of period + * @param null|DateTime $startDate (optional) The start date of period. Default: null. * @return $this */ - public function setStartDate(DateTime $startDate = null) + public function setStartDate(?DateTime $startDate = null): self { $this->startDate = $startDate; diff --git a/src/Type/OopVisibilityType.php b/src/Type/OopVisibilityType.php index 95eb52a..1299eea 100644 --- a/src/Type/OopVisibilityType.php +++ b/src/Type/OopVisibilityType.php @@ -17,21 +17,21 @@ class OopVisibilityType extends BaseType /** * The "private" visibility of OOP * - * @var int + * @var string */ - public const IS_PRIVATE = 3; + public const IS_PRIVATE = '3'; /** * The "protected" visibility of OOP * - * @var int + * @var string */ - public const IS_PROTECTED = 2; + public const IS_PROTECTED = '2'; /** * The "public" visibility of OOP * - * @var int + * @var string */ - public const IS_PUBLIC = 1; + public const IS_PUBLIC = '1'; } diff --git a/src/Utilities/Arrays.php b/src/Utilities/Arrays.php index b20fba7..3652ebb 100644 --- a/src/Utilities/Arrays.php +++ b/src/Utilities/Arrays.php @@ -335,7 +335,7 @@ class Arrays * The last row is not an array or it's an empty array? * Let's use the previous candidate */ - if (!is_array($effect) || (is_array($effect) && empty($effect))) { + if (!is_array($effect) || self::isEmptyArray($effect)) { $effect = $last; } } @@ -346,27 +346,29 @@ class Arrays /** * Replaces array keys that match given pattern with new key name * - * @param array $dataArray The array - * @param string $oldKeyPattern Old key pattern - * @param string $newKey New key name - * @return array + * @param array $array Array which keys should be replaced + * @param string $oldKeyPattern Regular expression of the old key + * @param string $newKey Name of the new key + * @return null|array */ - public static function replaceArrayKeys($dataArray, $oldKeyPattern, $newKey) + public static function replaceKeys(array $array, string $oldKeyPattern, string $newKey): ?array { + if (empty($array)) { + return null; + } + $effect = []; - if (is_array($dataArray) && !empty($dataArray)) { - foreach ($dataArray as $key => $value) { - if (preg_match($oldKeyPattern, $key)) { - $key = $newKey; - } - - if (is_array($value)) { - $value = self::replaceArrayKeys($value, $oldKeyPattern, $newKey); - } - - $effect[$key] = $value; + foreach ($array as $key => $value) { + if (preg_match($oldKeyPattern, $key)) { + $key = $newKey; } + + if (is_array($value)) { + $value = self::replaceKeys($value, $oldKeyPattern, $newKey); + } + + $effect[$key] = $value; } return $effect; @@ -376,17 +378,18 @@ class Arrays * Generates JavaScript code for given PHP array * * @param array $array The array that should be generated to JavaScript - * @param string $jsVariableName (optional) Name of the variable that will be in generated JavaScript code + * @param string $jsVariableName (optional) Name of the variable that will be in generated JavaScript code. + * Default: "autoGeneratedVariable". * @param bool $preserveIndexes (optional) If is set to true and $jsVariableName isn't empty, indexes also - * will be added to the JavaScript code. Otherwise not. + * will be added to the JavaScript code. Otherwise not (default behaviour). * @return null|string */ - public static function array2JavaScript(array $array, $jsVariableName = '', $preserveIndexes = false) - { - /* - * No elements? - * Nothing to do - */ + public static function array2JavaScript( + array $array, + string $jsVariableName = '', + bool $preserveIndexes = false + ): ?string { + // No elements? Nothing to do if (empty($array)) { return null; } @@ -396,7 +399,11 @@ class Arrays $arrayCount = count($array); $arrayPrepared = self::quoteStrings($array); - $isMultiDimensional = self::isMultiDimensional($arrayPrepared); + $isMultiDimensional = false; + + if (null !== $arrayPrepared) { + $isMultiDimensional = self::isMultiDimensional($arrayPrepared); + } /* * Name of the variable was not provided and it's a multi dimensional array? @@ -406,7 +413,7 @@ class Arrays $jsVariableName = 'autoGeneratedVariable'; } - if (!empty($jsVariableName) && is_string($jsVariableName)) { + if (!empty($jsVariableName)) { $result .= sprintf('var %s = ', $jsVariableName); } @@ -417,50 +424,52 @@ class Arrays $result .= ');'; } - foreach ($arrayPrepared as $index => $value) { - ++$counter; + if (null !== $arrayPrepared) { + foreach ($arrayPrepared as $index => $value) { + ++$counter; - if (is_array($value)) { - $variable = $index; + if (is_array($value)) { + $variable = $index; - if (is_int($index)) { - $variable = 'value_' . $variable; - } - - $value = self::array2JavaScript($value, $variable, $preserveIndexes); - - if (null !== $value && '' !== $value) { - /* - * Add an empty line for the 1st iteration only. Required to avoid missing empty line after - * declaration of variable: - * - * var autoGeneratedVariable = new Array(...);autoGeneratedVariable[0] = new Array(...); - * autoGeneratedVariable[1] = new Array(...); - */ - if (1 === $counter) { - $result .= "\n"; + if (is_int($index)) { + $variable = 'value_' . $variable; } - $result .= $value . "\n"; - $result .= sprintf('%s[%s] = %s;', $jsVariableName, Miscellaneous::quoteValue($index), $variable); + $value = self::array2JavaScript($value, $variable, $preserveIndexes); - if ($counter !== $arrayCount) { - $result .= "\n"; + if (null !== $value && '' !== $value) { + /* + * Add an empty line for the 1st iteration only. Required to avoid missing empty line after + * declaration of variable: + * + * var autoGeneratedVariable = new Array(...);autoGeneratedVariable[0] = new Array(...); + * autoGeneratedVariable[1] = new Array(...); + */ + if (1 === $counter) { + $result .= "\n"; + } + + $result .= $value . "\n"; + $result .= sprintf('%s[%s] = %s;', $jsVariableName, Miscellaneous::quoteValue($index), $variable); + + if ($counter !== $arrayCount) { + $result .= "\n"; + } } - } - } elseif ($preserveIndexes) { - if (!empty($jsVariableName)) { - $index = Miscellaneous::quoteValue($index); - $result .= sprintf("\n%s[%s] = %s;", $jsVariableName, $index, $value); - } - } else { - $format = '%s'; + } elseif ($preserveIndexes) { + if (!empty($jsVariableName)) { + $index = Miscellaneous::quoteValue($index); + $result .= sprintf("\n%s[%s] = %s;", $jsVariableName, $index, $value); + } + } else { + $format = '%s'; - if ($counter < $arrayCount) { - $format .= ', '; - } + if ($counter < $arrayCount) { + $format .= ', '; + } - $result .= sprintf($format, $value); + $result .= sprintf($format, $value); + } } } @@ -477,7 +486,7 @@ class Arrays * @param array $array The array to check for string values * @return null|array */ - public static function quoteStrings(array $array) + public static function quoteStrings(array $array): ?array { /* * No elements? @@ -492,10 +501,8 @@ class Arrays foreach ($array as $index => $value) { if (is_array($value)) { $value = self::quoteStrings($value); - } elseif (is_string($value)) { - if (!Regex::isQuoted($value)) { - $value = '\'' . $value . '\''; - } + } elseif (is_string($value) && !Regex::isQuoted($value)) { + $value = '\'' . $value . '\''; } $result[$index] = $value; @@ -505,31 +512,28 @@ class Arrays } /** - * Removes marginal element (first or last) + * Removes marginal element (first or last) from given array * - * @param array|string $item The item which should be shortened - * @param bool $last (optional) If is set to true, last element is removed. Otherwise - first. - * @return array|string + * @param array $array The array which should be shortened + * @param bool $last (optional) If is set to true, last element is removed (default behaviour). Otherwise - first. + * @return null|array */ - public static function removeMarginalElement($item, $last = true) + public static function removeMarginalElement(array $array, bool $last = true): ?array { - if (is_string($item)) { - if ($last) { - $item = substr($item, 0, -1); - } else { - $item = substr($item, 1); - } - } elseif (is_array($item)) { - $key = self::getFirstKey($item); - - if ($last) { - $key = self::getLastKey($item); - } - - unset($item[$key]); + // No elements? Nothing to do + if (empty($array)) { + return null; } - return $item; + $key = self::getFirstKey($array); + + if ($last) { + $key = self::getLastKey($array); + } + + unset($array[$key]); + + return $array; } /** @@ -590,7 +594,7 @@ class Arrays * @param bool $before (optional) If is set to true, all elements before given needle are removed. Otherwise - all * after needle. */ - public static function removeElements(array &$array, $needle, $before = true) + public static function removeElements(array &$array, $needle, $before = true): void { if (!empty($array)) { if (!$before) { @@ -604,7 +608,7 @@ class Arrays if ($isArray) { self::removeElements($value, $needle, $before); - if ($isArray && empty($value)) { + if (empty($value)) { $remove = true; } } elseif ($value === $needle) { @@ -730,7 +734,7 @@ class Arrays * @param array $array The array to count * @return null|int */ - public static function getNonArrayElementsCount(array $array) + public static function getNonArrayElementsCount(array $array): ?int { /* * No elements? @@ -742,9 +746,9 @@ class Arrays $count = 0; - foreach ($array as &$value) { + foreach ($array as $value) { if (is_array($value)) { - $count += self::getNonArrayElementsCount($value); + $count += (int)self::getNonArrayElementsCount($value); continue; } @@ -772,14 +776,14 @@ class Arrays * @param string $separator (optional) Separator used between name-value pairs in the string. * Default: "|". * @param string $valuesKeysSeparator (optional) Separator used between name and value in the string. Default: ":". - * @return array + * @return null|array */ - public static function string2array($string, $separator = '|', $valuesKeysSeparator = ':') - { - /* - * Empty string? - * Nothing to do - */ + public static function string2array( + string $string, + string $separator = '|', + string $valuesKeysSeparator = ':' + ): ?array { + // Empty string? Nothing to do if (empty($string)) { return null; } @@ -844,12 +848,12 @@ class Arrays /** * Returns paths of the last elements * - * @param array $array The array with elements - * @param string $separator (optional) Separator used between elements. Default: ".". - * @param string $parentPath (optional) Path of the parent element. Default: "". - * @param array|string $stopIfMatchedBy (optional) Patterns of keys or paths that matched will stop the process - * of path building and including children of those keys or paths (recursive - * will not be used for keys in lower level of given array). Default: "". + * @param array $array The array with elements + * @param string $separator (optional) Separator used between elements. Default: ".". + * @param string $parentPath (optional) Path of the parent element. Default: "". + * @param array $stopIfMatchedBy (optional) Patterns of keys or paths when matched will stop the process of path + * building and including children of those keys or paths (recursive will not be + * used for keys in lower level of given array). Default: []. * @return null|array * * Examples - $stopIfMatchedBy argument: @@ -859,21 +863,18 @@ class Arrays * "\d+", * ]; */ - public static function getLastElementsPaths(array $array, $separator = '.', $parentPath = '', $stopIfMatchedBy = '') - { - /* - * No elements? - * Nothing to do - */ + public static function getLastElementsPaths( + array $array, + string $separator = '.', + string $parentPath = '', + array $stopIfMatchedBy = [] + ): ?array { + // No elements? Nothing to do if (empty($array)) { return null; } - if (!empty($stopIfMatchedBy)) { - $stopIfMatchedBy = self::makeArray($stopIfMatchedBy); - } - - $paths = []; + $result = []; foreach ($array as $key => $value) { $path = $key; @@ -908,24 +909,27 @@ class Arrays /* * The value is passed to the returned array if: + * - the process is stopped, recursive is not used + * or * - it's not an array * or - * - the process is stopped, recursive is not used + * - it's an array, but empty */ - if (!$valueIsArray || ($valueIsArray && empty($value)) || $stopRecursion) { - $paths[$path] = $value; + if ($stopRecursion || !$valueIsArray || self::isEmptyArray($value)) { + $result[$path] = $value; continue; } // Let's iterate through the next level, using recursive - if ($valueIsArray) { - $recursivePaths = self::getLastElementsPaths($value, $separator, $path, $stopIfMatchedBy); - $paths += $recursivePaths; + $recursivePaths = self::getLastElementsPaths($value, $separator, $path, $stopIfMatchedBy); + + if (null !== $recursivePaths) { + $result += $recursivePaths; } } - return $paths; + return $result; } /** @@ -934,7 +938,7 @@ class Arrays * @param mixed $variable Variable that should be an array * @return array */ - public static function makeArray($variable) + public static function makeArray($variable): array { if (is_array($variable)) { return $variable; @@ -952,7 +956,7 @@ class Arrays * first level only. * @return bool */ - public static function areAllKeysMatchedByPattern(array $array, $pattern, $firstLevelOnly = false) + public static function areAllKeysMatchedByPattern(array $array, string $pattern, bool $firstLevelOnly = false): bool { /* * No elements? @@ -1413,9 +1417,9 @@ class Arrays * (default behaviour). * @return array */ - public static function arrayDiffRecursive(array $array1, array $array2, $valuesOnly = false) + public static function arrayDiffRecursive(array $array1, array $array2, bool $valuesOnly = false): array { - $effect = []; + $result = []; /* * Values should be compared only and both arrays are one-dimensional? @@ -1436,7 +1440,7 @@ class Arrays if ($array2HasKey && is_array($array2[$key])) { $difference = self::arrayDiffRecursive($value, $array2[$key], $valuesOnly); } - } elseif (!$array2HasKey || ($array2HasKey && $value !== $array2[$key])) { + } elseif (!$array2HasKey || $value !== $array2[$key]) { /* * We are here, because: * a) 2nd array hasn't key from 1st array @@ -1447,7 +1451,7 @@ class Arrays } if (null !== $difference) { - $effect[] = $difference; + $result[] = $difference; } // The key exists in 2nd array? @@ -1465,19 +1469,19 @@ class Arrays continue; } - $effect[$key] = $diff; + $result[$key] = $diff; } elseif ($value !== $array2[$key]) { // Value is different than in 2nd array? // OKay, I've got difference - $effect[$key] = $value; + $result[$key] = $value; } } else { // OKay, I've got difference - $effect[$key] = $value; + $result[$key] = $value; } } - return $effect; + return $result; } /** @@ -1513,7 +1517,7 @@ class Arrays * @param int $incrementStep (optional) Value used for incrementation. The step of incrementation. * @return null|array */ - public static function incrementIndexes(array $array, $startIndex = null, $incrementStep = 1) + public static function incrementIndexes(array $array, ?int $startIndex = null, int $incrementStep = 1): ?array { /* * No elements? @@ -1557,7 +1561,7 @@ class Arrays */ if (!empty($valuesToIncrement)) { foreach ($valuesToIncrement as $oldIndex => $value) { - $newIndex = $oldIndex + $incrementStep; + $newIndex = (int)$oldIndex + $incrementStep; $array[$newIndex] = $value; } } @@ -1596,7 +1600,7 @@ class Arrays * @param array $array The array to verify * @return null|bool */ - public static function isMultiDimensional(array $array) + public static function isMultiDimensional(array $array): ?bool { /* * No elements? @@ -1615,7 +1619,7 @@ class Arrays * @param array $array The array to verify * @return int */ - public static function getDimensionsCount(array $array) + public static function getDimensionsCount(array $array): int { /* * No elements? @@ -1650,7 +1654,7 @@ class Arrays * @param array $values The values to filter * @return null|array */ - public static function getNonEmptyValues(array $values) + public static function getNonEmptyValues(array $values): ?array { /* * No values? @@ -1660,9 +1664,9 @@ class Arrays return null; } - return array_filter($values, function ($value) { + return array_filter($values, static function ($value): bool { $nonEmptyScalar = is_scalar($value) && '' !== $value; - $nonEmptyArray = is_array($value) && !empty($value); + $nonEmptyArray = self::isNotEmptyArray($value); return $nonEmptyScalar || $nonEmptyArray || is_object($value); }); @@ -1675,7 +1679,7 @@ class Arrays * @param string $separator (optional) Separator used to implode the values. Default: ", ". * @return null|string */ - public static function getNonEmptyValuesAsString(array $values, $separator = ', ') + public static function getNonEmptyValuesAsString(array $values, string $separator = ', '): ?string { /* * No elements? @@ -1698,6 +1702,28 @@ class Arrays return implode($separator, $nonEmpty); } + /** + * Returns information if given value is an empty array + * + * @param mixed $value The value to verify + * @return bool + */ + public static function isEmptyArray($value): bool + { + return is_array($value) && empty($value); + } + + /** + * Returns information if given value is non-empty array + * + * @param mixed $value The value to verify + * @return bool + */ + public static function isNotEmptyArray($value): bool + { + return is_array($value) && !empty($value); + } + /** * Returns neighbour (next or previous element) for given element * @@ -1706,7 +1732,7 @@ class Arrays * @param bool $next (optional) If is set to true, returns next neighbour. Otherwise - previous. * @return null|mixed */ - private static function getNeighbour(array $array, $element, $next = true) + private static function getNeighbour(array $array, $element, bool $next = true) { /* * No elements? @@ -1730,7 +1756,7 @@ class Arrays * * Nothing to do */ - if ($noPrevious || $noNext || empty($array) || !in_array($element, $array, true)) { + if ($noPrevious || $noNext || !in_array($element, $array, true)) { return null; } diff --git a/src/Utilities/Miscellaneous.php b/src/Utilities/Miscellaneous.php index 7f45397..4ba0e37 100644 --- a/src/Utilities/Miscellaneous.php +++ b/src/Utilities/Miscellaneous.php @@ -1274,7 +1274,7 @@ class Miscellaneous * * @return string */ - public static function getProjectRootPath() + public static function getProjectRootPath(): string { $projectRootPath = ''; @@ -1298,4 +1298,25 @@ class Miscellaneous return $projectRootPath; } + + /** + * Removes marginal character (first or last) from given string + * + * @param string $string The string which should be shortened + * @param bool $last (optional) If is set to true, last element is removed (default behaviour). Otherwise - + * first. + * @return null|string + */ + public static function removeMarginalCharacter(string $string, bool $last = true): ?string + { + if (empty($string)) { + return null; + } + + if ($last) { + return substr($string, 0, -1); + } + + return substr($string, 1); + } } diff --git a/src/Utilities/Reflection.php b/src/Utilities/Reflection.php index d675b72..82c522a 100644 --- a/src/Utilities/Reflection.php +++ b/src/Utilities/Reflection.php @@ -15,6 +15,11 @@ use Meritoo\Common\Exception\Reflection\CannotResolveClassNameException; use Meritoo\Common\Exception\Reflection\MissingChildClassesException; use Meritoo\Common\Exception\Reflection\NotExistingPropertyException; use Meritoo\Common\Exception\Reflection\TooManyChildClassesException; +use ReflectionClass; +use ReflectionException; +use ReflectionMethod; +use ReflectionObject; +use ReflectionProperty; /** * Useful reflection methods @@ -32,18 +37,18 @@ class Reflection * Otherwise - all methods, with inherited methods too. * @return array */ - public static function getMethods($class, $withoutInheritance = false) + public static function getMethods($class, bool $withoutInheritance = false): array { $effect = []; - $reflection = new \ReflectionClass($class); + $reflection = new ReflectionClass($class); $methods = $reflection->getMethods(); if (!empty($methods)) { $className = self::getClassName($class); foreach ($methods as $method) { - if ($method instanceof \ReflectionMethod) { + if ($method instanceof ReflectionMethod) { if ($withoutInheritance && $className !== $method->class) { continue; } @@ -62,9 +67,9 @@ class Reflection * @param object|string $class The object or name of object's class * @return array */ - public static function getConstants($class) + public static function getConstants($class): array { - $reflection = new \ReflectionClass($class); + $reflection = new ReflectionClass($class); return $reflection->getConstants(); } @@ -76,7 +81,7 @@ class Reflection * @param object|string $class The object or name of object's class * @return null|int */ - public static function getMaxNumberConstant($class) + public static function getMaxNumberConstant($class): ?int { $constants = self::getConstants($class); @@ -102,9 +107,9 @@ class Reflection * @param string $method Name of the method to find * @return bool */ - public static function hasMethod($class, $method) + public static function hasMethod($class, string $method): bool { - $reflection = new \ReflectionClass($class); + $reflection = new ReflectionClass($class); return $reflection->hasMethod($method); } @@ -116,9 +121,9 @@ class Reflection * @param string $property Name of the property to find * @return bool */ - public static function hasProperty($class, $property) + public static function hasProperty($class, string $property): bool { - $reflection = new \ReflectionClass($class); + $reflection = new ReflectionClass($class); return $reflection->hasProperty($property); } @@ -130,9 +135,9 @@ class Reflection * @param string $constant Name of the constant to find * @return bool */ - public static function hasConstant($class, $constant) + public static function hasConstant($class, string $constant): bool { - $reflection = new \ReflectionClass($class); + $reflection = new ReflectionClass($class); return $reflection->hasConstant($constant); } @@ -144,9 +149,9 @@ class Reflection * @param string $constant Name of the constant that contains a value * @return mixed */ - public static function getConstantValue($class, $constant) + public static function getConstantValue($class, string $constant) { - $reflection = new \ReflectionClass($class); + $reflection = new ReflectionClass($class); if (self::hasConstant($class, $constant)) { return $reflection->getConstant($constant); @@ -165,7 +170,7 @@ class Reflection * property. Otherwise - not. * @return mixed */ - public static function getPropertyValue($source, $property, $force = false) + public static function getPropertyValue($source, string $property, bool $force = false) { if (Regex::contains($property, '.')) { return self::getPropertyValueByPropertiesChain($source, $property, $force); @@ -209,7 +214,7 @@ class Reflection * object does not have property. Otherwise - not. * @return array */ - public static function getPropertyValues($objects, $property, $force = false) + public static function getPropertyValues($objects, string $property, bool $force = false): array { /* * No objects? @@ -245,7 +250,7 @@ class Reflection * not, full name of class is returned, with namespace. * @return null|string */ - public static function getClassName($source, $withoutNamespace = false) + public static function getClassName($source, bool $withoutNamespace = false): ?string { /* * First argument is not proper source of class? @@ -303,7 +308,7 @@ class Reflection * @param array|object|string $source An array of objects, namespaces, object or namespace * @return string */ - public static function getClassNamespace($source) + public static function getClassNamespace($source): string { $fullClassName = self::getClassName($source); @@ -327,7 +332,7 @@ class Reflection * @param string $interface The interface that should be implemented * @return bool */ - public static function isInterfaceImplemented($source, $interface) + public static function isInterfaceImplemented($source, string $interface): bool { $className = self::getClassName($source); $interfaces = class_implements($className); @@ -342,7 +347,7 @@ class Reflection * @param array|object|string $parentClass The parent class. An array of objects, namespaces, object or namespace. * @return bool */ - public static function isChildOfClass($childClass, $parentClass) + public static function isChildOfClass($childClass, $parentClass): bool { $childClassName = self::getClassName($childClass); $parentClassName = self::getClassName($parentClass); @@ -364,18 +369,18 @@ class Reflection * constants. By default all properties are returned. * @param bool $includeParents (optional) If is set to true, properties of parent classes are * included (recursively). Otherwise - not. - * @return \ReflectionProperty[] + * @return ReflectionProperty[] */ - public static function getProperties($source, $filter = null, $includeParents = false): array + public static function getProperties($source, int $filter = null, bool $includeParents = false): array { $className = self::getClassName($source); - $reflection = new \ReflectionClass($className); + $reflection = new ReflectionClass($className); if (null === $filter) { - $filter = \ReflectionProperty::IS_PRIVATE - + \ReflectionProperty::IS_PROTECTED - + \ReflectionProperty::IS_PUBLIC - + \ReflectionProperty::IS_STATIC; + $filter = ReflectionProperty::IS_PRIVATE + + ReflectionProperty::IS_PROTECTED + + ReflectionProperty::IS_PUBLIC + + ReflectionProperty::IS_STATIC; } $properties = $reflection->getProperties($filter); @@ -397,12 +402,12 @@ class Reflection * Returns a parent class or false if there is no parent class * * @param array|object|string $source An array of objects, namespaces, object or namespace - * @return bool|\ReflectionClass + * @return false|ReflectionClass */ public static function getParentClass($source) { $className = self::getClassName($source); - $reflection = new \ReflectionClass($className); + $reflection = new ReflectionClass($className); return $reflection->getParentClass(); } @@ -416,7 +421,7 @@ class Reflection * @throws CannotResolveClassNameException * @return null|array */ - public static function getChildClasses($class) + public static function getChildClasses($class): ?array { $allClasses = get_declared_classes(); @@ -500,15 +505,15 @@ class Reflection * @param string $property Name of the property * @param int $filter (optional) Filter of properties. Uses \ReflectionProperty class constants. * By default all properties are allowed / processed. - * @return null|\ReflectionProperty + * @return null|ReflectionProperty */ - public static function getProperty($class, $property, $filter = null) + public static function getProperty($class, string $property, int $filter = null): ?ReflectionProperty { $className = self::getClassName($class); $properties = self::getProperties($className, $filter); if (!empty($properties)) { - /** @var \ReflectionProperty $reflectionProperty */ + /** @var ReflectionProperty $reflectionProperty */ foreach ($properties as $reflectionProperty) { if ($reflectionProperty->getName() === $property) { return $reflectionProperty; @@ -529,7 +534,7 @@ class Reflection * @throws CannotResolveClassNameException * @return null|bool */ - public static function usesTrait($class, $trait, $verifyParents = false) + public static function usesTrait($class, $trait, bool $verifyParents = false): ?bool { $className = self::getClassName($class); $traitName = self::getClassName($trait); @@ -544,7 +549,7 @@ class Reflection throw new CannotResolveClassNameException($class, false); } - $reflection = new \ReflectionClass($className); + $reflection = new ReflectionClass($className); $traitsNames = $reflection->getTraitNames(); $uses = in_array($traitName, $traitsNames, true); @@ -567,10 +572,10 @@ class Reflection * @param array|object|string $class An array of objects, namespaces, object or namespace * @return null|string */ - public static function getParentClassName($class) + public static function getParentClassName($class): ?string { $className = self::getClassName($class); - $reflection = new \ReflectionClass($className); + $reflection = new ReflectionClass($className); $parentClass = $reflection->getParentClass(); if (null === $parentClass || false === $parentClass) { @@ -588,7 +593,7 @@ class Reflection * @param mixed $value Value of the property * @throws NotExistingPropertyException */ - public static function setPropertyValue($object, $property, $value) + public static function setPropertyValue($object, string $property, $value): void { $reflectionProperty = self::getProperty($object, $property); @@ -616,7 +621,7 @@ class Reflection * @param mixed $object Object that should contains given property * @param array $propertiesValues Key-value pairs, where key - name of the property, value - value of the property */ - public static function setPropertiesValues($object, array $propertiesValues) + public static function setPropertiesValues($object, array $propertiesValues): void { /* * No properties? @@ -637,7 +642,7 @@ class Reflection * @param string $class Class to verify * @return string */ - private static function getRealClass($class): string + private static function getRealClass(string $class): string { if (false === $pos = strrpos($class, '\\' . Proxy::MARKER . '\\')) { return $class; @@ -650,15 +655,15 @@ class Reflection * Returns value of given property using the property represented by reflection. * If value cannot be fetched, makes the property accessible temporarily. * - * @param mixed $object Object that should contains given property - * @param string $property Name of the property that contains a value - * @param null|\ReflectionProperty $reflectionProperty (optional) Property represented by reflection + * @param mixed $object Object that should contains given property + * @param string $property Name of the property that contains a value + * @param null|ReflectionProperty $reflectionProperty (optional) Property represented by reflection * @return mixed */ private static function getPropertyValueByReflectionProperty( $object, string $property, - ?\ReflectionProperty $reflectionProperty = null + ?ReflectionProperty $reflectionProperty = null ) { $value = null; $valueFound = false; @@ -666,12 +671,12 @@ class Reflection try { if (null === $reflectionProperty) { - $reflectionProperty = new \ReflectionProperty($className, $property); + $reflectionProperty = new ReflectionProperty($className, $property); } $value = $reflectionProperty->getValue($object); $valueFound = true; - } catch (\ReflectionException $exception) { + } catch (ReflectionException $exception) { } if (null !== $reflectionProperty) { @@ -705,7 +710,7 @@ class Reflection $value = null; $valueFound = false; - $reflectionObject = new \ReflectionObject($source); + $reflectionObject = new ReflectionObject($source); $property = Inflector::classify($property); $gettersPrefixes = [ @@ -718,7 +723,7 @@ class Reflection $getter = sprintf('%s%s', $prefix, $property); if ($reflectionObject->hasMethod($getter)) { - $method = new \ReflectionMethod($source, $getter); + $method = new ReflectionMethod($source, $getter); /* * Getter is not accessible publicly? @@ -791,7 +796,7 @@ class Reflection * property. Otherwise - not. * @return mixed */ - private static function getPropertyValueByPropertiesChain($source, $property, $force) + private static function getPropertyValueByPropertiesChain($source, string $property, bool $force) { $exploded = explode('.', $property); diff --git a/tests/Collection/CollectionTest.php b/tests/Collection/CollectionTest.php index b2d90b2..1b0bef1 100644 --- a/tests/Collection/CollectionTest.php +++ b/tests/Collection/CollectionTest.php @@ -13,6 +13,7 @@ use Generator; use Meritoo\Common\Collection\Collection; use Meritoo\Common\Test\Base\BaseTestCase; use Meritoo\Common\Type\OopVisibilityType; +use ReflectionClass; /** * Test case of the collection of elements @@ -21,7 +22,7 @@ use Meritoo\Common\Type\OopVisibilityType; * @copyright Meritoo * * @internal - * @covers \Meritoo\Common\Collection\Collection + * @covers \Meritoo\Common\Collection\Collection */ class CollectionTest extends BaseTestCase { @@ -327,7 +328,16 @@ class CollectionTest extends BaseTestCase public function testExistsVisibilityAndArguments() { - static::assertMethodVisibilityAndArguments(Collection::class, 'exists', OopVisibilityType::IS_PRIVATE, 1, 1); + $reflectionClass = new ReflectionClass(Collection::class); + $method = $reflectionClass->getMethod('exists'); + + static::assertMethodVisibilityAndArguments( + Collection::class, + $method, + OopVisibilityType::IS_PRIVATE, + 1, + 1 + ); } /** diff --git a/tests/Exception/Bundle/IncorrectBundleNameExceptionTest.php b/tests/Exception/Bundle/IncorrectBundleNameExceptionTest.php index 69c40ab..a48dac5 100644 --- a/tests/Exception/Bundle/IncorrectBundleNameExceptionTest.php +++ b/tests/Exception/Bundle/IncorrectBundleNameExceptionTest.php @@ -8,6 +8,7 @@ namespace Meritoo\Test\Common\Exception\Bundle; +use Generator; use Meritoo\Common\Exception\Bundle\IncorrectBundleNameException; use Meritoo\Common\Test\Base\BaseTestCase; use Meritoo\Common\Type\OopVisibilityType; @@ -23,7 +24,7 @@ use Meritoo\Common\Type\OopVisibilityType; */ class IncorrectBundleNameExceptionTest extends BaseTestCase { - public function testConstructor() + public function testConstructor(): void { static::assertConstructorVisibilityAndArguments( IncorrectBundleNameException::class, @@ -39,13 +40,13 @@ class IncorrectBundleNameExceptionTest extends BaseTestCase * * @dataProvider provideBundleNameAndMessage */ - public function testCreate($description, $bundleName, $expectedMessage) + public function testCreate(string $description, string $bundleName, string $expectedMessage): void { $exception = IncorrectBundleNameException::create($bundleName); static::assertSame($expectedMessage, $exception->getMessage(), $description); } - public function provideBundleNameAndMessage() + public function provideBundleNameAndMessage(): Generator { $template = 'Name of bundle \'%s\' is incorrect. It should start with big letter and end with "Bundle". Is' . ' there everything ok?'; @@ -56,12 +57,6 @@ class IncorrectBundleNameExceptionTest extends BaseTestCase sprintf($template, ''), ]; - yield[ - 'Null as name of bundle', - null, - sprintf($template, ''), - ]; - yield[ 'String with spaces as name of bundle', 'This is test', diff --git a/tests/Exception/Reflection/CannotResolveClassNameExceptionTest.php b/tests/Exception/Reflection/CannotResolveClassNameExceptionTest.php index 5d4c8d6..8106936 100644 --- a/tests/Exception/Reflection/CannotResolveClassNameExceptionTest.php +++ b/tests/Exception/Reflection/CannotResolveClassNameExceptionTest.php @@ -12,6 +12,7 @@ use Generator; use Meritoo\Common\Exception\Reflection\CannotResolveClassNameException; use Meritoo\Common\Test\Base\BaseTestCase; use Meritoo\Common\Type\OopVisibilityType; +use stdClass; /** * Test case of an exception used while name of class or trait cannot be resolved @@ -20,13 +21,17 @@ use Meritoo\Common\Type\OopVisibilityType; * @copyright Meritoo * * @internal - * @covers \Meritoo\Common\Exception\Reflection\CannotResolveClassNameException + * @covers \Meritoo\Common\Exception\Reflection\CannotResolveClassNameException */ class CannotResolveClassNameExceptionTest extends BaseTestCase { - public function testConstructorVisibilityAndArguments() + public function testConstructorVisibilityAndArguments(): void { - static::assertConstructorVisibilityAndArguments(CannotResolveClassNameException::class, OopVisibilityType::IS_PUBLIC, 3); + static::assertConstructorVisibilityAndArguments( + CannotResolveClassNameException::class, + OopVisibilityType::IS_PUBLIC, + 3 + ); } /** @@ -38,7 +43,7 @@ class CannotResolveClassNameExceptionTest extends BaseTestCase * * @dataProvider provideClassName */ - public function testConstructorMessage($source, $forClass, $expectedMessage) + public function testCreate($source, bool $forClass, string $expectedMessage): void { $exception = CannotResolveClassNameException::create($source, $forClass); static::assertSame($expectedMessage, $exception->getMessage()); @@ -50,7 +55,7 @@ class CannotResolveClassNameExceptionTest extends BaseTestCase * * @return Generator */ - public function provideClassName() + public function provideClassName(): Generator { yield[ 'Not\Existing\Class', @@ -66,8 +71,8 @@ class CannotResolveClassNameExceptionTest extends BaseTestCase yield[ [ - new \stdClass(), - new \stdClass(), + new stdClass(), + new stdClass(), ], true, 'Name of class from given \'array\' cannot be resolved. Is there everything ok?', diff --git a/tests/Exception/Reflection/ClassWithoutConstructorExceptionTest.php b/tests/Exception/Reflection/ClassWithoutConstructorExceptionTest.php new file mode 100644 index 0000000..85c6fec --- /dev/null +++ b/tests/Exception/Reflection/ClassWithoutConstructorExceptionTest.php @@ -0,0 +1,66 @@ + + * @copyright Meritoo + * + * @internal + * @covers \Meritoo\Common\Exception\Reflection\ClassWithoutConstructorException + */ +class ClassWithoutConstructorExceptionTest extends BaseTestCase +{ + public function testConstructor(): void + { + static::assertConstructorVisibilityAndArguments( + ClassWithoutConstructorException::class, + OopVisibilityType::IS_PUBLIC, + 3 + ); + } + + /** + * @param string $description Description of test case + * @param string $className Fully-qualified name of class that hasn't constructor + * @param string $expectedMessage Expected exception's message + * + * @dataProvider provideClassName + */ + public function testCreate(string $description, string $className, string $expectedMessage): void + { + $exception = ClassWithoutConstructorException::create($className); + static::assertSame($expectedMessage, $exception->getMessage(), $description); + } + + public function provideClassName(): Generator + { + $template = 'Oops, class \'%s\' hasn\'t constructor. Did you use proper class?'; + + yield[ + 'An empty name of class', + '', + sprintf($template, ''), + ]; + + yield[ + 'The Arrays class', + Arrays::class, + sprintf($template, Arrays::class), + ]; + } +} diff --git a/tests/Exception/Reflection/MissingChildClassesExceptionTest.php b/tests/Exception/Reflection/MissingChildClassesExceptionTest.php index 7da3484..d3aaf2e 100644 --- a/tests/Exception/Reflection/MissingChildClassesExceptionTest.php +++ b/tests/Exception/Reflection/MissingChildClassesExceptionTest.php @@ -20,13 +20,17 @@ use Meritoo\Common\Type\OopVisibilityType; * @copyright Meritoo * * @internal - * @covers \Meritoo\Common\Exception\Reflection\MissingChildClassesException + * @covers \Meritoo\Common\Exception\Reflection\MissingChildClassesException */ class MissingChildClassesExceptionTest extends BaseTestCase { - public function testConstructorVisibilityAndArguments() + public function testConstructorVisibilityAndArguments(): void { - static::assertConstructorVisibilityAndArguments(MissingChildClassesException::class, OopVisibilityType::IS_PUBLIC, 3); + static::assertConstructorVisibilityAndArguments( + MissingChildClassesException::class, + OopVisibilityType::IS_PUBLIC, + 3 + ); } /** @@ -36,7 +40,7 @@ class MissingChildClassesExceptionTest extends BaseTestCase * * @dataProvider provideParentClass */ - public function testConstructorMessage($parentClass, $expectedMessage) + public function testCreate($parentClass, string $expectedMessage): void { $exception = MissingChildClassesException::create($parentClass); static::assertSame($expectedMessage, $exception->getMessage()); @@ -47,7 +51,7 @@ class MissingChildClassesExceptionTest extends BaseTestCase * * @return Generator */ - public function provideParentClass() + public function provideParentClass(): ?Generator { $template = 'The \'%s\' class requires one child class at least who will extend her (maybe is an abstract' . ' class), but the child classes are missing. Did you forget to extend this class?'; diff --git a/tests/Exception/Reflection/NotExistingPropertyExceptionTest.php b/tests/Exception/Reflection/NotExistingPropertyExceptionTest.php index aadd974..605aa36 100644 --- a/tests/Exception/Reflection/NotExistingPropertyExceptionTest.php +++ b/tests/Exception/Reflection/NotExistingPropertyExceptionTest.php @@ -19,11 +19,11 @@ use Meritoo\Common\Type\OopVisibilityType; * @copyright Meritoo * * @internal - * @covers \Meritoo\Common\Exception\Reflection\NotExistingPropertyException + * @covers \Meritoo\Common\Exception\Reflection\NotExistingPropertyException */ class NotExistingPropertyExceptionTest extends BaseTestCase { - public function testConstructor() + public function testConstructor(): void { static::assertConstructorVisibilityAndArguments( NotExistingPropertyException::class, @@ -33,20 +33,20 @@ class NotExistingPropertyExceptionTest extends BaseTestCase } /** - * @param string $description Description of test - * @param mixed $object Object that should contains given property - * @param string $property Name of the property - * @param string $expectedMessage Expected exception's message + * @param string $description Description of test + * @param mixed $object Object that should contains given property + * @param null|string $property Name of the property + * @param string $expectedMessage Expected exception's message * * @dataProvider provideObjectPropertyAndMessage */ - public function testCreate($description, $object, $property, $expectedMessage) + public function testCreate(string $description, $object, ?string $property, string $expectedMessage): void { $exception = NotExistingPropertyException::create($object, $property); static::assertSame($expectedMessage, $exception->getMessage(), $description); } - public function provideObjectPropertyAndMessage() + public function provideObjectPropertyAndMessage(): ?\Generator { $template = 'Property \'%s\' does not exist in instance of class \'%s\'. Did you use proper name of property?'; diff --git a/tests/Exception/Reflection/TooManyChildClassesExceptionTest.php b/tests/Exception/Reflection/TooManyChildClassesExceptionTest.php index 9bb26b0..b0d8dc6 100644 --- a/tests/Exception/Reflection/TooManyChildClassesExceptionTest.php +++ b/tests/Exception/Reflection/TooManyChildClassesExceptionTest.php @@ -20,13 +20,17 @@ use Meritoo\Common\Type\OopVisibilityType; * @copyright Meritoo * * @internal - * @covers \Meritoo\Common\Exception\Reflection\TooManyChildClassesException + * @covers \Meritoo\Common\Exception\Reflection\TooManyChildClassesException */ class TooManyChildClassesExceptionTest extends BaseTestCase { - public function testConstructorVisibilityAndArguments() + public function testConstructor(): void { - static::assertConstructorVisibilityAndArguments(TooManyChildClassesException::class, OopVisibilityType::IS_PUBLIC, 3); + static::assertConstructorVisibilityAndArguments( + TooManyChildClassesException::class, + OopVisibilityType::IS_PUBLIC, + 3 + ); } /** @@ -37,7 +41,7 @@ class TooManyChildClassesExceptionTest extends BaseTestCase * * @dataProvider provideParentAndChildClasses */ - public function testConstructorMessage($parentClass, array $childClasses, $expectedMessage) + public function testCreate($parentClass, array $childClasses, string $expectedMessage): void { $exception = TooManyChildClassesException::create($parentClass, $childClasses); static::assertSame($expectedMessage, $exception->getMessage()); @@ -49,7 +53,7 @@ class TooManyChildClassesExceptionTest extends BaseTestCase * * @return Generator */ - public function provideParentAndChildClasses() + public function provideParentAndChildClasses(): ?Generator { $template = "The '%s' class requires one child class at most who will extend her, but more than one child" . " class was found:\n- %s\n\nWhy did you create more than one classes that extend '%s' class?"; diff --git a/tests/Exception/Type/UnknownOopVisibilityTypeExceptionTest.php b/tests/Exception/Type/UnknownOopVisibilityTypeExceptionTest.php index f5440ad..a4f836d 100644 --- a/tests/Exception/Type/UnknownOopVisibilityTypeExceptionTest.php +++ b/tests/Exception/Type/UnknownOopVisibilityTypeExceptionTest.php @@ -21,13 +21,17 @@ use Meritoo\Common\Type\OopVisibilityType; * @copyright Meritoo * * @internal - * @covers \Meritoo\Common\Exception\Type\UnknownOopVisibilityTypeException + * @covers \Meritoo\Common\Exception\Type\UnknownOopVisibilityTypeException */ class UnknownOopVisibilityTypeExceptionTest extends BaseTestCase { - public function testConstructorVisibilityAndArguments() + public function testConstructorVisibilityAndArguments(): void { - static::assertConstructorVisibilityAndArguments(UnknownOopVisibilityTypeException::class, OopVisibilityType::IS_PUBLIC, 3); + static::assertConstructorVisibilityAndArguments( + UnknownOopVisibilityTypeException::class, + OopVisibilityType::IS_PUBLIC, + 3 + ); } /** @@ -36,7 +40,7 @@ class UnknownOopVisibilityTypeExceptionTest extends BaseTestCase * * @dataProvider provideUnknownType */ - public function testConstructorMessage($unknownType, $expectedMessage) + public function testConstructorMessage($unknownType, $expectedMessage): void { $exception = UnknownOopVisibilityTypeException::createException($unknownType); static::assertSame($expectedMessage, $exception->getMessage()); @@ -47,7 +51,7 @@ class UnknownOopVisibilityTypeExceptionTest extends BaseTestCase * * @return Generator */ - public function provideUnknownType() + public function provideUnknownType(): Generator { $allTypes = (new OopVisibilityType())->getAll(); diff --git a/tests/Type/DatePartTypeTest.php b/tests/Type/DatePartTypeTest.php index 73e5d2f..4e9b312 100644 --- a/tests/Type/DatePartTypeTest.php +++ b/tests/Type/DatePartTypeTest.php @@ -8,7 +8,9 @@ namespace Meritoo\Test\Common\Type; +use Generator; use Meritoo\Common\Test\Base\BaseTypeTestCase; +use Meritoo\Common\Type\Base\BaseType; use Meritoo\Common\Type\DatePartType; /** @@ -25,7 +27,7 @@ class DatePartTypeTest extends BaseTypeTestCase /** * {@inheritdoc} */ - public function provideTypeToVerify() + public function provideTypeToVerify(): Generator { yield[ '', @@ -38,12 +40,12 @@ class DatePartTypeTest extends BaseTypeTestCase ]; yield[ - 0, + '0', false, ]; yield[ - 1, + '1', false, ]; @@ -81,22 +83,22 @@ class DatePartTypeTest extends BaseTypeTestCase /** * {@inheritdoc} */ - protected function getAllExpectedTypes() + protected function getAllExpectedTypes(): array { return [ - 'DAY' => DatePartType::DAY, - 'HOUR' => DatePartType::HOUR, - 'MINUTE' => DatePartType::MINUTE, - 'MONTH' => DatePartType::MONTH, - 'SECOND' => DatePartType::SECOND, - 'YEAR' => DatePartType::YEAR, + 'DAY' => 'day', + 'HOUR' => 'hour', + 'MINUTE' => 'minute', + 'MONTH' => 'month', + 'SECOND' => 'second', + 'YEAR' => 'year', ]; } /** * {@inheritdoc} */ - protected function getTestedTypeInstance() + protected function getTestedTypeInstance(): BaseType { return new DatePartType(); } diff --git a/tests/Type/DatePeriodTest.php b/tests/Type/DatePeriodTest.php index fdfed51..bb57851 100644 --- a/tests/Type/DatePeriodTest.php +++ b/tests/Type/DatePeriodTest.php @@ -11,6 +11,7 @@ namespace Meritoo\Test\Common\Type; use DateTime; use Generator; use Meritoo\Common\Test\Base\BaseTypeTestCase; +use Meritoo\Common\Type\Base\BaseType; use Meritoo\Common\Type\DatePeriod; use Meritoo\Common\Type\OopVisibilityType; @@ -21,13 +22,17 @@ use Meritoo\Common\Type\OopVisibilityType; * @copyright Meritoo * * @internal - * @covers \Meritoo\Common\Type\DatePeriod + * @covers \Meritoo\Common\Type\DatePeriod */ class DatePeriodTest extends BaseTypeTestCase { - public function testConstructorVisibilityAndArguments() + public function testConstructorVisibilityAndArguments(): void { - static::assertConstructorVisibilityAndArguments(DatePeriod::class, OopVisibilityType::IS_PUBLIC, 2, 0); + static::assertConstructorVisibilityAndArguments( + DatePeriod::class, + OopVisibilityType::IS_PUBLIC, + 2 + ); } /** @@ -36,7 +41,7 @@ class DatePeriodTest extends BaseTypeTestCase * * @dataProvider provideDatePeriod */ - public function testConstruct(DateTime $startDate = null, DateTime $endDate = null) + public function testConstruct(DateTime $startDate = null, DateTime $endDate = null): void { $period = new DatePeriod($startDate, $endDate); @@ -50,7 +55,7 @@ class DatePeriodTest extends BaseTypeTestCase * * @dataProvider provideDatePeriod */ - public function testGettersAndSetters(DateTime $startDate = null, DateTime $endDate = null) + public function testGettersAndSetters(DateTime $startDate = null, DateTime $endDate = null): void { $period = new DatePeriod(); @@ -67,7 +72,7 @@ class DatePeriodTest extends BaseTypeTestCase * * @dataProvider provideDatePeriodAndIncorrectDateFormat */ - public function testGetFormattedDateIncorrectDateFormat(DatePeriod $period, $format) + public function testGetFormattedDateIncorrectDateFormat(DatePeriod $period, $format): void { self::assertEquals('', $period->getFormattedDate($format)); } @@ -80,7 +85,7 @@ class DatePeriodTest extends BaseTypeTestCase * * @dataProvider provideDatePeriodAndDateFormat */ - public function testGetFormattedDate(DatePeriod $period, $format, $startDate, $expected) + public function testGetFormattedDate(DatePeriod $period, $format, $startDate, $expected): void { self::assertEquals($expected, $period->getFormattedDate($format, $startDate)); } @@ -90,7 +95,7 @@ class DatePeriodTest extends BaseTypeTestCase * * @return Generator */ - public function provideDatePeriod() + public function provideDatePeriod(): Generator { $startDate = new DateTime('2001-01-01'); $endDate = new DateTime('2002-02-02'); @@ -123,7 +128,7 @@ class DatePeriodTest extends BaseTypeTestCase * * @return Generator */ - public function provideDatePeriodAndIncorrectDateFormat() + public function provideDatePeriodAndIncorrectDateFormat(): Generator { $startDate = new DateTime('2001-01-01'); $endDate = new DateTime('2002-02-02'); @@ -133,11 +138,6 @@ class DatePeriodTest extends BaseTypeTestCase '', ]; - yield[ - new DatePeriod($startDate, $endDate), - null, - ]; - yield[ new DatePeriod($startDate, $endDate), false, @@ -149,7 +149,7 @@ class DatePeriodTest extends BaseTypeTestCase * * @return Generator */ - public function provideDatePeriodAndDateFormat() + public function provideDatePeriodAndDateFormat(): Generator { $startDate = new DateTime('2001-01-01'); $endDate = new DateTime('2002-02-02'); @@ -216,7 +216,7 @@ class DatePeriodTest extends BaseTypeTestCase /** * {@inheritdoc} */ - public function provideTypeToVerify() + public function provideTypeToVerify(): Generator { yield[ '', @@ -224,27 +224,22 @@ class DatePeriodTest extends BaseTypeTestCase ]; yield[ - -1, + '-1', false, ]; yield[ - true, - false, - ]; - - yield[ - DatePeriod::LAST_MONTH, + '4', true, ]; yield[ - DatePeriod::NEXT_WEEK, + '3', true, ]; yield[ - DatePeriod::THIS_YEAR, + '8', true, ]; } @@ -254,25 +249,25 @@ class DatePeriodTest extends BaseTypeTestCase * * @return array */ - protected function getAllExpectedTypes() + protected function getAllExpectedTypes(): array { return [ - 'LAST_MONTH' => DatePeriod::LAST_MONTH, - 'LAST_WEEK' => DatePeriod::LAST_WEEK, - 'LAST_YEAR' => DatePeriod::LAST_YEAR, - 'NEXT_MONTH' => DatePeriod::NEXT_MONTH, - 'NEXT_WEEK' => DatePeriod::NEXT_WEEK, - 'NEXT_YEAR' => DatePeriod::NEXT_YEAR, - 'THIS_MONTH' => DatePeriod::THIS_MONTH, - 'THIS_WEEK' => DatePeriod::THIS_WEEK, - 'THIS_YEAR' => DatePeriod::THIS_YEAR, + 'LAST_MONTH' => 4, + 'LAST_WEEK' => 1, + 'LAST_YEAR' => 7, + 'NEXT_MONTH' => 6, + 'NEXT_WEEK' => 3, + 'NEXT_YEAR' => 9, + 'THIS_MONTH' => 5, + 'THIS_WEEK' => 2, + 'THIS_YEAR' => 8, ]; } /** * {@inheritdoc} */ - protected function getTestedTypeInstance() + protected function getTestedTypeInstance(): BaseType { return new DatePeriod(); } diff --git a/tests/Type/OopVisibilityTypeTest.php b/tests/Type/OopVisibilityTypeTest.php index 9f5ee5f..34fabc1 100644 --- a/tests/Type/OopVisibilityTypeTest.php +++ b/tests/Type/OopVisibilityTypeTest.php @@ -8,6 +8,7 @@ namespace Meritoo\Test\Common\Type; +use Generator; use Meritoo\Common\Test\Base\BaseTypeTestCase; use Meritoo\Common\Type\Base\BaseType; use Meritoo\Common\Type\OopVisibilityType; @@ -26,7 +27,7 @@ class OopVisibilityTypeTest extends BaseTypeTestCase /** * {@inheritdoc} */ - public function provideTypeToVerify(): ?\Generator + public function provideTypeToVerify(): Generator { yield[ '', @@ -39,27 +40,22 @@ class OopVisibilityTypeTest extends BaseTypeTestCase ]; yield[ - -1, + '-1', false, ]; yield[ - true, - false, - ]; - - yield[ - 1, + '1', true, ]; yield[ - 2, + '2', true, ]; yield[ - 3, + '3', true, ]; } diff --git a/tests/Utilities/ArraysTest.php b/tests/Utilities/ArraysTest.php index c553f73..81a1dbe 100644 --- a/tests/Utilities/ArraysTest.php +++ b/tests/Utilities/ArraysTest.php @@ -8,6 +8,7 @@ namespace Meritoo\Test\Common\Utilities; +use Generator; use Meritoo\Common\Test\Base\BaseTestCase; use Meritoo\Common\Utilities\Arrays; use Meritoo\Common\Utilities\Locale; @@ -20,7 +21,7 @@ use Meritoo\Test\Common\Utilities\Arrays\SimpleToString; * @copyright Meritoo * * @internal - * @covers \Meritoo\Common\Utilities\Arrays + * @covers \Meritoo\Common\Utilities\Arrays */ class ArraysTest extends BaseTestCase { @@ -212,7 +213,7 @@ class ArraysTest extends BaseTestCase self::assertEquals('amet/1/primis', Arrays::getLastElementBreadCrumb($this->complexArray)); } - public function testGetLastRow() + public function testGetLastRow(): void { // Negative cases self::assertNull(Arrays::getLastRow([])); @@ -234,34 +235,32 @@ class ArraysTest extends BaseTestCase ], Arrays::getLastRow($this->complexArray)); } - public function testReplaceArrayKeys() - { - $effect = [ - 'nullam' => 'donec', - 'x' => [ - 'vitae' => [ - 'x' => 'quis', - ], - ], - 'elit', - ]; - - $dataArray = $this->complexArray['sit']; - self::assertEquals($effect, Arrays::replaceArrayKeys($dataArray, '|.*li.*|', 'x')); - - self::assertEquals([ - 'x' => 'sit', - 4 => 'amet', - ], Arrays::replaceArrayKeys($this->simpleArray, '|[0-3]+|', 'x')); + /** + * @param string $description Description of test case + * @param array $array Array which keys should be replaced + * @param string $oldKeyPattern Regular expression of the old key + * @param string $newKey Name of the new key + * @param array $expected Expected result + * + * @dataProvider provideArrayToReplaceKeys + */ + public function testReplaceKeys( + string $description, + array $array, + string $oldKeyPattern, + string $newKey, + ?array $expected + ): void { + self::assertSame($expected, Arrays::replaceKeys($array, $oldKeyPattern, $newKey), $description); } - public function testMakeArray() + public function testMakeArray(): void { self::assertSame($this->simpleArray, Arrays::makeArray($this->simpleArray)); self::assertSame(['test'], Arrays::makeArray('test')); } - public function testArray2JavaScript() + public function testArray2JavaScript(): void { // Negative cases self::assertNull(Arrays::array2JavaScript([])); @@ -339,36 +338,25 @@ letsTest[2] = value_2;'; * * @dataProvider provideArrayToQuoteStrings */ - public function testQuoteStrings($description, $expected, array $array) + public function testQuoteStrings(string $description, ?array $expected, array $array): void { self::assertSame($expected, Arrays::quoteStrings($array), $description); } - public function testRemoveMarginalElement() + /** + * @param string $description Description of test case + * @param array $array The array which should be shortened + * @param bool $last If is set to true, last element is removed (default behaviour). Otherwise - first. + * @param null|array $expected Expected result + * + * @dataProvider provideArrayToRemoveMarginalElement + */ + public function testRemoveMarginalElement(string $description, array $array, bool $last, ?array $expected): void { - $array = $this->simpleArray; - $string = 'Lorem ipsum'; - - // Removing first element - self::assertSame([ - 0 => 'Lorem', - 1 => 'ipsum', - 2 => 'dolor', - 3 => 'sit', - ], Arrays::removeMarginalElement($array)); - self::assertEquals('Lorem ipsu', Arrays::removeMarginalElement($string)); - - // Removing last element - self::assertSame([ - 1 => 'ipsum', - 2 => 'dolor', - 3 => 'sit', - 4 => 'amet', - ], Arrays::removeMarginalElement($array, false)); - self::assertEquals('orem ipsum', Arrays::removeMarginalElement($string, false)); + self::assertSame($expected, Arrays::removeMarginalElement($array, $last), $description); } - public function testRemoveElements() + public function testRemoveElements(): void { $array1 = $this->simpleArray; $array2 = $this->simpleArray; @@ -467,7 +455,7 @@ letsTest[2] = value_2;'; self::assertEquals($replaced, Arrays::setKeysAsValues($array, false)); } - public function testGetNonArrayElementsCount() + public function testGetNonArrayElementsCount(): void { // Negative cases self::assertNull(Arrays::getNonArrayElementsCount([])); @@ -478,11 +466,10 @@ letsTest[2] = value_2;'; self::assertEquals(12, Arrays::getNonArrayElementsCount($this->twoDimensionsArray)); } - public function testString2array() + public function testString2array(): void { // Negative cases self::assertNull(Arrays::string2array('')); - self::assertNull(Arrays::string2array(null)); // Positive cases $array = [ @@ -504,7 +491,7 @@ letsTest[2] = value_2;'; self::assertEquals($array, Arrays::string2array('red : #f00 | green : #0f0 | blue : #00f')); } - public function testAreKeysInArray() + public function testAreKeysInArray(): void { // Negative cases self::assertFalse(Arrays::areKeysInArray([], [])); @@ -568,12 +555,12 @@ letsTest[2] = value_2;'; self::assertTrue(Arrays::areKeysInArray($keys17, $this->complexArray, false)); } - public function testGetLastElementsPathsUsingEmptyArray() + public function testGetLastElementsPathsUsingEmptyArray(): void { self::assertNull(Arrays::getLastElementsPaths([])); } - public function testGetLastElementsPathsUsingDefaults() + public function testGetLastElementsPathsUsingDefaults(): void { // Using default separator and other default arguments $expected = [ @@ -592,7 +579,7 @@ letsTest[2] = value_2;'; self::assertEquals($expected, Arrays::getLastElementsPaths($this->complexArray)); } - public function testGetLastElementsPathsUsingCustomSeparator() + public function testGetLastElementsPathsUsingCustomSeparator(): void { // Using custom separator $separator = ' -> '; @@ -613,20 +600,24 @@ letsTest[2] = value_2;'; } /** - * @param array|string $stopIfMatchedBy Patterns of keys or paths that matched will stop the process of path - * building and including children of those keys or paths (recursive will - * not be used for keys in lower level of given array) - * @param string $separator Separator used in resultant strings. Default: ".". - * @param array $expected Expected array + * @param array $stopIfMatchedBy Patterns of keys or paths that matched will stop the process of path building and + * including children of those keys or paths (recursive will not be used for keys in + * lower level of given array) + * @param string $separator Separator used in resultant strings. Default: ".". + * @param array $expected Expected array * * @dataProvider provideStopIfMatchedByForGetLastElementsPaths */ - public function testGetLastElementsPathsUsingStopIfMatchedBy($stopIfMatchedBy, $separator, array $expected) - { - self::assertEquals($expected, Arrays::getLastElementsPaths($this->superComplexArray, $separator, '', $stopIfMatchedBy)); + public function testGetLastElementsPathsUsingStopIfMatchedBy( + array $stopIfMatchedBy, + string $separator, + array $expected + ): void { + $paths = Arrays::getLastElementsPaths($this->superComplexArray, $separator, '', $stopIfMatchedBy); + self::assertEquals($expected, $paths); } - public function testAreAllKeysMatchedByPattern() + public function testAreAllKeysMatchedByPattern(): void { $pattern = '\d+'; @@ -1471,6 +1462,30 @@ letsTest[2] = value_2;'; self::assertSame($expected, Arrays::getNonEmptyValuesAsString($values, $separator), $description); } + /** + * @param string $description Description of test case + * @param mixed $value The value to verify + * @param bool $expected Expected information + * + * @dataProvider provideValueToIsEmptyArray + */ + public function testIsEmptyArray(string $description, $value, bool $expected): void + { + self::assertSame($expected, Arrays::isEmptyArray($value), $description); + } + + /** + * @param string $description Description of test case + * @param mixed $value The value to verify + * @param bool $expected Expected information + * + * @dataProvider provideValueToIsNotEmptyArray + */ + public function testIsNotEmptyArray(string $description, $value, bool $expected): void + { + self::assertSame($expected, Arrays::isNotEmptyArray($value), $description); + } + /** * Provides simple array to set/replace values with keys * @@ -1573,13 +1588,13 @@ letsTest[2] = value_2;'; * Provides patterns of keys or paths that matched will stop the process and the expected array for the * getLastElementsPaths() method * - * @return \Generator + * @return Generator */ - public function provideStopIfMatchedByForGetLastElementsPaths() + public function provideStopIfMatchedByForGetLastElementsPaths(): ?Generator { // Special exception: do not use, stop recursive on the "diam" key yield[ - 'diam', + ['diam'], '.', [ 'ipsum.quis.vestibulum.porta-1.0' => 'turpis', @@ -1787,9 +1802,9 @@ letsTest[2] = value_2;'; /** * Provide values to filter and get non-empty values * - * @return \Generator + * @return Generator */ - public function provideValuesToFilterNonEmpty() + public function provideValuesToFilterNonEmpty(): ?Generator { $simpleObject = new SimpleToString('1234'); @@ -2554,6 +2569,307 @@ letsTest[2] = value_2;'; ]; } + public function provideValueToIsEmptyArray(): ?\Generator + { + yield[ + 'An empty string', + '', + false, + ]; + + yield[ + 'Non-empty string', + 'test', + false, + ]; + + yield[ + 'Null', + null, + false, + ]; + + yield[ + 'An integer equals 0', + 1234, + false, + ]; + + yield[ + 'An integer greater than 0', + 1234, + false, + ]; + + yield[ + 'An empty array', + [], + true, + ]; + + yield[ + 'Non-empty array', + [ + 'test', + ], + false, + ]; + } + + public function provideValueToIsNotEmptyArray(): ?\Generator + { + yield[ + 'An empty string', + '', + false, + ]; + + yield[ + 'Non-empty string', + 'test', + false, + ]; + + yield[ + 'Null', + null, + false, + ]; + + yield[ + 'An integer equals 0', + 1234, + false, + ]; + + yield[ + 'An integer greater than 0', + 1234, + false, + ]; + + yield[ + 'An empty array', + [], + false, + ]; + + yield[ + 'Non-empty array', + [ + 'test', + ], + true, + ]; + } + + public function provideArrayToRemoveMarginalElement(): Generator + { + yield[ + 'An empty array - remove last element', + [], + true, + null, + ]; + + yield[ + 'An empty array - remove first element', + [], + false, + null, + ]; + + yield[ + 'One-dimensional array - remove last element', + [ + 'Lorem', + 'ipsum', + 'dolor', + 'sit', + 'amet', + ], + true, + [ + 0 => 'Lorem', + 1 => 'ipsum', + 2 => 'dolor', + 3 => 'sit', + ], + ]; + + yield[ + 'One-dimensional array - remove first element', + [ + 'Lorem', + 'ipsum', + 'dolor', + 'sit', + 'amet', + ], + false, + [ + 1 => 'ipsum', + 2 => 'dolor', + 3 => 'sit', + 4 => 'amet', + ], + ]; + + yield[ + 'Multi-dimensional array - remove last element', + [ + 'lorem' => [ + 'ipsum' => [ + 'dolor' => 'sit', + 'diam' => [ + 'non' => 'egestas', + ], + ], + ], + 'consectetur' => 'adipiscing', + 'mollis' => 1234, + 2 => [], + 'sit' => [ + 'nullam' => 'donec', + 'aliquet' => [ + 'vitae' => [ + 'ligula' => 'quis', + ], + ], + 'elit', + ], + 'amet' => [ + 'iaculis', + 'primis', + ], + ], + true, + [ + 'lorem' => [ + 'ipsum' => [ + 'dolor' => 'sit', + 'diam' => [ + 'non' => 'egestas', + ], + ], + ], + 'consectetur' => 'adipiscing', + 'mollis' => 1234, + 2 => [], + 'sit' => [ + 'nullam' => 'donec', + 'aliquet' => [ + 'vitae' => [ + 'ligula' => 'quis', + ], + ], + 'elit', + ], + ], + ]; + + yield[ + 'Multi-dimensional array - remove first element', + [ + 'lorem' => [ + 'ipsum' => [ + 'dolor' => 'sit', + 'diam' => [ + 'non' => 'egestas', + ], + ], + ], + 'consectetur' => 'adipiscing', + 'mollis' => 1234, + 2 => [], + 'sit' => [ + 'nullam' => 'donec', + 'aliquet' => [ + 'vitae' => [ + 'ligula' => 'quis', + ], + ], + 'elit', + ], + 'amet' => [ + 'iaculis', + 'primis', + ], + ], + false, + [ + 'consectetur' => 'adipiscing', + 'mollis' => 1234, + 2 => [], + 'sit' => [ + 'nullam' => 'donec', + 'aliquet' => [ + 'vitae' => [ + 'ligula' => 'quis', + ], + ], + 'elit', + ], + 'amet' => [ + 'iaculis', + 'primis', + ], + ], + ]; + } + + public function provideArrayToReplaceKeys(): Generator + { + yield[ + 'An empty array', + [], + '', + '', + null, + ]; + + yield[ + '1st case', + [ + 'nullam' => 'donec', + 'aliquet' => [ + 'vitae' => [ + 'ligula' => 'quis', + ], + ], + 'elit', + ], + '|.*li.*|', + 'x', + [ + 'nullam' => 'donec', + 'x' => [ + 'vitae' => [ + 'x' => 'quis', + ], + ], + 'elit', + ], + ]; + + yield[ + '2nd case', + [ + 'Lorem', + 'ipsum', + 'dolor', + 'sit', + 'amet', + ], + '|[0-3]+|', + 'x', + [ + 'x' => 'sit', + 4 => 'amet', + ], + ]; + } + /** * {@inheritdoc} */ diff --git a/tests/Utilities/DateTest.php b/tests/Utilities/DateTest.php index 419b837..15ae92b 100644 --- a/tests/Utilities/DateTest.php +++ b/tests/Utilities/DateTest.php @@ -28,7 +28,7 @@ use Meritoo\Common\Utilities\Locale; */ class DateTest extends BaseTestCase { - public function testConstructor() + public function testConstructor(): void { static::assertHasNoConstructor(Date::class); } @@ -37,7 +37,7 @@ class DateTest extends BaseTestCase * @param mixed $value Empty value, e.g. "" * @dataProvider provideEmptyValue */ - public function testGetDateTimeEmptyValue($value) + public function testGetDateTimeEmptyValue($value): void { self::assertFalse(Date::getDateTime($value)); } @@ -46,7 +46,7 @@ class DateTest extends BaseTestCase * @param mixed $value Incorrect source of DateTime * @dataProvider provideIncorrectDateTimeValue */ - public function testGetDateTimeIncorrectValue($value) + public function testGetDateTimeIncorrectValue($value): void { self::assertFalse(Date::getDateTime($value)); } @@ -55,7 +55,7 @@ class DateTest extends BaseTestCase * @param bool $value The value which maybe is a date * @dataProvider provideBooleanValue */ - public function testGetDateTimeBoolean($value) + public function testGetDateTimeBoolean($value): void { self::assertFalse(Date::getDateTime($value)); } @@ -64,7 +64,7 @@ class DateTest extends BaseTestCase * @param string $relativeFormat Relative / compound format of DateTime * @dataProvider provideDateTimeRelativeFormat */ - public function testGetDateTimeRelativeFormats($relativeFormat) + public function testGetDateTimeRelativeFormats($relativeFormat): void { /* * Values based on relative / compound formats, but... without explicitly declaring them as compound @@ -85,12 +85,12 @@ class DateTest extends BaseTestCase * @param DateTime $dateTime Instance of DateTime class * @dataProvider provideDateTimeInstance */ - public function testGetDateTimeInstanceDateTime(DateTime $dateTime) + public function testGetDateTimeInstanceDateTime(DateTime $dateTime): void { self::assertInstanceOf(DateTime::class, Date::getDateTime($dateTime)); } - public function testGetDateTimeConcreteDates() + public function testGetDateTimeConcreteDates(): void { // Using the standard date format provided by the tested method self::assertInstanceOf(DateTime::class, Date::getDateTime('2015-03-20')); @@ -104,7 +104,7 @@ class DateTest extends BaseTestCase * @param mixed $value Empty value, e.g. "" * @dataProvider provideEmptyValue */ - public function testIsValidDateEmptyDates($value) + public function testIsValidDateEmptyDates($value): void { self::assertFalse(Date::isValidDate($value)); } @@ -113,12 +113,12 @@ class DateTest extends BaseTestCase * @param mixed $value Incorrect source of DateTime * @dataProvider provideIncorrectDateTimeValue */ - public function testIsValidDateIncorrectDates($value) + public function testIsValidDateIncorrectDates($value): void { self::assertFalse(Date::isValidDate($value)); } - public function testIsValidDateValidDates() + public function testIsValidDateValidDates(): void { self::assertTrue(Date::isValidDate('2017-01-01')); self::assertTrue(Date::isValidDate('2017-01-01 10:30', true)); @@ -134,7 +134,7 @@ class DateTest extends BaseTestCase * @param mixed $value Empty source of date format * @dataProvider provideEmptyValue */ - public function testIsValidDateFormatEmptyFormats($value) + public function testIsValidDateFormatEmptyFormats($value): void { self::assertFalse(Date::isValidDateFormat($value)); } @@ -143,12 +143,12 @@ class DateTest extends BaseTestCase * @param mixed $format Invalid format of date * @dataProvider provideInvalidDateFormats */ - public function testIsValidDateFormatInvalidFormats($format) + public function testIsValidDateFormatInvalidFormats($format): void { self::assertFalse(Date::isValidDateFormat($format)); } - public function testIsValidDateFormatValidFormats() + public function testIsValidDateFormatValidFormats(): void { self::assertTrue(Date::isValidDateFormat('Y')); self::assertTrue(Date::isValidDateFormat('yy')); @@ -165,12 +165,12 @@ class DateTest extends BaseTestCase * @param mixed $value Empty value, e.g. "" * @dataProvider provideEmptyValue */ - public function testGenerateRandomTimeEmptyFormat($value) + public function testGenerateRandomTimeEmptyFormat($value): void { self::assertNull(Date::generateRandomTime($value)); } - public function testGenerateRandomTimeIncorrectFormat() + public function testGenerateRandomTimeIncorrectFormat(): void { self::assertNull(Date::generateRandomTime(',')); self::assertNull(Date::generateRandomTime(';')); @@ -178,12 +178,12 @@ class DateTest extends BaseTestCase self::assertNull(Date::generateRandomTime('?')); } - public function testGenerateRandomTimeDefaultFormat() + public function testGenerateRandomTimeDefaultFormat(): void { self::assertRegExp('/\d{2}:\d{2}:\d{2}/', Date::generateRandomTime()); } - public function testGenerateRandomTimeCustomFormat() + public function testGenerateRandomTimeCustomFormat(): void { self::assertRegExp('/^0[1-9]{1}|1[0-2]{1}$/', Date::generateRandomTime('h')); // 01 through 12 self::assertRegExp('/^[0-5]?[0-9]$/', Date::generateRandomTime('i')); // 00 through 59 @@ -193,12 +193,12 @@ class DateTest extends BaseTestCase self::assertRegExp('/^[1-9]|1[0-2]:\d{2}$/', Date::generateRandomTime('g:i')); } - public function testGetCurrentDayOfWeek() + public function testGetCurrentDayOfWeek(): void { self::assertRegExp('/^[0-6]{1}$/', (string)Date::getCurrentDayOfWeek()); } - public function testGetCurrentDayOfWeekName() + public function testGetCurrentDayOfWeekName(): void { // Required to avoid failure: // @@ -228,7 +228,7 @@ class DateTest extends BaseTestCase * * @dataProvider provideIncorrectYearMonthDay */ - public function testGetDayOfWeekIncorrectValues($year, $month, $day) + public function testGetDayOfWeekIncorrectValues($year, $month, $day): void { $this->expectException(UnknownDatePartTypeException::class); self::assertEmpty(Date::getDayOfWeek($year, $month, $day)); @@ -241,7 +241,7 @@ class DateTest extends BaseTestCase * * @dataProvider provideYearMonthDay */ - public function testGetDayOfWeek($year, $month, $day) + public function testGetDayOfWeek($year, $month, $day): void { self::assertRegExp('/^[0-6]{1}$/', (string)Date::getDayOfWeek($year, $month, $day)); } @@ -252,18 +252,18 @@ class DateTest extends BaseTestCase * * @dataProvider provideEmptyDatesForDateDifference */ - public function testGetDateDifferenceEmptyDates($dateStart, $dateEnd) + public function testGetDateDifferenceEmptyDates($dateStart, $dateEnd): void { self::assertNull(Date::getDateDifference($dateStart, $dateEnd)); } - public function testGetDateDifferenceInvalidDates() + public function testGetDateDifferenceInvalidDates(): void { self::assertNull(Date::getDateDifference('2017-01-40', '2017-13-01')); self::assertNull(Date::getDateDifference('xyz', 'lorem')); } - public function testGetDateDifferenceOneDay() + public function testGetDateDifferenceOneDay(): void { // Difference of 1 day $dateStart = '2017-01-01'; @@ -311,7 +311,7 @@ class DateTest extends BaseTestCase self::assertEquals(0, Date::getDateDifference(new DateTime('yesterday'), new DateTime('midnight'), Date::DATE_DIFFERENCE_UNIT_MINUTES)); } - public function testGetDateDifferenceOneDayTwoHours() + public function testGetDateDifferenceOneDayTwoHours(): void { // Difference of 1 day, 2 hours and 15 minutes $dateStart = '2017-01-01 12:00'; @@ -344,7 +344,7 @@ class DateTest extends BaseTestCase self::assertEquals(15, Date::getDateDifference(new DateTime($dateStart), new DateTime($dateEnd), Date::DATE_DIFFERENCE_UNIT_MINUTES)); } - public function testGetDateDifferenceOneMonthFortyOneDays() + public function testGetDateDifferenceOneMonthFortyOneDays(): void { // Difference of 1 month, 41 days, 4 hours and 30 minutes $dateStart = '2017-01-01 12:00'; @@ -377,7 +377,7 @@ class DateTest extends BaseTestCase self::assertEquals(30, Date::getDateDifference(new DateTime($dateStart), new DateTime($dateEnd), Date::DATE_DIFFERENCE_UNIT_MINUTES)); } - public function testGetDateDifferenceNewYear() + public function testGetDateDifferenceNewYear(): void { $dateStart = '2017-12-31 23:59'; $dateEnd = '2018-01-01 00:00'; @@ -409,7 +409,7 @@ class DateTest extends BaseTestCase self::assertEquals(1, Date::getDateDifference(new DateTime($dateStart), new DateTime($dateEnd), Date::DATE_DIFFERENCE_UNIT_MINUTES)); } - public function testGetDateDifferenceLessThan24Hours() + public function testGetDateDifferenceLessThan24Hours(): void { $dateStart = '2017-01-01 16:00'; $dateEnd = '2017-01-02 10:00'; @@ -441,7 +441,7 @@ class DateTest extends BaseTestCase self::assertEquals(0, Date::getDateDifference(new DateTime($dateStart), new DateTime($dateEnd), Date::DATE_DIFFERENCE_UNIT_MINUTES)); } - public function testGetDateDifferenceEqual24Hours() + public function testGetDateDifferenceEqual24Hours(): void { $dateStart = '2017-01-01 00:00'; $dateEnd = '2017-01-02 00:00'; @@ -473,7 +473,7 @@ class DateTest extends BaseTestCase self::assertEquals(0, Date::getDateDifference(new DateTime($dateStart), new DateTime($dateEnd), Date::DATE_DIFFERENCE_UNIT_MINUTES)); } - public function testGetDateDifferenceInvertedDates() + public function testGetDateDifferenceInvertedDates(): void { $dateStart = '2017-01-02 10:00'; $dateEnd = '2017-01-01 16:00'; @@ -505,7 +505,7 @@ class DateTest extends BaseTestCase self::assertEquals(0, Date::getDateDifference(new DateTime($dateStart), new DateTime($dateEnd), Date::DATE_DIFFERENCE_UNIT_MINUTES)); } - public function testGetDateDifferenceNoDifference() + public function testGetDateDifferenceNoDifference(): void { // No difference $dateStart = '2017-01-01 12:00'; @@ -542,7 +542,7 @@ class DateTest extends BaseTestCase * @param mixed $invalidCount Empty value, e.g. "" * @dataProvider provideEmptyValue */ - public function testGetDatesCollectionInvalidCount($invalidCount) + public function testGetDatesCollectionInvalidCount($invalidCount): void { self::assertEquals([], Date::getDatesCollection(new DateTime(), $invalidCount)); self::assertEquals([], Date::getDatesCollection(new DateTime(), -1)); @@ -552,14 +552,14 @@ class DateTest extends BaseTestCase * @param mixed $invalidInterval Empty value, e.g. "" * @dataProvider provideEmptyValue */ - public function testGetDatesCollectionInvalidInterval($invalidInterval) + public function testGetDatesCollectionInvalidInterval($invalidInterval): void { self::assertEquals([], Date::getDatesCollection(new DateTime(), 2, $invalidInterval)); self::assertEquals([], Date::getDatesCollection(new DateTime(), 2, 'lorem')); self::assertEquals([], Date::getDatesCollection(new DateTime(), 2, '%d')); } - public function testGetDatesCollection() + public function testGetDatesCollection(): void { // 1 date only $effect = [ @@ -596,7 +596,7 @@ class DateTest extends BaseTestCase self::assertEquals($effect, Date::getDatesCollection(new DateTime('2017-01-01'), 3, 'P%dM')); } - public function testGetRandomDateUsingDefaults() + public function testGetRandomDateUsingDefaults(): void { $startDate = new DateTime(); $start = 1; @@ -619,7 +619,7 @@ class DateTest extends BaseTestCase * * @dataProvider provideDataOfRandomDateIncorrectEnd */ - public function testGetRandomDateIncorrectEnd(DateTime $startDate, $start, $end) + public function testGetRandomDateIncorrectEnd(DateTime $startDate, $start, $end): void { $randomDate = Date::getRandomDate($startDate, $start, $end); @@ -636,7 +636,7 @@ class DateTest extends BaseTestCase * * @dataProvider provideDataOfRandomDate */ - public function testGetRandomDate(DateTime $startDate, $start, $end) + public function testGetRandomDate(DateTime $startDate, $start, $end): void { $randomDate = Date::getRandomDate($startDate, $start, $end); @@ -651,9 +651,9 @@ class DateTest extends BaseTestCase /** * @param mixed $period Empty value, e.g. "" - * @dataProvider provideEmptyValue + * @dataProvider provideEmptyScalarValue */ - public function testGetDatesForPeriodUsingEmptyPeriod($period) + public function testGetDatesForPeriodUsingEmptyPeriod($period): void { self::assertNull(Date::getDatesForPeriod($period)); } @@ -662,7 +662,7 @@ class DateTest extends BaseTestCase * @param int $period Incorrect period to verify * @dataProvider provideIncorrectPeriod */ - public function testGetDatesForPeriodUsingIncorrectPeriod($period) + public function testGetDatesForPeriodUsingIncorrectPeriod($period): void { self::assertNull(Date::getDatesForPeriod($period)); } @@ -674,7 +674,7 @@ class DateTest extends BaseTestCase * * @dataProvider provideCorrectPeriod */ - public function testGetDatesForPeriod($period, DatePeriod $expected) + public function testGetDatesForPeriod($period, DatePeriod $expected): void { self::assertEquals($expected, Date::getDatesForPeriod($period)); } diff --git a/tests/Utilities/MiscellaneousTest.php b/tests/Utilities/MiscellaneousTest.php index 7f48d98..93af639 100644 --- a/tests/Utilities/MiscellaneousTest.php +++ b/tests/Utilities/MiscellaneousTest.php @@ -23,7 +23,7 @@ use stdClass; * @copyright Meritoo * * @internal - * @covers \Meritoo\Common\Utilities\Miscellaneous + * @covers \Meritoo\Common\Utilities\Miscellaneous */ class MiscellaneousTest extends BaseTestCase { @@ -707,22 +707,40 @@ class MiscellaneousTest extends BaseTestCase * * @dataProvider provideNumberToFillMissingZeros */ - public function testFillMissingZeros($number, $length, $before, $expected) + public function testFillMissingZeros($number, $length, $before, $expected): void { self::assertSame($expected, Miscellaneous::fillMissingZeros($number, $length, $before)); } - public function testGetProjectRootPath() + public function testGetProjectRootPath(): void { self::assertNotEmpty(Miscellaneous::getProjectRootPath()); } + /** + * @param string $description Description of test case + * @param string $string The string which should be shortened + * @param bool $last (optional) If is set to true, last element is removed (default behaviour). + * Otherwise - first. + * @param null|string $expected Expected result + * + * @dataProvider provideStringToRemoveMarginalCharacter + */ + public function testRemoveMarginalCharacter( + string $description, + string $string, + bool $last, + ?string $expected + ): void { + self::assertEquals($expected, Miscellaneous::removeMarginalCharacter($string, $last), $description); + } + /** * Provides string to convert characters to latin characters and not lower cased and not human-readable * * @return Generator */ - public function provideStringToLatinNotLowerCaseHuman() + public function provideStringToLatinNotLowerCaseHuman(): ?Generator { yield[ 'asuo', @@ -1443,6 +1461,51 @@ class MiscellaneousTest extends BaseTestCase ]; } + public function provideStringToRemoveMarginalCharacter(): ?Generator + { + yield[ + 'An empty string - remove last character', + '', + true, + null, + ]; + + yield[ + 'An empty string - remove first character', + '', + false, + null, + ]; + + yield[ + 'Simple, two words - remove last character', + 'Lorem ipsum', + true, + 'Lorem ipsu', + ]; + + yield[ + 'Simple, two words - remove first character', + 'Lorem ipsum', + false, + 'orem ipsum', + ]; + + yield[ + 'Two sentences - remove last character', + 'Etiam ullamcorper. Suspendisse a pellentesque dui, non felis.', + true, + 'Etiam ullamcorper. Suspendisse a pellentesque dui, non felis', + ]; + + yield[ + 'Two sentences - remove first character', + 'Etiam ullamcorper. Suspendisse a pellentesque dui, non felis.', + false, + 'tiam ullamcorper. Suspendisse a pellentesque dui, non felis.', + ]; + } + /** * {@inheritdoc} */ diff --git a/tests/Utilities/ReflectionTest.php b/tests/Utilities/ReflectionTest.php index 1862ee3..7a0aaef 100644 --- a/tests/Utilities/ReflectionTest.php +++ b/tests/Utilities/ReflectionTest.php @@ -49,20 +49,20 @@ class ReflectionTest extends BaseTestCase * @param mixed $invalidClass Empty value, e.g. "" * @dataProvider provideEmptyValue */ - public function testGetClassNameInvalidClass($invalidClass) + public function testGetClassNameInvalidClass($invalidClass): void { self::assertNull(Reflection::getClassName($invalidClass)); self::assertNull(Reflection::getClassName(123)); } - public function testGetClassNameNotExistingClass() + public function testGetClassNameNotExistingClass(): void { // Not existing class self::assertEquals('', Reflection::getClassName('xyz')); self::assertEquals('', Reflection::getClassName('xyz', true)); } - public function testGetClassNameExistingClass() + public function testGetClassNameExistingClass(): void { // Existing class self::assertEquals(self::class, Reflection::getClassName(self::class)); @@ -77,9 +77,9 @@ class ReflectionTest extends BaseTestCase } /** - * A case when namespace of class contains name of class (name of class is duplicated, occurs twice) + * A case when namespace of class contains name of class (iow. name of class occurs twice) */ - public function testGetClassWhileNamespaceContainsClassName() + public function testGetClassWhileNamespaceContainsClassName(): void { self::assertEquals( 'Meritoo\Common\Collection\Collection', @@ -92,13 +92,13 @@ class ReflectionTest extends BaseTestCase ); } - public function testGetClassNamespaceNotExistingClass() + public function testGetClassNamespaceNotExistingClass(): void { // Not existing class self::assertEquals('', Reflection::getClassNamespace('xyz')); } - public function testGetClassNamespaceExistingClass() + public function testGetClassNamespaceExistingClass(): void { // Existing class self::assertEquals('Meritoo\Test\Common\Utilities', Reflection::getClassNamespace(self::class));