Fix code pointed by Psalm

This commit is contained in:
Meritoo
2019-05-05 09:49:03 +02:00
parent 421d19ff10
commit dd5ac0f7e6
33 changed files with 1085 additions and 524 deletions

View File

@@ -28,13 +28,13 @@ abstract class UnknownTypeException extends Exception
* @param string $typeName Name of the something * @param string $typeName Name of the something
* @return UnknownTypeException * @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' $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.'; . ' of these types: %s.';
$allTypes = $typeInstance->getAll(); $allTypes = $typeInstance->getAll();
$types = Arrays::values2string($allTypes, '', ', '); $types = Arrays::values2string($allTypes, '', ', ') ?? '[types not found]';
$message = sprintf($template, $unknownType, $typeName, $types); $message = sprintf($template, $unknownType, $typeName, $types);
return new static($message); return new static($message);

View File

@@ -18,8 +18,10 @@ class EmptyFilePathException extends \Exception
{ {
/** /**
* Creates 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?'); return new static('Path of the file is empty. Did you provide path of proper file?');
} }

View File

@@ -27,7 +27,7 @@ class CannotResolveClassNameException extends Exception
* prepared. Otherwise - for trait. * prepared. Otherwise - for trait.
* @return CannotResolveClassNameException * @return CannotResolveClassNameException
*/ */
public static function create($source, $forClass = true) public static function create($source, bool $forClass = true): CannotResolveClassNameException
{ {
$forWho = 'trait'; $forWho = 'trait';
$value = ''; $value = '';

View File

@@ -0,0 +1,34 @@
<?php
/**
* (c) Meritoo.pl, http://www.meritoo.pl
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Meritoo\Common\Exception\Reflection;
use Exception;
/**
* An exception used while given class hasn't constructor
*
* @author Meritoo <github@meritoo.pl>
* @copyright Meritoo <http://www.meritoo.pl>
*/
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);
}
}

View File

@@ -26,12 +26,12 @@ class MissingChildClassesException extends Exception
* strings, object or string. * strings, object or string.
* @return MissingChildClassesException * @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' $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?'; . ' 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); $message = sprintf($template, $parentClassName);
return new static($message); return new static($message);

View File

@@ -19,11 +19,11 @@ class NotExistingPropertyException extends \Exception
/** /**
* Creates exception * Creates exception
* *
* @param mixed $object Object that should contains given property * @param mixed $object Object that should contains given property
* @param string $property Name of the property * @param null|string $property Name of the property
* @return NotExistingPropertyException * @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?'; $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)); $message = sprintf($template, $property, get_class($object));

View File

@@ -27,12 +27,12 @@ class TooManyChildClassesException extends Exception
* @param array $childClasses Child classes * @param array $childClasses Child classes
* @return TooManyChildClassesException * @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" $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?"; . " 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); $message = sprintf($template, $parentClassName, implode("\n- ", $childClasses), $parentClassName);
return new static($message); return new static($message);

View File

@@ -26,7 +26,7 @@ class UnknownDatePartTypeException extends UnknownTypeException
* @param string $value Incorrect value * @param string $value Incorrect value
* @return UnknownDatePartTypeException * @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)); return parent::create($unknownDatePart, new DatePartType(), sprintf('date part (with value %s)', $value));
} }

View File

@@ -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 * @param string $unknownType Unknown visibility of a property, a method or (as of PHP 7.1.0) a constant
* @return UnknownOopVisibilityTypeException * @return UnknownOopVisibilityTypeException
*/ */
public static function createException($unknownType) public static function createException(string $unknownType): UnknownOopVisibilityTypeException
{ {
return parent::create($unknownType, new OopVisibilityType(), 'OOP-related visibility'); return parent::create($unknownType, new OopVisibilityType(), 'OOP-related visibility');
} }

View File

@@ -10,11 +10,13 @@ namespace Meritoo\Common\Traits\Test\Base;
use DateTime; use DateTime;
use Generator; use Generator;
use Meritoo\Common\Exception\Reflection\ClassWithoutConstructorException;
use Meritoo\Common\Exception\Type\UnknownOopVisibilityTypeException; use Meritoo\Common\Exception\Type\UnknownOopVisibilityTypeException;
use Meritoo\Common\Type\OopVisibilityType; use Meritoo\Common\Type\OopVisibilityType;
use Meritoo\Common\Utilities\Miscellaneous; use Meritoo\Common\Utilities\Miscellaneous;
use ReflectionClass; use ReflectionClass;
use ReflectionMethod; use ReflectionMethod;
use RuntimeException;
use stdClass; use stdClass;
/** /**
@@ -37,7 +39,7 @@ trait BaseTestCaseTrait
* *
* @return Generator * @return Generator
*/ */
public function provideEmptyValue() public function provideEmptyValue(): ?Generator
{ {
yield['']; yield[''];
yield[' ']; yield[' '];
@@ -52,7 +54,7 @@ trait BaseTestCaseTrait
* *
* @return Generator * @return Generator
*/ */
public function provideEmptyScalarValue() public function provideEmptyScalarValue(): ?Generator
{ {
yield['']; yield[''];
yield[' ']; yield[' '];
@@ -66,7 +68,7 @@ trait BaseTestCaseTrait
* *
* @return Generator * @return Generator
*/ */
public function provideBooleanValue() public function provideBooleanValue(): ?Generator
{ {
yield[false]; yield[false];
yield[true]; yield[true];
@@ -77,7 +79,7 @@ trait BaseTestCaseTrait
* *
* @return Generator * @return Generator
*/ */
public function provideDateTimeInstance() public function provideDateTimeInstance(): ?Generator
{ {
yield[new DateTime()]; yield[new DateTime()];
yield[new DateTime('yesterday')]; yield[new DateTime('yesterday')];
@@ -90,7 +92,7 @@ trait BaseTestCaseTrait
* *
* @return Generator * @return Generator
*/ */
public function provideDateTimeRelativeFormat() public function provideDateTimeRelativeFormat(): ?Generator
{ {
yield['now']; yield['now'];
yield['yesterday']; yield['yesterday'];
@@ -110,7 +112,7 @@ trait BaseTestCaseTrait
* *
* @return Generator * @return Generator
*/ */
public function provideNotExistingFilePath() public function provideNotExistingFilePath(): ?Generator
{ {
yield['lets-test.doc']; yield['lets-test.doc'];
yield['lorem/ipsum.jpg']; yield['lorem/ipsum.jpg'];
@@ -122,7 +124,7 @@ trait BaseTestCaseTrait
* *
* @return Generator * @return Generator
*/ */
public function provideNonScalarValue() public function provideNonScalarValue(): ?Generator
{ {
yield[ yield[
[], [],
@@ -145,7 +147,7 @@ trait BaseTestCaseTrait
* @param string $directoryPath (optional) Path of directory containing the file * @param string $directoryPath (optional) Path of directory containing the file
* @return string * @return string
*/ */
public function getFilePathForTesting($fileName, $directoryPath = '') public function getFilePathForTesting(string $fileName, string $directoryPath = ''): string
{ {
$rootPath = Miscellaneous::getProjectRootPath(); $rootPath = Miscellaneous::getProjectRootPath();
@@ -162,33 +164,34 @@ trait BaseTestCaseTrait
/** /**
* Verifies visibility and arguments of method * Verifies visibility and arguments of method
* *
* @param string $classNamespace Namespace of class that contains method to verify * @param string $className Fully-qualified name of class that contains method to verify
* @param ReflectionMethod|string $method Name of method or just the 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 * @param string $visibilityType Expected visibility of verified method. One of OopVisibilityType
* OopVisibilityType class constants. * class constants.
* @param int $argumentsCount (optional) Expected count/amount of arguments of the * @param int $argumentsCount (optional) Expected count/amount of arguments of the verified
* verified method * method
* @param int $requiredArgumentsCount (optional) Expected count/amount of required arguments * @param int $requiredArgumentsCount (optional) Expected count/amount of required arguments of the
* of the verified method * verified method
* @throws UnknownOopVisibilityTypeException * @throws UnknownOopVisibilityTypeException
* @throws RuntimeException
* *
* Attention. 2nd argument, the $method, may be: * Attention. 2nd argument, the $method, may be:
* - string - name of the method * - string - name of the method
* - instance of ReflectionMethod - just the method (provided by ReflectionClass::getMethod() method) * - instance of ReflectionMethod - just the method (provided by ReflectionClass::getMethod() method)
*/ */
protected static function assertMethodVisibilityAndArguments( protected static function assertMethodVisibilityAndArguments(
$classNamespace, string $className,
$method, ReflectionMethod $method,
$visibilityType, string $visibilityType,
$argumentsCount = 0, int $argumentsCount = 0,
$requiredArgumentsCount = 0 int $requiredArgumentsCount = 0
) { ): void {
// Type of visibility is not correct? // Type of visibility is not correct?
if (!(new OopVisibilityType())->isCorrectType($visibilityType)) { 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? // Name of method provided only?
// Let's find instance of the method (based on reflection) // Let's find instance of the method (based on reflection)
@@ -218,24 +221,29 @@ trait BaseTestCaseTrait
/** /**
* Verifies visibility and arguments of class constructor * 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 * @param string $visibilityType Expected visibility of verified method. One of OopVisibilityType class
* constants. * constants.
* @param int $argumentsCount (optional) Expected count/amount of arguments of the verified method * @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 * @param int $requiredArgumentsCount (optional) Expected count/amount of required arguments of the verified
* method * method
* @throws ClassWithoutConstructorException
*/ */
protected static function assertConstructorVisibilityAndArguments( protected static function assertConstructorVisibilityAndArguments(
$classNamespace, string $className,
$visibilityType, string $visibilityType,
$argumentsCount = 0, int $argumentsCount = 0,
$requiredArgumentsCount = 0 int $requiredArgumentsCount = 0
) { ): void {
$reflection = new ReflectionClass($classNamespace); $reflection = new ReflectionClass($className);
$method = $reflection->getConstructor(); $method = $reflection->getConstructor();
if (null === $method) {
throw ClassWithoutConstructorException::create($className);
}
static::assertMethodVisibilityAndArguments( static::assertMethodVisibilityAndArguments(
$classNamespace, $className,
$method, $method,
$visibilityType, $visibilityType,
$argumentsCount, $argumentsCount,
@@ -246,11 +254,11 @@ trait BaseTestCaseTrait
/** /**
* Asserts that class with given namespace has no constructor * 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(); $constructor = $reflection->getConstructor();
static::assertNull($constructor); static::assertNull($constructor);
@@ -261,7 +269,7 @@ trait BaseTestCaseTrait
* *
* @param string $testsDataDirPath Path of directory with data used by test cases * @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; static::$testsDataDirPath = $testsDataDirPath;
} }

View File

@@ -22,7 +22,7 @@ trait BaseTypeTestCaseTrait
/** /**
* Verifies availability of all types * Verifies availability of all types
*/ */
public function testAvailabilityOfAllTypes() public function testAvailabilityOfAllTypes(): void
{ {
$available = $this->getTestedTypeInstance()->getAll(); $available = $this->getTestedTypeInstance()->getAll();
$all = $this->getAllExpectedTypes(); $all = $this->getAllExpectedTypes();
@@ -33,12 +33,12 @@ trait BaseTypeTestCaseTrait
/** /**
* Verifies whether given type is correct or not * Verifies whether given type is correct or not
* *
* @param string $type Type to verify * @param null|string $type Type to verify
* @param bool $expected Information if given type is correct or not * @param bool $expected Information if given type is correct or not
* *
* @dataProvider provideTypeToVerify * @dataProvider provideTypeToVerify
*/ */
public function testIfGivenTypeIsCorrect($type, $expected) public function testIfGivenTypeIsCorrect(?string $type, bool $expected): void
{ {
static::assertEquals($expected, $this->getTestedTypeInstance()->isCorrectType($type)); static::assertEquals($expected, $this->getTestedTypeInstance()->isCorrectType($type));
} }
@@ -48,19 +48,19 @@ trait BaseTypeTestCaseTrait
* *
* @return Generator * @return Generator
*/ */
abstract public function provideTypeToVerify(); abstract public function provideTypeToVerify(): Generator;
/** /**
* Returns instance of the tested type * Returns instance of the tested type
* *
* @return BaseType * @return BaseType
*/ */
abstract protected function getTestedTypeInstance(); abstract protected function getTestedTypeInstance(): BaseType;
/** /**
* Returns all expected types of the tested type * Returns all expected types of the tested type
* *
* @return array * @return array
*/ */
abstract protected function getAllExpectedTypes(); abstract protected function getAllExpectedTypes(): array;
} }

View File

@@ -8,6 +8,8 @@
namespace Meritoo\Common\Traits\ValueObject; namespace Meritoo\Common\Traits\ValueObject;
use DateTime;
/** /**
* Methods and properties related to human * Methods and properties related to human
* *
@@ -33,26 +35,26 @@ trait HumanTrait
/** /**
* Email address * Email address
* *
* @var string * @var null|string
*/ */
protected $email; protected $email;
/** /**
* Birth date * Birth date
* *
* @var \DateTime * @var null|DateTime
*/ */
protected $birthDate; protected $birthDate;
/** /**
* Class constructor * Class constructor
* *
* @param string $firstName First name * @param string $firstName First name
* @param string $lastName Last name * @param string $lastName Last name
* @param string $email (optional) Email address * @param null|string $email (optional) Email address. Default: null.
* @param \DateTime $birthDate (optional) Birth date * @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->firstName = $firstName;
$this->lastName = $lastName; $this->lastName = $lastName;
@@ -68,12 +70,14 @@ trait HumanTrait
public function __toString() public function __toString()
{ {
$template = '%s'; $template = '%s';
$email = '';
if ('' !== $this->email && null !== $this->email) { if ('' !== $this->email && null !== $this->email) {
$template .= ' <%s>'; $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 * @return string
*/ */
public function getFirstName() public function getFirstName(): string
{ {
return $this->firstName; return $this->firstName;
} }
@@ -91,7 +95,7 @@ trait HumanTrait
* *
* @return string * @return string
*/ */
public function getLastName() public function getLastName(): string
{ {
return $this->lastName; return $this->lastName;
} }
@@ -101,7 +105,7 @@ trait HumanTrait
* *
* @return null|string * @return null|string
*/ */
public function getEmail() public function getEmail(): ?string
{ {
return $this->email; return $this->email;
} }
@@ -109,9 +113,9 @@ trait HumanTrait
/** /**
* Returns birth date * Returns birth date
* *
* @return null|\DateTime * @return null|DateTime
*/ */
public function getBirthDate() public function getBirthDate(): ?DateTime
{ {
return $this->birthDate; return $this->birthDate;
} }
@@ -119,10 +123,11 @@ trait HumanTrait
/** /**
* Returns the full name * 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 * @return string
*/ */
public function getFullName($firstNameFirst = true) public function getFullName(bool $firstNameFirst = true): string
{ {
$beginning = $this->lastName; $beginning = $this->lastName;
$finish = $this->firstName; $finish = $this->firstName;

View File

@@ -22,7 +22,7 @@ abstract class BaseType
/** /**
* All types * All types
* *
* @var array * @var null|array
*/ */
private $all; private $all;
@@ -31,7 +31,7 @@ abstract class BaseType
* *
* @return array * @return array
*/ */
public function getAll() public function getAll(): array
{ {
if (null === $this->all) { if (null === $this->all) {
$this->all = Reflection::getConstants($this); $this->all = Reflection::getConstants($this);
@@ -43,10 +43,10 @@ abstract class BaseType
/** /**
* Returns information if given type is correct * Returns information if given type is correct
* *
* @param mixed $type The type to check * @param null|string $type The type to check
* @return bool * @return bool
*/ */
public function isCorrectType($type) public function isCorrectType(?string $type): bool
{ {
return in_array($type, $this->getAll(), true); return in_array($type, $this->getAll(), true);
} }

View File

@@ -24,87 +24,87 @@ class DatePeriod extends BaseType
/** /**
* The period constant: last month * The period constant: last month
* *
* @var int * @var string
*/ */
public const LAST_MONTH = 4; public const LAST_MONTH = '4';
/** /**
* The period constant: last week * The period constant: last week
* *
* @var int * @var string
*/ */
public const LAST_WEEK = 1; public const LAST_WEEK = '1';
/** /**
* The period constant: last year * The period constant: last year
* *
* @var int * @var string
*/ */
public const LAST_YEAR = 7; public const LAST_YEAR = '7';
/** /**
* The period constant: next month * The period constant: next month
* *
* @var int * @var string
*/ */
public const NEXT_MONTH = 6; public const NEXT_MONTH = '6';
/** /**
* The period constant: next week * The period constant: next week
* *
* @var int * @var string
*/ */
public const NEXT_WEEK = 3; public const NEXT_WEEK = '3';
/** /**
* The period constant: next year * The period constant: next year
* *
* @var int * @var string
*/ */
public const NEXT_YEAR = 9; public const NEXT_YEAR = '9';
/** /**
* The period constant: this month * The period constant: this month
* *
* @var int * @var string
*/ */
public const THIS_MONTH = 5; public const THIS_MONTH = '5';
/** /**
* The period constant: this week * The period constant: this week
* *
* @var int * @var string
*/ */
public const THIS_WEEK = 2; public const THIS_WEEK = '2';
/** /**
* The period constant: this year * The period constant: this year
* *
* @var int * @var string
*/ */
public const THIS_YEAR = 8; public const THIS_YEAR = '8';
/** /**
* The start date of period * The start date of period
* *
* @var DateTime * @var null|DateTime
*/ */
private $startDate; private $startDate;
/** /**
* The end date of period * The end date of period
* *
* @var DateTime * @var null|DateTime
*/ */
private $endDate; private $endDate;
/** /**
* Class constructor * Class constructor
* *
* @param DateTime $startDate (optional) The start date of period * @param null|DateTime $startDate (optional) The start date of period
* @param DateTime $endDate (optional) The end 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->startDate = $startDate;
$this->endDate = $endDate; $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. * @param bool $startDate (optional) If is set to true, start date will be formatted. Otherwise - end date.
* @return string * @return string
*/ */
public function getFormattedDate($format, $startDate = true) public function getFormattedDate(string $format, bool $startDate = true): string
{ {
$date = $this->getEndDate(); $date = $this->getEndDate();
@@ -138,9 +138,9 @@ class DatePeriod extends BaseType
/** /**
* Returns the end date of period * Returns the end date of period
* *
* @return DateTime * @return null|DateTime
*/ */
public function getEndDate() public function getEndDate(): ?DateTime
{ {
return $this->endDate; return $this->endDate;
} }
@@ -148,10 +148,10 @@ class DatePeriod extends BaseType
/** /**
* Sets the end date of period * 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 * @return $this
*/ */
public function setEndDate(DateTime $endDate = null) public function setEndDate(?DateTime $endDate = null): self
{ {
$this->endDate = $endDate; $this->endDate = $endDate;
@@ -161,9 +161,9 @@ class DatePeriod extends BaseType
/** /**
* Returns the start date of period * Returns the start date of period
* *
* @return DateTime * @return null|DateTime
*/ */
public function getStartDate() public function getStartDate(): ?DateTime
{ {
return $this->startDate; return $this->startDate;
} }
@@ -171,10 +171,10 @@ class DatePeriod extends BaseType
/** /**
* Sets the start date of period * 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 * @return $this
*/ */
public function setStartDate(DateTime $startDate = null) public function setStartDate(?DateTime $startDate = null): self
{ {
$this->startDate = $startDate; $this->startDate = $startDate;

View File

@@ -17,21 +17,21 @@ class OopVisibilityType extends BaseType
/** /**
* The "private" visibility of OOP * The "private" visibility of OOP
* *
* @var int * @var string
*/ */
public const IS_PRIVATE = 3; public const IS_PRIVATE = '3';
/** /**
* The "protected" visibility of OOP * The "protected" visibility of OOP
* *
* @var int * @var string
*/ */
public const IS_PROTECTED = 2; public const IS_PROTECTED = '2';
/** /**
* The "public" visibility of OOP * The "public" visibility of OOP
* *
* @var int * @var string
*/ */
public const IS_PUBLIC = 1; public const IS_PUBLIC = '1';
} }

View File

@@ -335,7 +335,7 @@ class Arrays
* The last row is not an array or it's an empty array? * The last row is not an array or it's an empty array?
* Let's use the previous candidate * Let's use the previous candidate
*/ */
if (!is_array($effect) || (is_array($effect) && empty($effect))) { if (!is_array($effect) || self::isEmptyArray($effect)) {
$effect = $last; $effect = $last;
} }
} }
@@ -346,27 +346,29 @@ class Arrays
/** /**
* Replaces array keys that match given pattern with new key name * Replaces array keys that match given pattern with new key name
* *
* @param array $dataArray The array * @param array $array Array which keys should be replaced
* @param string $oldKeyPattern Old key pattern * @param string $oldKeyPattern Regular expression of the old key
* @param string $newKey New key name * @param string $newKey Name of the new key
* @return array * @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 = []; $effect = [];
if (is_array($dataArray) && !empty($dataArray)) { foreach ($array as $key => $value) {
foreach ($dataArray as $key => $value) { if (preg_match($oldKeyPattern, $key)) {
if (preg_match($oldKeyPattern, $key)) { $key = $newKey;
$key = $newKey;
}
if (is_array($value)) {
$value = self::replaceArrayKeys($value, $oldKeyPattern, $newKey);
}
$effect[$key] = $value;
} }
if (is_array($value)) {
$value = self::replaceKeys($value, $oldKeyPattern, $newKey);
}
$effect[$key] = $value;
} }
return $effect; return $effect;
@@ -376,17 +378,18 @@ class Arrays
* Generates JavaScript code for given PHP array * Generates JavaScript code for given PHP array
* *
* @param array $array The array that should be generated to JavaScript * @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 * @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 * @return null|string
*/ */
public static function array2JavaScript(array $array, $jsVariableName = '', $preserveIndexes = false) public static function array2JavaScript(
{ array $array,
/* string $jsVariableName = '',
* No elements? bool $preserveIndexes = false
* Nothing to do ): ?string {
*/ // No elements? Nothing to do
if (empty($array)) { if (empty($array)) {
return null; return null;
} }
@@ -396,7 +399,11 @@ class Arrays
$arrayCount = count($array); $arrayCount = count($array);
$arrayPrepared = self::quoteStrings($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? * Name of the variable was not provided and it's a multi dimensional array?
@@ -406,7 +413,7 @@ class Arrays
$jsVariableName = 'autoGeneratedVariable'; $jsVariableName = 'autoGeneratedVariable';
} }
if (!empty($jsVariableName) && is_string($jsVariableName)) { if (!empty($jsVariableName)) {
$result .= sprintf('var %s = ', $jsVariableName); $result .= sprintf('var %s = ', $jsVariableName);
} }
@@ -417,50 +424,52 @@ class Arrays
$result .= ');'; $result .= ');';
} }
foreach ($arrayPrepared as $index => $value) { if (null !== $arrayPrepared) {
++$counter; foreach ($arrayPrepared as $index => $value) {
++$counter;
if (is_array($value)) { if (is_array($value)) {
$variable = $index; $variable = $index;
if (is_int($index)) { if (is_int($index)) {
$variable = 'value_' . $variable; $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";
} }
$result .= $value . "\n"; $value = self::array2JavaScript($value, $variable, $preserveIndexes);
$result .= sprintf('%s[%s] = %s;', $jsVariableName, Miscellaneous::quoteValue($index), $variable);
if ($counter !== $arrayCount) { if (null !== $value && '' !== $value) {
$result .= "\n"; /*
* 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) {
} elseif ($preserveIndexes) { if (!empty($jsVariableName)) {
if (!empty($jsVariableName)) { $index = Miscellaneous::quoteValue($index);
$index = Miscellaneous::quoteValue($index); $result .= sprintf("\n%s[%s] = %s;", $jsVariableName, $index, $value);
$result .= sprintf("\n%s[%s] = %s;", $jsVariableName, $index, $value); }
} } else {
} else { $format = '%s';
$format = '%s';
if ($counter < $arrayCount) { if ($counter < $arrayCount) {
$format .= ', '; $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 * @param array $array The array to check for string values
* @return null|array * @return null|array
*/ */
public static function quoteStrings(array $array) public static function quoteStrings(array $array): ?array
{ {
/* /*
* No elements? * No elements?
@@ -492,10 +501,8 @@ class Arrays
foreach ($array as $index => $value) { foreach ($array as $index => $value) {
if (is_array($value)) { if (is_array($value)) {
$value = self::quoteStrings($value); $value = self::quoteStrings($value);
} elseif (is_string($value)) { } elseif (is_string($value) && !Regex::isQuoted($value)) {
if (!Regex::isQuoted($value)) { $value = '\'' . $value . '\'';
$value = '\'' . $value . '\'';
}
} }
$result[$index] = $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 array $array The array which should be shortened
* @param bool $last (optional) If is set to true, last element is removed. Otherwise - first. * @param bool $last (optional) If is set to true, last element is removed (default behaviour). Otherwise - first.
* @return array|string * @return null|array
*/ */
public static function removeMarginalElement($item, $last = true) public static function removeMarginalElement(array $array, bool $last = true): ?array
{ {
if (is_string($item)) { // No elements? Nothing to do
if ($last) { if (empty($array)) {
$item = substr($item, 0, -1); return null;
} else {
$item = substr($item, 1);
}
} elseif (is_array($item)) {
$key = self::getFirstKey($item);
if ($last) {
$key = self::getLastKey($item);
}
unset($item[$key]);
} }
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 * @param bool $before (optional) If is set to true, all elements before given needle are removed. Otherwise - all
* after needle. * 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 (!empty($array)) {
if (!$before) { if (!$before) {
@@ -604,7 +608,7 @@ class Arrays
if ($isArray) { if ($isArray) {
self::removeElements($value, $needle, $before); self::removeElements($value, $needle, $before);
if ($isArray && empty($value)) { if (empty($value)) {
$remove = true; $remove = true;
} }
} elseif ($value === $needle) { } elseif ($value === $needle) {
@@ -730,7 +734,7 @@ class Arrays
* @param array $array The array to count * @param array $array The array to count
* @return null|int * @return null|int
*/ */
public static function getNonArrayElementsCount(array $array) public static function getNonArrayElementsCount(array $array): ?int
{ {
/* /*
* No elements? * No elements?
@@ -742,9 +746,9 @@ class Arrays
$count = 0; $count = 0;
foreach ($array as &$value) { foreach ($array as $value) {
if (is_array($value)) { if (is_array($value)) {
$count += self::getNonArrayElementsCount($value); $count += (int)self::getNonArrayElementsCount($value);
continue; continue;
} }
@@ -772,14 +776,14 @@ class Arrays
* @param string $separator (optional) Separator used between name-value pairs in the string. * @param string $separator (optional) Separator used between name-value pairs in the string.
* Default: "|". * Default: "|".
* @param string $valuesKeysSeparator (optional) Separator used between name and value 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 = ':') public static function string2array(
{ string $string,
/* string $separator = '|',
* Empty string? string $valuesKeysSeparator = ':'
* Nothing to do ): ?array {
*/ // Empty string? Nothing to do
if (empty($string)) { if (empty($string)) {
return null; return null;
} }
@@ -844,12 +848,12 @@ class Arrays
/** /**
* Returns paths of the last elements * Returns paths of the last elements
* *
* @param array $array The array with elements * @param array $array The array with elements
* @param string $separator (optional) Separator used between elements. Default: ".". * @param string $separator (optional) Separator used between elements. Default: ".".
* @param string $parentPath (optional) Path of the parent element. 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 * @param array $stopIfMatchedBy (optional) Patterns of keys or paths when matched will stop the process of path
* of path building and including children of those keys or paths (recursive * building and including children of those keys or paths (recursive will not be
* will not be used for keys in lower level of given array). Default: "". * used for keys in lower level of given array). Default: [].
* @return null|array * @return null|array
* *
* Examples - $stopIfMatchedBy argument: * Examples - $stopIfMatchedBy argument:
@@ -859,21 +863,18 @@ class Arrays
* "\d+", * "\d+",
* ]; * ];
*/ */
public static function getLastElementsPaths(array $array, $separator = '.', $parentPath = '', $stopIfMatchedBy = '') public static function getLastElementsPaths(
{ array $array,
/* string $separator = '.',
* No elements? string $parentPath = '',
* Nothing to do array $stopIfMatchedBy = []
*/ ): ?array {
// No elements? Nothing to do
if (empty($array)) { if (empty($array)) {
return null; return null;
} }
if (!empty($stopIfMatchedBy)) { $result = [];
$stopIfMatchedBy = self::makeArray($stopIfMatchedBy);
}
$paths = [];
foreach ($array as $key => $value) { foreach ($array as $key => $value) {
$path = $key; $path = $key;
@@ -908,24 +909,27 @@ class Arrays
/* /*
* The value is passed to the returned array if: * The value is passed to the returned array if:
* - the process is stopped, recursive is not used
* or
* - it's not an array * - it's not an array
* or * or
* - the process is stopped, recursive is not used * - it's an array, but empty
*/ */
if (!$valueIsArray || ($valueIsArray && empty($value)) || $stopRecursion) { if ($stopRecursion || !$valueIsArray || self::isEmptyArray($value)) {
$paths[$path] = $value; $result[$path] = $value;
continue; continue;
} }
// Let's iterate through the next level, using recursive // Let's iterate through the next level, using recursive
if ($valueIsArray) { $recursivePaths = self::getLastElementsPaths($value, $separator, $path, $stopIfMatchedBy);
$recursivePaths = self::getLastElementsPaths($value, $separator, $path, $stopIfMatchedBy);
$paths += $recursivePaths; if (null !== $recursivePaths) {
$result += $recursivePaths;
} }
} }
return $paths; return $result;
} }
/** /**
@@ -934,7 +938,7 @@ class Arrays
* @param mixed $variable Variable that should be an array * @param mixed $variable Variable that should be an array
* @return array * @return array
*/ */
public static function makeArray($variable) public static function makeArray($variable): array
{ {
if (is_array($variable)) { if (is_array($variable)) {
return $variable; return $variable;
@@ -952,7 +956,7 @@ class Arrays
* first level only. * first level only.
* @return bool * @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? * No elements?
@@ -1413,9 +1417,9 @@ class Arrays
* (default behaviour). * (default behaviour).
* @return array * @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? * Values should be compared only and both arrays are one-dimensional?
@@ -1436,7 +1440,7 @@ class Arrays
if ($array2HasKey && is_array($array2[$key])) { if ($array2HasKey && is_array($array2[$key])) {
$difference = self::arrayDiffRecursive($value, $array2[$key], $valuesOnly); $difference = self::arrayDiffRecursive($value, $array2[$key], $valuesOnly);
} }
} elseif (!$array2HasKey || ($array2HasKey && $value !== $array2[$key])) { } elseif (!$array2HasKey || $value !== $array2[$key]) {
/* /*
* We are here, because: * We are here, because:
* a) 2nd array hasn't key from 1st array * a) 2nd array hasn't key from 1st array
@@ -1447,7 +1451,7 @@ class Arrays
} }
if (null !== $difference) { if (null !== $difference) {
$effect[] = $difference; $result[] = $difference;
} }
// The key exists in 2nd array? // The key exists in 2nd array?
@@ -1465,19 +1469,19 @@ class Arrays
continue; continue;
} }
$effect[$key] = $diff; $result[$key] = $diff;
} elseif ($value !== $array2[$key]) { } elseif ($value !== $array2[$key]) {
// Value is different than in 2nd array? // Value is different than in 2nd array?
// OKay, I've got difference // OKay, I've got difference
$effect[$key] = $value; $result[$key] = $value;
} }
} else { } else {
// OKay, I've got difference // 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. * @param int $incrementStep (optional) Value used for incrementation. The step of incrementation.
* @return null|array * @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? * No elements?
@@ -1557,7 +1561,7 @@ class Arrays
*/ */
if (!empty($valuesToIncrement)) { if (!empty($valuesToIncrement)) {
foreach ($valuesToIncrement as $oldIndex => $value) { foreach ($valuesToIncrement as $oldIndex => $value) {
$newIndex = $oldIndex + $incrementStep; $newIndex = (int)$oldIndex + $incrementStep;
$array[$newIndex] = $value; $array[$newIndex] = $value;
} }
} }
@@ -1596,7 +1600,7 @@ class Arrays
* @param array $array The array to verify * @param array $array The array to verify
* @return null|bool * @return null|bool
*/ */
public static function isMultiDimensional(array $array) public static function isMultiDimensional(array $array): ?bool
{ {
/* /*
* No elements? * No elements?
@@ -1615,7 +1619,7 @@ class Arrays
* @param array $array The array to verify * @param array $array The array to verify
* @return int * @return int
*/ */
public static function getDimensionsCount(array $array) public static function getDimensionsCount(array $array): int
{ {
/* /*
* No elements? * No elements?
@@ -1650,7 +1654,7 @@ class Arrays
* @param array $values The values to filter * @param array $values The values to filter
* @return null|array * @return null|array
*/ */
public static function getNonEmptyValues(array $values) public static function getNonEmptyValues(array $values): ?array
{ {
/* /*
* No values? * No values?
@@ -1660,9 +1664,9 @@ class Arrays
return null; return null;
} }
return array_filter($values, function ($value) { return array_filter($values, static function ($value): bool {
$nonEmptyScalar = is_scalar($value) && '' !== $value; $nonEmptyScalar = is_scalar($value) && '' !== $value;
$nonEmptyArray = is_array($value) && !empty($value); $nonEmptyArray = self::isNotEmptyArray($value);
return $nonEmptyScalar || $nonEmptyArray || is_object($value); return $nonEmptyScalar || $nonEmptyArray || is_object($value);
}); });
@@ -1675,7 +1679,7 @@ class Arrays
* @param string $separator (optional) Separator used to implode the values. Default: ", ". * @param string $separator (optional) Separator used to implode the values. Default: ", ".
* @return null|string * @return null|string
*/ */
public static function getNonEmptyValuesAsString(array $values, $separator = ', ') public static function getNonEmptyValuesAsString(array $values, string $separator = ', '): ?string
{ {
/* /*
* No elements? * No elements?
@@ -1698,6 +1702,28 @@ class Arrays
return implode($separator, $nonEmpty); 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 * 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. * @param bool $next (optional) If is set to true, returns next neighbour. Otherwise - previous.
* @return null|mixed * @return null|mixed
*/ */
private static function getNeighbour(array $array, $element, $next = true) private static function getNeighbour(array $array, $element, bool $next = true)
{ {
/* /*
* No elements? * No elements?
@@ -1730,7 +1756,7 @@ class Arrays
* *
* Nothing to do * Nothing to do
*/ */
if ($noPrevious || $noNext || empty($array) || !in_array($element, $array, true)) { if ($noPrevious || $noNext || !in_array($element, $array, true)) {
return null; return null;
} }

View File

@@ -1274,7 +1274,7 @@ class Miscellaneous
* *
* @return string * @return string
*/ */
public static function getProjectRootPath() public static function getProjectRootPath(): string
{ {
$projectRootPath = ''; $projectRootPath = '';
@@ -1298,4 +1298,25 @@ class Miscellaneous
return $projectRootPath; 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);
}
} }

View File

@@ -15,6 +15,11 @@ use Meritoo\Common\Exception\Reflection\CannotResolveClassNameException;
use Meritoo\Common\Exception\Reflection\MissingChildClassesException; use Meritoo\Common\Exception\Reflection\MissingChildClassesException;
use Meritoo\Common\Exception\Reflection\NotExistingPropertyException; use Meritoo\Common\Exception\Reflection\NotExistingPropertyException;
use Meritoo\Common\Exception\Reflection\TooManyChildClassesException; use Meritoo\Common\Exception\Reflection\TooManyChildClassesException;
use ReflectionClass;
use ReflectionException;
use ReflectionMethod;
use ReflectionObject;
use ReflectionProperty;
/** /**
* Useful reflection methods * Useful reflection methods
@@ -32,18 +37,18 @@ class Reflection
* Otherwise - all methods, with inherited methods too. * Otherwise - all methods, with inherited methods too.
* @return array * @return array
*/ */
public static function getMethods($class, $withoutInheritance = false) public static function getMethods($class, bool $withoutInheritance = false): array
{ {
$effect = []; $effect = [];
$reflection = new \ReflectionClass($class); $reflection = new ReflectionClass($class);
$methods = $reflection->getMethods(); $methods = $reflection->getMethods();
if (!empty($methods)) { if (!empty($methods)) {
$className = self::getClassName($class); $className = self::getClassName($class);
foreach ($methods as $method) { foreach ($methods as $method) {
if ($method instanceof \ReflectionMethod) { if ($method instanceof ReflectionMethod) {
if ($withoutInheritance && $className !== $method->class) { if ($withoutInheritance && $className !== $method->class) {
continue; continue;
} }
@@ -62,9 +67,9 @@ class Reflection
* @param object|string $class The object or name of object's class * @param object|string $class The object or name of object's class
* @return array * @return array
*/ */
public static function getConstants($class) public static function getConstants($class): array
{ {
$reflection = new \ReflectionClass($class); $reflection = new ReflectionClass($class);
return $reflection->getConstants(); return $reflection->getConstants();
} }
@@ -76,7 +81,7 @@ class Reflection
* @param object|string $class The object or name of object's class * @param object|string $class The object or name of object's class
* @return null|int * @return null|int
*/ */
public static function getMaxNumberConstant($class) public static function getMaxNumberConstant($class): ?int
{ {
$constants = self::getConstants($class); $constants = self::getConstants($class);
@@ -102,9 +107,9 @@ class Reflection
* @param string $method Name of the method to find * @param string $method Name of the method to find
* @return bool * @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); return $reflection->hasMethod($method);
} }
@@ -116,9 +121,9 @@ class Reflection
* @param string $property Name of the property to find * @param string $property Name of the property to find
* @return bool * @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); return $reflection->hasProperty($property);
} }
@@ -130,9 +135,9 @@ class Reflection
* @param string $constant Name of the constant to find * @param string $constant Name of the constant to find
* @return bool * @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); return $reflection->hasConstant($constant);
} }
@@ -144,9 +149,9 @@ class Reflection
* @param string $constant Name of the constant that contains a value * @param string $constant Name of the constant that contains a value
* @return mixed * @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)) { if (self::hasConstant($class, $constant)) {
return $reflection->getConstant($constant); return $reflection->getConstant($constant);
@@ -165,7 +170,7 @@ class Reflection
* property. Otherwise - not. * property. Otherwise - not.
* @return mixed * @return mixed
*/ */
public static function getPropertyValue($source, $property, $force = false) public static function getPropertyValue($source, string $property, bool $force = false)
{ {
if (Regex::contains($property, '.')) { if (Regex::contains($property, '.')) {
return self::getPropertyValueByPropertiesChain($source, $property, $force); return self::getPropertyValueByPropertiesChain($source, $property, $force);
@@ -209,7 +214,7 @@ class Reflection
* object does not have property. Otherwise - not. * object does not have property. Otherwise - not.
* @return array * @return array
*/ */
public static function getPropertyValues($objects, $property, $force = false) public static function getPropertyValues($objects, string $property, bool $force = false): array
{ {
/* /*
* No objects? * No objects?
@@ -245,7 +250,7 @@ class Reflection
* not, full name of class is returned, with namespace. * not, full name of class is returned, with namespace.
* @return null|string * @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? * 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 * @param array|object|string $source An array of objects, namespaces, object or namespace
* @return string * @return string
*/ */
public static function getClassNamespace($source) public static function getClassNamespace($source): string
{ {
$fullClassName = self::getClassName($source); $fullClassName = self::getClassName($source);
@@ -327,7 +332,7 @@ class Reflection
* @param string $interface The interface that should be implemented * @param string $interface The interface that should be implemented
* @return bool * @return bool
*/ */
public static function isInterfaceImplemented($source, $interface) public static function isInterfaceImplemented($source, string $interface): bool
{ {
$className = self::getClassName($source); $className = self::getClassName($source);
$interfaces = class_implements($className); $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. * @param array|object|string $parentClass The parent class. An array of objects, namespaces, object or namespace.
* @return bool * @return bool
*/ */
public static function isChildOfClass($childClass, $parentClass) public static function isChildOfClass($childClass, $parentClass): bool
{ {
$childClassName = self::getClassName($childClass); $childClassName = self::getClassName($childClass);
$parentClassName = self::getClassName($parentClass); $parentClassName = self::getClassName($parentClass);
@@ -364,18 +369,18 @@ class Reflection
* constants. By default all properties are returned. * constants. By default all properties are returned.
* @param bool $includeParents (optional) If is set to true, properties of parent classes are * @param bool $includeParents (optional) If is set to true, properties of parent classes are
* included (recursively). Otherwise - not. * 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); $className = self::getClassName($source);
$reflection = new \ReflectionClass($className); $reflection = new ReflectionClass($className);
if (null === $filter) { if (null === $filter) {
$filter = \ReflectionProperty::IS_PRIVATE $filter = ReflectionProperty::IS_PRIVATE
+ \ReflectionProperty::IS_PROTECTED + ReflectionProperty::IS_PROTECTED
+ \ReflectionProperty::IS_PUBLIC + ReflectionProperty::IS_PUBLIC
+ \ReflectionProperty::IS_STATIC; + ReflectionProperty::IS_STATIC;
} }
$properties = $reflection->getProperties($filter); $properties = $reflection->getProperties($filter);
@@ -397,12 +402,12 @@ class Reflection
* Returns a parent class or false if there is no parent class * 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 * @param array|object|string $source An array of objects, namespaces, object or namespace
* @return bool|\ReflectionClass * @return false|ReflectionClass
*/ */
public static function getParentClass($source) public static function getParentClass($source)
{ {
$className = self::getClassName($source); $className = self::getClassName($source);
$reflection = new \ReflectionClass($className); $reflection = new ReflectionClass($className);
return $reflection->getParentClass(); return $reflection->getParentClass();
} }
@@ -416,7 +421,7 @@ class Reflection
* @throws CannotResolveClassNameException * @throws CannotResolveClassNameException
* @return null|array * @return null|array
*/ */
public static function getChildClasses($class) public static function getChildClasses($class): ?array
{ {
$allClasses = get_declared_classes(); $allClasses = get_declared_classes();
@@ -500,15 +505,15 @@ class Reflection
* @param string $property Name of the property * @param string $property Name of the property
* @param int $filter (optional) Filter of properties. Uses \ReflectionProperty class constants. * @param int $filter (optional) Filter of properties. Uses \ReflectionProperty class constants.
* By default all properties are allowed / processed. * 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); $className = self::getClassName($class);
$properties = self::getProperties($className, $filter); $properties = self::getProperties($className, $filter);
if (!empty($properties)) { if (!empty($properties)) {
/** @var \ReflectionProperty $reflectionProperty */ /** @var ReflectionProperty $reflectionProperty */
foreach ($properties as $reflectionProperty) { foreach ($properties as $reflectionProperty) {
if ($reflectionProperty->getName() === $property) { if ($reflectionProperty->getName() === $property) {
return $reflectionProperty; return $reflectionProperty;
@@ -529,7 +534,7 @@ class Reflection
* @throws CannotResolveClassNameException * @throws CannotResolveClassNameException
* @return null|bool * @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); $className = self::getClassName($class);
$traitName = self::getClassName($trait); $traitName = self::getClassName($trait);
@@ -544,7 +549,7 @@ class Reflection
throw new CannotResolveClassNameException($class, false); throw new CannotResolveClassNameException($class, false);
} }
$reflection = new \ReflectionClass($className); $reflection = new ReflectionClass($className);
$traitsNames = $reflection->getTraitNames(); $traitsNames = $reflection->getTraitNames();
$uses = in_array($traitName, $traitsNames, true); $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 * @param array|object|string $class An array of objects, namespaces, object or namespace
* @return null|string * @return null|string
*/ */
public static function getParentClassName($class) public static function getParentClassName($class): ?string
{ {
$className = self::getClassName($class); $className = self::getClassName($class);
$reflection = new \ReflectionClass($className); $reflection = new ReflectionClass($className);
$parentClass = $reflection->getParentClass(); $parentClass = $reflection->getParentClass();
if (null === $parentClass || false === $parentClass) { if (null === $parentClass || false === $parentClass) {
@@ -588,7 +593,7 @@ class Reflection
* @param mixed $value Value of the property * @param mixed $value Value of the property
* @throws NotExistingPropertyException * @throws NotExistingPropertyException
*/ */
public static function setPropertyValue($object, $property, $value) public static function setPropertyValue($object, string $property, $value): void
{ {
$reflectionProperty = self::getProperty($object, $property); $reflectionProperty = self::getProperty($object, $property);
@@ -616,7 +621,7 @@ class Reflection
* @param mixed $object Object that should contains given property * @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 * @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? * No properties?
@@ -637,7 +642,7 @@ class Reflection
* @param string $class Class to verify * @param string $class Class to verify
* @return string * @return string
*/ */
private static function getRealClass($class): string private static function getRealClass(string $class): string
{ {
if (false === $pos = strrpos($class, '\\' . Proxy::MARKER . '\\')) { if (false === $pos = strrpos($class, '\\' . Proxy::MARKER . '\\')) {
return $class; return $class;
@@ -650,15 +655,15 @@ class Reflection
* Returns value of given property using the property represented by reflection. * Returns value of given property using the property represented by reflection.
* If value cannot be fetched, makes the property accessible temporarily. * If value cannot be fetched, makes the property accessible temporarily.
* *
* @param mixed $object Object that should contains given property * @param mixed $object Object that should contains given property
* @param string $property Name of the property that contains a value * @param string $property Name of the property that contains a value
* @param null|\ReflectionProperty $reflectionProperty (optional) Property represented by reflection * @param null|ReflectionProperty $reflectionProperty (optional) Property represented by reflection
* @return mixed * @return mixed
*/ */
private static function getPropertyValueByReflectionProperty( private static function getPropertyValueByReflectionProperty(
$object, $object,
string $property, string $property,
?\ReflectionProperty $reflectionProperty = null ?ReflectionProperty $reflectionProperty = null
) { ) {
$value = null; $value = null;
$valueFound = false; $valueFound = false;
@@ -666,12 +671,12 @@ class Reflection
try { try {
if (null === $reflectionProperty) { if (null === $reflectionProperty) {
$reflectionProperty = new \ReflectionProperty($className, $property); $reflectionProperty = new ReflectionProperty($className, $property);
} }
$value = $reflectionProperty->getValue($object); $value = $reflectionProperty->getValue($object);
$valueFound = true; $valueFound = true;
} catch (\ReflectionException $exception) { } catch (ReflectionException $exception) {
} }
if (null !== $reflectionProperty) { if (null !== $reflectionProperty) {
@@ -705,7 +710,7 @@ class Reflection
$value = null; $value = null;
$valueFound = false; $valueFound = false;
$reflectionObject = new \ReflectionObject($source); $reflectionObject = new ReflectionObject($source);
$property = Inflector::classify($property); $property = Inflector::classify($property);
$gettersPrefixes = [ $gettersPrefixes = [
@@ -718,7 +723,7 @@ class Reflection
$getter = sprintf('%s%s', $prefix, $property); $getter = sprintf('%s%s', $prefix, $property);
if ($reflectionObject->hasMethod($getter)) { if ($reflectionObject->hasMethod($getter)) {
$method = new \ReflectionMethod($source, $getter); $method = new ReflectionMethod($source, $getter);
/* /*
* Getter is not accessible publicly? * Getter is not accessible publicly?
@@ -791,7 +796,7 @@ class Reflection
* property. Otherwise - not. * property. Otherwise - not.
* @return mixed * @return mixed
*/ */
private static function getPropertyValueByPropertiesChain($source, $property, $force) private static function getPropertyValueByPropertiesChain($source, string $property, bool $force)
{ {
$exploded = explode('.', $property); $exploded = explode('.', $property);

View File

@@ -13,6 +13,7 @@ use Generator;
use Meritoo\Common\Collection\Collection; use Meritoo\Common\Collection\Collection;
use Meritoo\Common\Test\Base\BaseTestCase; use Meritoo\Common\Test\Base\BaseTestCase;
use Meritoo\Common\Type\OopVisibilityType; use Meritoo\Common\Type\OopVisibilityType;
use ReflectionClass;
/** /**
* Test case of the collection of elements * Test case of the collection of elements
@@ -21,7 +22,7 @@ use Meritoo\Common\Type\OopVisibilityType;
* @copyright Meritoo <http://www.meritoo.pl> * @copyright Meritoo <http://www.meritoo.pl>
* *
* @internal * @internal
* @covers \Meritoo\Common\Collection\Collection * @covers \Meritoo\Common\Collection\Collection
*/ */
class CollectionTest extends BaseTestCase class CollectionTest extends BaseTestCase
{ {
@@ -327,7 +328,16 @@ class CollectionTest extends BaseTestCase
public function testExistsVisibilityAndArguments() 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
);
} }
/** /**

View File

@@ -8,6 +8,7 @@
namespace Meritoo\Test\Common\Exception\Bundle; namespace Meritoo\Test\Common\Exception\Bundle;
use Generator;
use Meritoo\Common\Exception\Bundle\IncorrectBundleNameException; use Meritoo\Common\Exception\Bundle\IncorrectBundleNameException;
use Meritoo\Common\Test\Base\BaseTestCase; use Meritoo\Common\Test\Base\BaseTestCase;
use Meritoo\Common\Type\OopVisibilityType; use Meritoo\Common\Type\OopVisibilityType;
@@ -23,7 +24,7 @@ use Meritoo\Common\Type\OopVisibilityType;
*/ */
class IncorrectBundleNameExceptionTest extends BaseTestCase class IncorrectBundleNameExceptionTest extends BaseTestCase
{ {
public function testConstructor() public function testConstructor(): void
{ {
static::assertConstructorVisibilityAndArguments( static::assertConstructorVisibilityAndArguments(
IncorrectBundleNameException::class, IncorrectBundleNameException::class,
@@ -39,13 +40,13 @@ class IncorrectBundleNameExceptionTest extends BaseTestCase
* *
* @dataProvider provideBundleNameAndMessage * @dataProvider provideBundleNameAndMessage
*/ */
public function testCreate($description, $bundleName, $expectedMessage) public function testCreate(string $description, string $bundleName, string $expectedMessage): void
{ {
$exception = IncorrectBundleNameException::create($bundleName); $exception = IncorrectBundleNameException::create($bundleName);
static::assertSame($expectedMessage, $exception->getMessage(), $description); 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' $template = 'Name of bundle \'%s\' is incorrect. It should start with big letter and end with "Bundle". Is'
. ' there everything ok?'; . ' there everything ok?';
@@ -56,12 +57,6 @@ class IncorrectBundleNameExceptionTest extends BaseTestCase
sprintf($template, ''), sprintf($template, ''),
]; ];
yield[
'Null as name of bundle',
null,
sprintf($template, ''),
];
yield[ yield[
'String with spaces as name of bundle', 'String with spaces as name of bundle',
'This is test', 'This is test',

View File

@@ -12,6 +12,7 @@ use Generator;
use Meritoo\Common\Exception\Reflection\CannotResolveClassNameException; use Meritoo\Common\Exception\Reflection\CannotResolveClassNameException;
use Meritoo\Common\Test\Base\BaseTestCase; use Meritoo\Common\Test\Base\BaseTestCase;
use Meritoo\Common\Type\OopVisibilityType; use Meritoo\Common\Type\OopVisibilityType;
use stdClass;
/** /**
* Test case of an exception used while name of class or trait cannot be resolved * 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 <http://www.meritoo.pl> * @copyright Meritoo <http://www.meritoo.pl>
* *
* @internal * @internal
* @covers \Meritoo\Common\Exception\Reflection\CannotResolveClassNameException * @covers \Meritoo\Common\Exception\Reflection\CannotResolveClassNameException
*/ */
class CannotResolveClassNameExceptionTest extends BaseTestCase 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 * @dataProvider provideClassName
*/ */
public function testConstructorMessage($source, $forClass, $expectedMessage) public function testCreate($source, bool $forClass, string $expectedMessage): void
{ {
$exception = CannotResolveClassNameException::create($source, $forClass); $exception = CannotResolveClassNameException::create($source, $forClass);
static::assertSame($expectedMessage, $exception->getMessage()); static::assertSame($expectedMessage, $exception->getMessage());
@@ -50,7 +55,7 @@ class CannotResolveClassNameExceptionTest extends BaseTestCase
* *
* @return Generator * @return Generator
*/ */
public function provideClassName() public function provideClassName(): Generator
{ {
yield[ yield[
'Not\Existing\Class', 'Not\Existing\Class',
@@ -66,8 +71,8 @@ class CannotResolveClassNameExceptionTest extends BaseTestCase
yield[ yield[
[ [
new \stdClass(), new stdClass(),
new \stdClass(), new stdClass(),
], ],
true, true,
'Name of class from given \'array\' cannot be resolved. Is there everything ok?', 'Name of class from given \'array\' cannot be resolved. Is there everything ok?',

View File

@@ -0,0 +1,66 @@
<?php
/**
* (c) Meritoo.pl, http://www.meritoo.pl
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Meritoo\Test\Common\Exception\Reflection;
use Generator;
use Meritoo\Common\Exception\Reflection\ClassWithoutConstructorException;
use Meritoo\Common\Test\Base\BaseTestCase;
use Meritoo\Common\Type\OopVisibilityType;
use Meritoo\Common\Utilities\Arrays;
/**
* Test case of an exception used while given class hasn't constructor
*
* @author Meritoo <github@meritoo.pl>
* @copyright Meritoo <http://www.meritoo.pl>
*
* @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),
];
}
}

View File

@@ -20,13 +20,17 @@ use Meritoo\Common\Type\OopVisibilityType;
* @copyright Meritoo <http://www.meritoo.pl> * @copyright Meritoo <http://www.meritoo.pl>
* *
* @internal * @internal
* @covers \Meritoo\Common\Exception\Reflection\MissingChildClassesException * @covers \Meritoo\Common\Exception\Reflection\MissingChildClassesException
*/ */
class MissingChildClassesExceptionTest extends BaseTestCase 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 * @dataProvider provideParentClass
*/ */
public function testConstructorMessage($parentClass, $expectedMessage) public function testCreate($parentClass, string $expectedMessage): void
{ {
$exception = MissingChildClassesException::create($parentClass); $exception = MissingChildClassesException::create($parentClass);
static::assertSame($expectedMessage, $exception->getMessage()); static::assertSame($expectedMessage, $exception->getMessage());
@@ -47,7 +51,7 @@ class MissingChildClassesExceptionTest extends BaseTestCase
* *
* @return Generator * @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' $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?'; . ' class), but the child classes are missing. Did you forget to extend this class?';

View File

@@ -19,11 +19,11 @@ use Meritoo\Common\Type\OopVisibilityType;
* @copyright Meritoo <http://www.meritoo.pl> * @copyright Meritoo <http://www.meritoo.pl>
* *
* @internal * @internal
* @covers \Meritoo\Common\Exception\Reflection\NotExistingPropertyException * @covers \Meritoo\Common\Exception\Reflection\NotExistingPropertyException
*/ */
class NotExistingPropertyExceptionTest extends BaseTestCase class NotExistingPropertyExceptionTest extends BaseTestCase
{ {
public function testConstructor() public function testConstructor(): void
{ {
static::assertConstructorVisibilityAndArguments( static::assertConstructorVisibilityAndArguments(
NotExistingPropertyException::class, NotExistingPropertyException::class,
@@ -33,20 +33,20 @@ class NotExistingPropertyExceptionTest extends BaseTestCase
} }
/** /**
* @param string $description Description of test * @param string $description Description of test
* @param mixed $object Object that should contains given property * @param mixed $object Object that should contains given property
* @param string $property Name of the property * @param null|string $property Name of the property
* @param string $expectedMessage Expected exception's message * @param string $expectedMessage Expected exception's message
* *
* @dataProvider provideObjectPropertyAndMessage * @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); $exception = NotExistingPropertyException::create($object, $property);
static::assertSame($expectedMessage, $exception->getMessage(), $description); 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?'; $template = 'Property \'%s\' does not exist in instance of class \'%s\'. Did you use proper name of property?';

View File

@@ -20,13 +20,17 @@ use Meritoo\Common\Type\OopVisibilityType;
* @copyright Meritoo <http://www.meritoo.pl> * @copyright Meritoo <http://www.meritoo.pl>
* *
* @internal * @internal
* @covers \Meritoo\Common\Exception\Reflection\TooManyChildClassesException * @covers \Meritoo\Common\Exception\Reflection\TooManyChildClassesException
*/ */
class TooManyChildClassesExceptionTest extends BaseTestCase 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 * @dataProvider provideParentAndChildClasses
*/ */
public function testConstructorMessage($parentClass, array $childClasses, $expectedMessage) public function testCreate($parentClass, array $childClasses, string $expectedMessage): void
{ {
$exception = TooManyChildClassesException::create($parentClass, $childClasses); $exception = TooManyChildClassesException::create($parentClass, $childClasses);
static::assertSame($expectedMessage, $exception->getMessage()); static::assertSame($expectedMessage, $exception->getMessage());
@@ -49,7 +53,7 @@ class TooManyChildClassesExceptionTest extends BaseTestCase
* *
* @return Generator * @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" $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?"; . " class was found:\n- %s\n\nWhy did you create more than one classes that extend '%s' class?";

View File

@@ -21,13 +21,17 @@ use Meritoo\Common\Type\OopVisibilityType;
* @copyright Meritoo <http://www.meritoo.pl> * @copyright Meritoo <http://www.meritoo.pl>
* *
* @internal * @internal
* @covers \Meritoo\Common\Exception\Type\UnknownOopVisibilityTypeException * @covers \Meritoo\Common\Exception\Type\UnknownOopVisibilityTypeException
*/ */
class UnknownOopVisibilityTypeExceptionTest extends BaseTestCase 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 * @dataProvider provideUnknownType
*/ */
public function testConstructorMessage($unknownType, $expectedMessage) public function testConstructorMessage($unknownType, $expectedMessage): void
{ {
$exception = UnknownOopVisibilityTypeException::createException($unknownType); $exception = UnknownOopVisibilityTypeException::createException($unknownType);
static::assertSame($expectedMessage, $exception->getMessage()); static::assertSame($expectedMessage, $exception->getMessage());
@@ -47,7 +51,7 @@ class UnknownOopVisibilityTypeExceptionTest extends BaseTestCase
* *
* @return Generator * @return Generator
*/ */
public function provideUnknownType() public function provideUnknownType(): Generator
{ {
$allTypes = (new OopVisibilityType())->getAll(); $allTypes = (new OopVisibilityType())->getAll();

View File

@@ -8,7 +8,9 @@
namespace Meritoo\Test\Common\Type; namespace Meritoo\Test\Common\Type;
use Generator;
use Meritoo\Common\Test\Base\BaseTypeTestCase; use Meritoo\Common\Test\Base\BaseTypeTestCase;
use Meritoo\Common\Type\Base\BaseType;
use Meritoo\Common\Type\DatePartType; use Meritoo\Common\Type\DatePartType;
/** /**
@@ -25,7 +27,7 @@ class DatePartTypeTest extends BaseTypeTestCase
/** /**
* {@inheritdoc} * {@inheritdoc}
*/ */
public function provideTypeToVerify() public function provideTypeToVerify(): Generator
{ {
yield[ yield[
'', '',
@@ -38,12 +40,12 @@ class DatePartTypeTest extends BaseTypeTestCase
]; ];
yield[ yield[
0, '0',
false, false,
]; ];
yield[ yield[
1, '1',
false, false,
]; ];
@@ -81,22 +83,22 @@ class DatePartTypeTest extends BaseTypeTestCase
/** /**
* {@inheritdoc} * {@inheritdoc}
*/ */
protected function getAllExpectedTypes() protected function getAllExpectedTypes(): array
{ {
return [ return [
'DAY' => DatePartType::DAY, 'DAY' => 'day',
'HOUR' => DatePartType::HOUR, 'HOUR' => 'hour',
'MINUTE' => DatePartType::MINUTE, 'MINUTE' => 'minute',
'MONTH' => DatePartType::MONTH, 'MONTH' => 'month',
'SECOND' => DatePartType::SECOND, 'SECOND' => 'second',
'YEAR' => DatePartType::YEAR, 'YEAR' => 'year',
]; ];
} }
/** /**
* {@inheritdoc} * {@inheritdoc}
*/ */
protected function getTestedTypeInstance() protected function getTestedTypeInstance(): BaseType
{ {
return new DatePartType(); return new DatePartType();
} }

View File

@@ -11,6 +11,7 @@ namespace Meritoo\Test\Common\Type;
use DateTime; use DateTime;
use Generator; use Generator;
use Meritoo\Common\Test\Base\BaseTypeTestCase; use Meritoo\Common\Test\Base\BaseTypeTestCase;
use Meritoo\Common\Type\Base\BaseType;
use Meritoo\Common\Type\DatePeriod; use Meritoo\Common\Type\DatePeriod;
use Meritoo\Common\Type\OopVisibilityType; use Meritoo\Common\Type\OopVisibilityType;
@@ -21,13 +22,17 @@ use Meritoo\Common\Type\OopVisibilityType;
* @copyright Meritoo <http://www.meritoo.pl> * @copyright Meritoo <http://www.meritoo.pl>
* *
* @internal * @internal
* @covers \Meritoo\Common\Type\DatePeriod * @covers \Meritoo\Common\Type\DatePeriod
*/ */
class DatePeriodTest extends BaseTypeTestCase 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 * @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); $period = new DatePeriod($startDate, $endDate);
@@ -50,7 +55,7 @@ class DatePeriodTest extends BaseTypeTestCase
* *
* @dataProvider provideDatePeriod * @dataProvider provideDatePeriod
*/ */
public function testGettersAndSetters(DateTime $startDate = null, DateTime $endDate = null) public function testGettersAndSetters(DateTime $startDate = null, DateTime $endDate = null): void
{ {
$period = new DatePeriod(); $period = new DatePeriod();
@@ -67,7 +72,7 @@ class DatePeriodTest extends BaseTypeTestCase
* *
* @dataProvider provideDatePeriodAndIncorrectDateFormat * @dataProvider provideDatePeriodAndIncorrectDateFormat
*/ */
public function testGetFormattedDateIncorrectDateFormat(DatePeriod $period, $format) public function testGetFormattedDateIncorrectDateFormat(DatePeriod $period, $format): void
{ {
self::assertEquals('', $period->getFormattedDate($format)); self::assertEquals('', $period->getFormattedDate($format));
} }
@@ -80,7 +85,7 @@ class DatePeriodTest extends BaseTypeTestCase
* *
* @dataProvider provideDatePeriodAndDateFormat * @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)); self::assertEquals($expected, $period->getFormattedDate($format, $startDate));
} }
@@ -90,7 +95,7 @@ class DatePeriodTest extends BaseTypeTestCase
* *
* @return Generator * @return Generator
*/ */
public function provideDatePeriod() public function provideDatePeriod(): Generator
{ {
$startDate = new DateTime('2001-01-01'); $startDate = new DateTime('2001-01-01');
$endDate = new DateTime('2002-02-02'); $endDate = new DateTime('2002-02-02');
@@ -123,7 +128,7 @@ class DatePeriodTest extends BaseTypeTestCase
* *
* @return Generator * @return Generator
*/ */
public function provideDatePeriodAndIncorrectDateFormat() public function provideDatePeriodAndIncorrectDateFormat(): Generator
{ {
$startDate = new DateTime('2001-01-01'); $startDate = new DateTime('2001-01-01');
$endDate = new DateTime('2002-02-02'); $endDate = new DateTime('2002-02-02');
@@ -133,11 +138,6 @@ class DatePeriodTest extends BaseTypeTestCase
'', '',
]; ];
yield[
new DatePeriod($startDate, $endDate),
null,
];
yield[ yield[
new DatePeriod($startDate, $endDate), new DatePeriod($startDate, $endDate),
false, false,
@@ -149,7 +149,7 @@ class DatePeriodTest extends BaseTypeTestCase
* *
* @return Generator * @return Generator
*/ */
public function provideDatePeriodAndDateFormat() public function provideDatePeriodAndDateFormat(): Generator
{ {
$startDate = new DateTime('2001-01-01'); $startDate = new DateTime('2001-01-01');
$endDate = new DateTime('2002-02-02'); $endDate = new DateTime('2002-02-02');
@@ -216,7 +216,7 @@ class DatePeriodTest extends BaseTypeTestCase
/** /**
* {@inheritdoc} * {@inheritdoc}
*/ */
public function provideTypeToVerify() public function provideTypeToVerify(): Generator
{ {
yield[ yield[
'', '',
@@ -224,27 +224,22 @@ class DatePeriodTest extends BaseTypeTestCase
]; ];
yield[ yield[
-1, '-1',
false, false,
]; ];
yield[ yield[
true, '4',
false,
];
yield[
DatePeriod::LAST_MONTH,
true, true,
]; ];
yield[ yield[
DatePeriod::NEXT_WEEK, '3',
true, true,
]; ];
yield[ yield[
DatePeriod::THIS_YEAR, '8',
true, true,
]; ];
} }
@@ -254,25 +249,25 @@ class DatePeriodTest extends BaseTypeTestCase
* *
* @return array * @return array
*/ */
protected function getAllExpectedTypes() protected function getAllExpectedTypes(): array
{ {
return [ return [
'LAST_MONTH' => DatePeriod::LAST_MONTH, 'LAST_MONTH' => 4,
'LAST_WEEK' => DatePeriod::LAST_WEEK, 'LAST_WEEK' => 1,
'LAST_YEAR' => DatePeriod::LAST_YEAR, 'LAST_YEAR' => 7,
'NEXT_MONTH' => DatePeriod::NEXT_MONTH, 'NEXT_MONTH' => 6,
'NEXT_WEEK' => DatePeriod::NEXT_WEEK, 'NEXT_WEEK' => 3,
'NEXT_YEAR' => DatePeriod::NEXT_YEAR, 'NEXT_YEAR' => 9,
'THIS_MONTH' => DatePeriod::THIS_MONTH, 'THIS_MONTH' => 5,
'THIS_WEEK' => DatePeriod::THIS_WEEK, 'THIS_WEEK' => 2,
'THIS_YEAR' => DatePeriod::THIS_YEAR, 'THIS_YEAR' => 8,
]; ];
} }
/** /**
* {@inheritdoc} * {@inheritdoc}
*/ */
protected function getTestedTypeInstance() protected function getTestedTypeInstance(): BaseType
{ {
return new DatePeriod(); return new DatePeriod();
} }

View File

@@ -8,6 +8,7 @@
namespace Meritoo\Test\Common\Type; namespace Meritoo\Test\Common\Type;
use Generator;
use Meritoo\Common\Test\Base\BaseTypeTestCase; use Meritoo\Common\Test\Base\BaseTypeTestCase;
use Meritoo\Common\Type\Base\BaseType; use Meritoo\Common\Type\Base\BaseType;
use Meritoo\Common\Type\OopVisibilityType; use Meritoo\Common\Type\OopVisibilityType;
@@ -26,7 +27,7 @@ class OopVisibilityTypeTest extends BaseTypeTestCase
/** /**
* {@inheritdoc} * {@inheritdoc}
*/ */
public function provideTypeToVerify(): ?\Generator public function provideTypeToVerify(): Generator
{ {
yield[ yield[
'', '',
@@ -39,27 +40,22 @@ class OopVisibilityTypeTest extends BaseTypeTestCase
]; ];
yield[ yield[
-1, '-1',
false, false,
]; ];
yield[ yield[
true, '1',
false,
];
yield[
1,
true, true,
]; ];
yield[ yield[
2, '2',
true, true,
]; ];
yield[ yield[
3, '3',
true, true,
]; ];
} }

View File

@@ -8,6 +8,7 @@
namespace Meritoo\Test\Common\Utilities; namespace Meritoo\Test\Common\Utilities;
use Generator;
use Meritoo\Common\Test\Base\BaseTestCase; use Meritoo\Common\Test\Base\BaseTestCase;
use Meritoo\Common\Utilities\Arrays; use Meritoo\Common\Utilities\Arrays;
use Meritoo\Common\Utilities\Locale; use Meritoo\Common\Utilities\Locale;
@@ -20,7 +21,7 @@ use Meritoo\Test\Common\Utilities\Arrays\SimpleToString;
* @copyright Meritoo <http://www.meritoo.pl> * @copyright Meritoo <http://www.meritoo.pl>
* *
* @internal * @internal
* @covers \Meritoo\Common\Utilities\Arrays * @covers \Meritoo\Common\Utilities\Arrays
*/ */
class ArraysTest extends BaseTestCase class ArraysTest extends BaseTestCase
{ {
@@ -212,7 +213,7 @@ class ArraysTest extends BaseTestCase
self::assertEquals('amet/1/primis', Arrays::getLastElementBreadCrumb($this->complexArray)); self::assertEquals('amet/1/primis', Arrays::getLastElementBreadCrumb($this->complexArray));
} }
public function testGetLastRow() public function testGetLastRow(): void
{ {
// Negative cases // Negative cases
self::assertNull(Arrays::getLastRow([])); self::assertNull(Arrays::getLastRow([]));
@@ -234,34 +235,32 @@ class ArraysTest extends BaseTestCase
], Arrays::getLastRow($this->complexArray)); ], Arrays::getLastRow($this->complexArray));
} }
public function testReplaceArrayKeys() /**
{ * @param string $description Description of test case
$effect = [ * @param array $array Array which keys should be replaced
'nullam' => 'donec', * @param string $oldKeyPattern Regular expression of the old key
'x' => [ * @param string $newKey Name of the new key
'vitae' => [ * @param array $expected Expected result
'x' => 'quis', *
], * @dataProvider provideArrayToReplaceKeys
], */
'elit', public function testReplaceKeys(
]; string $description,
array $array,
$dataArray = $this->complexArray['sit']; string $oldKeyPattern,
self::assertEquals($effect, Arrays::replaceArrayKeys($dataArray, '|.*li.*|', 'x')); string $newKey,
?array $expected
self::assertEquals([ ): void {
'x' => 'sit', self::assertSame($expected, Arrays::replaceKeys($array, $oldKeyPattern, $newKey), $description);
4 => 'amet',
], Arrays::replaceArrayKeys($this->simpleArray, '|[0-3]+|', 'x'));
} }
public function testMakeArray() public function testMakeArray(): void
{ {
self::assertSame($this->simpleArray, Arrays::makeArray($this->simpleArray)); self::assertSame($this->simpleArray, Arrays::makeArray($this->simpleArray));
self::assertSame(['test'], Arrays::makeArray('test')); self::assertSame(['test'], Arrays::makeArray('test'));
} }
public function testArray2JavaScript() public function testArray2JavaScript(): void
{ {
// Negative cases // Negative cases
self::assertNull(Arrays::array2JavaScript([])); self::assertNull(Arrays::array2JavaScript([]));
@@ -339,36 +338,25 @@ letsTest[2] = value_2;';
* *
* @dataProvider provideArrayToQuoteStrings * @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); 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; self::assertSame($expected, Arrays::removeMarginalElement($array, $last), $description);
$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));
} }
public function testRemoveElements() public function testRemoveElements(): void
{ {
$array1 = $this->simpleArray; $array1 = $this->simpleArray;
$array2 = $this->simpleArray; $array2 = $this->simpleArray;
@@ -467,7 +455,7 @@ letsTest[2] = value_2;';
self::assertEquals($replaced, Arrays::setKeysAsValues($array, false)); self::assertEquals($replaced, Arrays::setKeysAsValues($array, false));
} }
public function testGetNonArrayElementsCount() public function testGetNonArrayElementsCount(): void
{ {
// Negative cases // Negative cases
self::assertNull(Arrays::getNonArrayElementsCount([])); self::assertNull(Arrays::getNonArrayElementsCount([]));
@@ -478,11 +466,10 @@ letsTest[2] = value_2;';
self::assertEquals(12, Arrays::getNonArrayElementsCount($this->twoDimensionsArray)); self::assertEquals(12, Arrays::getNonArrayElementsCount($this->twoDimensionsArray));
} }
public function testString2array() public function testString2array(): void
{ {
// Negative cases // Negative cases
self::assertNull(Arrays::string2array('')); self::assertNull(Arrays::string2array(''));
self::assertNull(Arrays::string2array(null));
// Positive cases // Positive cases
$array = [ $array = [
@@ -504,7 +491,7 @@ letsTest[2] = value_2;';
self::assertEquals($array, Arrays::string2array('red : #f00 | green : #0f0 | blue : #00f')); self::assertEquals($array, Arrays::string2array('red : #f00 | green : #0f0 | blue : #00f'));
} }
public function testAreKeysInArray() public function testAreKeysInArray(): void
{ {
// Negative cases // Negative cases
self::assertFalse(Arrays::areKeysInArray([], [])); self::assertFalse(Arrays::areKeysInArray([], []));
@@ -568,12 +555,12 @@ letsTest[2] = value_2;';
self::assertTrue(Arrays::areKeysInArray($keys17, $this->complexArray, false)); self::assertTrue(Arrays::areKeysInArray($keys17, $this->complexArray, false));
} }
public function testGetLastElementsPathsUsingEmptyArray() public function testGetLastElementsPathsUsingEmptyArray(): void
{ {
self::assertNull(Arrays::getLastElementsPaths([])); self::assertNull(Arrays::getLastElementsPaths([]));
} }
public function testGetLastElementsPathsUsingDefaults() public function testGetLastElementsPathsUsingDefaults(): void
{ {
// Using default separator and other default arguments // Using default separator and other default arguments
$expected = [ $expected = [
@@ -592,7 +579,7 @@ letsTest[2] = value_2;';
self::assertEquals($expected, Arrays::getLastElementsPaths($this->complexArray)); self::assertEquals($expected, Arrays::getLastElementsPaths($this->complexArray));
} }
public function testGetLastElementsPathsUsingCustomSeparator() public function testGetLastElementsPathsUsingCustomSeparator(): void
{ {
// Using custom separator // Using custom separator
$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 * @param array $stopIfMatchedBy Patterns of keys or paths that matched will stop the process of path building and
* building and including children of those keys or paths (recursive will * including children of those keys or paths (recursive will not be used for keys in
* not be used for keys in lower level of given array) * lower level of given array)
* @param string $separator Separator used in resultant strings. Default: ".". * @param string $separator Separator used in resultant strings. Default: ".".
* @param array $expected Expected array * @param array $expected Expected array
* *
* @dataProvider provideStopIfMatchedByForGetLastElementsPaths * @dataProvider provideStopIfMatchedByForGetLastElementsPaths
*/ */
public function testGetLastElementsPathsUsingStopIfMatchedBy($stopIfMatchedBy, $separator, array $expected) public function testGetLastElementsPathsUsingStopIfMatchedBy(
{ array $stopIfMatchedBy,
self::assertEquals($expected, Arrays::getLastElementsPaths($this->superComplexArray, $separator, '', $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+'; $pattern = '\d+';
@@ -1471,6 +1462,30 @@ letsTest[2] = value_2;';
self::assertSame($expected, Arrays::getNonEmptyValuesAsString($values, $separator), $description); 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 * 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 * Provides patterns of keys or paths that matched will stop the process and the expected array for the
* getLastElementsPaths() method * getLastElementsPaths() method
* *
* @return \Generator * @return Generator
*/ */
public function provideStopIfMatchedByForGetLastElementsPaths() public function provideStopIfMatchedByForGetLastElementsPaths(): ?Generator
{ {
// Special exception: do not use, stop recursive on the "diam" key // Special exception: do not use, stop recursive on the "diam" key
yield[ yield[
'diam', ['diam'],
'.', '.',
[ [
'ipsum.quis.vestibulum.porta-1.0' => 'turpis', 'ipsum.quis.vestibulum.porta-1.0' => 'turpis',
@@ -1787,9 +1802,9 @@ letsTest[2] = value_2;';
/** /**
* Provide values to filter and get non-empty values * Provide values to filter and get non-empty values
* *
* @return \Generator * @return Generator
*/ */
public function provideValuesToFilterNonEmpty() public function provideValuesToFilterNonEmpty(): ?Generator
{ {
$simpleObject = new SimpleToString('1234'); $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} * {@inheritdoc}
*/ */

View File

@@ -28,7 +28,7 @@ use Meritoo\Common\Utilities\Locale;
*/ */
class DateTest extends BaseTestCase class DateTest extends BaseTestCase
{ {
public function testConstructor() public function testConstructor(): void
{ {
static::assertHasNoConstructor(Date::class); static::assertHasNoConstructor(Date::class);
} }
@@ -37,7 +37,7 @@ class DateTest extends BaseTestCase
* @param mixed $value Empty value, e.g. "" * @param mixed $value Empty value, e.g. ""
* @dataProvider provideEmptyValue * @dataProvider provideEmptyValue
*/ */
public function testGetDateTimeEmptyValue($value) public function testGetDateTimeEmptyValue($value): void
{ {
self::assertFalse(Date::getDateTime($value)); self::assertFalse(Date::getDateTime($value));
} }
@@ -46,7 +46,7 @@ class DateTest extends BaseTestCase
* @param mixed $value Incorrect source of DateTime * @param mixed $value Incorrect source of DateTime
* @dataProvider provideIncorrectDateTimeValue * @dataProvider provideIncorrectDateTimeValue
*/ */
public function testGetDateTimeIncorrectValue($value) public function testGetDateTimeIncorrectValue($value): void
{ {
self::assertFalse(Date::getDateTime($value)); self::assertFalse(Date::getDateTime($value));
} }
@@ -55,7 +55,7 @@ class DateTest extends BaseTestCase
* @param bool $value The value which maybe is a date * @param bool $value The value which maybe is a date
* @dataProvider provideBooleanValue * @dataProvider provideBooleanValue
*/ */
public function testGetDateTimeBoolean($value) public function testGetDateTimeBoolean($value): void
{ {
self::assertFalse(Date::getDateTime($value)); self::assertFalse(Date::getDateTime($value));
} }
@@ -64,7 +64,7 @@ class DateTest extends BaseTestCase
* @param string $relativeFormat Relative / compound format of DateTime * @param string $relativeFormat Relative / compound format of DateTime
* @dataProvider provideDateTimeRelativeFormat * @dataProvider provideDateTimeRelativeFormat
*/ */
public function testGetDateTimeRelativeFormats($relativeFormat) public function testGetDateTimeRelativeFormats($relativeFormat): void
{ {
/* /*
* Values based on relative / compound formats, but... without explicitly declaring them as compound * 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 * @param DateTime $dateTime Instance of DateTime class
* @dataProvider provideDateTimeInstance * @dataProvider provideDateTimeInstance
*/ */
public function testGetDateTimeInstanceDateTime(DateTime $dateTime) public function testGetDateTimeInstanceDateTime(DateTime $dateTime): void
{ {
self::assertInstanceOf(DateTime::class, Date::getDateTime($dateTime)); self::assertInstanceOf(DateTime::class, Date::getDateTime($dateTime));
} }
public function testGetDateTimeConcreteDates() public function testGetDateTimeConcreteDates(): void
{ {
// Using the standard date format provided by the tested method // Using the standard date format provided by the tested method
self::assertInstanceOf(DateTime::class, Date::getDateTime('2015-03-20')); self::assertInstanceOf(DateTime::class, Date::getDateTime('2015-03-20'));
@@ -104,7 +104,7 @@ class DateTest extends BaseTestCase
* @param mixed $value Empty value, e.g. "" * @param mixed $value Empty value, e.g. ""
* @dataProvider provideEmptyValue * @dataProvider provideEmptyValue
*/ */
public function testIsValidDateEmptyDates($value) public function testIsValidDateEmptyDates($value): void
{ {
self::assertFalse(Date::isValidDate($value)); self::assertFalse(Date::isValidDate($value));
} }
@@ -113,12 +113,12 @@ class DateTest extends BaseTestCase
* @param mixed $value Incorrect source of DateTime * @param mixed $value Incorrect source of DateTime
* @dataProvider provideIncorrectDateTimeValue * @dataProvider provideIncorrectDateTimeValue
*/ */
public function testIsValidDateIncorrectDates($value) public function testIsValidDateIncorrectDates($value): void
{ {
self::assertFalse(Date::isValidDate($value)); 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'));
self::assertTrue(Date::isValidDate('2017-01-01 10:30', true)); 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 * @param mixed $value Empty source of date format
* @dataProvider provideEmptyValue * @dataProvider provideEmptyValue
*/ */
public function testIsValidDateFormatEmptyFormats($value) public function testIsValidDateFormatEmptyFormats($value): void
{ {
self::assertFalse(Date::isValidDateFormat($value)); self::assertFalse(Date::isValidDateFormat($value));
} }
@@ -143,12 +143,12 @@ class DateTest extends BaseTestCase
* @param mixed $format Invalid format of date * @param mixed $format Invalid format of date
* @dataProvider provideInvalidDateFormats * @dataProvider provideInvalidDateFormats
*/ */
public function testIsValidDateFormatInvalidFormats($format) public function testIsValidDateFormatInvalidFormats($format): void
{ {
self::assertFalse(Date::isValidDateFormat($format)); self::assertFalse(Date::isValidDateFormat($format));
} }
public function testIsValidDateFormatValidFormats() public function testIsValidDateFormatValidFormats(): void
{ {
self::assertTrue(Date::isValidDateFormat('Y')); self::assertTrue(Date::isValidDateFormat('Y'));
self::assertTrue(Date::isValidDateFormat('yy')); self::assertTrue(Date::isValidDateFormat('yy'));
@@ -165,12 +165,12 @@ class DateTest extends BaseTestCase
* @param mixed $value Empty value, e.g. "" * @param mixed $value Empty value, e.g. ""
* @dataProvider provideEmptyValue * @dataProvider provideEmptyValue
*/ */
public function testGenerateRandomTimeEmptyFormat($value) public function testGenerateRandomTimeEmptyFormat($value): void
{ {
self::assertNull(Date::generateRandomTime($value)); self::assertNull(Date::generateRandomTime($value));
} }
public function testGenerateRandomTimeIncorrectFormat() public function testGenerateRandomTimeIncorrectFormat(): void
{ {
self::assertNull(Date::generateRandomTime(',')); self::assertNull(Date::generateRandomTime(','));
self::assertNull(Date::generateRandomTime(';')); self::assertNull(Date::generateRandomTime(';'));
@@ -178,12 +178,12 @@ class DateTest extends BaseTestCase
self::assertNull(Date::generateRandomTime('?')); self::assertNull(Date::generateRandomTime('?'));
} }
public function testGenerateRandomTimeDefaultFormat() public function testGenerateRandomTimeDefaultFormat(): void
{ {
self::assertRegExp('/\d{2}:\d{2}:\d{2}/', Date::generateRandomTime()); 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[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 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')); 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()); self::assertRegExp('/^[0-6]{1}$/', (string)Date::getCurrentDayOfWeek());
} }
public function testGetCurrentDayOfWeekName() public function testGetCurrentDayOfWeekName(): void
{ {
// Required to avoid failure: // Required to avoid failure:
// //
@@ -228,7 +228,7 @@ class DateTest extends BaseTestCase
* *
* @dataProvider provideIncorrectYearMonthDay * @dataProvider provideIncorrectYearMonthDay
*/ */
public function testGetDayOfWeekIncorrectValues($year, $month, $day) public function testGetDayOfWeekIncorrectValues($year, $month, $day): void
{ {
$this->expectException(UnknownDatePartTypeException::class); $this->expectException(UnknownDatePartTypeException::class);
self::assertEmpty(Date::getDayOfWeek($year, $month, $day)); self::assertEmpty(Date::getDayOfWeek($year, $month, $day));
@@ -241,7 +241,7 @@ class DateTest extends BaseTestCase
* *
* @dataProvider provideYearMonthDay * @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)); self::assertRegExp('/^[0-6]{1}$/', (string)Date::getDayOfWeek($year, $month, $day));
} }
@@ -252,18 +252,18 @@ class DateTest extends BaseTestCase
* *
* @dataProvider provideEmptyDatesForDateDifference * @dataProvider provideEmptyDatesForDateDifference
*/ */
public function testGetDateDifferenceEmptyDates($dateStart, $dateEnd) public function testGetDateDifferenceEmptyDates($dateStart, $dateEnd): void
{ {
self::assertNull(Date::getDateDifference($dateStart, $dateEnd)); 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('2017-01-40', '2017-13-01'));
self::assertNull(Date::getDateDifference('xyz', 'lorem')); self::assertNull(Date::getDateDifference('xyz', 'lorem'));
} }
public function testGetDateDifferenceOneDay() public function testGetDateDifferenceOneDay(): void
{ {
// Difference of 1 day // Difference of 1 day
$dateStart = '2017-01-01'; $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)); 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 // Difference of 1 day, 2 hours and 15 minutes
$dateStart = '2017-01-01 12:00'; $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)); 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 // Difference of 1 month, 41 days, 4 hours and 30 minutes
$dateStart = '2017-01-01 12:00'; $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)); 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'; $dateStart = '2017-12-31 23:59';
$dateEnd = '2018-01-01 00:00'; $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)); 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'; $dateStart = '2017-01-01 16:00';
$dateEnd = '2017-01-02 10: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)); 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'; $dateStart = '2017-01-01 00:00';
$dateEnd = '2017-01-02 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)); 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'; $dateStart = '2017-01-02 10:00';
$dateEnd = '2017-01-01 16: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)); 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 // No difference
$dateStart = '2017-01-01 12:00'; $dateStart = '2017-01-01 12:00';
@@ -542,7 +542,7 @@ class DateTest extends BaseTestCase
* @param mixed $invalidCount Empty value, e.g. "" * @param mixed $invalidCount Empty value, e.g. ""
* @dataProvider provideEmptyValue * @dataProvider provideEmptyValue
*/ */
public function testGetDatesCollectionInvalidCount($invalidCount) public function testGetDatesCollectionInvalidCount($invalidCount): void
{ {
self::assertEquals([], Date::getDatesCollection(new DateTime(), $invalidCount)); self::assertEquals([], Date::getDatesCollection(new DateTime(), $invalidCount));
self::assertEquals([], Date::getDatesCollection(new DateTime(), -1)); self::assertEquals([], Date::getDatesCollection(new DateTime(), -1));
@@ -552,14 +552,14 @@ class DateTest extends BaseTestCase
* @param mixed $invalidInterval Empty value, e.g. "" * @param mixed $invalidInterval Empty value, e.g. ""
* @dataProvider provideEmptyValue * @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, $invalidInterval));
self::assertEquals([], Date::getDatesCollection(new DateTime(), 2, 'lorem')); self::assertEquals([], Date::getDatesCollection(new DateTime(), 2, 'lorem'));
self::assertEquals([], Date::getDatesCollection(new DateTime(), 2, '%d')); self::assertEquals([], Date::getDatesCollection(new DateTime(), 2, '%d'));
} }
public function testGetDatesCollection() public function testGetDatesCollection(): void
{ {
// 1 date only // 1 date only
$effect = [ $effect = [
@@ -596,7 +596,7 @@ class DateTest extends BaseTestCase
self::assertEquals($effect, Date::getDatesCollection(new DateTime('2017-01-01'), 3, 'P%dM')); self::assertEquals($effect, Date::getDatesCollection(new DateTime('2017-01-01'), 3, 'P%dM'));
} }
public function testGetRandomDateUsingDefaults() public function testGetRandomDateUsingDefaults(): void
{ {
$startDate = new DateTime(); $startDate = new DateTime();
$start = 1; $start = 1;
@@ -619,7 +619,7 @@ class DateTest extends BaseTestCase
* *
* @dataProvider provideDataOfRandomDateIncorrectEnd * @dataProvider provideDataOfRandomDateIncorrectEnd
*/ */
public function testGetRandomDateIncorrectEnd(DateTime $startDate, $start, $end) public function testGetRandomDateIncorrectEnd(DateTime $startDate, $start, $end): void
{ {
$randomDate = Date::getRandomDate($startDate, $start, $end); $randomDate = Date::getRandomDate($startDate, $start, $end);
@@ -636,7 +636,7 @@ class DateTest extends BaseTestCase
* *
* @dataProvider provideDataOfRandomDate * @dataProvider provideDataOfRandomDate
*/ */
public function testGetRandomDate(DateTime $startDate, $start, $end) public function testGetRandomDate(DateTime $startDate, $start, $end): void
{ {
$randomDate = Date::getRandomDate($startDate, $start, $end); $randomDate = Date::getRandomDate($startDate, $start, $end);
@@ -651,9 +651,9 @@ class DateTest extends BaseTestCase
/** /**
* @param mixed $period Empty value, e.g. "" * @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)); self::assertNull(Date::getDatesForPeriod($period));
} }
@@ -662,7 +662,7 @@ class DateTest extends BaseTestCase
* @param int $period Incorrect period to verify * @param int $period Incorrect period to verify
* @dataProvider provideIncorrectPeriod * @dataProvider provideIncorrectPeriod
*/ */
public function testGetDatesForPeriodUsingIncorrectPeriod($period) public function testGetDatesForPeriodUsingIncorrectPeriod($period): void
{ {
self::assertNull(Date::getDatesForPeriod($period)); self::assertNull(Date::getDatesForPeriod($period));
} }
@@ -674,7 +674,7 @@ class DateTest extends BaseTestCase
* *
* @dataProvider provideCorrectPeriod * @dataProvider provideCorrectPeriod
*/ */
public function testGetDatesForPeriod($period, DatePeriod $expected) public function testGetDatesForPeriod($period, DatePeriod $expected): void
{ {
self::assertEquals($expected, Date::getDatesForPeriod($period)); self::assertEquals($expected, Date::getDatesForPeriod($period));
} }

View File

@@ -23,7 +23,7 @@ use stdClass;
* @copyright Meritoo <http://www.meritoo.pl> * @copyright Meritoo <http://www.meritoo.pl>
* *
* @internal * @internal
* @covers \Meritoo\Common\Utilities\Miscellaneous * @covers \Meritoo\Common\Utilities\Miscellaneous
*/ */
class MiscellaneousTest extends BaseTestCase class MiscellaneousTest extends BaseTestCase
{ {
@@ -707,22 +707,40 @@ class MiscellaneousTest extends BaseTestCase
* *
* @dataProvider provideNumberToFillMissingZeros * @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)); self::assertSame($expected, Miscellaneous::fillMissingZeros($number, $length, $before));
} }
public function testGetProjectRootPath() public function testGetProjectRootPath(): void
{ {
self::assertNotEmpty(Miscellaneous::getProjectRootPath()); 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 * Provides string to convert characters to latin characters and not lower cased and not human-readable
* *
* @return Generator * @return Generator
*/ */
public function provideStringToLatinNotLowerCaseHuman() public function provideStringToLatinNotLowerCaseHuman(): ?Generator
{ {
yield[ yield[
'asuo', '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} * {@inheritdoc}
*/ */

View File

@@ -49,20 +49,20 @@ class ReflectionTest extends BaseTestCase
* @param mixed $invalidClass Empty value, e.g. "" * @param mixed $invalidClass Empty value, e.g. ""
* @dataProvider provideEmptyValue * @dataProvider provideEmptyValue
*/ */
public function testGetClassNameInvalidClass($invalidClass) public function testGetClassNameInvalidClass($invalidClass): void
{ {
self::assertNull(Reflection::getClassName($invalidClass)); self::assertNull(Reflection::getClassName($invalidClass));
self::assertNull(Reflection::getClassName(123)); self::assertNull(Reflection::getClassName(123));
} }
public function testGetClassNameNotExistingClass() public function testGetClassNameNotExistingClass(): void
{ {
// Not existing class // Not existing class
self::assertEquals('', Reflection::getClassName('xyz')); self::assertEquals('', Reflection::getClassName('xyz'));
self::assertEquals('', Reflection::getClassName('xyz', true)); self::assertEquals('', Reflection::getClassName('xyz', true));
} }
public function testGetClassNameExistingClass() public function testGetClassNameExistingClass(): void
{ {
// Existing class // Existing class
self::assertEquals(self::class, Reflection::getClassName(self::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( self::assertEquals(
'Meritoo\Common\Collection\Collection', 'Meritoo\Common\Collection\Collection',
@@ -92,13 +92,13 @@ class ReflectionTest extends BaseTestCase
); );
} }
public function testGetClassNamespaceNotExistingClass() public function testGetClassNamespaceNotExistingClass(): void
{ {
// Not existing class // Not existing class
self::assertEquals('', Reflection::getClassNamespace('xyz')); self::assertEquals('', Reflection::getClassNamespace('xyz'));
} }
public function testGetClassNamespaceExistingClass() public function testGetClassNamespaceExistingClass(): void
{ {
// Existing class // Existing class
self::assertEquals('Meritoo\Test\Common\Utilities', Reflection::getClassNamespace(self::class)); self::assertEquals('Meritoo\Test\Common\Utilities', Reflection::getClassNamespace(self::class));