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
* @return UnknownTypeException
*/
public static function create($unknownType, BaseType $typeInstance, $typeName)
public static function create($unknownType, BaseType $typeInstance, string $typeName): UnknownTypeException
{
$template = 'The \'%s\' type of %s is unknown. Probably doesn\'t exist or there is a typo. You should use one'
. ' of these types: %s.';
$allTypes = $typeInstance->getAll();
$types = Arrays::values2string($allTypes, '', ', ');
$types = Arrays::values2string($allTypes, '', ', ') ?? '[types not found]';
$message = sprintf($template, $unknownType, $typeName, $types);
return new static($message);

View File

@@ -18,8 +18,10 @@ class EmptyFilePathException extends \Exception
{
/**
* Creates exception
*
* @return EmptyFilePathException
*/
public static function create()
public static function create(): EmptyFilePathException
{
return new static('Path of the file is empty. Did you provide path of proper file?');
}

View File

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

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.
* @return MissingChildClassesException
*/
public static function create($parentClass)
public static function create($parentClass): MissingChildClassesException
{
$template = 'The \'%s\' class requires one child class at least who will extend her (maybe is an abstract'
. ' class), but the child classes are missing. Did you forget to extend this class?';
$parentClassName = Reflection::getClassName($parentClass);
$parentClassName = Reflection::getClassName($parentClass) ?? '[unknown class]';
$message = sprintf($template, $parentClassName);
return new static($message);

View File

@@ -19,11 +19,11 @@ class NotExistingPropertyException extends \Exception
/**
* Creates exception
*
* @param mixed $object Object that should contains given property
* @param string $property Name of the property
* @param mixed $object Object that should contains given property
* @param null|string $property Name of the property
* @return NotExistingPropertyException
*/
public static function create($object, $property)
public static function create($object, ?string $property): NotExistingPropertyException
{
$template = 'Property \'%s\' does not exist in instance of class \'%s\'. Did you use proper name of property?';
$message = sprintf($template, $property, get_class($object));

View File

@@ -27,12 +27,12 @@ class TooManyChildClassesException extends Exception
* @param array $childClasses Child classes
* @return TooManyChildClassesException
*/
public static function create($parentClass, array $childClasses)
public static function create($parentClass, array $childClasses): TooManyChildClassesException
{
$template = "The '%s' class requires one child class at most who will extend her, but more than one child"
. " class was found:\n- %s\n\nWhy did you create more than one classes that extend '%s' class?";
$parentClassName = Reflection::getClassName($parentClass);
$parentClassName = Reflection::getClassName($parentClass) ?? '[unknown class]';
$message = sprintf($template, $parentClassName, implode("\n- ", $childClasses), $parentClassName);
return new static($message);

View File

@@ -26,7 +26,7 @@ class UnknownDatePartTypeException extends UnknownTypeException
* @param string $value Incorrect value
* @return UnknownDatePartTypeException
*/
public static function createException($unknownDatePart, $value)
public static function createException(string $unknownDatePart, string $value): UnknownDatePartTypeException
{
return parent::create($unknownDatePart, new DatePartType(), sprintf('date part (with value %s)', $value));
}

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
* @return UnknownOopVisibilityTypeException
*/
public static function createException($unknownType)
public static function createException(string $unknownType): UnknownOopVisibilityTypeException
{
return parent::create($unknownType, new OopVisibilityType(), 'OOP-related visibility');
}

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@@ -1274,7 +1274,7 @@ class Miscellaneous
*
* @return string
*/
public static function getProjectRootPath()
public static function getProjectRootPath(): string
{
$projectRootPath = '';
@@ -1298,4 +1298,25 @@ class Miscellaneous
return $projectRootPath;
}
/**
* Removes marginal character (first or last) from given string
*
* @param string $string The string which should be shortened
* @param bool $last (optional) If is set to true, last element is removed (default behaviour). Otherwise -
* first.
* @return null|string
*/
public static function removeMarginalCharacter(string $string, bool $last = true): ?string
{
if (empty($string)) {
return null;
}
if ($last) {
return substr($string, 0, -1);
}
return substr($string, 1);
}
}

View File

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