PHP Coding Standards Fixer > fix coding standard

This commit is contained in:
Meritoo
2019-04-06 08:00:01 +02:00
parent 0f64705132
commit a13a629408
71 changed files with 812 additions and 1133 deletions

View File

@@ -30,7 +30,6 @@ class Templates extends Collection
*/ */
public function findTemplate(string $index): Template public function findTemplate(string $index): Template
{ {
/* @var Template $template */
$template = $this->getByIndex($index); $template = $this->getByIndex($index);
if ($template instanceof Template) { if ($template instanceof Template) {

View File

@@ -28,9 +28,6 @@ class UnknownDatePartTypeException extends UnknownTypeException
*/ */
public static function createException($unknownDatePart, $value) public static function createException($unknownDatePart, $value)
{ {
/* @var UnknownDatePartTypeException $exception */ return parent::create($unknownDatePart, new DatePartType(), sprintf('date part (with value %s)', $value));
$exception = parent::create($unknownDatePart, new DatePartType(), sprintf('date part (with value %s)', $value));
return $exception;
} }
} }

View File

@@ -27,9 +27,6 @@ class UnknownOopVisibilityTypeException extends UnknownTypeException
*/ */
public static function createException($unknownType) public static function createException($unknownType)
{ {
/* @var UnknownOopVisibilityTypeException $exception */ return parent::create($unknownType, new OopVisibilityType(), 'OOP-related visibility');
$exception = parent::create($unknownType, new OopVisibilityType(), 'OOP-related visibility');
return $exception;
} }
} }

View File

@@ -57,7 +57,7 @@ trait ArrayAccessTrait
/** /**
* Returns information if element with given index/key exists * Returns information if element with given index/key exists
* *
* @param string|int $index The index/key of element * @param int|string $index The index/key of element
* @return bool * @return bool
*/ */
private function exists($index) private function exists($index)

View File

@@ -58,6 +58,7 @@ trait MainTrait
foreach ($elements as $index => $element) { foreach ($elements as $index => $element) {
if ($useIndexes) { if ($useIndexes) {
$this->add($element, $index); $this->add($element, $index);
continue; continue;
} }
@@ -93,6 +94,7 @@ trait MainTrait
foreach ($this->elements as $index => $existing) { foreach ($this->elements as $index => $existing) {
if ($element === $existing) { if ($element === $existing) {
unset($this->elements[$index]); unset($this->elements[$index]);
break; break;
} }
} }
@@ -150,7 +152,7 @@ trait MainTrait
* Returns previous element for given element * Returns previous element for given element
* *
* @param mixed $element The element to verify * @param mixed $element The element to verify
* @return mixed|null * @return null|mixed
*/ */
public function getPrevious($element) public function getPrevious($element)
{ {
@@ -161,7 +163,7 @@ trait MainTrait
* Returns next element for given element * Returns next element for given element
* *
* @param mixed $element The element to verify * @param mixed $element The element to verify
* @return mixed|null * @return null|mixed
*/ */
public function getNext($element) public function getNext($element)
{ {
@@ -192,7 +194,7 @@ trait MainTrait
* Returns element with given index * Returns element with given index
* *
* @param mixed $index Index / key of the element * @param mixed $index Index / key of the element
* @return mixed|null * @return null|mixed
*/ */
public function getByIndex($index) public function getByIndex($index)
{ {

View File

@@ -163,7 +163,7 @@ 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 $classNamespace Namespace of class that contains method to verify
* @param string|ReflectionMethod $method Name of method or just the 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 * @param string $visibilityType Expected visibility of verified method. One of
* OopVisibilityType class constants. * OopVisibilityType class constants.
* @param int $argumentsCount (optional) Expected count/amount of arguments of the * @param int $argumentsCount (optional) Expected count/amount of arguments of the
@@ -183,19 +183,15 @@ trait BaseTestCaseTrait
$argumentsCount = 0, $argumentsCount = 0,
$requiredArgumentsCount = 0 $requiredArgumentsCount = 0
) { ) {
/* // Type of visibility is not correct?
* Type of visibility is correct?
*/
if (!(new OopVisibilityType())->isCorrectType($visibilityType)) { if (!(new OopVisibilityType())->isCorrectType($visibilityType)) {
throw new UnknownOopVisibilityTypeException($visibilityType); throw new UnknownOopVisibilityTypeException($visibilityType);
} }
$reflection = new ReflectionClass($classNamespace); $reflection = new ReflectionClass($classNamespace);
/* // 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)
*/
if (!$method instanceof ReflectionMethod) { if (!$method instanceof ReflectionMethod) {
$method = $reflection->getMethod($method); $method = $reflection->getMethod($method);
} }
@@ -203,14 +199,15 @@ trait BaseTestCaseTrait
switch ($visibilityType) { switch ($visibilityType) {
case OopVisibilityType::IS_PUBLIC: case OopVisibilityType::IS_PUBLIC:
static::assertTrue($method->isPublic()); static::assertTrue($method->isPublic());
break;
break;
case OopVisibilityType::IS_PROTECTED: case OopVisibilityType::IS_PROTECTED:
static::assertTrue($method->isProtected()); static::assertTrue($method->isProtected());
break;
break;
case OopVisibilityType::IS_PRIVATE: case OopVisibilityType::IS_PRIVATE:
static::assertTrue($method->isPrivate()); static::assertTrue($method->isPrivate());
break; break;
} }
@@ -234,9 +231,6 @@ trait BaseTestCaseTrait
$argumentsCount = 0, $argumentsCount = 0,
$requiredArgumentsCount = 0 $requiredArgumentsCount = 0
) { ) {
/*
* Let's grab the constructor
*/
$reflection = new ReflectionClass($classNamespace); $reflection = new ReflectionClass($classNamespace);
$method = $reflection->getConstructor(); $method = $reflection->getConstructor();
@@ -256,9 +250,6 @@ trait BaseTestCaseTrait
*/ */
protected static function assertHasNoConstructor($classNamespace) protected static function assertHasNoConstructor($classNamespace)
{ {
/*
* Let's grab the constructor
*/
$reflection = new ReflectionClass($classNamespace); $reflection = new ReflectionClass($classNamespace);
$constructor = $reflection->getConstructor(); $constructor = $reflection->getConstructor();

View File

@@ -99,7 +99,7 @@ trait HumanTrait
/** /**
* Returns email address * Returns email address
* *
* @return string|null * @return null|string
*/ */
public function getEmail() public function getEmail()
{ {
@@ -109,7 +109,7 @@ trait HumanTrait
/** /**
* Returns birth date * Returns birth date
* *
* @return \DateTime|null * @return null|\DateTime
*/ */
public function getBirthDate() public function getBirthDate()
{ {

View File

@@ -23,40 +23,40 @@ class DatePartType extends BaseType
* *
* @var string * @var string
*/ */
const DAY = 'day'; public const DAY = 'day';
/** /**
* The "hour" date part * The "hour" date part
* *
* @var string * @var string
*/ */
const HOUR = 'hour'; public const HOUR = 'hour';
/** /**
* The "minute" date part * The "minute" date part
* *
* @var string * @var string
*/ */
const MINUTE = 'minute'; public const MINUTE = 'minute';
/** /**
* The "month" date part * The "month" date part
* *
* @var string * @var string
*/ */
const MONTH = 'month'; public const MONTH = 'month';
/** /**
* The "second" date part * The "second" date part
* *
* @var string * @var string
*/ */
const SECOND = 'second'; public const SECOND = 'second';
/** /**
* The "year" date part * The "year" date part
* *
* @var string * @var string
*/ */
const YEAR = 'year'; public const YEAR = 'year';
} }

View File

@@ -26,63 +26,63 @@ class DatePeriod extends BaseType
* *
* @var int * @var int
*/ */
const LAST_MONTH = 4; public const LAST_MONTH = 4;
/** /**
* The period constant: last week * The period constant: last week
* *
* @var int * @var int
*/ */
const LAST_WEEK = 1; public const LAST_WEEK = 1;
/** /**
* The period constant: last year * The period constant: last year
* *
* @var int * @var int
*/ */
const LAST_YEAR = 7; public const LAST_YEAR = 7;
/** /**
* The period constant: next month * The period constant: next month
* *
* @var int * @var int
*/ */
const NEXT_MONTH = 6; public const NEXT_MONTH = 6;
/** /**
* The period constant: next week * The period constant: next week
* *
* @var int * @var int
*/ */
const NEXT_WEEK = 3; public const NEXT_WEEK = 3;
/** /**
* The period constant: next year * The period constant: next year
* *
* @var int * @var int
*/ */
const NEXT_YEAR = 9; public const NEXT_YEAR = 9;
/** /**
* The period constant: this month * The period constant: this month
* *
* @var int * @var int
*/ */
const THIS_MONTH = 5; public const THIS_MONTH = 5;
/** /**
* The period constant: this week * The period constant: this week
* *
* @var int * @var int
*/ */
const THIS_WEEK = 2; public const THIS_WEEK = 2;
/** /**
* The period constant: this year * The period constant: this year
* *
* @var int * @var int
*/ */
const THIS_YEAR = 8; public const THIS_YEAR = 8;
/** /**
* The start date of period * The start date of period
@@ -114,23 +114,20 @@ class DatePeriod extends BaseType
* Returns formatted one of the period's date: start date or end date * Returns formatted one of the period's date: start date or end date
* *
* @param string $format Format used to format the date * @param string $format Format used to format the date
* @param bool $startDate (optional) If is set to true, start date is 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($format, $startDate = true)
{ {
$date = $this->getEndDate(); $date = $this->getEndDate();
/* // Start date should be formatted?
* Start date should be formatted?
*/
if ($startDate) { if ($startDate) {
$date = $this->getStartDate(); $date = $this->getStartDate();
} }
/* // Unknown date or format is invalid?
* Unknown date or format is invalid? // Nothing to do
*/
if (null === $date || !Date::isValidDateFormat($format)) { if (null === $date || !Date::isValidDateFormat($format)) {
return ''; return '';
} }

View File

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

View File

@@ -21,16 +21,16 @@ class Arrays
* *
* @var string * @var string
*/ */
const POSITION_KEY_NAME = 'position'; public const POSITION_KEY_NAME = 'position';
/** /**
* Converts given array's column to string. * Converts given array's column to string.
* Recursive call is made for multi-dimensional arrays. * Recursive call is made for multi-dimensional arrays.
* *
* @param array $array Data to be converted * @param array $array Data to be converted
* @param string|int $arrayColumnKey (optional) Column name. Default: "". * @param int|string $arrayColumnKey (optional) Column name. Default: "".
* @param string $separator (optional) Separator used between values. Default: ",". * @param string $separator (optional) Separator used between values. Default: ",".
* @return string|null * @return null|string
*/ */
public static function values2string(array $array, $arrayColumnKey = '', $separator = ',') public static function values2string(array $array, $arrayColumnKey = '', $separator = ',')
{ {
@@ -85,7 +85,7 @@ class Arrays
* @param string $valuesKeysSeparator (optional) Separator used between name and value. Default: "=". * @param string $valuesKeysSeparator (optional) Separator used between name and value. Default: "=".
* @param string $valuesWrapper (optional) Wrapper used to wrap values, e.g. double-quote: key="value". * @param string $valuesWrapper (optional) Wrapper used to wrap values, e.g. double-quote: key="value".
* Default: "". * Default: "".
* @return string|null * @return null|string
*/ */
public static function valuesKeys2string( public static function valuesKeys2string(
array $array, array $array,
@@ -123,7 +123,7 @@ class Arrays
* *
* @param array $array Data to be converted. It have to be an array that represents database table. * @param array $array Data to be converted. It have to be an array that represents database table.
* @param string $separator (optional) Separator used between values. Default: ",". * @param string $separator (optional) Separator used between values. Default: ",".
* @return string|null * @return null|string
*/ */
public static function values2csv(array $array, $separator = ',') public static function values2csv(array $array, $separator = ',')
{ {
@@ -279,7 +279,7 @@ class Arrays
* *
* @param array $array Data to get the breadcrumb * @param array $array Data to get the breadcrumb
* @param string $separator (optional) Separator used to stick the elements. Default: "/". * @param string $separator (optional) Separator used to stick the elements. Default: "/".
* @return string|null * @return null|string
*/ */
public static function getLastElementBreadCrumb(array $array, $separator = '/') public static function getLastElementBreadCrumb(array $array, $separator = '/')
{ {
@@ -328,9 +328,7 @@ class Arrays
$last = end($array); $last = end($array);
if (is_array($last)) { if (is_array($last)) {
/* // We've got an array, so looking for the last row of array will be done recursively
* We've got an array, so looking for the last row of array will be done recursively
*/
$effect = self::getLastRow($last); $effect = self::getLastRow($last);
/* /*
@@ -381,7 +379,7 @@ class Arrays
* @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
* @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.
* @return string|null * @return null|string
*/ */
public static function array2JavaScript(array $array, $jsVariableName = '', $preserveIndexes = false) public static function array2JavaScript(array $array, $jsVariableName = '', $preserveIndexes = false)
{ {
@@ -477,7 +475,7 @@ class Arrays
* Quotes (adds quotes) to elements that are strings and returns new array (with quoted elements) * Quotes (adds quotes) to elements that are strings and returns new array (with quoted elements)
* *
* @param array $array The array to check for string values * @param array $array The array to check for string values
* @return array|null * @return null|array
*/ */
public static function quoteStrings(array $array) public static function quoteStrings(array $array)
{ {
@@ -509,9 +507,9 @@ class Arrays
/** /**
* Removes marginal element (first or last) * Removes marginal element (first or last)
* *
* @param string|array $item The item which should be shortened * @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. * @param bool $last (optional) If is set to true, last element is removed. Otherwise - first.
* @return string|array * @return array|string
*/ */
public static function removeMarginalElement($item, $last = true) public static function removeMarginalElement($item, $last = true)
{ {
@@ -560,7 +558,7 @@ class Arrays
* *
* @param array $array The array that contains element / item which should be removed * @param array $array The array that contains element / item which should be removed
* @param mixed $item The element / item which should be removed * @param mixed $item The element / item which should be removed
* @return bool|array * @return array|bool
*/ */
public static function removeElement(array $array, $item) public static function removeElement(array $array, $item)
{ {
@@ -572,19 +570,13 @@ class Arrays
return false; return false;
} }
/* // Flip the array to make it looks like: value => key
* Flip the array to make it looks like: value => key
*/
$arrayFlipped = array_flip($array); $arrayFlipped = array_flip($array);
/* // Take the key of element / item that should be removed
* Take the key of element / item that should be removed
*/
$key = $arrayFlipped[$item]; $key = $arrayFlipped[$item];
/* // ...and remove the element / item
* ...and remove the element / item
*/
unset($array[$key]); unset($array[$key]);
return $array; return $array;
@@ -642,7 +634,7 @@ class Arrays
* value will be used with it's key, because other will be overridden. * value will be used with it's key, because other will be overridden.
* Otherwise - values are preserved and keys assigned to that values are * Otherwise - values are preserved and keys assigned to that values are
* returned as an array. * returned as an array.
* @return array|null * @return null|array
* *
* Example of $ignoreDuplicatedValues = false: * Example of $ignoreDuplicatedValues = false:
* - provided array * - provided array
@@ -680,13 +672,12 @@ class Arrays
*/ */
if (is_array($value)) { if (is_array($value)) {
$replaced[$key] = self::setKeysAsValues($value, $ignoreDuplicatedValues); $replaced[$key] = self::setKeysAsValues($value, $ignoreDuplicatedValues);
continue; continue;
} }
/* // Duplicated values shouldn't be ignored and processed value is used as key already?
* Duplicated values shouldn't be ignored and processed value is used as key already? // Let's use an array and that will contain all values (to avoid ignoring / overriding duplicated values)
* Let's use an array and that will contain all values (to avoid ignoring / overriding duplicated values)
*/
if (!$ignoreDuplicatedValues && isset($replaced[$value])) { if (!$ignoreDuplicatedValues && isset($replaced[$value])) {
$existing = self::makeArray($replaced[$value]); $existing = self::makeArray($replaced[$value]);
@@ -697,9 +688,7 @@ class Arrays
continue; continue;
} }
/* // Standard behaviour
* Standard behaviour
*/
$replaced[$value] = $key; $replaced[$value] = $key;
} }
@@ -711,7 +700,7 @@ class Arrays
* *
* @param array $array The array to sort * @param array $array The array to sort
* @param int $sortFlags (optional) Options of ksort() function * @param int $sortFlags (optional) Options of ksort() function
* @return array|null * @return null|array
*/ */
public static function ksortRecursive(array &$array, $sortFlags = SORT_REGULAR) public static function ksortRecursive(array &$array, $sortFlags = SORT_REGULAR)
{ {
@@ -739,7 +728,7 @@ class Arrays
* Returns count / amount of elements that are not array * Returns count / amount of elements that are not array
* *
* @param array $array The array to count * @param array $array The array to count
* @return int|null * @return null|int
*/ */
public static function getNonArrayElementsCount(array $array) public static function getNonArrayElementsCount(array $array)
{ {
@@ -756,6 +745,7 @@ class Arrays
foreach ($array as &$value) { foreach ($array as &$value) {
if (is_array($value)) { if (is_array($value)) {
$count += self::getNonArrayElementsCount($value); $count += self::getNonArrayElementsCount($value);
continue; continue;
} }
@@ -857,10 +847,10 @@ class Arrays
* @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 string|array $stopIfMatchedBy (optional) Patterns of keys or paths that matched will stop the process * @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 * 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: "". * will not be used for keys in lower level of given array). Default: "".
* @return array|null * @return null|array
* *
* Examples - $stopIfMatchedBy argument: * Examples - $stopIfMatchedBy argument:
* a) "\d+" * a) "\d+"
@@ -910,6 +900,7 @@ class Arrays
if (preg_match($pattern, $key) || preg_match($pattern, $path)) { if (preg_match($pattern, $key) || preg_match($pattern, $path)) {
$stopRecursion = true; $stopRecursion = true;
break; break;
} }
} }
@@ -923,12 +914,11 @@ class Arrays
*/ */
if (!$valueIsArray || ($valueIsArray && empty($value)) || $stopRecursion) { if (!$valueIsArray || ($valueIsArray && empty($value)) || $stopRecursion) {
$paths[$path] = $value; $paths[$path] = $value;
continue; continue;
} }
/* // Let's iterate through the next level, using recursive
* Let's iterate through the next level, using recursive
*/
if ($valueIsArray) { if ($valueIsArray) {
$recursivePaths = self::getLastElementsPaths($value, $separator, $path, $stopIfMatchedBy); $recursivePaths = self::getLastElementsPaths($value, $separator, $path, $stopIfMatchedBy);
$paths += $recursivePaths; $paths += $recursivePaths;
@@ -978,9 +968,7 @@ class Arrays
*/ */
$areMatched = true; $areMatched = true;
/* // Building the pattern
* Building the pattern
*/
$rawPattern = $pattern; $rawPattern = $pattern;
$pattern = sprintf('|%s|', $rawPattern); $pattern = sprintf('|%s|', $rawPattern);
@@ -991,6 +979,7 @@ class Arrays
*/ */
if (!preg_match($pattern, $key)) { if (!preg_match($pattern, $key)) {
$areMatched = false; $areMatched = false;
break; break;
} }
@@ -1141,7 +1130,7 @@ class Arrays
* *
* @param array $array The array which should contain values of the key * @param array $array The array which should contain values of the key
* @param string $key The key * @param string $key The key
* @return array|null * @return null|array
*/ */
public static function getAllValuesOfKey(array $array, $key) public static function getAllValuesOfKey(array $array, $key)
{ {
@@ -1158,6 +1147,7 @@ class Arrays
foreach ($array as $index => $value) { foreach ($array as $index => $value) {
if ($index === $key) { if ($index === $key) {
$values[] = $value; $values[] = $value;
continue; continue;
} }
@@ -1184,7 +1174,7 @@ class Arrays
* @param string $keyName (optional) Name of key which will contain the position value * @param string $keyName (optional) Name of key which will contain the position value
* @param int $startPosition (optional) Default, start value of the position for main / given array, not the * @param int $startPosition (optional) Default, start value of the position for main / given array, not the
* children * children
* @return array|null * @return null|array
*/ */
public static function setPositions(array $array, $keyName = self::POSITION_KEY_NAME, $startPosition = null) public static function setPositions(array $array, $keyName = self::POSITION_KEY_NAME, $startPosition = null)
{ {
@@ -1233,6 +1223,7 @@ class Arrays
foreach ($array as $key => $value) { foreach ($array as $key => $value) {
if (is_array($value)) { if (is_array($value)) {
$result[$key] = self::trimRecursive($value); $result[$key] = self::trimRecursive($value);
continue; continue;
} }
@@ -1287,7 +1278,7 @@ class Arrays
* *
* @param array $array An array to sort * @param array $array An array to sort
* @param array $keysOrder An array with keys of the 1st argument in proper / required order * @param array $keysOrder An array with keys of the 1st argument in proper / required order
* @return array|null * @return null|array
*/ */
public static function sortByCustomKeysOrder(array $array, array $keysOrder) public static function sortByCustomKeysOrder(array $array, array $keysOrder)
{ {
@@ -1336,7 +1327,7 @@ class Arrays
* *
* @param array $array The array with elements to implode * @param array $array The array with elements to implode
* @param string $separator Separator used to stick together elements of given array * @param string $separator Separator used to stick together elements of given array
* @return string|null * @return null|string
*/ */
public static function implodeSmart(array $array, $separator) public static function implodeSmart(array $array, $separator)
{ {
@@ -1437,9 +1428,7 @@ class Arrays
foreach ($array1 as $key => $value) { foreach ($array1 as $key => $value) {
$array2HasKey = array_key_exists($key, $array2); $array2HasKey = array_key_exists($key, $array2);
/* // Values should be compared only?
* Values should be compared only?
*/
if ($valuesOnly) { if ($valuesOnly) {
$difference = null; $difference = null;
@@ -1461,20 +1450,14 @@ class Arrays
$effect[] = $difference; $effect[] = $difference;
} }
/* // The key exists in 2nd array?
* The key exists in 2nd array?
*/
} elseif ($array2HasKey) { } elseif ($array2HasKey) {
/* // The value it's an array (it's a nested array)?
* The value it's an array (it's a nested array)?
*/
if (is_array($value)) { if (is_array($value)) {
$diff = []; $diff = [];
if (is_array($array2[$key])) { if (is_array($array2[$key])) {
/* // Let's verify the nested array
* Let's verify the nested array
*/
$diff = self::arrayDiffRecursive($value, $array2[$key], $valuesOnly); $diff = self::arrayDiffRecursive($value, $array2[$key], $valuesOnly);
} }
@@ -1484,16 +1467,12 @@ class Arrays
$effect[$key] = $diff; $effect[$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; $effect[$key] = $value;
} }
} else { } else {
/* // OKay, I've got difference
* OKay, I've got difference
*/
$effect[$key] = $value; $effect[$key] = $value;
} }
} }
@@ -1506,14 +1485,12 @@ class Arrays
* *
* @param array $array The array to verify * @param array $array The array to verify
* @param mixed $element The element who index / key is needed * @param mixed $element The element who index / key is needed
* @return bool|mixed|null * @return null|bool|mixed
*/ */
public static function getIndexOf(array $array, $element) public static function getIndexOf(array $array, $element)
{ {
/* // No elements?
* No elements? // Nothing to do
* Nothing to do
*/
if (empty($array)) { if (empty($array)) {
return false; return false;
} }
@@ -1531,10 +1508,10 @@ class Arrays
* Returns an array with incremented indexes / keys * Returns an array with incremented indexes / keys
* *
* @param array $array The array which indexes / keys should be incremented * @param array $array The array which indexes / keys should be incremented
* @param int|null $startIndex (optional) Index from which incrementation should be started. If not provided, * @param null|int $startIndex (optional) Index from which incrementation should be started. If not provided,
* the first index / key will be used. * the first index / key will be used.
* @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 array|null * @return null|array
*/ */
public static function incrementIndexes(array $array, $startIndex = null, $incrementStep = 1) public static function incrementIndexes(array $array, $startIndex = null, $incrementStep = 1)
{ {
@@ -1594,7 +1571,7 @@ class Arrays
* *
* @param array $array The array with elements * @param array $array The array with elements
* @param mixed $element Element for who next element should be returned * @param mixed $element Element for who next element should be returned
* @return mixed|null * @return null|mixed
*/ */
public static function getNextElement(array $array, $element) public static function getNextElement(array $array, $element)
{ {
@@ -1606,7 +1583,7 @@ class Arrays
* *
* @param array $array The array with elements * @param array $array The array with elements
* @param mixed $element Element for who previous element should be returned * @param mixed $element Element for who previous element should be returned
* @return mixed|null * @return null|mixed
*/ */
public static function getPreviousElement(array $array, $element) public static function getPreviousElement(array $array, $element)
{ {
@@ -1617,7 +1594,7 @@ class Arrays
* Returns information if given array is a multi dimensional array * Returns information if given array is a multi dimensional array
* *
* @param array $array The array to verify * @param array $array The array to verify
* @return bool|null * @return null|bool
*/ */
public static function isMultiDimensional(array $array) public static function isMultiDimensional(array $array)
{ {
@@ -1671,7 +1648,7 @@ class Arrays
* Returns non-empty values, e.g. without "" (empty string), null or [] * Returns non-empty values, e.g. without "" (empty string), null or []
* *
* @param array $values The values to filter * @param array $values The values to filter
* @return array|null * @return null|array
*/ */
public static function getNonEmptyValues(array $values) public static function getNonEmptyValues(array $values)
{ {
@@ -1696,7 +1673,7 @@ class Arrays
* *
* @param array $values The values to filter * @param array $values The values to filter
* @param string $separator (optional) Separator used to implode the values. Default: ", ". * @param string $separator (optional) Separator used to implode the values. Default: ", ".
* @return string|null * @return null|string
*/ */
public static function getNonEmptyValuesAsString(array $values, $separator = ', ') public static function getNonEmptyValuesAsString(array $values, $separator = ', ')
{ {
@@ -1727,7 +1704,7 @@ class Arrays
* @param array $array The array with elements * @param array $array The array with elements
* @param mixed $element Element for who next element should be returned * @param mixed $element Element for who next element should be returned
* @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 mixed|null * @return null|mixed
*/ */
private static function getNeighbour(array $array, $element, $next = true) private static function getNeighbour(array $array, $element, $next = true)
{ {
@@ -1770,9 +1747,7 @@ class Arrays
return null; return null;
} }
/* // Looking for key of the neighbour (next or previous element)
* Looking for key of the neighbour (next or previous element)
*/
if ($next) { if ($next) {
++$indexOfKey; ++$indexOfKey;
} else { } else {

View File

@@ -25,7 +25,7 @@ class Bundle
* @param string $bundleName Full name of the bundle, e.g. "MyExtraBundle" * @param string $bundleName Full name of the bundle, e.g. "MyExtraBundle"
* @param string $extension (optional) Extension of the view / template (default: "html.twig") * @param string $extension (optional) Extension of the view / template (default: "html.twig")
* @throws IncorrectBundleNameException * @throws IncorrectBundleNameException
* @return string|null * @return null|string
*/ */
public static function getBundleViewPath($viewPath, $bundleName, $extension = 'html.twig') public static function getBundleViewPath($viewPath, $bundleName, $extension = 'html.twig')
{ {
@@ -37,23 +37,17 @@ class Bundle
return null; return null;
} }
/* // Oops, given name of bundle is invalid
* Given name of bundle is invalid?
*/
if (!Regex::isValidBundleName($bundleName)) { if (!Regex::isValidBundleName($bundleName)) {
throw IncorrectBundleNameException::create($bundleName); throw IncorrectBundleNameException::create($bundleName);
} }
/* // Make sure that path of the view / template ends with given extension
* Path of the view / template doesn't end with given extension?
*/
if (!Regex::endsWith($viewPath, $extension)) { if (!Regex::endsWith($viewPath, $extension)) {
$viewPath = sprintf('%s.%s', $viewPath, $extension); $viewPath = sprintf('%s.%s', $viewPath, $extension);
} }
/* // Prepare short name of bundle and path of view / template with "/" (instead of ":")
* Prepare short name of bundle and path of view / template with "/" (instead of ":")
*/
$shortBundleName = static::getShortBundleName($bundleName); $shortBundleName = static::getShortBundleName($bundleName);
$viewPath = str_replace(':', '/', $viewPath); $viewPath = str_replace(':', '/', $viewPath);
@@ -65,13 +59,11 @@ class Bundle
* *
* @param string $fullBundleName Full name of the bundle, e.g. "MyExtraBundle" * @param string $fullBundleName Full name of the bundle, e.g. "MyExtraBundle"
* @throws IncorrectBundleNameException * @throws IncorrectBundleNameException
* @return string|null * @return null|string
*/ */
public static function getShortBundleName($fullBundleName) public static function getShortBundleName($fullBundleName)
{ {
/* // Oops, given name of bundle is invalid
* Given name of bundle is invalid?
*/
if (!Regex::isValidBundleName($fullBundleName)) { if (!Regex::isValidBundleName($fullBundleName)) {
if (!is_string($fullBundleName)) { if (!is_string($fullBundleName)) {
$fullBundleName = gettype($fullBundleName); $fullBundleName = gettype($fullBundleName);

View File

@@ -8,8 +8,6 @@
namespace Meritoo\Common\Utilities; namespace Meritoo\Common\Utilities;
use stdClass;
/** /**
* Useful Composer-related methods (only static functions) * Useful Composer-related methods (only static functions)
* *
@@ -23,14 +21,14 @@ class Composer
* *
* @var string * @var string
*/ */
const FILE_NAME_MAIN = 'composer.json'; public const FILE_NAME_MAIN = 'composer.json';
/** /**
* Returns value from composer.json file * Returns value from composer.json file
* *
* @param string $composerJsonPath Path of composer.json file * @param string $composerJsonPath Path of composer.json file
* @param string $nodeName Name of node who value should be returned * @param string $nodeName Name of node who value should be returned
* @return string|null * @return null|string
*/ */
public static function getValue($composerJsonPath, $nodeName) public static function getValue($composerJsonPath, $nodeName)
{ {
@@ -63,7 +61,6 @@ class Composer
return null; return null;
} }
/* @var stdClass $data */
return $data->{$nodeName}; return $data->{$nodeName};
} }
} }

View File

@@ -29,7 +29,7 @@ class Date
* *
* @var string * @var string
*/ */
const DATE_DIFFERENCE_UNIT_DAYS = 'days'; public const DATE_DIFFERENCE_UNIT_DAYS = 'days';
/** /**
* The 'hours' unit of date difference. * The 'hours' unit of date difference.
@@ -37,7 +37,7 @@ class Date
* *
* @var string * @var string
*/ */
const DATE_DIFFERENCE_UNIT_HOURS = 'hours'; public const DATE_DIFFERENCE_UNIT_HOURS = 'hours';
/** /**
* The 'minutes' unit of date difference. * The 'minutes' unit of date difference.
@@ -45,7 +45,7 @@ class Date
* *
* @var string * @var string
*/ */
const DATE_DIFFERENCE_UNIT_MINUTES = 'minutes'; public const DATE_DIFFERENCE_UNIT_MINUTES = 'minutes';
/** /**
* The 'months' unit of date difference. * The 'months' unit of date difference.
@@ -53,7 +53,7 @@ class Date
* *
* @var string * @var string
*/ */
const DATE_DIFFERENCE_UNIT_MONTHS = 'months'; public const DATE_DIFFERENCE_UNIT_MONTHS = 'months';
/** /**
* The 'years' unit of date difference. * The 'years' unit of date difference.
@@ -61,14 +61,14 @@ class Date
* *
* @var string * @var string
*/ */
const DATE_DIFFERENCE_UNIT_YEARS = 'years'; public const DATE_DIFFERENCE_UNIT_YEARS = 'years';
/** /**
* Returns date's period (that contains start and end date) for given period * Returns date's period (that contains start and end date) for given period
* *
* @param int $period The period, type of period. One of DatePeriod class constants, e.g. DatePeriod::LAST_WEEK. * @param int $period The period, type of period. One of DatePeriod class constants, e.g. DatePeriod::LAST_WEEK.
* @throws Exception * @throws Exception
* @return DatePeriod|null * @return null|DatePeriod
*/ */
public static function getDatesForPeriod($period) public static function getDatesForPeriod($period)
{ {
@@ -183,7 +183,7 @@ class Date
* *
* @param string $format (optional) Format of returned value. A string acceptable by the DateTime::format() * @param string $format (optional) Format of returned value. A string acceptable by the DateTime::format()
* method. * method.
* @return string|null * @return null|string
*/ */
public static function generateRandomTime($format = 'H:i:s') public static function generateRandomTime($format = 'H:i:s')
{ {
@@ -213,9 +213,7 @@ class Date
$seconds[] = $i; $seconds[] = $i;
} }
/* // Prepare random time (hour, minute and second)
* Prepare random time (hour, minute and second)
*/
$hour = $hours[array_rand($hours)]; $hour = $hours[array_rand($hours)];
$minute = $minutes[array_rand($minutes)]; $minute = $minutes[array_rand($minutes)];
$second = $seconds[array_rand($seconds)]; $second = $seconds[array_rand($seconds)];
@@ -259,23 +257,17 @@ class Date
$month = (int)$month; $month = (int)$month;
$day = (int)$day; $day = (int)$day;
/* // Oops, given year is incorrect
* Oops, incorrect year
*/
if ($year <= 0) { if ($year <= 0) {
throw UnknownDatePartTypeException::createException(DatePartType::YEAR, $year); throw UnknownDatePartTypeException::createException(DatePartType::YEAR, $year);
} }
/* // Oops, given month is incorrect
* Oops, incorrect month
*/
if ($month < 1 || $month > 12) { if ($month < 1 || $month > 12) {
throw UnknownDatePartTypeException::createException(DatePartType::MONTH, $month); throw UnknownDatePartTypeException::createException(DatePartType::MONTH, $month);
} }
/* // Oops, given day is incorrect
* Oops, incorrect day
*/
if ($day < 1 || $day > 31) { if ($day < 1 || $day > 31) {
throw UnknownDatePartTypeException::createException(DatePartType::DAY, $day); throw UnknownDatePartTypeException::createException(DatePartType::DAY, $day);
} }
@@ -353,8 +345,8 @@ class Date
* If the unit of date difference is null, all units are returned in array (units are keys of the array). * If the unit of date difference is null, all units are returned in array (units are keys of the array).
* Otherwise - one, integer value is returned. * Otherwise - one, integer value is returned.
* *
* @param string|DateTime $dateStart The start date * @param DateTime|string $dateStart The start date
* @param string|DateTime $dateEnd The end date * @param DateTime|string $dateEnd The end date
* @param string $differenceUnit (optional) Unit of date difference. One of this class * @param string $differenceUnit (optional) Unit of date difference. One of this class
* DATE_DIFFERENCE_UNIT_* constants. If is set to null all units are * DATE_DIFFERENCE_UNIT_* constants. If is set to null all units are
* returned in the array. * returned in the array.
@@ -401,9 +393,7 @@ class Date
if (null === $differenceUnit || self::DATE_DIFFERENCE_UNIT_YEARS === $differenceUnit) { if (null === $differenceUnit || self::DATE_DIFFERENCE_UNIT_YEARS === $differenceUnit) {
$diff = $end->diff($start); $diff = $end->diff($start);
/* // Difference between dates in years should be returned only?
* Difference between dates in years should be returned only?
*/
if (self::DATE_DIFFERENCE_UNIT_YEARS === $differenceUnit) { if (self::DATE_DIFFERENCE_UNIT_YEARS === $differenceUnit) {
return $diff->y; return $diff->y;
} }
@@ -414,9 +404,7 @@ class Date
if (null === $differenceUnit || self::DATE_DIFFERENCE_UNIT_MONTHS === $differenceUnit) { if (null === $differenceUnit || self::DATE_DIFFERENCE_UNIT_MONTHS === $differenceUnit) {
$diff = $end->diff($start); $diff = $end->diff($start);
/* // Difference between dates in months should be returned only?
* Difference between dates in months should be returned only?
*/
if (self::DATE_DIFFERENCE_UNIT_MONTHS === $differenceUnit) { if (self::DATE_DIFFERENCE_UNIT_MONTHS === $differenceUnit) {
return $diff->m; return $diff->m;
} }
@@ -427,55 +415,41 @@ class Date
if (null === $differenceUnit || in_array($differenceUnit, $relatedUnits, true)) { if (null === $differenceUnit || in_array($differenceUnit, $relatedUnits, true)) {
$days = (int)floor($dateDiff / $daySeconds); $days = (int)floor($dateDiff / $daySeconds);
/* // Difference between dates in days should be returned only?
* Difference between dates in days should be returned only?
*/
if (self::DATE_DIFFERENCE_UNIT_DAYS === $differenceUnit) { if (self::DATE_DIFFERENCE_UNIT_DAYS === $differenceUnit) {
return $days; return $days;
} }
/* // All units should be returned?
* All units should be returned?
*/
if (null === $differenceUnit) { if (null === $differenceUnit) {
$difference[self::DATE_DIFFERENCE_UNIT_DAYS] = $days; $difference[self::DATE_DIFFERENCE_UNIT_DAYS] = $days;
} }
/* // Calculation for later usage
* Calculation for later usage
*/
$daysInSeconds = $days * $daySeconds; $daysInSeconds = $days * $daySeconds;
} }
if (null === $differenceUnit || in_array($differenceUnit, $relatedUnits, true)) { if (null === $differenceUnit || in_array($differenceUnit, $relatedUnits, true)) {
$hours = (int)floor(($dateDiff - $daysInSeconds) / $hourSeconds); $hours = (int)floor(($dateDiff - $daysInSeconds) / $hourSeconds);
/* // Difference between dates in hours should be returned only?
* Difference between dates in hours should be returned only?
*/
if (self::DATE_DIFFERENCE_UNIT_HOURS === $differenceUnit) { if (self::DATE_DIFFERENCE_UNIT_HOURS === $differenceUnit) {
return $hours; return $hours;
} }
/* // All units should be returned?
* All units should be returned?
*/
if (null === $differenceUnit) { if (null === $differenceUnit) {
$difference[self::DATE_DIFFERENCE_UNIT_HOURS] = $hours; $difference[self::DATE_DIFFERENCE_UNIT_HOURS] = $hours;
} }
/* // Calculation for later usage
* Calculation for later usage
*/
$hoursInSeconds = $hours * $hourSeconds; $hoursInSeconds = $hours * $hourSeconds;
} }
if (null === $differenceUnit || self::DATE_DIFFERENCE_UNIT_MINUTES === $differenceUnit) { if (null === $differenceUnit || self::DATE_DIFFERENCE_UNIT_MINUTES === $differenceUnit) {
$minutes = (int)floor(($dateDiff - $daysInSeconds - $hoursInSeconds) / 60); $minutes = (int)floor(($dateDiff - $daysInSeconds - $hoursInSeconds) / 60);
/* // Difference between dates in minutes should be returned only?
* Difference between dates in minutes should be returned only?
*/
if (self::DATE_DIFFERENCE_UNIT_MINUTES === $differenceUnit) { if (self::DATE_DIFFERENCE_UNIT_MINUTES === $differenceUnit) {
return $minutes; return $minutes;
} }
@@ -583,7 +557,7 @@ class Date
* @param string $dateFormat (optional) Format of date used to verify if given value is actually a date. * @param string $dateFormat (optional) Format of date used to verify if given value is actually a date.
* It should be format matched to the given value, e.g. "Y-m-d H:i" for * It should be format matched to the given value, e.g. "Y-m-d H:i" for
* "2015-01-01 10:00" value. Default: "Y-m-d". * "2015-01-01 10:00" value. Default: "Y-m-d".
* @return DateTime|bool * @return bool|DateTime
*/ */
public static function getDateTime($value, $allowCompoundFormats = false, $dateFormat = 'Y-m-d') public static function getDateTime($value, $allowCompoundFormats = false, $dateFormat = 'Y-m-d')
{ {
@@ -710,28 +684,19 @@ class Date
return false; return false;
} }
/*
* Datetime to string
*/
$formatted = (new DateTime())->format($format); $formatted = (new DateTime())->format($format);
/* // Formatted date it's the format who is validated?
* Formatted date it's the format who is validated? // The format is invalid
* The format is invalid
*/
if ($formatted === $format) { if ($formatted === $format) {
return false; return false;
} }
/* // Validate the format used to create the datetime
* Validate the format used to create the datetime
*/
$fromFormat = DateTime::createFromFormat($format, $formatted); $fromFormat = DateTime::createFromFormat($format, $formatted);
/* // It's instance of DateTime?
* It's instance of DateTime? // The format is valid
* The format is valid
*/
if ($fromFormat instanceof DateTime) { if ($fromFormat instanceof DateTime) {
return true; return true;
} }

View File

@@ -706,9 +706,6 @@ class MimeTypes
continue; continue;
} }
/*
* Extensions should be returned as upper case?
*/
if ($asUpperCase) { if ($asUpperCase) {
if (is_array($extension)) { if (is_array($extension)) {
array_walk($extension, function (&$value) { array_walk($extension, function (&$value) {
@@ -729,7 +726,7 @@ class MimeTypes
* Returns extension for given mime type * Returns extension for given mime type
* *
* @param string $mimeType The mime type, e.g. "video/mpeg" * @param string $mimeType The mime type, e.g. "video/mpeg"
* @return string|array * @return array|string
*/ */
public static function getExtension($mimeType) public static function getExtension($mimeType)
{ {
@@ -772,29 +769,24 @@ class MimeTypes
return ''; return '';
} }
/* // 1st possibility: the finfo class
* 1st possibility: the finfo class
*/
if (class_exists('finfo')) { if (class_exists('finfo')) {
$finfo = new \finfo(); $finfo = new \finfo();
return $finfo->file($filePath, FILEINFO_MIME_TYPE); return $finfo->file($filePath, FILEINFO_MIME_TYPE);
} }
/* // 2nd possibility: the mime_content_type function
* 2nd possibility: the mime_content_type function
*/
if (function_exists('mime_content_type')) { if (function_exists('mime_content_type')) {
return mime_content_type($filePath); return mime_content_type($filePath);
} }
/* // Oops, there is no possibility to read the mime type
* Oops, there is no possibility to read the mime type
*/
$template = 'Neither \'finfo\' class nor \'mime_content_type\' function exists. There is no way to read the' $template = 'Neither \'finfo\' class nor \'mime_content_type\' function exists. There is no way to read the'
. ' mime type of file \'%s\'.'; . ' mime type of file \'%s\'.';
$message = sprintf($template, $filePath); $message = sprintf($template, $filePath);
throw new \RuntimeException($message); throw new \RuntimeException($message);
} }

View File

@@ -27,7 +27,7 @@ class Miscellaneous
* Otherwise - only content of given directory is returned. * Otherwise - only content of given directory is returned.
* @param int $maxFilesCount (optional) Maximum files that will be returned. If it's null, all files are * @param int $maxFilesCount (optional) Maximum files that will be returned. If it's null, all files are
* returned. * returned.
* @return array|null * @return null|array
*/ */
public static function getDirectoryContent($directoryPath, $recursive = false, $maxFilesCount = null) public static function getDirectoryContent($directoryPath, $recursive = false, $maxFilesCount = null)
{ {
@@ -222,11 +222,6 @@ class Miscellaneous
*/ */
public static function getUniqueFileName($originalFileName, $objectId = 0) public static function getUniqueFileName($originalFileName, $objectId = 0)
{ {
/*
* Get parts of the file name:
* - without extension
* - and... the extension
*/
$withoutExtension = self::getFileNameWithoutExtension($originalFileName); $withoutExtension = self::getFileNameWithoutExtension($originalFileName);
$extension = self::getFileExtension($originalFileName, true); $extension = self::getFileExtension($originalFileName, true);
@@ -238,20 +233,13 @@ class Miscellaneous
*/ */
$withoutExtension = Urlizer::urlize($withoutExtension); $withoutExtension = Urlizer::urlize($withoutExtension);
/* // Now I have to complete the template used to build / generate unique name
* Now I have to complete the template used to build / generate unique name
*/
$template = '%s-%s.%s'; // [file's name]-[unique key].[file's extension] $template = '%s-%s.%s'; // [file's name]-[unique key].[file's extension]
/* // Add some uniqueness
* Add some uniqueness
*/
$unique = self::getUniqueString(mt_rand()); $unique = self::getUniqueString(mt_rand());
/* // Finally build and return the unique name
* Finally build and return the unique name
*/
if ($objectId > 0) { if ($objectId > 0) {
$template = '%s-%s-%s.%s'; // [file's name]-[unique key]-[object ID].[file's extension] $template = '%s-%s-%s.%s'; // [file's name]-[unique key]-[object ID].[file's extension]
@@ -345,9 +333,7 @@ class Miscellaneous
$converted = $converter->transliterate($string); $converted = $converter->transliterate($string);
/* // Make the string lowercase and human-readable
* Make the string lowercase and human-readable
*/
if ($lowerCaseHuman) { if ($lowerCaseHuman) {
$matches = []; $matches = [];
$matchCount = preg_match_all('|[A-Z]{1}[^A-Z]*|', $converted, $matches); $matchCount = preg_match_all('|[A-Z]{1}[^A-Z]*|', $converted, $matches);
@@ -390,10 +376,10 @@ class Miscellaneous
* Replaces part of string with other string or strings. * Replaces part of string with other string or strings.
* There is a few combination of what should be searched and with what it should be replaced. * There is a few combination of what should be searched and with what it should be replaced.
* *
* @param string|array $subject The string or an array of strings to search and replace * @param array|string $subject The string or an array of strings to search and replace
* @param string|array $search String or pattern or array of patterns to find. It may be: string, an array * @param array|string $search String or pattern or array of patterns to find. It may be: string, an array
* of strings or an array of patterns. * of strings or an array of patterns.
* @param string|array $replacement The string or an array of strings to replace. It may be: string or an array * @param array|string $replacement The string or an array of strings to replace. It may be: string or an array
* of strings. * of strings.
* @param bool $quoteStrings (optional) If is set to true, strings are surrounded with single quote sign * @param bool $quoteStrings (optional) If is set to true, strings are surrounded with single quote sign
* @return string * @return string
@@ -466,9 +452,7 @@ class Miscellaneous
} }
} }
/* // 1st step: replace strings, simple operation with strings
* 1st step: replace strings, simple operation with strings
*/
if ($bothAreStrings) { if ($bothAreStrings) {
$effect = str_replace($search, $replacement, $subject); $effect = str_replace($search, $replacement, $subject);
} }
@@ -503,15 +487,10 @@ class Miscellaneous
$effect = []; $effect = [];
} }
/*
* I have to make the subject an array...
*/
$subject = Arrays::makeArray($subject); $subject = Arrays::makeArray($subject);
/* // I have to iterate through the subjects, because explode() function expects strings as both arguments
* ...and use iterate through the subjects, // (1st and 2nd)
* because explode() function expects strings as both arguments (1st and 2nd)
*/
foreach ($subject as $subSubject) { foreach ($subject as $subSubject) {
$subEffect = ''; $subEffect = '';
@@ -521,9 +500,7 @@ class Miscellaneous
foreach ($exploded as $key => $item) { foreach ($exploded as $key => $item) {
$subEffect .= $item; $subEffect .= $item;
/* // The replacement shouldn't be included when the searched string was not found
* The replacement shouldn't be included when the searched string was not found
*/
if ($explodedCount > 1 && $key < $explodedCount - 1 && isset($replacement[$key])) { if ($explodedCount > 1 && $key < $explodedCount - 1 && isset($replacement[$key])) {
$subEffect .= $replacement[$key]; $subEffect .= $replacement[$key];
} }
@@ -531,6 +508,7 @@ class Miscellaneous
if ($subjectIsArray) { if ($subjectIsArray) {
$effect[] = $subEffect; $effect[] = $subEffect;
continue; continue;
} }
@@ -571,7 +549,6 @@ class Miscellaneous
public static function getOperatingSystemNameServer() public static function getOperatingSystemNameServer()
{ {
return PHP_OS; return PHP_OS;
/* /*
* Previous version: * Previous version:
* return php_uname('s'); * return php_uname('s');
@@ -668,7 +645,7 @@ class Miscellaneous
$spacePosition = mb_strrpos($lineWithAberration, ' ', 0, $encoding); $spacePosition = mb_strrpos($lineWithAberration, ' ', 0, $encoding);
if (false !== $spacePosition && 0 < $spacePosition) { if (false !== $spacePosition && 0 < $spacePosition) {
/* @var int $spacePosition */ /** @var int $spacePosition */
$perLine = $spacePosition; $perLine = $spacePosition;
$insertSeparator = true; $insertSeparator = true;
} }
@@ -705,7 +682,7 @@ class Miscellaneous
* @param string $directoryPath Directory path * @param string $directoryPath Directory path
* @param bool $contentOnly (optional) If is set to true, only content of the directory is removed, not * @param bool $contentOnly (optional) If is set to true, only content of the directory is removed, not
* directory itself. Otherwise - directory is removed too (default behaviour). * directory itself. Otherwise - directory is removed too (default behaviour).
* @return bool|null * @return null|bool
*/ */
public static function removeDirectory($directoryPath, $contentOnly = false) public static function removeDirectory($directoryPath, $contentOnly = false)
{ {
@@ -735,9 +712,7 @@ class Miscellaneous
} }
} }
/* // Directory should be removed too?
* Directory should be removed too?
*/
if (!$contentOnly) { if (!$contentOnly) {
return rmdir($directoryPath); return rmdir($directoryPath);
} }
@@ -789,7 +764,7 @@ class Miscellaneous
* Make a string's first character lowercase * Make a string's first character lowercase
* *
* @param string $text The text to get first character lowercase * @param string $text The text to get first character lowercase
* @param bool|null $restLowercase (optional) Information that to do with rest of given string * @param null|bool $restLowercase (optional) Information that to do with rest of given string
* @return string * @return string
* *
* Values of the $restLowercase argument: * Values of the $restLowercase argument:
@@ -818,7 +793,7 @@ class Miscellaneous
* Make a string's first character uppercase * Make a string's first character uppercase
* *
* @param string $text The text to get uppercase * @param string $text The text to get uppercase
* @param bool|null $restLowercase (optional) Information that to do with rest of given string * @param null|bool $restLowercase (optional) Information that to do with rest of given string
* @return string * @return string
* *
* Values of the $restLowercase argument: * Values of the $restLowercase argument:
@@ -932,7 +907,7 @@ class Miscellaneous
* *
* @param string $string The string to check * @param string $string The string to check
* @param string $separator The separator which divides elements of string * @param string $separator The separator which divides elements of string
* @return string|null * @return null|string
*/ */
public static function getLastElementOfString($string, $separator) public static function getLastElementOfString($string, $separator)
{ {
@@ -980,30 +955,23 @@ class Miscellaneous
* - concatenatePaths(['path/first', 'path/second', 'path/third']); * - concatenatePaths(['path/first', 'path/second', 'path/third']);
* - concatenatePaths('path/first', 'path/second', 'path/third'); * - concatenatePaths('path/first', 'path/second', 'path/third');
* *
* @param string|array $paths Paths co concatenate. As described above: an array of paths / strings or strings * @param array|string $paths Paths co concatenate. As described above: an array of paths / strings or strings
* passed as following arguments. * passed as following arguments.
* @return string * @return string
*/ */
public static function concatenatePaths($paths) public static function concatenatePaths($paths)
{ {
/* // If paths are not provided as array, get the paths from methods' arguments
* If paths are not provided as array, get the paths from methods' arguments
*/
if (!is_array($paths)) { if (!is_array($paths)) {
$paths = func_get_args(); $paths = func_get_args();
} }
/* // No paths provided?
* No paths provided? // Nothing to do
* Nothing to do
*/
if (empty($paths)) { if (empty($paths)) {
return ''; return '';
} }
/*
* Some useful variables
*/
$concatenated = ''; $concatenated = '';
$firstWindowsBased = false; $firstWindowsBased = false;
$separator = DIRECTORY_SEPARATOR; $separator = DIRECTORY_SEPARATOR;
@@ -1011,16 +979,12 @@ class Miscellaneous
foreach ($paths as $path) { foreach ($paths as $path) {
$path = trim($path); $path = trim($path);
/* // Empty paths are useless
* Empty paths are useless
*/
if (empty($path)) { if (empty($path)) {
continue; continue;
} }
/* // Does the first path is a Windows-based path?
* Does the first path is a Windows-based path?
*/
if (Arrays::isFirstElement($paths, $path)) { if (Arrays::isFirstElement($paths, $path)) {
$firstWindowsBased = Regex::isWindowsBasedPath($path); $firstWindowsBased = Regex::isWindowsBasedPath($path);
@@ -1029,14 +993,10 @@ class Miscellaneous
} }
} }
/* // Remove the starting / beginning directory's separator
* Remove the starting / beginning directory's separator
*/
$path = self::removeStartingDirectorySeparator($path, $separator); $path = self::removeStartingDirectorySeparator($path, $separator);
/* // Removes the ending directory's separator
* Removes the ending directory's separator
*/
$path = self::removeEndingDirectorySeparator($path, $separator); $path = self::removeEndingDirectorySeparator($path, $separator);
/* /*
@@ -1046,12 +1006,11 @@ class Miscellaneous
*/ */
if ($firstWindowsBased && empty($concatenated)) { if ($firstWindowsBased && empty($concatenated)) {
$concatenated = $path; $concatenated = $path;
continue; continue;
} }
/* // Concatenate the paths / strings with OS-related directory separator between them (slash or backslash)
* Concatenate the paths / strings with OS-related directory separator between them (slash or backslash)
*/
$concatenated = sprintf('%s%s%s', $concatenated, $separator, $path); $concatenated = sprintf('%s%s%s', $concatenated, $separator, $path);
} }
@@ -1138,22 +1097,23 @@ class Miscellaneous
switch ($globalSourceType) { switch ($globalSourceType) {
case INPUT_GET: case INPUT_GET:
$globalSource = $_GET; $globalSource = $_GET;
break;
break;
case INPUT_POST: case INPUT_POST:
$globalSource = $_POST; $globalSource = $_POST;
break;
break;
case INPUT_COOKIE: case INPUT_COOKIE:
$globalSource = $_COOKIE; $globalSource = $_COOKIE;
break;
break;
case INPUT_SERVER: case INPUT_SERVER:
$globalSource = $_SERVER; $globalSource = $_SERVER;
break;
break;
case INPUT_ENV: case INPUT_ENV:
$globalSource = $_ENV; $globalSource = $_ENV;
break; break;
} }
@@ -1201,6 +1161,7 @@ class Miscellaneous
for ($i = ($length - $textLength); 0 < $i; --$i) { for ($i = ($length - $textLength); 0 < $i; --$i) {
if ($before) { if ($before) {
$text = '0' . $text; $text = '0' . $text;
continue; continue;
} }
@@ -1213,9 +1174,9 @@ class Miscellaneous
/** /**
* Returns information if given value is located in interval between given utmost left and right values * Returns information if given value is located in interval between given utmost left and right values
* *
* @param int|float $value Value to verify * @param float|int $value Value to verify
* @param int|float $left Left utmost value of interval * @param float|int $left Left utmost value of interval
* @param int|float $right Right utmost value of interval * @param float|int $right Right utmost value of interval
* @return bool * @return bool
*/ */
public static function isBetween($value, $left, $right) public static function isBetween($value, $left, $right)
@@ -1277,9 +1238,7 @@ class Miscellaneous
*/ */
public static function getInvertedColor($color) public static function getInvertedColor($color)
{ {
/* // Prepare the color for later usage
* Prepare the color for later usage
*/
$color = trim($color); $color = trim($color);
$withHash = Regex::startsWith($color, '#'); $withHash = Regex::startsWith($color, '#');
@@ -1289,23 +1248,17 @@ class Miscellaneous
*/ */
$validColor = Regex::getValidColorHexValue($color); $validColor = Regex::getValidColorHexValue($color);
/* // Grab color's components
* Grab color's components
*/
$red = hexdec(substr($validColor, 0, 2)); $red = hexdec(substr($validColor, 0, 2));
$green = hexdec(substr($validColor, 2, 2)); $green = hexdec(substr($validColor, 2, 2));
$blue = hexdec(substr($validColor, 4, 2)); $blue = hexdec(substr($validColor, 4, 2));
/* // Calculate inverted color's components
* Calculate inverted color's components
*/
$redInverted = self::getValidColorComponent(255 - $red); $redInverted = self::getValidColorComponent(255 - $red);
$greenInverted = self::getValidColorComponent(255 - $green); $greenInverted = self::getValidColorComponent(255 - $green);
$blueInverted = self::getValidColorComponent(255 - $blue); $blueInverted = self::getValidColorComponent(255 - $blue);
/* // Voila, here is the inverted color
* Voila, here is the inverted color
*/
$invertedColor = sprintf('%s%s%s', $redInverted, $greenInverted, $blueInverted); $invertedColor = sprintf('%s%s%s', $redInverted, $greenInverted, $blueInverted);
if ($withHash) { if ($withHash) {
@@ -1328,9 +1281,7 @@ class Miscellaneous
$fileName = 'composer.json'; $fileName = 'composer.json';
$directoryPath = __DIR__; $directoryPath = __DIR__;
/* // Path of directory it's not the path of last directory?
* Path of directory it's not the path of last directory?
*/
while (DIRECTORY_SEPARATOR !== $directoryPath) { while (DIRECTORY_SEPARATOR !== $directoryPath) {
$filePath = static::concatenatePaths($directoryPath, $fileName); $filePath = static::concatenatePaths($directoryPath, $fileName);

View File

@@ -27,7 +27,7 @@ class QueryBuilderUtility
* If null is returned, alias was not found. * If null is returned, alias was not found.
* *
* @param QueryBuilder $queryBuilder The query builder to retrieve root alias * @param QueryBuilder $queryBuilder The query builder to retrieve root alias
* @return string|null * @return null|string
*/ */
public static function getRootAlias(QueryBuilder $queryBuilder) public static function getRootAlias(QueryBuilder $queryBuilder)
{ {
@@ -52,7 +52,7 @@ class QueryBuilderUtility
* *
* @param QueryBuilder $queryBuilder The query builder to verify * @param QueryBuilder $queryBuilder The query builder to verify
* @param string $property Name of property that maybe is joined * @param string $property Name of property that maybe is joined
* @return string|null * @return null|string
*/ */
public static function getJoinedPropertyAlias(QueryBuilder $queryBuilder, $property) public static function getJoinedPropertyAlias(QueryBuilder $queryBuilder, $property)
{ {
@@ -70,7 +70,7 @@ class QueryBuilderUtility
$pattern = sprintf($patternTemplate, $property); $pattern = sprintf($patternTemplate, $property);
foreach ($joins as $joinExpressions) { foreach ($joins as $joinExpressions) {
/* @var $expression Join */ /** @var Join $expression */
foreach ($joinExpressions as $expression) { foreach ($joinExpressions as $expression) {
$joinedProperty = $expression->getJoin(); $joinedProperty = $expression->getJoin();
@@ -90,7 +90,7 @@ class QueryBuilderUtility
* @param array $criteria (optional) The criteria used in WHERE clause. It may simple array with pairs * @param array $criteria (optional) The criteria used in WHERE clause. It may simple array with pairs
* key-value or an array of arrays where second element of sub-array is the * key-value or an array of arrays where second element of sub-array is the
* comparison operator. Example below. * comparison operator. Example below.
* @param string|null $alias (optional) Alias used in the query * @param null|string $alias (optional) Alias used in the query
* @return QueryBuilder * @return QueryBuilder
* *
* Example of the $criteria argument: * Example of the $criteria argument:
@@ -173,9 +173,7 @@ class QueryBuilderUtility
$entityManager->remove($entity); $entityManager->remove($entity);
} }
/* // The deleted objects should be flushed?
* The deleted objects should be flushed?
*/
if ($flushDeleted) { if ($flushDeleted) {
$entityManager->flush(); $entityManager->flush();
} }

View File

@@ -74,7 +74,7 @@ class Reflection
* Constants whose values are integers are considered only. * Constants whose values are integers are considered only.
* *
* @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 int|null * @return null|int
*/ */
public static function getMaxNumberConstant($class) public static function getMaxNumberConstant($class)
{ {
@@ -249,6 +249,7 @@ class Reflection
$value = $object->{$getterName}(); $value = $object->{$getterName}();
$valueFound = true; $valueFound = true;
break; break;
} }
} }
@@ -275,7 +276,7 @@ class Reflection
* Returns values of given property for given objects. * Returns values of given property for given objects.
* Looks for proper getter for the property. * Looks for proper getter for the property.
* *
* @param Collection|object|array $objects The objects that should contain given property. It may be also one * @param array|Collection|object $objects The objects that should contain given property. It may be also one
* object. * object.
* @param string $property Name of the property that contains a value * @param string $property Name of the property that contains a value
* @param bool $force (optional) If is set to true, try to retrieve value even if the * @param bool $force (optional) If is set to true, try to retrieve value even if the
@@ -316,7 +317,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
* @param bool $withoutNamespace (optional) If is set to true, namespace is omitted. Otherwise - * @param bool $withoutNamespace (optional) If is set to true, namespace is omitted. Otherwise -
* not, full name of class is returned, with namespace. * not, full name of class is returned, with namespace.
* @return string|null * @return null|string
*/ */
public static function getClassName($source, $withoutNamespace = false) public static function getClassName($source, $withoutNamespace = false)
{ {
@@ -338,9 +339,7 @@ class Reflection
$source = Arrays::getFirstElement($source); $source = Arrays::getFirstElement($source);
} }
/* // Let's prepare name of class
* Let's prepare name of class
*/
if (is_object($source)) { if (is_object($source)) {
$name = get_class($source); $name = get_class($source);
} elseif (is_string($source) && (class_exists($source) || trait_exists($source))) { } elseif (is_string($source) && (class_exists($source) || trait_exists($source))) {
@@ -472,7 +471,7 @@ 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 \ReflectionClass|bool * @return bool|\ReflectionClass
*/ */
public static function getParentClass($source) public static function getParentClass($source)
{ {
@@ -489,7 +488,7 @@ class Reflection
* @param array|object|string $class Class who child classes should be returned. An array of objects, strings, * @param array|object|string $class Class who child classes should be returned. An array of objects, strings,
* object or string. * object or string.
* @throws CannotResolveClassNameException * @throws CannotResolveClassNameException
* @return array|null * @return null|array
*/ */
public static function getChildClasses($class) public static function getChildClasses($class)
{ {
@@ -505,9 +504,7 @@ class Reflection
$className = self::getClassName($class); $className = self::getClassName($class);
/* // Oops, cannot resolve class
* Oops, cannot resolve class
*/
if (null === $className) { if (null === $className) {
throw CannotResolveClassNameException::create($class); throw CannotResolveClassNameException::create($class);
} }
@@ -577,7 +574,7 @@ 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 \ReflectionProperty|null * @return null|\ReflectionProperty
*/ */
public static function getProperty($class, $property, $filter = null) public static function getProperty($class, $property, $filter = null)
{ {
@@ -585,7 +582,7 @@ class Reflection
$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;
@@ -604,23 +601,19 @@ class Reflection
* @param bool $verifyParents If is set to true, parent classes are verified if they use given * @param bool $verifyParents If is set to true, parent classes are verified if they use given
* trait. Otherwise - not. * trait. Otherwise - not.
* @throws CannotResolveClassNameException * @throws CannotResolveClassNameException
* @return bool|null * @return null|bool
*/ */
public static function usesTrait($class, $trait, $verifyParents = false) public static function usesTrait($class, $trait, $verifyParents = false)
{ {
$className = self::getClassName($class); $className = self::getClassName($class);
$traitName = self::getClassName($trait); $traitName = self::getClassName($trait);
/* // Oops, cannot resolve class
* Oops, cannot resolve class
*/
if (null === $className || '' === $className) { if (null === $className || '' === $className) {
throw CannotResolveClassNameException::create($class); throw CannotResolveClassNameException::create($class);
} }
/* // Oops, cannot resolve trait
* Oops, cannot resolve trait
*/
if (null === $traitName || '' === $traitName) { if (null === $traitName || '' === $traitName) {
throw new CannotResolveClassNameException($class, false); throw new CannotResolveClassNameException($class, false);
} }
@@ -646,7 +639,7 @@ class Reflection
* If given class does not extend another, returns null. * If given class does not extend another, returns null.
* *
* @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 string|null * @return null|string
*/ */
public static function getParentClassName($class) public static function getParentClassName($class)
{ {
@@ -673,9 +666,7 @@ class Reflection
{ {
$reflectionProperty = self::getProperty($object, $property); $reflectionProperty = self::getProperty($object, $property);
/* // Oops, property does not exist
* Oops, property does not exist
*/
if (null === $reflectionProperty) { if (null === $reflectionProperty) {
throw NotExistingPropertyException::create($object, $property); throw NotExistingPropertyException::create($object, $property);
} }

View File

@@ -271,7 +271,7 @@ class Regex
eval(sprintf('$isEqual = %s%s;', $value, $filterExpression)); eval(sprintf('$isEqual = %s%s;', $value, $filterExpression));
/* @var bool $isEqual */ /** @var bool $isEqual */
$remove = !$isEqual; $remove = !$isEqual;
} }
@@ -317,6 +317,7 @@ class Regex
$effect = $effect && $matched; $effect = $effect && $matched;
} elseif ($matched) { } elseif ($matched) {
$effect = $matched; $effect = $matched;
break; break;
} }
} }
@@ -458,14 +459,10 @@ class Regex
return false; return false;
} }
/* // I have to escape all slashes (directory separators): "/" -> "\/"
* I have to escape all slashes (directory separators): "/" -> "\/"
*/
$prepared = preg_quote($path, '/'); $prepared = preg_quote($path, '/');
/* // Slash at the ending is optional
* Slash at the ending is optional
*/
if (self::endsWith($path, '/')) { if (self::endsWith($path, '/')) {
$prepared .= '?'; $prepared .= '?';
} }
@@ -775,7 +772,7 @@ class Regex
* (default behaviour). Otherwise - not. * (default behaviour). Otherwise - not.
* @throws IncorrectColorHexLengthException * @throws IncorrectColorHexLengthException
* @throws InvalidColorHexValueException * @throws InvalidColorHexValueException
* @return string|bool * @return bool|string
*/ */
public static function getValidColorHexValue($color, $throwException = true) public static function getValidColorHexValue($color, $throwException = true)
{ {
@@ -986,7 +983,7 @@ class Regex
* Returns slug for given value * Returns slug for given value
* *
* @param string $value Value that should be transformed to slug * @param string $value Value that should be transformed to slug
* @return string|bool * @return bool|string
*/ */
public static function createSlug($value) public static function createSlug($value)
{ {

View File

@@ -24,7 +24,7 @@ class Repository
* *
* @var string * @var string
*/ */
const POSITION_KEY = 'position'; public const POSITION_KEY = 'position';
/** /**
* Replenishes positions of given items * Replenishes positions of given items
@@ -57,24 +57,17 @@ class Repository
} }
foreach ($items as &$item) { foreach ($items as &$item) {
/* // Not sortable?
* The item is not sortable?
*/
if (!self::isSortable($item)) { if (!self::isSortable($item)) {
continue; continue;
} }
/* // Sorted already (position has been set)?
* Position has been set?
* Nothing to do
*/
if (self::isSorted($item)) { if (self::isSorted($item)) {
continue; continue;
} }
/* // Calculate position
* Calculate position
*/
if ($asLast) { if ($asLast) {
++$position; ++$position;
} else { } else {
@@ -87,6 +80,7 @@ class Repository
*/ */
if (is_object($item)) { if (is_object($item)) {
$item->setPosition($position); $item->setPosition($position);
continue; continue;
} }
@@ -118,31 +112,23 @@ class Repository
$extreme = null; $extreme = null;
foreach ($items as $item) { foreach ($items as $item) {
/* // Not sortable?
* The item is not sortable?
*/
if (!self::isSortable($item)) { if (!self::isSortable($item)) {
continue; continue;
} }
$position = null; $position = null;
/* // Let's grab the position
* Let's grab the position
*/
if (is_object($item)) { if (is_object($item)) {
$position = $item->getPosition(); $position = $item->getPosition();
} elseif (array_key_exists(static::POSITION_KEY, $item)) { } elseif (array_key_exists(static::POSITION_KEY, $item)) {
$position = $item[static::POSITION_KEY]; $position = $item[static::POSITION_KEY];
} }
/* // Maximum value is expected?
* Maximum value is expected?
*/
if ($max) { if ($max) {
/* // Position was found and it's larger than previously found position (the extreme position)?
* Position was found and it's larger than previously found position (the extreme position)?
*/
if (null === $extreme || (null !== $position && $position > $extreme)) { if (null === $extreme || (null !== $position && $position > $extreme)) {
$extreme = $position; $extreme = $position;
} }
@@ -218,17 +204,12 @@ class Repository
*/ */
private static function isSorted($item) private static function isSorted($item)
{ {
/* // Not sortable?
* Given item is not sortable?
*/
if (!self::isSortable($item)) { if (!self::isSortable($item)) {
return false; return false;
} }
/* // It's an object or it's an array and position has been set?
* It's an object or it's an array
* and position has been set?
*/
return return
(is_object($item) && null !== $item->getPosition()) (is_object($item) && null !== $item->getPosition())

View File

@@ -90,9 +90,7 @@ class Uri
* $matches[2] - protocol version, e.g. 1.1 * $matches[2] - protocol version, e.g. 1.1
*/ */
/* // Oops, cannot match protocol
* Oops, cannot match protocol
*/
if (0 === $matchCount) { if (0 === $matchCount) {
return ''; return '';
} }
@@ -244,9 +242,7 @@ class Uri
$currentUrl = self::getServerNameOrIp(true); $currentUrl = self::getServerNameOrIp(true);
$url = self::replenishProtocol($url); $url = self::replenishProtocol($url);
/* // Let's prepare pattern of current url
* Let's prepare pattern of current url
*/
$search = [ $search = [
':', ':',
'/', '/',
@@ -274,9 +270,7 @@ class Uri
*/ */
public static function replenishProtocol($url, $protocol = '') public static function replenishProtocol($url, $protocol = '')
{ {
/* // Let's trim the url
* Let's trim the url
*/
if (is_string($url)) { if (is_string($url)) {
$url = trim($url); $url = trim($url);
} }
@@ -297,9 +291,7 @@ class Uri
return $url; return $url;
} }
/* // Protocol is not provided?
* Protocol is not provided?
*/
if (empty($protocol)) { if (empty($protocol)) {
$protocol = self::getProtocolName(); $protocol = self::getProtocolName();
} }

View File

@@ -44,7 +44,7 @@ class Company
* *
* @param string $name Name of company * @param string $name Name of company
* @param Address $address Address of company * @param Address $address Address of company
* @param BankAccount|null $bankAccount (optional) Bank account of company * @param null|BankAccount $bankAccount (optional) Bank account of company
*/ */
public function __construct($name, Address $address, BankAccount $bankAccount = null) public function __construct($name, Address $address, BankAccount $bankAccount = null)
{ {
@@ -92,7 +92,7 @@ class Company
/** /**
* Returns bank account of company * Returns bank account of company
* *
* @return BankAccount|null * @return null|BankAccount
*/ */
public function getBankAccount() public function getBankAccount()
{ {

View File

@@ -195,7 +195,7 @@ class Size
* @param string $size The size represented as string (width and height separated by given separator) * @param string $size The size represented as string (width and height separated by given separator)
* @param string $unit (optional) Unit used when width or height should be returned with unit. Default: "px". * @param string $unit (optional) Unit used when width or height should be returned with unit. Default: "px".
* @param string $separator (optional) Separator used to split width and height. Default: " x ". * @param string $separator (optional) Separator used to split width and height. Default: " x ".
* @return Size|null * @return null|Size
*/ */
public static function fromString($size, $unit = 'px', $separator = ' x ') public static function fromString($size, $unit = 'px', $separator = ' x ')
{ {
@@ -223,7 +223,7 @@ class Size
* *
* @param array $array The size represented as array * @param array $array The size represented as array
* @param string $unit (optional) Unit used when width or height should be returned with unit. Default: "px". * @param string $unit (optional) Unit used when width or height should be returned with unit. Default: "px".
* @return Size|null * @return null|Size
*/ */
public static function fromArray(array $array, $unit = 'px') public static function fromArray(array $array, $unit = 'px')
{ {

View File

@@ -54,6 +54,16 @@ class Version
$this->patchPart = $patchPart; $this->patchPart = $patchPart;
} }
/**
* Returns representation of object as string
*
* @return string
*/
public function __toString()
{
return sprintf('%d.%d.%d', $this->getMajorPart(), $this->getMinorPart(), $this->getPatchPart());
}
/** /**
* Returns the "major" part. * Returns the "major" part.
* Incremented when you make incompatible API changes. * Incremented when you make incompatible API changes.
@@ -87,16 +97,6 @@ class Version
return $this->patchPart; return $this->patchPart;
} }
/**
* Returns representation of object as string
*
* @return string
*/
public function __toString()
{
return sprintf('%d.%d.%d', $this->getMajorPart(), $this->getMinorPart(), $this->getPatchPart());
}
/** /**
* Returns new instance based on given version as string. * Returns new instance based on given version as string.
* Given version should contain 3 dot-separated integers, 1 per each part ("major", "minor" and "patch"). * Given version should contain 3 dot-separated integers, 1 per each part ("major", "minor" and "patch").
@@ -106,7 +106,7 @@ class Version
* "10.4.0"; * "10.4.0";
* *
* @param string $version The version * @param string $version The version
* @return Version|null * @return null|Version
*/ */
public static function fromString(string $version) public static function fromString(string $version)
{ {
@@ -148,7 +148,7 @@ class Version
* [10, 4, 0]; * [10, 4, 0];
* *
* @param array $version The version * @param array $version The version
* @return Version|null * @return null|Version
*/ */
public static function fromArray(array $version) public static function fromArray(array $version)
{ {

View File

@@ -19,6 +19,9 @@ use Meritoo\Common\Type\OopVisibilityType;
* *
* @author Meritoo <github@meritoo.pl> * @author Meritoo <github@meritoo.pl>
* @copyright Meritoo <http://www.meritoo.pl> * @copyright Meritoo <http://www.meritoo.pl>
*
* @internal
* @covers \Meritoo\Common\Collection\Collection
*/ */
class CollectionTest extends BaseTestCase class CollectionTest extends BaseTestCase
{ {
@@ -43,6 +46,24 @@ class CollectionTest extends BaseTestCase
*/ */
private $simpleElements; private $simpleElements;
/**
* {@inheritdoc}
*/
protected function setUp(): void
{
parent::setUp();
$this->simpleElements = [
'lorem',
'ipsum',
123 => 'dolor',
345 => 'sit',
];
$this->emptyCollection = new Collection();
$this->simpleCollection = new Collection($this->simpleElements);
}
public function testEmptyCollection() public function testEmptyCollection()
{ {
static::assertSame(0, $this->emptyCollection->count()); static::assertSame(0, $this->emptyCollection->count());
@@ -502,22 +523,4 @@ class CollectionTest extends BaseTestCase
new \DateTime('2001-01-01'), new \DateTime('2001-01-01'),
]; ];
} }
/**
* {@inheritdoc}
*/
protected function setUp(): void
{
parent::setUp();
$this->simpleElements = [
'lorem',
'ipsum',
123 => 'dolor',
345 => 'sit',
];
$this->emptyCollection = new Collection();
$this->simpleCollection = new Collection($this->simpleElements);
}
} }

View File

@@ -18,12 +18,15 @@ use Meritoo\Common\Type\OopVisibilityType;
* *
* @author Meritoo <github@meritoo.pl> * @author Meritoo <github@meritoo.pl>
* @copyright Meritoo <http://www.meritoo.pl> * @copyright Meritoo <http://www.meritoo.pl>
*
* @internal
* @covers \Meritoo\Common\Exception\Base\UnknownTypeException
*/ */
class UnknownTypeExceptionTest extends BaseTestCase class UnknownTypeExceptionTest extends BaseTestCase
{ {
public function testConstructorVisibilityAndArguments() public function testConstructorVisibilityAndArguments()
{ {
static::assertConstructorVisibilityAndArguments(UnknownTestTypeException::class, OopVisibilityType::IS_PUBLIC, 3); static::assertConstructorVisibilityAndArguments(UnknownTypeException::class, OopVisibilityType::IS_PUBLIC, 3);
} }
public function testWithoutException() public function testWithoutException()
@@ -46,9 +49,9 @@ class UnknownTypeExceptionTest extends BaseTestCase
*/ */
class TestType extends BaseType class TestType extends BaseType
{ {
const TEST_1 = 'test_1'; public const TEST_1 = 'test_1';
const TEST_2 = 'test_2'; public const TEST_2 = 'test_2';
} }
/** /**
@@ -56,6 +59,9 @@ class TestType extends BaseType
* *
* @author Meritoo <github@meritoo.pl> * @author Meritoo <github@meritoo.pl>
* @copyright Meritoo <http://www.meritoo.pl> * @copyright Meritoo <http://www.meritoo.pl>
*
* @internal
* @covers \Meritoo\Common\Exception\Base\UnknownTypeException
*/ */
class UnknownTestTypeException extends UnknownTypeException class UnknownTestTypeException extends UnknownTypeException
{ {
@@ -67,10 +73,7 @@ class UnknownTestTypeException extends UnknownTypeException
*/ */
public static function createException($unknownType) public static function createException($unknownType)
{ {
/* @var UnknownTestTypeException $exception */ return parent::create($unknownType, new TestType(), 'type of something used for testing');
$exception = parent::create($unknownType, new TestType(), 'type of something used for testing');
return $exception;
} }
} }

View File

@@ -17,6 +17,9 @@ use Meritoo\Common\Type\OopVisibilityType;
* *
* @author Meritoo <github@meritoo.pl> * @author Meritoo <github@meritoo.pl>
* @copyright Meritoo <http://www.meritoo.pl> * @copyright Meritoo <http://www.meritoo.pl>
*
* @internal
* @covers \Meritoo\Common\Exception\Bundle\IncorrectBundleNameException
*/ */
class IncorrectBundleNameExceptionTest extends BaseTestCase class IncorrectBundleNameExceptionTest extends BaseTestCase
{ {

View File

@@ -19,6 +19,9 @@ use Meritoo\Common\Type\OopVisibilityType;
* *
* @author Meritoo <github@meritoo.pl> * @author Meritoo <github@meritoo.pl>
* @copyright Meritoo <http://www.meritoo.pl> * @copyright Meritoo <http://www.meritoo.pl>
*
* @internal
* @covers \Meritoo\Common\Exception\Type\UnknownDatePartTypeException
*/ */
class UnknownDatePartTypeExceptionTest extends BaseTestCase class UnknownDatePartTypeExceptionTest extends BaseTestCase
{ {

View File

@@ -18,6 +18,9 @@ use Meritoo\Common\Type\OopVisibilityType;
* *
* @author Meritoo <github@meritoo.pl> * @author Meritoo <github@meritoo.pl>
* @copyright Meritoo <http://www.meritoo.pl> * @copyright Meritoo <http://www.meritoo.pl>
*
* @internal
* @covers \Meritoo\Common\Exception\File\EmptyFileException
*/ */
class EmptyFileExceptionTest extends BaseTestCase class EmptyFileExceptionTest extends BaseTestCase
{ {

View File

@@ -17,6 +17,9 @@ use Meritoo\Common\Type\OopVisibilityType;
* *
* @author Meritoo <github@meritoo.pl> * @author Meritoo <github@meritoo.pl>
* @copyright Meritoo <http://www.meritoo.pl> * @copyright Meritoo <http://www.meritoo.pl>
*
* @internal
* @covers \Meritoo\Common\Exception\File\EmptyFilePathException
*/ */
class EmptyFilePathExceptionTest extends BaseTestCase class EmptyFilePathExceptionTest extends BaseTestCase
{ {

View File

@@ -18,6 +18,9 @@ use Meritoo\Common\Type\OopVisibilityType;
* *
* @author Meritoo <github@meritoo.pl> * @author Meritoo <github@meritoo.pl>
* @copyright Meritoo <http://www.meritoo.pl> * @copyright Meritoo <http://www.meritoo.pl>
*
* @internal
* @covers \Meritoo\Common\Exception\File\NotExistingFileException
*/ */
class NotExistingFileExceptionTest extends BaseTestCase class NotExistingFileExceptionTest extends BaseTestCase
{ {

View File

@@ -18,6 +18,9 @@ use Meritoo\Common\Type\OopVisibilityType;
* *
* @author Meritoo <github@meritoo.pl> * @author Meritoo <github@meritoo.pl>
* @copyright Meritoo <http://www.meritoo.pl> * @copyright Meritoo <http://www.meritoo.pl>
*
* @internal
* @covers \Meritoo\Common\Exception\Method\DisabledMethodException
*/ */
class DisabledMethodExceptionTest extends BaseTestCase class DisabledMethodExceptionTest extends BaseTestCase
{ {

View File

@@ -18,6 +18,9 @@ use Meritoo\Common\Type\OopVisibilityType;
* *
* @author Meritoo <github@meritoo.pl> * @author Meritoo <github@meritoo.pl>
* @copyright Meritoo <http://www.meritoo.pl> * @copyright Meritoo <http://www.meritoo.pl>
*
* @internal
* @covers \Meritoo\Common\Exception\Reflection\CannotResolveClassNameException
*/ */
class CannotResolveClassNameExceptionTest extends BaseTestCase class CannotResolveClassNameExceptionTest extends BaseTestCase
{ {

View File

@@ -18,6 +18,9 @@ use Meritoo\Common\Type\OopVisibilityType;
* *
* @author Meritoo <github@meritoo.pl> * @author Meritoo <github@meritoo.pl>
* @copyright Meritoo <http://www.meritoo.pl> * @copyright Meritoo <http://www.meritoo.pl>
*
* @internal
* @covers \Meritoo\Common\Exception\Reflection\MissingChildClassesException
*/ */
class MissingChildClassesExceptionTest extends BaseTestCase class MissingChildClassesExceptionTest extends BaseTestCase
{ {

View File

@@ -17,6 +17,9 @@ use Meritoo\Common\Type\OopVisibilityType;
* *
* @author Meritoo <github@meritoo.pl> * @author Meritoo <github@meritoo.pl>
* @copyright Meritoo <http://www.meritoo.pl> * @copyright Meritoo <http://www.meritoo.pl>
*
* @internal
* @covers \Meritoo\Common\Exception\Reflection\NotExistingPropertyException
*/ */
class NotExistingPropertyExceptionTest extends BaseTestCase class NotExistingPropertyExceptionTest extends BaseTestCase
{ {

View File

@@ -18,6 +18,9 @@ use Meritoo\Common\Type\OopVisibilityType;
* *
* @author Meritoo <github@meritoo.pl> * @author Meritoo <github@meritoo.pl>
* @copyright Meritoo <http://www.meritoo.pl> * @copyright Meritoo <http://www.meritoo.pl>
*
* @internal
* @covers \Meritoo\Common\Exception\Reflection\TooManyChildClassesException
*/ */
class TooManyChildClassesExceptionTest extends BaseTestCase class TooManyChildClassesExceptionTest extends BaseTestCase
{ {

View File

@@ -18,6 +18,9 @@ use Meritoo\Common\Type\OopVisibilityType;
* *
* @author Meritoo <github@meritoo.pl> * @author Meritoo <github@meritoo.pl>
* @copyright Meritoo <http://www.meritoo.pl> * @copyright Meritoo <http://www.meritoo.pl>
*
* @internal
* @covers \Meritoo\Common\Exception\Regex\IncorrectColorHexLengthException
*/ */
class IncorrectColorHexLengthExceptionTest extends BaseTestCase class IncorrectColorHexLengthExceptionTest extends BaseTestCase
{ {

View File

@@ -18,6 +18,9 @@ use Meritoo\Common\Type\OopVisibilityType;
* *
* @author Meritoo <github@meritoo.pl> * @author Meritoo <github@meritoo.pl>
* @copyright Meritoo <http://www.meritoo.pl> * @copyright Meritoo <http://www.meritoo.pl>
*
* @internal
* @covers \Meritoo\Common\Exception\Regex\InvalidColorHexValueException
*/ */
class InvalidColorHexValueExceptionTest extends BaseTestCase class InvalidColorHexValueExceptionTest extends BaseTestCase
{ {

View File

@@ -18,6 +18,9 @@ use Meritoo\Common\Type\OopVisibilityType;
* *
* @author Meritoo <github@meritoo.pl> * @author Meritoo <github@meritoo.pl>
* @copyright Meritoo <http://www.meritoo.pl> * @copyright Meritoo <http://www.meritoo.pl>
*
* @internal
* @covers \Meritoo\Common\Exception\Regex\InvalidHtmlAttributesException
*/ */
class InvalidHtmlAttributesExceptionTest extends BaseTestCase class InvalidHtmlAttributesExceptionTest extends BaseTestCase
{ {

View File

@@ -18,6 +18,9 @@ use Meritoo\Common\Type\OopVisibilityType;
* *
* @author Meritoo <github@meritoo.pl> * @author Meritoo <github@meritoo.pl>
* @copyright Meritoo <http://www.meritoo.pl> * @copyright Meritoo <http://www.meritoo.pl>
*
* @internal
* @covers \Meritoo\Common\Exception\Regex\InvalidUrlException
*/ */
class InvalidUrlExceptionTest extends BaseTestCase class InvalidUrlExceptionTest extends BaseTestCase
{ {

View File

@@ -19,6 +19,9 @@ use Meritoo\Common\Type\OopVisibilityType;
* *
* @author Meritoo <github@meritoo.pl> * @author Meritoo <github@meritoo.pl>
* @copyright Meritoo <http://www.meritoo.pl> * @copyright Meritoo <http://www.meritoo.pl>
*
* @internal
* @covers \Meritoo\Common\Exception\Type\UnknownOopVisibilityTypeException
*/ */
class UnknownOopVisibilityTypeExceptionTest extends BaseTestCase class UnknownOopVisibilityTypeExceptionTest extends BaseTestCase
{ {

View File

@@ -17,6 +17,9 @@ use Meritoo\Common\Type\OopVisibilityType;
* *
* @author Meritoo <github@meritoo.pl> * @author Meritoo <github@meritoo.pl>
* @copyright Meritoo <http://www.meritoo.pl> * @copyright Meritoo <http://www.meritoo.pl>
*
* @internal
* @covers \Meritoo\Common\Exception\ValueObject\InvalidSizeDimensionsException
*/ */
class InvalidSizeDimensionsExceptionTest extends BaseTestCase class InvalidSizeDimensionsExceptionTest extends BaseTestCase
{ {

View File

@@ -19,6 +19,9 @@ use Meritoo\Common\Utilities\GeneratorUtility;
* *
* @author Meritoo <github@meritoo.pl> * @author Meritoo <github@meritoo.pl>
* @copyright Meritoo <http://www.meritoo.pl> * @copyright Meritoo <http://www.meritoo.pl>
*
* @internal
* @covers \Meritoo\Common\Test\Base\BaseTestCase
*/ */
class BaseTestCaseTest extends BaseTestCase class BaseTestCaseTest extends BaseTestCase
{ {
@@ -67,16 +70,16 @@ class BaseTestCaseTest extends BaseTestCase
$generator = (new SimpleTestCase())->provideDateTimeInstance(); $generator = (new SimpleTestCase())->provideDateTimeInstance();
$generatedElements = GeneratorUtility::getGeneratorElements($generator); $generatedElements = GeneratorUtility::getGeneratorElements($generator);
/* @var DateTime $instance1 */ /** @var DateTime $instance1 */
$instance1 = $generatedElements[0][0]; $instance1 = $generatedElements[0][0];
/* @var DateTime $instance2 */ /** @var DateTime $instance2 */
$instance2 = $generatedElements[1][0]; $instance2 = $generatedElements[1][0];
/* @var DateTime $instance3 */ /** @var DateTime $instance3 */
$instance3 = $generatedElements[2][0]; $instance3 = $generatedElements[2][0];
/* @var DateTime $instance4 */ /** @var DateTime $instance4 */
$instance4 = $generatedElements[3][0]; $instance4 = $generatedElements[3][0];
self::assertCount(count($expectedElements), $generatedElements); self::assertCount(count($expectedElements), $generatedElements);
@@ -170,6 +173,9 @@ class BaseTestCaseTest extends BaseTestCase
* *
* @author Meritoo <github@meritoo.pl> * @author Meritoo <github@meritoo.pl>
* @copyright Meritoo <http://www.meritoo.pl> * @copyright Meritoo <http://www.meritoo.pl>
*
* @internal
* @coversNothing
*/ */
class SimpleTestCase extends BaseTestCase class SimpleTestCase extends BaseTestCase
{ {

View File

@@ -17,6 +17,9 @@ use Meritoo\Common\Type\Base\BaseType;
* *
* @author Meritoo <github@meritoo.pl> * @author Meritoo <github@meritoo.pl>
* @copyright Meritoo <http://www.meritoo.pl> * @copyright Meritoo <http://www.meritoo.pl>
*
* @internal
* @covers \Meritoo\Common\Type\Base\BaseType
*/ */
class BaseTypeTest extends BaseTestCase class BaseTypeTest extends BaseTestCase
{ {
@@ -199,7 +202,7 @@ class TestEmptyType extends BaseType
*/ */
class TestType extends BaseType class TestType extends BaseType
{ {
const TEST_1 = 'test_1'; public const TEST_1 = 'test_1';
const TEST_2 = 'test_2'; public const TEST_2 = 'test_2';
} }

View File

@@ -16,6 +16,9 @@ use Meritoo\Common\Type\DatePartType;
* *
* @author Meritoo <github@meritoo.pl> * @author Meritoo <github@meritoo.pl>
* @copyright Meritoo <http://www.meritoo.pl> * @copyright Meritoo <http://www.meritoo.pl>
*
* @internal
* @covers \Meritoo\Common\Type\DatePartType
*/ */
class DatePartTypeTest extends BaseTypeTestCase class DatePartTypeTest extends BaseTypeTestCase
{ {

View File

@@ -19,6 +19,9 @@ use Meritoo\Common\Type\OopVisibilityType;
* *
* @author Meritoo <github@meritoo.pl> * @author Meritoo <github@meritoo.pl>
* @copyright Meritoo <http://www.meritoo.pl> * @copyright Meritoo <http://www.meritoo.pl>
*
* @internal
* @covers \Meritoo\Common\Type\DatePeriod
*/ */
class DatePeriodTest extends BaseTypeTestCase class DatePeriodTest extends BaseTypeTestCase
{ {
@@ -151,9 +154,7 @@ class DatePeriodTest extends BaseTypeTestCase
$startDate = new DateTime('2001-01-01'); $startDate = new DateTime('2001-01-01');
$endDate = new DateTime('2002-02-02'); $endDate = new DateTime('2002-02-02');
/* // For start date
* For start date
*/
yield[ yield[
new DatePeriod($startDate, $endDate), new DatePeriod($startDate, $endDate),
'Y', 'Y',
@@ -182,9 +183,7 @@ class DatePeriodTest extends BaseTypeTestCase
'2001-01-01 00:00', '2001-01-01 00:00',
]; ];
/* // For end date
* For end date
*/
yield[ yield[
new DatePeriod($startDate, $endDate), new DatePeriod($startDate, $endDate),
'Y', 'Y',

View File

@@ -18,6 +18,9 @@ use Meritoo\Test\Common\Utilities\Arrays\SimpleToString;
* *
* @author Meritoo <github@meritoo.pl> * @author Meritoo <github@meritoo.pl>
* @copyright Meritoo <http://www.meritoo.pl> * @copyright Meritoo <http://www.meritoo.pl>
*
* @internal
* @covers \Meritoo\Common\Utilities\Arrays
*/ */
class ArraysTest extends BaseTestCase class ArraysTest extends BaseTestCase
{ {
@@ -27,6 +30,132 @@ class ArraysTest extends BaseTestCase
private $complexArray; private $complexArray;
private $superComplexArray; private $superComplexArray;
/**
* {@inheritdoc}
*/
protected function setUp(): void
{
parent::setUp();
$this->simpleArray = [
'Lorem',
'ipsum',
'dolor',
'sit',
'amet',
];
$this->simpleArrayWithKeys = [
'Lorem' => 'ipsum',
'dolor' => 'sit',
'amet' => 'consectetur',
];
$this->twoDimensionsArray = [
[
'lorem',
'ipsum',
'dolor',
'sit',
'amet',
],
[
'consectetur',
'adipiscing',
'elit',
],
[
'donec',
'sagittis',
'fringilla',
'eleifend',
],
];
$this->complexArray = [
'lorem' => [
'ipsum' => [
'dolor' => 'sit',
'diam' => [
'non' => 'egestas',
],
],
],
'consectetur' => 'adipiscing',
'mollis' => 1234,
2 => [],
'sit' => [
'nullam' => 'donec',
'aliquet' => [
'vitae' => [
'ligula' => 'quis',
],
],
'elit',
],
'amet' => [
'iaculis',
'primis',
],
];
$this->superComplexArray = [
'ipsum' => [
'quis' => [
'vestibulum' => [
'porta-1' => [
'turpis',
'urna',
],
'porta-2' => [
'tortor' => [
'in' => [
'dui',
'dolor' => [
'aliquam',
],
],
],
],
'porta-3' => [
1,
2,
3,
],
],
],
],
'primis' => [
[
'in',
'faucibus',
'orci',
],
[
'luctus',
'et',
'ultrices',
],
],
];
}
/**
* {@inheritdoc}
*/
protected function tearDown(): void
{
parent::tearDown();
unset(
$this->simpleArray,
$this->simpleArrayWithKeys,
$this->twoDimensionsArray,
$this->complexArray,
$this->superComplexArray
);
}
public function testConstructor() public function testConstructor()
{ {
static::assertHasNoConstructor(Arrays::class); static::assertHasNoConstructor(Arrays::class);
@@ -136,7 +265,8 @@ class ArraysTest extends BaseTestCase
self::assertSame($expected, Arrays::values2csv($array, $separator), $description); self::assertSame($expected, Arrays::values2csv($array, $separator), $description);
self::assertSame('', Arrays::values2csv($this->simpleArray), 'Simple array'); self::assertSame('', Arrays::values2csv($this->simpleArray), 'Simple array');
self::assertSame("lorem,ipsum,dolor,sit,amet\n" self::assertSame(
"lorem,ipsum,dolor,sit,amet\n"
. "consectetur,adipiscing,elit\n" . "consectetur,adipiscing,elit\n"
. 'donec,sagittis,fringilla,eleifend', . 'donec,sagittis,fringilla,eleifend',
Arrays::values2csv($this->twoDimensionsArray), Arrays::values2csv($this->twoDimensionsArray),
@@ -146,14 +276,10 @@ class ArraysTest extends BaseTestCase
public function testGetFirstKey() public function testGetFirstKey()
{ {
/* // Negative cases
* Negative cases
*/
self::assertNull(Arrays::getFirstKey([])); self::assertNull(Arrays::getFirstKey([]));
/* // Positive cases
* Positive cases
*/
self::assertEquals(0, Arrays::getFirstKey($this->simpleArray)); self::assertEquals(0, Arrays::getFirstKey($this->simpleArray));
self::assertEquals('lorem', Arrays::getFirstKey($this->complexArray)); self::assertEquals('lorem', Arrays::getFirstKey($this->complexArray));
} }
@@ -167,14 +293,10 @@ class ArraysTest extends BaseTestCase
public function testGetFirstElement() public function testGetFirstElement()
{ {
/* // Negative cases
* Negative cases
*/
self::assertNull(Arrays::getFirstElement([])); self::assertNull(Arrays::getFirstElement([]));
/* // Positive cases
* Positive cases
*/
self::assertEquals('Lorem', Arrays::getFirstElement($this->simpleArray)); self::assertEquals('Lorem', Arrays::getFirstElement($this->simpleArray));
self::assertEquals('Lorem', Arrays::getFirstElement($this->simpleArray)); self::assertEquals('Lorem', Arrays::getFirstElement($this->simpleArray));
self::assertEquals('lorem', Arrays::getFirstElement($this->twoDimensionsArray, false)); self::assertEquals('lorem', Arrays::getFirstElement($this->twoDimensionsArray, false));
@@ -191,14 +313,10 @@ class ArraysTest extends BaseTestCase
public function testGetLastElement() public function testGetLastElement()
{ {
/* // Negative cases
* Negative cases
*/
self::assertNull(Arrays::getLastElement([])); self::assertNull(Arrays::getLastElement([]));
/* // Positive cases
* Positive cases
*/
self::assertEquals('amet', Arrays::getLastElement($this->simpleArray)); self::assertEquals('amet', Arrays::getLastElement($this->simpleArray));
self::assertEquals('eleifend', Arrays::getLastElement($this->twoDimensionsArray, false)); self::assertEquals('eleifend', Arrays::getLastElement($this->twoDimensionsArray, false));
self::assertEquals('primis', Arrays::getLastElement($this->complexArray, false)); self::assertEquals('primis', Arrays::getLastElement($this->complexArray, false));
@@ -222,14 +340,10 @@ class ArraysTest extends BaseTestCase
public function testGetLastRow() public function testGetLastRow()
{ {
/* // Negative cases
* Negative cases
*/
self::assertNull(Arrays::getLastRow([])); self::assertNull(Arrays::getLastRow([]));
/* // Positive cases
* Positive cases
*/
self::assertEquals([], Arrays::getLastRow($this->simpleArray)); self::assertEquals([], Arrays::getLastRow($this->simpleArray));
self::assertEquals([], Arrays::getLastRow($this->simpleArrayWithKeys)); self::assertEquals([], Arrays::getLastRow($this->simpleArrayWithKeys));
@@ -275,14 +389,10 @@ class ArraysTest extends BaseTestCase
public function testArray2JavaScript() public function testArray2JavaScript()
{ {
/* // Negative cases
* Negative cases
*/
self::assertNull(Arrays::array2JavaScript([])); self::assertNull(Arrays::array2JavaScript([]));
/* // Positive cases
* Positive cases
*/
self::assertEquals('new Array(\'Lorem\', \'ipsum\', \'dolor\', \'sit\', \'amet\');', Arrays::array2JavaScript($this->simpleArray)); self::assertEquals('new Array(\'Lorem\', \'ipsum\', \'dolor\', \'sit\', \'amet\');', Arrays::array2JavaScript($this->simpleArray));
self::assertEquals('var letsTest = new Array(\'Lorem\', \'ipsum\', \'dolor\', \'sit\', \'amet\');', Arrays::array2JavaScript($this->simpleArray, 'letsTest')); self::assertEquals('var letsTest = new Array(\'Lorem\', \'ipsum\', \'dolor\', \'sit\', \'amet\');', Arrays::array2JavaScript($this->simpleArray, 'letsTest'));
@@ -350,7 +460,7 @@ letsTest[2] = value_2;';
/** /**
* @param string $description Description of test case * @param string $description Description of test case
* @param array|null $expected Expected new array (with quoted elements) * @param null|array $expected Expected new array (with quoted elements)
* @param array $array The array to check for string values * @param array $array The array to check for string values
* *
* @dataProvider provideArrayToQuoteStrings * @dataProvider provideArrayToQuoteStrings
@@ -365,9 +475,7 @@ letsTest[2] = value_2;';
$array = $this->simpleArray; $array = $this->simpleArray;
$string = 'Lorem ipsum'; $string = 'Lorem ipsum';
/* // Removing first element
* Removing first element
*/
self::assertSame([ self::assertSame([
0 => 'Lorem', 0 => 'Lorem',
1 => 'ipsum', 1 => 'ipsum',
@@ -376,9 +484,7 @@ letsTest[2] = value_2;';
], Arrays::removeMarginalElement($array)); ], Arrays::removeMarginalElement($array));
self::assertEquals('Lorem ipsu', Arrays::removeMarginalElement($string)); self::assertEquals('Lorem ipsu', Arrays::removeMarginalElement($string));
/* // Removing last element
* Removing last element
*/
self::assertSame([ self::assertSame([
1 => 'ipsum', 1 => 'ipsum',
2 => 'dolor', 2 => 'dolor',
@@ -489,14 +595,10 @@ letsTest[2] = value_2;';
public function testGetNonArrayElementsCount() public function testGetNonArrayElementsCount()
{ {
/* // Negative cases
* Negative cases
*/
self::assertNull(Arrays::getNonArrayElementsCount([])); self::assertNull(Arrays::getNonArrayElementsCount([]));
/* // Positive cases
* Positive cases
*/
self::assertEquals(5, Arrays::getNonArrayElementsCount($this->simpleArray)); self::assertEquals(5, Arrays::getNonArrayElementsCount($this->simpleArray));
self::assertEquals(3, Arrays::getNonArrayElementsCount($this->simpleArrayWithKeys)); self::assertEquals(3, Arrays::getNonArrayElementsCount($this->simpleArrayWithKeys));
self::assertEquals(12, Arrays::getNonArrayElementsCount($this->twoDimensionsArray)); self::assertEquals(12, Arrays::getNonArrayElementsCount($this->twoDimensionsArray));
@@ -504,15 +606,11 @@ letsTest[2] = value_2;';
public function testString2array() public function testString2array()
{ {
/* // Negative cases
* Negative cases
*/
self::assertNull(Arrays::string2array('')); self::assertNull(Arrays::string2array(''));
self::assertNull(Arrays::string2array(null)); self::assertNull(Arrays::string2array(null));
/* // Positive cases
* Positive cases
*/
$array = [ $array = [
'light' => '#fff', 'light' => '#fff',
'dark' => '#000', 'dark' => '#000',
@@ -534,9 +632,7 @@ letsTest[2] = value_2;';
public function testAreKeysInArray() public function testAreKeysInArray()
{ {
/* // Negative cases
* Negative cases
*/
self::assertFalse(Arrays::areKeysInArray([], [])); self::assertFalse(Arrays::areKeysInArray([], []));
self::assertFalse(Arrays::areKeysInArray([null], $this->simpleArray)); self::assertFalse(Arrays::areKeysInArray([null], $this->simpleArray));
self::assertFalse(Arrays::areKeysInArray([''], $this->simpleArray)); self::assertFalse(Arrays::areKeysInArray([''], $this->simpleArray));
@@ -552,9 +648,7 @@ letsTest[2] = value_2;';
self::assertFalse(Arrays::areKeysInArray($keys1, $this->complexArray)); self::assertFalse(Arrays::areKeysInArray($keys1, $this->complexArray));
self::assertFalse(Arrays::areKeysInArray($keys1, $this->complexArray, false)); self::assertFalse(Arrays::areKeysInArray($keys1, $this->complexArray, false));
/* // Positive cases
* Positive cases
*/
$keys12 = [ $keys12 = [
2, 2,
'mollis', 'mollis',
@@ -607,9 +701,7 @@ letsTest[2] = value_2;';
public function testGetLastElementsPathsUsingDefaults() public function testGetLastElementsPathsUsingDefaults()
{ {
/* // Using default separator and other default arguments
* Using default separator and other default arguments
*/
$expected = [ $expected = [
'lorem.ipsum.dolor' => 'sit', 'lorem.ipsum.dolor' => 'sit',
'lorem.ipsum.diam.non' => 'egestas', 'lorem.ipsum.diam.non' => 'egestas',
@@ -628,9 +720,7 @@ letsTest[2] = value_2;';
public function testGetLastElementsPathsUsingCustomSeparator() public function testGetLastElementsPathsUsingCustomSeparator()
{ {
/* // Using custom separator
* Using custom separator
*/
$separator = ' -> '; $separator = ' -> ';
$expected = [ $expected = [
sprintf('lorem%sipsum%sdolor', $separator, $separator) => 'sit', sprintf('lorem%sipsum%sdolor', $separator, $separator) => 'sit',
@@ -649,7 +739,7 @@ letsTest[2] = value_2;';
} }
/** /**
* @param string|array $stopIfMatchedBy Patterns of keys or paths that matched will stop the process of path * @param array|string $stopIfMatchedBy Patterns of keys or paths that matched will stop the process of path
* building and including children of those keys or paths (recursive will * building and including children of those keys or paths (recursive will
* not be used for keys in lower level of given array) * not be used for keys in lower level of given array)
* @param string $separator Separator used in resultant strings. Default: ".". * @param string $separator Separator used in resultant strings. Default: ".".
@@ -666,19 +756,13 @@ letsTest[2] = value_2;';
{ {
$pattern = '\d+'; $pattern = '\d+';
/* // Empty array
* Empty array
*/
self::assertFalse(Arrays::areAllKeysMatchedByPattern([], $pattern)); self::assertFalse(Arrays::areAllKeysMatchedByPattern([], $pattern));
/* // Simple array with integers as keys only
* Simple array with integers as keys only
*/
self::assertTrue(Arrays::areAllKeysMatchedByPattern($this->simpleArray, $pattern)); self::assertTrue(Arrays::areAllKeysMatchedByPattern($this->simpleArray, $pattern));
/* // Complex array with strings and integers as keys
* Complex array with strings and integers as keys
*/
self::assertFalse(Arrays::areAllKeysMatchedByPattern($this->complexArray, $pattern)); self::assertFalse(Arrays::areAllKeysMatchedByPattern($this->complexArray, $pattern));
$array = [ $array = [
@@ -686,33 +770,23 @@ letsTest[2] = value_2;';
'c' => 'd', 'c' => 'd',
]; ];
/* // Yet another simple array, but with strings as keys
* Yet another simple array, but with strings as keys
*/
self::assertFalse(Arrays::areAllKeysMatchedByPattern($array, $pattern)); self::assertFalse(Arrays::areAllKeysMatchedByPattern($array, $pattern));
/* // The same array with another pattern
* The same array with another pattern
*/
$pattern = '\w+'; $pattern = '\w+';
self::assertTrue(Arrays::areAllKeysMatchedByPattern($array, $pattern)); self::assertTrue(Arrays::areAllKeysMatchedByPattern($array, $pattern));
/* // The same array with mixed keys (strings and integers as keys)
* The same array with mixed keys (strings and integers as keys)
*/
$array[1] = 'x'; $array[1] = 'x';
$pattern = '\d+'; $pattern = '\d+';
self::assertFalse(Arrays::areAllKeysMatchedByPattern($array, $pattern)); self::assertFalse(Arrays::areAllKeysMatchedByPattern($array, $pattern));
/* // Multidimensional array - negative case
* Multidimensional array - negative case
*/
$array['e'] = ['f' => 'g']; $array['e'] = ['f' => 'g'];
self::assertFalse(Arrays::areAllKeysMatchedByPattern($array, $pattern)); self::assertFalse(Arrays::areAllKeysMatchedByPattern($array, $pattern));
/* // Multidimensional array - positive case
* Multidimensional array - positive case
*/
unset($array[1]); unset($array[1]);
$pattern = '\w+'; $pattern = '\w+';
self::assertTrue(Arrays::areAllKeysMatchedByPattern($array, $pattern)); self::assertTrue(Arrays::areAllKeysMatchedByPattern($array, $pattern));
@@ -728,14 +802,10 @@ letsTest[2] = value_2;';
public function testIssetRecursive() public function testIssetRecursive()
{ {
/* // Negative cases
* Negative cases
*/
self::assertFalse(Arrays::issetRecursive([], [])); self::assertFalse(Arrays::issetRecursive([], []));
/* // Positive cases
* Positive cases
*/
$unExistingKeys = [ $unExistingKeys = [
'a', 'a',
'b', 'b',
@@ -778,14 +848,10 @@ letsTest[2] = value_2;';
public function testGetValueByKeysPath() public function testGetValueByKeysPath()
{ {
/* // Negative cases
* Negative cases
*/
self::assertNull(Arrays::getValueByKeysPath([], [])); self::assertNull(Arrays::getValueByKeysPath([], []));
/* // Positive cases
* Positive cases
*/
self::assertNull(Arrays::getValueByKeysPath($this->simpleArray, [])); self::assertNull(Arrays::getValueByKeysPath($this->simpleArray, []));
self::assertEquals('ipsum', Arrays::getValueByKeysPath($this->simpleArray, [1])); self::assertEquals('ipsum', Arrays::getValueByKeysPath($this->simpleArray, [1]));
self::assertEquals('sit', Arrays::getValueByKeysPath($this->simpleArray, [3])); self::assertEquals('sit', Arrays::getValueByKeysPath($this->simpleArray, [3]));
@@ -839,14 +905,10 @@ letsTest[2] = value_2;';
public function testGetAllValuesOfKey() public function testGetAllValuesOfKey()
{ {
/* // Positive case - 1-dimension array
* Positive case - 1-dimension array
*/
self::assertEquals(['ipsum'], Arrays::getAllValuesOfKey($this->simpleArray, 1)); self::assertEquals(['ipsum'], Arrays::getAllValuesOfKey($this->simpleArray, 1));
/* // Positive case - 2-dimensions array
* Positive case - 2-dimensions array
*/
$effect = [ $effect = [
[ [
'lorem', 'lorem',
@@ -861,14 +923,10 @@ letsTest[2] = value_2;';
self::assertEquals($effect, Arrays::getAllValuesOfKey($this->twoDimensionsArray, 0)); self::assertEquals($effect, Arrays::getAllValuesOfKey($this->twoDimensionsArray, 0));
/* // Positive case - multi-dimensions array
* Positive case - multi-dimensions array
*/
self::assertEquals(['primis'], Arrays::getAllValuesOfKey($this->complexArray, 1)); self::assertEquals(['primis'], Arrays::getAllValuesOfKey($this->complexArray, 1));
/* // Positive case - multi-dimensions array
* Positive case - multi-dimensions array
*/
$effect = [ $effect = [
0 => [ 0 => [
'in' => [ 'in' => [
@@ -885,22 +943,16 @@ letsTest[2] = value_2;';
public function testKsortRecursive() public function testKsortRecursive()
{ {
/* // Negative cases
* Negative cases
*/
$array = []; $array = [];
self::assertNull(Arrays::ksortRecursive($array)); self::assertNull(Arrays::ksortRecursive($array));
/* // Positive cases
* Positive cases
*/
self::assertEquals($this->simpleArray, Arrays::ksortRecursive($this->simpleArray)); self::assertEquals($this->simpleArray, Arrays::ksortRecursive($this->simpleArray));
self::assertEquals($this->simpleArray, Arrays::ksortRecursive($this->simpleArray, SORT_NUMERIC)); self::assertEquals($this->simpleArray, Arrays::ksortRecursive($this->simpleArray, SORT_NUMERIC));
self::assertEquals($this->twoDimensionsArray, Arrays::ksortRecursive($this->twoDimensionsArray)); self::assertEquals($this->twoDimensionsArray, Arrays::ksortRecursive($this->twoDimensionsArray));
/* // Positive case - multi-dimensions array
* Positive case - multi-dimensions array
*/
$effect = [ $effect = [
'amet' => [ 'amet' => [
'iaculis', 'iaculis',
@@ -930,9 +982,7 @@ letsTest[2] = value_2;';
self::assertEquals($effect, Arrays::ksortRecursive($this->complexArray)); self::assertEquals($effect, Arrays::ksortRecursive($this->complexArray));
/* // Positive case - multi-dimensions array - with options of ksort() function
* Positive case - multi-dimensions array - with options of ksort() function
*/
$effect = [ $effect = [
2 => [], 2 => [],
'amet' => [ 'amet' => [
@@ -965,23 +1015,17 @@ letsTest[2] = value_2;';
public function testSetPositions() public function testSetPositions()
{ {
/* // Negative cases
* Negative cases
*/
self::assertNull(Arrays::setPositions([])); self::assertNull(Arrays::setPositions([]));
/* // Positive case - 1-dimension array
* Positive case - 1-dimension array
*/
$array = [ $array = [
'abc', 'abc',
]; ];
self::assertEquals($array, Arrays::setPositions($array)); self::assertEquals($array, Arrays::setPositions($array));
/* // Positive case - 2-dimensions array
* Positive case - 2-dimensions array
*/
$effect = $this->twoDimensionsArray; $effect = $this->twoDimensionsArray;
$effect[0][Arrays::POSITION_KEY_NAME] = 1; $effect[0][Arrays::POSITION_KEY_NAME] = 1;
$effect[1][Arrays::POSITION_KEY_NAME] = 2; $effect[1][Arrays::POSITION_KEY_NAME] = 2;
@@ -989,9 +1033,7 @@ letsTest[2] = value_2;';
self::assertEquals($effect, Arrays::setPositions($this->twoDimensionsArray)); self::assertEquals($effect, Arrays::setPositions($this->twoDimensionsArray));
/* // Positive case - multi-level array
* Positive case - multi-level array
*/
$array = [ $array = [
'lorem', 'lorem',
'ipsum' => [ 'ipsum' => [
@@ -1034,9 +1076,7 @@ letsTest[2] = value_2;';
self::assertEquals($effect, Arrays::setPositions($array)); self::assertEquals($effect, Arrays::setPositions($array));
/* // Positive case - non-default name of key with position value & 2-dimensions array
* Positive case - non-default name of key with position value & 2-dimensions array
*/
$keyName = 'level'; $keyName = 'level';
$effect = $this->twoDimensionsArray; $effect = $this->twoDimensionsArray;
@@ -1046,9 +1086,7 @@ letsTest[2] = value_2;';
self::assertEquals($effect, Arrays::setPositions($this->twoDimensionsArray, $keyName)); self::assertEquals($effect, Arrays::setPositions($this->twoDimensionsArray, $keyName));
/* // Positive case - non-default start value of position & 2-dimensions array
* Positive case - non-default start value of position & 2-dimensions array
*/
$startPosition = 5; $startPosition = 5;
$effect = $this->twoDimensionsArray; $effect = $this->twoDimensionsArray;
@@ -1062,14 +1100,10 @@ letsTest[2] = value_2;';
public function testTrimRecursive() public function testTrimRecursive()
{ {
/* // Negative cases
* Negative cases
*/
self::assertSame([], Arrays::trimRecursive([])); self::assertSame([], Arrays::trimRecursive([]));
/* // Positive cases
* Positive cases
*/
self::assertEquals(['a'], Arrays::trimRecursive([' a '])); self::assertEquals(['a'], Arrays::trimRecursive([' a ']));
self::assertEquals([ self::assertEquals([
'a', 'a',
@@ -1126,14 +1160,10 @@ letsTest[2] = value_2;';
public function testSortByCustomKeysOrder() public function testSortByCustomKeysOrder()
{ {
/* // Negative cases
* Negative cases
*/
self::assertNull(Arrays::sortByCustomKeysOrder([], [])); self::assertNull(Arrays::sortByCustomKeysOrder([], []));
/* // Positive cases
* Positive cases
*/
self::assertEquals([0], Arrays::sortByCustomKeysOrder([0], [])); self::assertEquals([0], Arrays::sortByCustomKeysOrder([0], []));
self::assertEquals($this->simpleArray, Arrays::sortByCustomKeysOrder($this->simpleArray, [])); self::assertEquals($this->simpleArray, Arrays::sortByCustomKeysOrder($this->simpleArray, []));
@@ -1204,19 +1234,13 @@ letsTest[2] = value_2;';
{ {
$separator = '/'; $separator = '/';
/* // Empty array
* Empty array
*/
self::assertNull(Arrays::implodeSmart([], $separator)); self::assertNull(Arrays::implodeSmart([], $separator));
/* // Simple, one-dimension array
* Simple, one-dimension array
*/
self::assertEquals(implode($separator, $this->simpleArray), Arrays::implodeSmart($this->simpleArray, $separator)); self::assertEquals(implode($separator, $this->simpleArray), Arrays::implodeSmart($this->simpleArray, $separator));
/* // An array with elements that contain separator
* An array with elements that contain separator
*/
$array = [ $array = [
'lorem' . $separator, 'lorem' . $separator,
'ipsum', 'ipsum',
@@ -1229,9 +1253,7 @@ letsTest[2] = value_2;';
'dolor', 'dolor',
]), Arrays::implodeSmart($array, $separator)); ]), Arrays::implodeSmart($array, $separator));
/* // Complex array
* Complex array
*/
self::assertEquals(implode($separator, [ self::assertEquals(implode($separator, [
'donec', 'donec',
'quis', 'quis',
@@ -1241,51 +1263,39 @@ letsTest[2] = value_2;';
public function testGetNextElement() public function testGetNextElement()
{ {
/* // Negative cases
* Negative cases
*/
self::assertNull(Arrays::getNextElement($this->simpleArray, 'amet')); self::assertNull(Arrays::getNextElement($this->simpleArray, 'amet'));
self::assertNull(Arrays::getNextElement($this->simpleArray, 'xyz')); self::assertNull(Arrays::getNextElement($this->simpleArray, 'xyz'));
self::assertNull(Arrays::getNextElement($this->simpleArray, 0)); self::assertNull(Arrays::getNextElement($this->simpleArray, 0));
self::assertNull(Arrays::getNextElement([], '')); self::assertNull(Arrays::getNextElement([], ''));
self::assertNull(Arrays::getNextElement([], null)); self::assertNull(Arrays::getNextElement([], null));
/* // Positive cases
* Positive cases
*/
self::assertEquals('ipsum', Arrays::getNextElement($this->simpleArray, 'Lorem')); self::assertEquals('ipsum', Arrays::getNextElement($this->simpleArray, 'Lorem'));
self::assertEquals('sit', Arrays::getNextElement($this->simpleArray, 'dolor')); self::assertEquals('sit', Arrays::getNextElement($this->simpleArray, 'dolor'));
} }
public function testGetPreviousElement() public function testGetPreviousElement()
{ {
/* // Negative cases
* Negative cases
*/
self::assertNull(Arrays::getPreviousElement($this->simpleArray, 'Lorem')); self::assertNull(Arrays::getPreviousElement($this->simpleArray, 'Lorem'));
self::assertNull(Arrays::getPreviousElement($this->simpleArray, 'xyz')); self::assertNull(Arrays::getPreviousElement($this->simpleArray, 'xyz'));
self::assertNull(Arrays::getPreviousElement($this->simpleArray, 0)); self::assertNull(Arrays::getPreviousElement($this->simpleArray, 0));
self::assertNull(Arrays::getPreviousElement([], '')); self::assertNull(Arrays::getPreviousElement([], ''));
self::assertNull(Arrays::getPreviousElement([], null)); self::assertNull(Arrays::getPreviousElement([], null));
/* // Positive cases
* Positive cases
*/
self::assertEquals('ipsum', Arrays::getPreviousElement($this->simpleArray, 'dolor')); self::assertEquals('ipsum', Arrays::getPreviousElement($this->simpleArray, 'dolor'));
self::assertEquals('sit', Arrays::getPreviousElement($this->simpleArray, 'amet')); self::assertEquals('sit', Arrays::getPreviousElement($this->simpleArray, 'amet'));
} }
public function testGetIndexOf() public function testGetIndexOf()
{ {
/* // Negative cases
* Negative cases
*/
self::assertFalse(Arrays::getIndexOf([], 'a')); self::assertFalse(Arrays::getIndexOf([], 'a'));
self::assertNull(Arrays::getIndexOf($this->simpleArray, 'loremmm')); self::assertNull(Arrays::getIndexOf($this->simpleArray, 'loremmm'));
/* // Positive cases
* Positive cases
*/
self::assertEquals(1, Arrays::getIndexOf($this->simpleArray, 'ipsum')); self::assertEquals(1, Arrays::getIndexOf($this->simpleArray, 'ipsum'));
self::assertEquals('dolor', Arrays::getIndexOf($this->simpleArrayWithKeys, 'sit')); self::assertEquals('dolor', Arrays::getIndexOf($this->simpleArrayWithKeys, 'sit'));
self::assertEquals('mollis', Arrays::getIndexOf($this->complexArray, 1234)); self::assertEquals('mollis', Arrays::getIndexOf($this->complexArray, 1234));
@@ -1293,14 +1303,10 @@ letsTest[2] = value_2;';
public function testIncrementIndexes() public function testIncrementIndexes()
{ {
/* // Negative cases
* Negative cases
*/
self::assertNull(Arrays::incrementIndexes([])); self::assertNull(Arrays::incrementIndexes([]));
/* // Positive cases
* Positive cases
*/
$array = [ $array = [
1 => 'Lorem', 1 => 'Lorem',
2 => 'ipsum', 2 => 'ipsum',
@@ -1331,9 +1337,7 @@ letsTest[2] = value_2;';
public function testAreAllValuesEmpty() public function testAreAllValuesEmpty()
{ {
/* // Negative cases
* Negative cases
*/
self::assertFalse(Arrays::areAllValuesEmpty([])); self::assertFalse(Arrays::areAllValuesEmpty([]));
self::assertFalse(Arrays::areAllValuesEmpty([], true)); self::assertFalse(Arrays::areAllValuesEmpty([], true));
self::assertFalse(Arrays::areAllValuesEmpty($this->simpleArray)); self::assertFalse(Arrays::areAllValuesEmpty($this->simpleArray));
@@ -1353,9 +1357,7 @@ letsTest[2] = value_2;';
]; ];
self::assertFalse(Arrays::areAllValuesEmpty($array, true)); self::assertFalse(Arrays::areAllValuesEmpty($array, true));
/* // Positive cases
* Positive cases
*/
$array = [ $array = [
'', '',
0, 0,
@@ -1371,15 +1373,11 @@ letsTest[2] = value_2;';
public function testDiffRecursive() public function testDiffRecursive()
{ {
/* // Negative cases
* Negative cases
*/
self::assertEquals([], Arrays::arrayDiffRecursive([], [])); self::assertEquals([], Arrays::arrayDiffRecursive([], []));
self::assertEquals([], Arrays::arrayDiffRecursive([], [], true)); self::assertEquals([], Arrays::arrayDiffRecursive([], [], true));
/* // Positive cases - full comparison (keys and values)
* Positive cases - full comparison (keys and values)
*/
self::assertEquals(['a'], Arrays::arrayDiffRecursive(['a'], [])); self::assertEquals(['a'], Arrays::arrayDiffRecursive(['a'], []));
self::assertEquals([], Arrays::arrayDiffRecursive([], ['a'])); self::assertEquals([], Arrays::arrayDiffRecursive([], ['a']));
self::assertEquals([], Arrays::arrayDiffRecursive($this->simpleArray, $this->simpleArray)); self::assertEquals([], Arrays::arrayDiffRecursive($this->simpleArray, $this->simpleArray));
@@ -1432,9 +1430,7 @@ letsTest[2] = value_2;';
self::assertEquals($this->twoDimensionsArray[1], Arrays::arrayDiffRecursive($this->twoDimensionsArray[1], $this->twoDimensionsArray)); self::assertEquals($this->twoDimensionsArray[1], Arrays::arrayDiffRecursive($this->twoDimensionsArray[1], $this->twoDimensionsArray));
/* // Positive cases - simple comparison (values only)
* Positive cases - simple comparison (values only)
*/
self::assertEquals(['a'], Arrays::arrayDiffRecursive(['a'], [], true)); self::assertEquals(['a'], Arrays::arrayDiffRecursive(['a'], [], true));
$array = [ $array = [
@@ -1533,35 +1529,25 @@ letsTest[2] = value_2;';
public function testGetDimensionsCount() public function testGetDimensionsCount()
{ {
/* // Basic cases
* Basic cases
*/
self::assertEquals(0, Arrays::getDimensionsCount([])); self::assertEquals(0, Arrays::getDimensionsCount([]));
self::assertEquals(1, Arrays::getDimensionsCount([''])); self::assertEquals(1, Arrays::getDimensionsCount(['']));
/* // Simple cases
* Simple cases
*/
self::assertEquals(1, Arrays::getDimensionsCount($this->simpleArray)); self::assertEquals(1, Arrays::getDimensionsCount($this->simpleArray));
self::assertEquals(1, Arrays::getDimensionsCount($this->simpleArrayWithKeys)); self::assertEquals(1, Arrays::getDimensionsCount($this->simpleArrayWithKeys));
/* // Complex cases
* Complex cases
*/
self::assertEquals(2, Arrays::getDimensionsCount($this->twoDimensionsArray)); self::assertEquals(2, Arrays::getDimensionsCount($this->twoDimensionsArray));
self::assertEquals(4, Arrays::getDimensionsCount($this->complexArray)); self::assertEquals(4, Arrays::getDimensionsCount($this->complexArray));
} }
public function testIsMultiDimensional() public function testIsMultiDimensional()
{ {
/* // Negative cases
* Negative cases
*/
self::assertNull(Arrays::isMultiDimensional([])); self::assertNull(Arrays::isMultiDimensional([]));
/* // Positive cases
* Positive cases
*/
self::assertFalse(Arrays::isMultiDimensional($this->simpleArray)); self::assertFalse(Arrays::isMultiDimensional($this->simpleArray));
self::assertFalse(Arrays::isMultiDimensional($this->simpleArrayWithKeys)); self::assertFalse(Arrays::isMultiDimensional($this->simpleArrayWithKeys));
@@ -1717,9 +1703,7 @@ letsTest[2] = value_2;';
*/ */
public function provideStopIfMatchedByForGetLastElementsPaths() public function provideStopIfMatchedByForGetLastElementsPaths()
{ {
/* // 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',
'.', '.',
@@ -1780,9 +1764,7 @@ letsTest[2] = value_2;';
], ],
]; ];
/* // Stop building of paths on more sophisticated keys
* Stop building of paths on more sophisticated keys
*/
yield[ yield[
[ [
'porta\-\d+', 'porta\-\d+',
@@ -1857,9 +1839,7 @@ letsTest[2] = value_2;';
], ],
]; ];
/* // Stop building of paths on these paths (verify paths only)
* Stop building of paths on these paths (verify paths only)
*/
yield[ yield[
[ [
'ipsum > quis > vestibulum > porta-1', 'ipsum > quis > vestibulum > porta-1',
@@ -1894,9 +1874,7 @@ letsTest[2] = value_2;';
], ],
]; ];
/* // Stop building of paths if path contains any of these part (verify part of paths only)
* Stop building of paths if path contains any of these part (verify part of paths only)
*/
yield[ yield[
[ [
'vestibulum > porta-1', 'vestibulum > porta-1',
@@ -2701,130 +2679,4 @@ letsTest[2] = value_2;';
], ],
]; ];
} }
/**
* {@inheritdoc}
*/
protected function setUp(): void
{
parent::setUp();
$this->simpleArray = [
'Lorem',
'ipsum',
'dolor',
'sit',
'amet',
];
$this->simpleArrayWithKeys = [
'Lorem' => 'ipsum',
'dolor' => 'sit',
'amet' => 'consectetur',
];
$this->twoDimensionsArray = [
[
'lorem',
'ipsum',
'dolor',
'sit',
'amet',
],
[
'consectetur',
'adipiscing',
'elit',
],
[
'donec',
'sagittis',
'fringilla',
'eleifend',
],
];
$this->complexArray = [
'lorem' => [
'ipsum' => [
'dolor' => 'sit',
'diam' => [
'non' => 'egestas',
],
],
],
'consectetur' => 'adipiscing',
'mollis' => 1234,
2 => [],
'sit' => [
'nullam' => 'donec',
'aliquet' => [
'vitae' => [
'ligula' => 'quis',
],
],
'elit',
],
'amet' => [
'iaculis',
'primis',
],
];
$this->superComplexArray = [
'ipsum' => [
'quis' => [
'vestibulum' => [
'porta-1' => [
'turpis',
'urna',
],
'porta-2' => [
'tortor' => [
'in' => [
'dui',
'dolor' => [
'aliquam',
],
],
],
],
'porta-3' => [
1,
2,
3,
],
],
],
],
'primis' => [
[
'in',
'faucibus',
'orci',
],
[
'luctus',
'et',
'ultrices',
],
],
];
}
/**
* {@inheritdoc}
*/
protected function tearDown(): void
{
parent::tearDown();
unset(
$this->simpleArray,
$this->simpleArrayWithKeys,
$this->twoDimensionsArray,
$this->complexArray,
$this->superComplexArray
);
}
} }

View File

@@ -16,6 +16,9 @@ use Meritoo\Common\Utilities\Bootstrap4CssSelector;
* *
* @author Meritoo <github@meritoo.pl> * @author Meritoo <github@meritoo.pl>
* @copyright Meritoo <http://www.meritoo.pl> * @copyright Meritoo <http://www.meritoo.pl>
*
* @internal
* @covers \Meritoo\Common\Utilities\Bootstrap4CssSelector
*/ */
class Bootstrap4CssSelectorTest extends BaseTestCase class Bootstrap4CssSelectorTest extends BaseTestCase
{ {

View File

@@ -18,6 +18,9 @@ use Meritoo\Common\Utilities\Bundle;
* *
* @author Meritoo <github@meritoo.pl> * @author Meritoo <github@meritoo.pl>
* @copyright Meritoo <http://www.meritoo.pl> * @copyright Meritoo <http://www.meritoo.pl>
*
* @internal
* @covers \Meritoo\Common\Utilities\Bundle
*/ */
class BundleTest extends BaseTestCase class BundleTest extends BaseTestCase
{ {

View File

@@ -17,6 +17,9 @@ use Meritoo\Common\Utilities\Composer;
* *
* @author Meritoo <github@meritoo.pl> * @author Meritoo <github@meritoo.pl>
* @copyright Meritoo <http://www.meritoo.pl> * @copyright Meritoo <http://www.meritoo.pl>
*
* @internal
* @covers \Meritoo\Common\Utilities\Composer
*/ */
class ComposerTest extends BaseTestCase class ComposerTest extends BaseTestCase
{ {
@@ -27,6 +30,16 @@ class ComposerTest extends BaseTestCase
*/ */
private $composerJsonPath; private $composerJsonPath;
/**
* {@inheritdoc}
*/
protected function setUp(): void
{
parent::setUp();
$this->composerJsonPath = $this->getFilePathForTesting(Composer::FILE_NAME_MAIN);
}
public function testConstructor() public function testConstructor()
{ {
static::assertHasNoConstructor(Composer::class); static::assertHasNoConstructor(Composer::class);
@@ -80,14 +93,4 @@ class ComposerTest extends BaseTestCase
'1.0.2', '1.0.2',
]; ];
} }
/**
* {@inheritdoc}
*/
protected function setUp(): void
{
parent::setUp();
$this->composerJsonPath = $this->getFilePathForTesting(Composer::FILE_NAME_MAIN);
}
} }

View File

@@ -16,6 +16,9 @@ use Meritoo\Common\Utilities\CssSelector;
* *
* @author Meritoo <github@meritoo.pl> * @author Meritoo <github@meritoo.pl>
* @copyright Meritoo <http://www.meritoo.pl> * @copyright Meritoo <http://www.meritoo.pl>
*
* @internal
* @covers \Meritoo\Common\Utilities\CssSelector
*/ */
class CssSelectorTest extends BaseTestCase class CssSelectorTest extends BaseTestCase
{ {

View File

@@ -22,6 +22,9 @@ use Meritoo\Common\Utilities\Locale;
* *
* @author Meritoo <github@meritoo.pl> * @author Meritoo <github@meritoo.pl>
* @copyright Meritoo <http://www.meritoo.pl> * @copyright Meritoo <http://www.meritoo.pl>
*
* @internal
* @covers \Meritoo\Common\Utilities\Date
*/ */
class DateTest extends BaseTestCase class DateTest extends BaseTestCase
{ {
@@ -89,14 +92,10 @@ class DateTest extends BaseTestCase
public function testGetDateTimeConcreteDates() public function testGetDateTimeConcreteDates()
{ {
/* // 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'));
/* // Using custom date format
* Using custom date format
*/
self::assertInstanceOf(DateTime::class, Date::getDateTime('2015-03-20 11:30', false, 'Y-m-d H:i')); self::assertInstanceOf(DateTime::class, Date::getDateTime('2015-03-20 11:30', false, 'Y-m-d H:i'));
self::assertInstanceOf(DateTime::class, Date::getDateTime('20.03.2015', false, 'd.m.Y')); self::assertInstanceOf(DateTime::class, Date::getDateTime('20.03.2015', false, 'd.m.Y'));
} }
@@ -248,8 +247,8 @@ class DateTest extends BaseTestCase
} }
/** /**
* @param string|DateTime $dateStart The start date * @param DateTime|string $dateStart The start date
* @param string|DateTime $dateEnd The end date * @param DateTime|string $dateEnd The end date
* *
* @dataProvider provideEmptyDatesForDateDifference * @dataProvider provideEmptyDatesForDateDifference
*/ */
@@ -266,9 +265,7 @@ class DateTest extends BaseTestCase
public function testGetDateDifferenceOneDay() public function testGetDateDifferenceOneDay()
{ {
/* // Difference of 1 day
* Difference of 1 day
*/
$dateStart = '2017-01-01'; $dateStart = '2017-01-01';
$dateEnd = '2017-01-02'; $dateEnd = '2017-01-02';
@@ -298,9 +295,7 @@ class DateTest extends BaseTestCase
self::assertEquals(0, Date::getDateDifference($dateStart, $dateEnd, Date::DATE_DIFFERENCE_UNIT_MINUTES)); self::assertEquals(0, Date::getDateDifference($dateStart, $dateEnd, Date::DATE_DIFFERENCE_UNIT_MINUTES));
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));
/* // Difference of 1 day (using the relative date format)
* Difference of 1 day (using the relative date format)
*/
$effect = [ $effect = [
Date::DATE_DIFFERENCE_UNIT_YEARS => 0, Date::DATE_DIFFERENCE_UNIT_YEARS => 0,
Date::DATE_DIFFERENCE_UNIT_MONTHS => 0, Date::DATE_DIFFERENCE_UNIT_MONTHS => 0,
@@ -318,9 +313,7 @@ class DateTest extends BaseTestCase
public function testGetDateDifferenceOneDayTwoHours() public function testGetDateDifferenceOneDayTwoHours()
{ {
/* // 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';
$dateEnd = '2017-01-02 14:15'; $dateEnd = '2017-01-02 14:15';
@@ -353,9 +346,7 @@ class DateTest extends BaseTestCase
public function testGetDateDifferenceOneMonthFortyOneDays() public function testGetDateDifferenceOneMonthFortyOneDays()
{ {
/* // 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';
$dateEnd = '2017-02-11 16:30'; $dateEnd = '2017-02-11 16:30';
@@ -516,9 +507,7 @@ class DateTest extends BaseTestCase
public function testGetDateDifferenceNoDifference() public function testGetDateDifferenceNoDifference()
{ {
/* // No difference
* No difference
*/
$dateStart = '2017-01-01 12:00'; $dateStart = '2017-01-01 12:00';
$dateEnd = $dateStart; $dateEnd = $dateStart;
@@ -572,18 +561,14 @@ class DateTest extends BaseTestCase
public function testGetDatesCollection() public function testGetDatesCollection()
{ {
/* // 1 date only
* 1 date only
*/
$effect = [ $effect = [
1 => new DateTime('2017-01-02'), 1 => new DateTime('2017-01-02'),
]; ];
self::assertEquals($effect, Date::getDatesCollection(new DateTime('2017-01-01'), 1)); self::assertEquals($effect, Date::getDatesCollection(new DateTime('2017-01-01'), 1));
/* // 3 dates with default date interval (days)
* 3 dates with default date interval (days)
*/
$effect = [ $effect = [
1 => new DateTime('2017-01-02'), 1 => new DateTime('2017-01-02'),
2 => new DateTime('2017-01-03'), 2 => new DateTime('2017-01-03'),
@@ -592,9 +577,7 @@ class DateTest extends BaseTestCase
self::assertEquals($effect, Date::getDatesCollection(new DateTime('2017-01-01'), 3)); self::assertEquals($effect, Date::getDatesCollection(new DateTime('2017-01-01'), 3));
/* // 3 dates with custom date interval (hours)
* 3 dates with custom date interval (hours)
*/
$effect = [ $effect = [
1 => new DateTime('2017-01-01 10:30'), 1 => new DateTime('2017-01-01 10:30'),
2 => new DateTime('2017-01-01 11:30'), 2 => new DateTime('2017-01-01 11:30'),
@@ -603,9 +586,7 @@ class DateTest extends BaseTestCase
self::assertEquals($effect, Date::getDatesCollection(new DateTime('2017-01-01 09:30'), 3, 'PT%dH')); self::assertEquals($effect, Date::getDatesCollection(new DateTime('2017-01-01 09:30'), 3, 'PT%dH'));
/* // 3 dates with custom date interval (months)
* 3 dates with custom date interval (months)
*/
$effect = [ $effect = [
1 => new DateTime('2017-02-01'), 1 => new DateTime('2017-02-01'),
2 => new DateTime('2017-03-01'), 2 => new DateTime('2017-03-01'),
@@ -705,42 +686,32 @@ class DateTest extends BaseTestCase
*/ */
public function provideIncorrectDateTimeValue() public function provideIncorrectDateTimeValue()
{ {
/* // Incorrect one-character values
* Incorrect one-character values
*/
yield['a']; yield['a'];
yield['m']; yield['m'];
/* // Incorrect strings
* Incorrect strings
*/
yield['ss']; yield['ss'];
yield['sss']; yield['sss'];
yield['mm']; yield['mm'];
yield['yy']; yield['yy'];
yield['yyyy']; yield['yyyy'];
/* // Incorrect integer values
* Incorrect integer values
*/
yield[1]; yield[1];
yield[10]; yield[10];
yield[15]; yield[15];
yield[100]; yield[100];
yield[1000]; yield[1000];
/* // Incorrect string / numeric values
* Incorrect string / numeric values
*/
yield['1']; yield['1'];
yield['10']; yield['10'];
yield['15']; yield['15'];
yield['100']; yield['100'];
yield['1000']; yield['1000'];
/* // Incorrect dates
* Incorrect dates
*/
yield['0-0-0']; yield['0-0-0'];
yield['20-01-01']; yield['20-01-01'];
yield['2015-0-0']; yield['2015-0-0'];

View File

@@ -16,6 +16,9 @@ use Meritoo\Common\Utilities\GeneratorUtility;
* *
* @author Meritoo <github@meritoo.pl> * @author Meritoo <github@meritoo.pl>
* @copyright Meritoo <http://www.meritoo.pl> * @copyright Meritoo <http://www.meritoo.pl>
*
* @internal
* @covers \Meritoo\Common\Utilities\GeneratorUtility
*/ */
class GeneratorUtilityTest extends BaseTestCase class GeneratorUtilityTest extends BaseTestCase
{ {
@@ -26,9 +29,7 @@ class GeneratorUtilityTest extends BaseTestCase
public function testGetGeneratorElements() public function testGetGeneratorElements()
{ {
/* // Generator that provides boolean value
* Generator that provides boolean value
*/
$elements = [ $elements = [
[false], [false],
[true], [true],
@@ -46,15 +47,11 @@ class GeneratorUtilityTest extends BaseTestCase
[[]], [[]],
]; ];
/* // Generator that provides an empty value
* Generator that provides an empty value
*/
$generator = $this->provideEmptyValue(); $generator = $this->provideEmptyValue();
self::assertEquals($elements, GeneratorUtility::getGeneratorElements($generator)); self::assertEquals($elements, GeneratorUtility::getGeneratorElements($generator));
/* // Generator that provides instance of DateTime class
* Generator that provides instance of DateTime class
*/
$generator = $this->provideDateTimeInstance(); $generator = $this->provideDateTimeInstance();
self::assertCount(4, GeneratorUtility::getGeneratorElements($generator)); self::assertCount(4, GeneratorUtility::getGeneratorElements($generator));
} }

View File

@@ -18,6 +18,9 @@ use ReflectionException;
* *
* @author Meritoo <github@meritoo.pl> * @author Meritoo <github@meritoo.pl>
* @copyright Meritoo <http://www.meritoo.pl> * @copyright Meritoo <http://www.meritoo.pl>
*
* @internal
* @covers \Meritoo\Common\Utilities\Locale
*/ */
class LocaleTest extends BaseTestCase class LocaleTest extends BaseTestCase
{ {

View File

@@ -17,6 +17,9 @@ use Meritoo\Common\Utilities\MimeTypes;
* *
* @author Meritoo <github@meritoo.pl> * @author Meritoo <github@meritoo.pl>
* @copyright Meritoo <http://www.meritoo.pl> * @copyright Meritoo <http://www.meritoo.pl>
*
* @internal
* @covers \Meritoo\Common\Utilities\MimeTypes
*/ */
class MimeTypesTest extends BaseTestCase class MimeTypesTest extends BaseTestCase
{ {

View File

@@ -21,6 +21,9 @@ use stdClass;
* *
* @author Meritoo <github@meritoo.pl> * @author Meritoo <github@meritoo.pl>
* @copyright Meritoo <http://www.meritoo.pl> * @copyright Meritoo <http://www.meritoo.pl>
*
* @internal
* @covers \Meritoo\Common\Utilities\Miscellaneous
*/ */
class MiscellaneousTest extends BaseTestCase class MiscellaneousTest extends BaseTestCase
{ {
@@ -29,6 +32,28 @@ class MiscellaneousTest extends BaseTestCase
private $stringDotSeparated; private $stringDotSeparated;
private $stringWithoutSpaces; private $stringWithoutSpaces;
/**
* {@inheritdoc}
*/
protected function setUp(): void
{
parent::setUp();
$this->stringSmall = 'Lorem ipsum dolor sit amet.';
$this->stringCommaSeparated = 'Lorem ipsum dolor sit amet, consectetur adipiscing elit';
$this->stringDotSeparated = 'Etiam ullamcorper. Suspendisse a pellentesque dui, non felis.';
$this->stringWithoutSpaces = 'LoremIpsumDolorSitAmetConsecteturAdipiscingElit';
}
/**
* {@inheritdoc}
*/
protected function tearDown(): void
{
parent::tearDown();
unset($this->stringSmall, $this->stringCommaSeparated, $this->stringDotSeparated, $this->stringWithoutSpaces);
}
public function testConstructor() public function testConstructor()
{ {
static::assertHasNoConstructor(Miscellaneous::class); static::assertHasNoConstructor(Miscellaneous::class);
@@ -93,24 +118,16 @@ class MiscellaneousTest extends BaseTestCase
public function testGetFileNameFromPath() public function testGetFileNameFromPath()
{ {
/* // Path with file
* Path with file
*/
self::assertEquals('sit.amet.JPG', Miscellaneous::getFileNameFromPath('lorem/ipsum-dolor/sit.amet.JPG')); self::assertEquals('sit.amet.JPG', Miscellaneous::getFileNameFromPath('lorem/ipsum-dolor/sit.amet.JPG'));
/* // Path without file
* Path without file
*/
self::assertEquals('', Miscellaneous::getFileNameFromPath('lorem/ipsum-dolor/sit-amet')); self::assertEquals('', Miscellaneous::getFileNameFromPath('lorem/ipsum-dolor/sit-amet'));
/* // Path with a dot "." in name of directory
* Path with a dot "." in name of directory
*/
self::assertEquals('sit.amet.JPG', Miscellaneous::getFileNameFromPath('lorem/ipsum.dolor/sit.amet.JPG')); self::assertEquals('sit.amet.JPG', Miscellaneous::getFileNameFromPath('lorem/ipsum.dolor/sit.amet.JPG'));
/* // Relative path
* Relative path
*/
self::assertEquals('sit.amet.JPG', Miscellaneous::getFileNameFromPath('lorem/ipsum/../dolor/sit.amet.JPG')); self::assertEquals('sit.amet.JPG', Miscellaneous::getFileNameFromPath('lorem/ipsum/../dolor/sit.amet.JPG'));
} }
@@ -119,14 +136,10 @@ class MiscellaneousTest extends BaseTestCase
$originalFileName = 'Lorem.ipsum-dolor.sit.JPG'; $originalFileName = 'Lorem.ipsum-dolor.sit.JPG';
$pattern = '|^lorem\-ipsum\-dolor\-sit\-[a-z0-9.-]+\.jpg$|'; $pattern = '|^lorem\-ipsum\-dolor\-sit\-[a-z0-9.-]+\.jpg$|';
/* // With object ID
* With object ID
*/
$uniqueFileName1 = Miscellaneous::getUniqueFileName($originalFileName, 123); $uniqueFileName1 = Miscellaneous::getUniqueFileName($originalFileName, 123);
/* // Without object ID
* Without object ID
*/
$uniqueFileName2 = Miscellaneous::getUniqueFileName($originalFileName); $uniqueFileName2 = Miscellaneous::getUniqueFileName($originalFileName);
$isCorrect1 = (bool)preg_match($pattern, $uniqueFileName1); $isCorrect1 = (bool)preg_match($pattern, $uniqueFileName1);
@@ -200,7 +213,7 @@ class MiscellaneousTest extends BaseTestCase
} }
/** /**
* @param string|array $search An empty value to find * @param array|string $search An empty value to find
* @dataProvider provideEmptyValue * @dataProvider provideEmptyValue
*/ */
public function testReplaceEmptyValue($search) public function testReplaceEmptyValue($search)
@@ -224,10 +237,10 @@ class MiscellaneousTest extends BaseTestCase
/** /**
* @param string $description Description of test * @param string $description Description of test
* @param string|array $subject The string or an array of strings to search and replace * @param array|string $subject The string or an array of strings to search and replace
* @param string|array $search String or pattern or array of patterns to find. It may be: string, an array * @param array|string $search String or pattern or array of patterns to find. It may be: string, an array
* of strings or an array of patterns. * of strings or an array of patterns.
* @param string|array $replacement The string or an array of strings to replace. It may be: string or an array * @param array|string $replacement The string or an array of strings to replace. It may be: string or an array
* of strings. * of strings.
* @param mixed $result Result of replacing * @param mixed $result Result of replacing
* *
@@ -328,9 +341,7 @@ class MiscellaneousTest extends BaseTestCase
public function testGetOperatingSystemNameServer() public function testGetOperatingSystemNameServer()
{ {
/* // While running Docker OS is a Linux
* While running Docker OS is a Linux
*/
self::assertEquals('Linux', Miscellaneous::getOperatingSystemNameServer()); self::assertEquals('Linux', Miscellaneous::getOperatingSystemNameServer());
} }
@@ -531,9 +542,7 @@ class MiscellaneousTest extends BaseTestCase
public function testConcatenatePathsInNixOs() public function testConcatenatePathsInNixOs()
{ {
/* // For *nix operating system
* For *nix operating system
*/
$paths1 = [ $paths1 = [
'first/directory', 'first/directory',
'second/one', 'second/one',
@@ -546,9 +555,7 @@ class MiscellaneousTest extends BaseTestCase
public function testConcatenatePathsInWindowsOs() public function testConcatenatePathsInWindowsOs()
{ {
/* // For Windows operating system
* For Windows operating system
*/
$paths2 = [ $paths2 = [
'C:\first\directory', 'C:\first\directory',
'second\one', 'second\one',
@@ -597,18 +604,14 @@ class MiscellaneousTest extends BaseTestCase
public function testIsBetween() public function testIsBetween()
{ {
/* // Negative cases
* Negative cases
*/
self::assertFalse(Miscellaneous::isBetween(0, 0, 0)); self::assertFalse(Miscellaneous::isBetween(0, 0, 0));
self::assertFalse(Miscellaneous::isBetween('0', '0', '0')); self::assertFalse(Miscellaneous::isBetween('0', '0', '0'));
self::assertFalse(Miscellaneous::isBetween(0, 0, 1)); self::assertFalse(Miscellaneous::isBetween(0, 0, 1));
self::assertFalse(Miscellaneous::isBetween(-1, -1, -1)); self::assertFalse(Miscellaneous::isBetween(-1, -1, -1));
self::assertFalse(Miscellaneous::isBetween(1.2, 0.1, 1.1)); self::assertFalse(Miscellaneous::isBetween(1.2, 0.1, 1.1));
/* // Positive cases
* Positive cases
*/
self::assertTrue(Miscellaneous::isBetween(1, 0, 2)); self::assertTrue(Miscellaneous::isBetween(1, 0, 2));
self::assertTrue(Miscellaneous::isBetween('1', '0', '2')); self::assertTrue(Miscellaneous::isBetween('1', '0', '2'));
self::assertTrue(Miscellaneous::isBetween(-1, -2, 2)); self::assertTrue(Miscellaneous::isBetween(-1, -2, 2));
@@ -628,9 +631,7 @@ class MiscellaneousTest extends BaseTestCase
public function testGetValidColorComponent() public function testGetValidColorComponent()
{ {
/* // Negative cases
* Negative cases
*/
self::assertEquals(0, Miscellaneous::getValidColorComponent(null)); self::assertEquals(0, Miscellaneous::getValidColorComponent(null));
self::assertEquals(0, Miscellaneous::getValidColorComponent('')); self::assertEquals(0, Miscellaneous::getValidColorComponent(''));
self::assertEquals(0, Miscellaneous::getValidColorComponent('0')); self::assertEquals(0, Miscellaneous::getValidColorComponent('0'));
@@ -638,18 +639,14 @@ class MiscellaneousTest extends BaseTestCase
self::assertEquals(0, Miscellaneous::getValidColorComponent(256)); self::assertEquals(0, Miscellaneous::getValidColorComponent(256));
self::assertEquals(0, Miscellaneous::getValidColorComponent(256, false)); self::assertEquals(0, Miscellaneous::getValidColorComponent(256, false));
/* // Positive cases - part 1
* Positive cases - part 1
*/
self::assertEquals(1, Miscellaneous::getValidColorComponent(1)); self::assertEquals(1, Miscellaneous::getValidColorComponent(1));
self::assertEquals('0a', Miscellaneous::getValidColorComponent(10)); self::assertEquals('0a', Miscellaneous::getValidColorComponent(10));
self::assertEquals('0f', Miscellaneous::getValidColorComponent(15)); self::assertEquals('0f', Miscellaneous::getValidColorComponent(15));
self::assertEquals(64, Miscellaneous::getValidColorComponent(100)); self::assertEquals(64, Miscellaneous::getValidColorComponent(100));
self::assertEquals('ff', Miscellaneous::getValidColorComponent(255)); self::assertEquals('ff', Miscellaneous::getValidColorComponent(255));
/* // Positive cases - part 2
* Positive cases - part 2
*/
self::assertEquals(1, Miscellaneous::getValidColorComponent(1, false)); self::assertEquals(1, Miscellaneous::getValidColorComponent(1, false));
self::assertEquals(10, Miscellaneous::getValidColorComponent(10, false)); self::assertEquals(10, Miscellaneous::getValidColorComponent(10, false));
self::assertEquals(15, Miscellaneous::getValidColorComponent(15, false)); self::assertEquals(15, Miscellaneous::getValidColorComponent(15, false));
@@ -684,9 +681,7 @@ class MiscellaneousTest extends BaseTestCase
public function testGetInvertedColor() public function testGetInvertedColor()
{ {
/* // Simple cases
* Simple cases
*/
self::assertEquals('000000', Miscellaneous::getInvertedColor('fff')); self::assertEquals('000000', Miscellaneous::getInvertedColor('fff'));
self::assertEquals('ffffff', Miscellaneous::getInvertedColor('000')); self::assertEquals('ffffff', Miscellaneous::getInvertedColor('000'));
self::assertEquals('000000', Miscellaneous::getInvertedColor('ffffff')); self::assertEquals('000000', Miscellaneous::getInvertedColor('ffffff'));
@@ -694,18 +689,14 @@ class MiscellaneousTest extends BaseTestCase
self::assertEquals('#000000', Miscellaneous::getInvertedColor('#ffffff')); self::assertEquals('#000000', Miscellaneous::getInvertedColor('#ffffff'));
self::assertEquals('#ffffff', Miscellaneous::getInvertedColor('#000000')); self::assertEquals('#ffffff', Miscellaneous::getInvertedColor('#000000'));
/* // Advanced cases - part 1
* Advanced cases - part 1
*/
self::assertEquals('ffffee', Miscellaneous::getInvertedColor('001')); self::assertEquals('ffffee', Miscellaneous::getInvertedColor('001'));
self::assertEquals('ffeeff', Miscellaneous::getInvertedColor('010')); self::assertEquals('ffeeff', Miscellaneous::getInvertedColor('010'));
self::assertEquals('eeffff', Miscellaneous::getInvertedColor('100')); self::assertEquals('eeffff', Miscellaneous::getInvertedColor('100'));
self::assertEquals('333333', Miscellaneous::getInvertedColor('ccc')); self::assertEquals('333333', Miscellaneous::getInvertedColor('ccc'));
self::assertEquals('333333', Miscellaneous::getInvertedColor('CCC')); self::assertEquals('333333', Miscellaneous::getInvertedColor('CCC'));
/* // Advanced cases - part 2
* Advanced cases - part 2
*/
self::assertEquals('3e3e3e', Miscellaneous::getInvertedColor('c1c1c1')); self::assertEquals('3e3e3e', Miscellaneous::getInvertedColor('c1c1c1'));
self::assertEquals('3e3e3e', Miscellaneous::getInvertedColor('C1C1C1')); self::assertEquals('3e3e3e', Miscellaneous::getInvertedColor('C1C1C1'));
self::assertEquals('#dd5a01', Miscellaneous::getInvertedColor('#22a5fe')); self::assertEquals('#dd5a01', Miscellaneous::getInvertedColor('#22a5fe'));
@@ -713,9 +704,7 @@ class MiscellaneousTest extends BaseTestCase
self::assertEquals('#464646', Miscellaneous::getInvertedColor('#b9b9b9')); self::assertEquals('#464646', Miscellaneous::getInvertedColor('#b9b9b9'));
self::assertEquals('#080808', Miscellaneous::getInvertedColor('#f7f7f7')); self::assertEquals('#080808', Miscellaneous::getInvertedColor('#f7f7f7'));
/* // Advanced cases - verification
* Advanced cases - verification
*/
self::assertEquals('000011', Miscellaneous::getInvertedColor('ffffee')); self::assertEquals('000011', Miscellaneous::getInvertedColor('ffffee'));
self::assertEquals('cccccc', Miscellaneous::getInvertedColor('333333')); self::assertEquals('cccccc', Miscellaneous::getInvertedColor('333333'));
self::assertEquals('#22a5fe', Miscellaneous::getInvertedColor('#dd5a01')); self::assertEquals('#22a5fe', Miscellaneous::getInvertedColor('#dd5a01'));
@@ -1475,26 +1464,4 @@ class MiscellaneousTest extends BaseTestCase
'Lorem \'commodo\' dolor sit \'egestas\'', 'Lorem \'commodo\' dolor sit \'egestas\'',
]; ];
} }
/**
* {@inheritdoc}
*/
protected function setUp(): void
{
parent::setUp();
$this->stringSmall = 'Lorem ipsum dolor sit amet.';
$this->stringCommaSeparated = 'Lorem ipsum dolor sit amet, consectetur adipiscing elit';
$this->stringDotSeparated = 'Etiam ullamcorper. Suspendisse a pellentesque dui, non felis.';
$this->stringWithoutSpaces = 'LoremIpsumDolorSitAmetConsecteturAdipiscingElit';
}
/**
* {@inheritdoc}
*/
protected function tearDown(): void
{
parent::tearDown();
unset($this->stringSmall, $this->stringCommaSeparated, $this->stringDotSeparated, $this->stringWithoutSpaces);
}
} }

View File

@@ -23,6 +23,9 @@ use Meritoo\Common\Utilities\QueryBuilderUtility;
* *
* @author Meritoo <github@meritoo.pl> * @author Meritoo <github@meritoo.pl>
* @copyright Meritoo <http://www.meritoo.pl> * @copyright Meritoo <http://www.meritoo.pl>
*
* @internal
* @covers \Meritoo\Common\Utilities\QueryBuilderUtility
*/ */
class QueryBuilderUtilityTest extends BaseTestCase class QueryBuilderUtilityTest extends BaseTestCase
{ {
@@ -33,7 +36,7 @@ class QueryBuilderUtilityTest extends BaseTestCase
/** /**
* @param QueryBuilder $queryBuilder The query builder to retrieve root alias * @param QueryBuilder $queryBuilder The query builder to retrieve root alias
* @param string|null $rootAlias Expected root alias of given query builder * @param null|string $rootAlias Expected root alias of given query builder
* *
* @dataProvider provideQueryBuilderAndRootAlias * @dataProvider provideQueryBuilderAndRootAlias
*/ */
@@ -45,7 +48,7 @@ class QueryBuilderUtilityTest extends BaseTestCase
/** /**
* @param QueryBuilder $queryBuilder The query builder to verify * @param QueryBuilder $queryBuilder The query builder to verify
* @param string $propertyName Name of property that maybe is joined * @param string $propertyName Name of property that maybe is joined
* @param string|null $propertyAlias Expected alias of given property joined in given query builder * @param null|string $propertyAlias Expected alias of given property joined in given query builder
* *
* @dataProvider provideQueryBuilderAndPropertyAlias * @dataProvider provideQueryBuilderAndPropertyAlias
*/ */
@@ -93,9 +96,7 @@ class QueryBuilderUtilityTest extends BaseTestCase
$criteriaCount = count($criteria); $criteriaCount = count($criteria);
$nullsCount = 0; $nullsCount = 0;
/* // I have to verify count/amount of NULLs and decrease $criteriaCount, because for null parameter is not added
* I have to verify count/amount of NULLs and decrease $criteriaCount, because for null parameter is not added
*/
array_walk($criteria, function ($value) use (&$nullsCount) { array_walk($criteria, function ($value) use (&$nullsCount) {
if (null === $value) { if (null === $value) {
++$nullsCount; ++$nullsCount;

View File

@@ -31,9 +31,7 @@ class F
$this->username = $username; $this->username = $username;
$this->gInstance = new G($firstName, $lastName); $this->gInstance = new G($firstName, $lastName);
/* // Called to avoid "Unused private method getAccountBalance" warning only
* Called to avoid "Unused private method getAccountBalance" warning only
*/
$this->getAccountBalance(); $this->getAccountBalance();
} }

View File

@@ -17,11 +17,11 @@ namespace Meritoo\Test\Common\Utilities\Reflection;
*/ */
class H class H
{ {
const DOLOR = 'sit'; public const DOLOR = 'sit';
const LOREM = 'ipsum'; public const LOREM = 'ipsum';
const MAX_USERS = 5; public const MAX_USERS = 5;
const MIN_USERS = 2; public const MIN_USERS = 2;
} }

View File

@@ -33,6 +33,9 @@ use ReflectionProperty;
* *
* @author Meritoo <github@meritoo.pl> * @author Meritoo <github@meritoo.pl>
* @copyright Meritoo <http://www.meritoo.pl> * @copyright Meritoo <http://www.meritoo.pl>
*
* @internal
* @covers \Meritoo\Common\Utilities\Reflection
*/ */
class ReflectionTest extends BaseTestCase class ReflectionTest extends BaseTestCase
{ {
@@ -53,18 +56,14 @@ class ReflectionTest extends BaseTestCase
public function testGetClassNameNotExistingClass() public function testGetClassNameNotExistingClass()
{ {
/* // 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()
{ {
/* // Existing class
* Existing class
*/
self::assertEquals(self::class, Reflection::getClassName(self::class)); self::assertEquals(self::class, Reflection::getClassName(self::class));
self::assertEquals('ReflectionTest', Reflection::getClassName(self::class, true)); self::assertEquals('ReflectionTest', Reflection::getClassName(self::class, true));
self::assertEquals(DateTime::class, Reflection::getClassName(new DateTime())); self::assertEquals(DateTime::class, Reflection::getClassName(new DateTime()));
@@ -94,17 +93,13 @@ class ReflectionTest extends BaseTestCase
public function testGetClassNamespaceNotExistingClass() public function testGetClassNamespaceNotExistingClass()
{ {
/* // Not existing class
* Not existing class
*/
self::assertEquals('', Reflection::getClassNamespace('xyz')); self::assertEquals('', Reflection::getClassNamespace('xyz'));
} }
public function testGetClassNamespaceExistingClass() public function testGetClassNamespaceExistingClass()
{ {
/* // Existing class
* Existing class
*/
self::assertEquals('Meritoo\Test\Common\Utilities', Reflection::getClassNamespace(self::class)); self::assertEquals('Meritoo\Test\Common\Utilities', Reflection::getClassNamespace(self::class));
self::assertEquals(DateTime::class, Reflection::getClassNamespace(new DateTime())); self::assertEquals(DateTime::class, Reflection::getClassNamespace(new DateTime()));

View File

@@ -6,24 +6,49 @@
* file that was distributed with this source code. * file that was distributed with this source code.
*/ */
namespace Meritoo\Common\Utilities; namespace Meritoo\Test\Common\Utilities;
use Generator; use Generator;
use Meritoo\Common\Exception\Regex\IncorrectColorHexLengthException; use Meritoo\Common\Exception\Regex\IncorrectColorHexLengthException;
use Meritoo\Common\Exception\Regex\InvalidColorHexValueException; use Meritoo\Common\Exception\Regex\InvalidColorHexValueException;
use Meritoo\Common\Test\Base\BaseTestCase; use Meritoo\Common\Test\Base\BaseTestCase;
use Meritoo\Common\Utilities\Regex;
/** /**
* Test case of the useful regular expressions methods * Test case of the useful regular expressions methods
* *
* @author Meritoo <github@meritoo.pl> * @author Meritoo <github@meritoo.pl>
* @copyright Meritoo <http://www.meritoo.pl> * @copyright Meritoo <http://www.meritoo.pl>
*
* @internal
* @covers \Meritoo\Common\Utilities\Regex
*/ */
class RegexTest extends BaseTestCase class RegexTest extends BaseTestCase
{ {
private $simpleText; private $simpleText;
private $camelCaseText; private $camelCaseText;
/**
* {@inheritdoc}
*/
protected function setUp(): void
{
parent::setUp();
$this->simpleText = 'lorem ipsum dolor sit';
$simpleUppercase = ucwords($this->simpleText);
$this->camelCaseText = str_replace(' ', '', lcfirst($simpleUppercase)); // 'loremIpsumDolorSit'
}
/**
* {@inheritdoc}
*/
protected function tearDown(): void
{
parent::tearDown();
unset($this->simpleText, $this->camelCaseText);
}
public function testConstructor() public function testConstructor()
{ {
static::assertHasNoConstructor(Regex::class); static::assertHasNoConstructor(Regex::class);
@@ -171,23 +196,17 @@ class RegexTest extends BaseTestCase
public function testStartsWithDirectorySeparator() public function testStartsWithDirectorySeparator()
{ {
/* // Not provided, default separator
* Not provided, default separator
*/
self::assertTrue(Regex::startsWithDirectorySeparator('/my/extra/directory')); self::assertTrue(Regex::startsWithDirectorySeparator('/my/extra/directory'));
self::assertFalse(Regex::startsWithDirectorySeparator('my/extra/directory')); self::assertFalse(Regex::startsWithDirectorySeparator('my/extra/directory'));
/* // Slash as separator
* Slash as separator
*/
$separatorSlash = '/'; $separatorSlash = '/';
self::assertTrue(Regex::startsWithDirectorySeparator('/my/extra/directory', $separatorSlash)); self::assertTrue(Regex::startsWithDirectorySeparator('/my/extra/directory', $separatorSlash));
self::assertFalse(Regex::startsWithDirectorySeparator('my/extra/directory', $separatorSlash)); self::assertFalse(Regex::startsWithDirectorySeparator('my/extra/directory', $separatorSlash));
/* // Backslash as separator
* Backslash as separator
*/
$separatorBackslash = '\\'; $separatorBackslash = '\\';
self::assertTrue(Regex::startsWithDirectorySeparator('\my\extra\directory', $separatorBackslash)); self::assertTrue(Regex::startsWithDirectorySeparator('\my\extra\directory', $separatorBackslash));
@@ -196,23 +215,17 @@ class RegexTest extends BaseTestCase
public function testEndsWithDirectorySeparator() public function testEndsWithDirectorySeparator()
{ {
/* // Not provided, default separator
* Not provided, default separator
*/
self::assertTrue(Regex::endsWithDirectorySeparator('my simple text/')); self::assertTrue(Regex::endsWithDirectorySeparator('my simple text/'));
self::assertFalse(Regex::endsWithDirectorySeparator('my simple text')); self::assertFalse(Regex::endsWithDirectorySeparator('my simple text'));
/* // Slash as separator
* Slash as separator
*/
$separatorSlash = '/'; $separatorSlash = '/';
self::assertTrue(Regex::endsWithDirectorySeparator('my simple text/', $separatorSlash)); self::assertTrue(Regex::endsWithDirectorySeparator('my simple text/', $separatorSlash));
self::assertFalse(Regex::endsWithDirectorySeparator('my simple text', $separatorSlash)); self::assertFalse(Regex::endsWithDirectorySeparator('my simple text', $separatorSlash));
/* // Backslash as separator
* Backslash as separator
*/
$separatorBackslash = '\\'; $separatorBackslash = '\\';
self::assertTrue(Regex::endsWithDirectorySeparator('my simple text\\', $separatorBackslash)); self::assertTrue(Regex::endsWithDirectorySeparator('my simple text\\', $separatorBackslash));
@@ -912,17 +925,13 @@ class RegexTest extends BaseTestCase
false, false,
]; ];
/* // Microsoft sp. z o.o.
* Microsoft sp. z o.o.
*/
yield[ yield[
'5270103391', '5270103391',
true, true,
]; ];
/* // Onet S.A.
* Onet S.A.
*/
yield[ yield[
'7340009469', '7340009469',
true, true,
@@ -1994,25 +2003,4 @@ class RegexTest extends BaseTestCase
true, true,
]; ];
} }
/**
* {@inheritdoc}
*/
protected function setUp(): void
{
parent::setUp();
$this->simpleText = 'lorem ipsum dolor sit';
$simpleUppercase = ucwords($this->simpleText);
$this->camelCaseText = str_replace(' ', '', lcfirst($simpleUppercase)); // 'loremIpsumDolorSit'
}
/**
* {@inheritdoc}
*/
protected function tearDown(): void
{
parent::tearDown();
unset($this->simpleText, $this->camelCaseText);
}
} }

View File

@@ -34,6 +34,16 @@ class Sortable
$this->position = $position; $this->position = $position;
} }
/**
* Returns representation of object as string
*
* @return string
*/
public function __toString()
{
return sprintf('%s (position: %d)', self::class, $this->getPosition());
}
/** /**
* Returns position used while sorting * Returns position used while sorting
* *
@@ -53,14 +63,4 @@ class Sortable
{ {
$this->position = $position; $this->position = $position;
} }
/**
* Returns representation of object as string
*
* @return string
*/
public function __toString()
{
return sprintf('%s (position: %d)', self::class, $this->getPosition());
}
} }

View File

@@ -10,7 +10,6 @@ namespace Meritoo\Test\Common\Utilities;
use Doctrine\ORM\EntityManagerInterface; use Doctrine\ORM\EntityManagerInterface;
use Doctrine\ORM\EntityRepository; use Doctrine\ORM\EntityRepository;
use Doctrine\ORM\Query\Expr\OrderBy;
use Doctrine\ORM\QueryBuilder; use Doctrine\ORM\QueryBuilder;
use Generator; use Generator;
use Meritoo\Common\Test\Base\BaseTestCase; use Meritoo\Common\Test\Base\BaseTestCase;
@@ -23,6 +22,9 @@ use stdClass;
* *
* @author Meritoo <github@meritoo.pl> * @author Meritoo <github@meritoo.pl>
* @copyright Meritoo <http://www.meritoo.pl> * @copyright Meritoo <http://www.meritoo.pl>
*
* @internal
* @covers \Meritoo\Common\Utilities\Repository
*/ */
class RepositoryTest extends BaseTestCase class RepositoryTest extends BaseTestCase
{ {
@@ -53,27 +55,19 @@ class RepositoryTest extends BaseTestCase
new stdClass(), new stdClass(),
]; ];
/* // Using defaults
* Using defaults
*/
Repository::replenishPositions($before); Repository::replenishPositions($before);
static::assertEquals($before, $after); static::assertEquals($before, $after);
/* // Place items at the top
* Place items at the top
*/
Repository::replenishPositions($before, false); Repository::replenishPositions($before, false);
static::assertEquals($before, $after); static::assertEquals($before, $after);
/* // Set positions even there is no extreme position (at the end)
* Set positions even there is no extreme position (at the end)
*/
Repository::replenishPositions($before, true, true); Repository::replenishPositions($before, true, true);
static::assertEquals($before, $after); static::assertEquals($before, $after);
/* // Set positions even there is no extreme position (at the top)
* Set positions even there is no extreme position (at the top)
*/
Repository::replenishPositions($before, false, true); Repository::replenishPositions($before, false, true);
static::assertEquals($before, $after); static::assertEquals($before, $after);
} }
@@ -238,7 +232,7 @@ class RepositoryTest extends BaseTestCase
$orderDQLPart = $queryBuilder->getDQLPart('orderBy'); $orderDQLPart = $queryBuilder->getDQLPart('orderBy');
$rootAliases = $queryBuilder->getRootAliases(); $rootAliases = $queryBuilder->getRootAliases();
/* @var OrderBy $orderBy */ /** @var OrderBy $orderBy */
$orderBy = $orderDQLPart[0]; $orderBy = $orderDQLPart[0];
static::assertInstanceOf(QueryBuilder::class, $queryBuilder); static::assertInstanceOf(QueryBuilder::class, $queryBuilder);
@@ -293,7 +287,7 @@ class RepositoryTest extends BaseTestCase
if (empty($property)) { if (empty($property)) {
static::assertSame([], $orderDQLPart); static::assertSame([], $orderDQLPart);
} else { } else {
/* @var OrderBy $orderBy */ /** @var OrderBy $orderBy */
$orderBy = $orderDQLPart[0]; $orderBy = $orderDQLPart[0];
static::assertSame([$expectedOrderBy], $orderBy->getParts()); static::assertSame([$expectedOrderBy], $orderBy->getParts());

View File

@@ -17,6 +17,9 @@ use Meritoo\Common\Utilities\Uri;
* *
* @author Meritoo <github@meritoo.pl> * @author Meritoo <github@meritoo.pl>
* @copyright Meritoo <http://www.meritoo.pl> * @copyright Meritoo <http://www.meritoo.pl>
*
* @internal
* @covers \Meritoo\Common\Utilities\Uri
*/ */
class UriTest extends BaseTestCase class UriTest extends BaseTestCase
{ {

View File

@@ -17,38 +17,15 @@ use SimpleXMLElement;
* *
* @author Meritoo <github@meritoo.pl> * @author Meritoo <github@meritoo.pl>
* @copyright Meritoo <http://www.meritoo.pl> * @copyright Meritoo <http://www.meritoo.pl>
*
* @internal
* @covers \Meritoo\Common\Utilities\Xml
*/ */
class XmlTest extends BaseTestCase class XmlTest extends BaseTestCase
{ {
private $simpleXml; private $simpleXml;
private $advancedXml; private $advancedXml;
public function testConstructor()
{
static::assertHasNoConstructor(Xml::class);
}
public function testMergeNodes()
{
/*
* An empty XMLs
*/
$element1 = new SimpleXMLElement('<?xml version="1.0" encoding="UTF-8"?><cars />');
$element2 = new SimpleXMLElement('<?xml version="1.0" encoding="UTF-8"?><employees />');
$merged = Xml::mergeNodes($element1, $element2);
self::assertEquals('', (string)$merged);
/*
* XMLs with data
*/
$element1 = new SimpleXMLElement($this->simpleXml);
$element2 = new SimpleXMLElement($this->advancedXml);
$merged = Xml::mergeNodes($element1, $element2);
self::assertEquals('John', (string)$merged->author[0]->first_name);
}
/** /**
* {@inheritdoc} * {@inheritdoc}
*/ */
@@ -90,7 +67,28 @@ class XmlTest extends BaseTestCase
{ {
parent::tearDown(); parent::tearDown();
unset($this->simpleXml); unset($this->simpleXml, $this->advancedXml);
unset($this->advancedXml); }
public function testConstructor()
{
static::assertHasNoConstructor(Xml::class);
}
public function testMergeNodes()
{
// An empty XMLs
$element1 = new SimpleXMLElement('<?xml version="1.0" encoding="UTF-8"?><cars />');
$element2 = new SimpleXMLElement('<?xml version="1.0" encoding="UTF-8"?><employees />');
$merged = Xml::mergeNodes($element1, $element2);
self::assertEquals('', (string)$merged);
// XMLs with data
$element1 = new SimpleXMLElement($this->simpleXml);
$element2 = new SimpleXMLElement($this->advancedXml);
$merged = Xml::mergeNodes($element1, $element2);
self::assertEquals('John', (string)$merged->author[0]->first_name);
} }
} }

View File

@@ -17,6 +17,9 @@ use Meritoo\Common\ValueObject\Address;
* *
* @author Meritoo <github@meritoo.pl> * @author Meritoo <github@meritoo.pl>
* @copyright Meritoo <http://www.meritoo.pl> * @copyright Meritoo <http://www.meritoo.pl>
*
* @internal
* @covers \Meritoo\Common\ValueObject\Address
*/ */
class AddressTest extends BaseTestCase class AddressTest extends BaseTestCase
{ {
@@ -35,6 +38,15 @@ class AddressTest extends BaseTestCase
*/ */
private $addressWithoutStreet; private $addressWithoutStreet;
protected function setUp(): void
{
parent::setUp();
$this->address = new Address('New York', '00123', '4th Avenue', '10', '200');
$this->addressWithoutFlat = new Address('San Francisco', '00456', 'Green Street', '22');
$this->addressWithoutStreet = new Address('Saint Louis', '00111', '', '1', '300');
}
public function testConstructor() public function testConstructor()
{ {
static::assertConstructorVisibilityAndArguments( static::assertConstructorVisibilityAndArguments(
@@ -93,13 +105,4 @@ class AddressTest extends BaseTestCase
static::assertSame('Green Street 22, 00456, San Francisco', (string)$this->addressWithoutFlat); static::assertSame('Green Street 22, 00456, San Francisco', (string)$this->addressWithoutFlat);
static::assertSame('00111, Saint Louis', (string)$this->addressWithoutStreet); static::assertSame('00111, Saint Louis', (string)$this->addressWithoutStreet);
} }
protected function setUp(): void
{
parent::setUp();
$this->address = new Address('New York', '00123', '4th Avenue', '10', '200');
$this->addressWithoutFlat = new Address('San Francisco', '00456', 'Green Street', '22');
$this->addressWithoutStreet = new Address('Saint Louis', '00111', '', '1', '300');
}
} }

View File

@@ -17,6 +17,9 @@ use Meritoo\Common\ValueObject\BankAccount;
* *
* @author Meritoo <github@meritoo.pl> * @author Meritoo <github@meritoo.pl>
* @copyright Meritoo <http://www.meritoo.pl> * @copyright Meritoo <http://www.meritoo.pl>
*
* @internal
* @covers \Meritoo\Common\ValueObject\BankAccount
*/ */
class BankAccountTest extends BaseTestCase class BankAccountTest extends BaseTestCase
{ {
@@ -30,6 +33,17 @@ class BankAccountTest extends BaseTestCase
*/ */
private $bankAccount; private $bankAccount;
/**
* {@inheritdoc}
*/
protected function setUp(): void
{
parent::setUp();
$this->emptyBankAccount = new BankAccount('', '');
$this->bankAccount = new BankAccount('Bank of America', '1234567890');
}
public function testConstructor() public function testConstructor()
{ {
static::assertConstructorVisibilityAndArguments( static::assertConstructorVisibilityAndArguments(
@@ -57,15 +71,4 @@ class BankAccountTest extends BaseTestCase
static::assertSame('', (string)$this->emptyBankAccount); static::assertSame('', (string)$this->emptyBankAccount);
static::assertSame('Bank of America, 1234567890', (string)$this->bankAccount); static::assertSame('Bank of America, 1234567890', (string)$this->bankAccount);
} }
/**
* {@inheritdoc}
*/
protected function setUp(): void
{
parent::setUp();
$this->emptyBankAccount = new BankAccount('', '');
$this->bankAccount = new BankAccount('Bank of America', '1234567890');
}
} }

View File

@@ -19,6 +19,9 @@ use Meritoo\Common\ValueObject\Company;
* *
* @author Meritoo <github@meritoo.pl> * @author Meritoo <github@meritoo.pl>
* @copyright Meritoo <http://www.meritoo.pl> * @copyright Meritoo <http://www.meritoo.pl>
*
* @internal
* @covers \Meritoo\Common\ValueObject\Company
*/ */
class CompanyTest extends BaseTestCase class CompanyTest extends BaseTestCase
{ {
@@ -32,6 +35,25 @@ class CompanyTest extends BaseTestCase
*/ */
private $companyWithoutBankAccount; private $companyWithoutBankAccount;
/**
* {@inheritdoc}
*/
protected function setUp(): void
{
parent::setUp();
$this->company = new Company(
'Test 1',
new Address('New York', '00123', '4th Avenue', '10', '200'),
new BankAccount('Bank 1', '12345')
);
$this->companyWithoutBankAccount = new Company(
'Test 2',
new Address('San Francisco', '00456', 'Green Street', '22')
);
}
public function testConstructor() public function testConstructor()
{ {
static::assertConstructorVisibilityAndArguments( static::assertConstructorVisibilityAndArguments(
@@ -76,23 +98,4 @@ class CompanyTest extends BaseTestCase
static::assertSame('Test 1, 4th Avenue 10/200, 00123, New York, Bank 1, 12345', (string)$this->company); static::assertSame('Test 1, 4th Avenue 10/200, 00123, New York, Bank 1, 12345', (string)$this->company);
static::assertSame('Test 2, Green Street 22, 00456, San Francisco', (string)$this->companyWithoutBankAccount); static::assertSame('Test 2, Green Street 22, 00456, San Francisco', (string)$this->companyWithoutBankAccount);
} }
/**
* {@inheritdoc}
*/
protected function setUp(): void
{
parent::setUp();
$this->company = new Company(
'Test 1',
new Address('New York', '00123', '4th Avenue', '10', '200'),
new BankAccount('Bank 1', '12345')
);
$this->companyWithoutBankAccount = new Company(
'Test 2',
new Address('San Francisco', '00456', 'Green Street', '22')
);
}
} }

View File

@@ -17,6 +17,9 @@ use Meritoo\Common\ValueObject\Human;
* *
* @author Meritoo <github@meritoo.pl> * @author Meritoo <github@meritoo.pl>
* @copyright Meritoo <http://www.meritoo.pl> * @copyright Meritoo <http://www.meritoo.pl>
*
* @internal
* @covers \Meritoo\Common\ValueObject\Human
*/ */
class HumanTest extends BaseTestCase class HumanTest extends BaseTestCase
{ {

View File

@@ -18,6 +18,9 @@ use Meritoo\Common\ValueObject\Size;
* *
* @author Meritoo <github@meritoo.pl> * @author Meritoo <github@meritoo.pl>
* @copyright Meritoo <http://www.meritoo.pl> * @copyright Meritoo <http://www.meritoo.pl>
*
* @internal
* @covers \Meritoo\Common\ValueObject\Size
*/ */
class SizeTest extends BaseTestCase class SizeTest extends BaseTestCase
{ {
@@ -32,12 +35,12 @@ class SizeTest extends BaseTestCase
/** /**
* @param string $description Description of test * @param string $description Description of test
* @param Size|null $size Size to convert * @param null|Size $size Size to convert
* @param string $expected Expected result * @param string $expected Expected result
* *
* @dataProvider provideSizeForConvertingToString * @dataProvider provideSizeForConvertingToString
*/ */
public function test__toString($description, $size, $expected) public function testToStringConverting($description, $size, $expected)
{ {
static::assertEquals($expected, (string)$size, $description); static::assertEquals($expected, (string)$size, $description);
} }
@@ -57,7 +60,7 @@ class SizeTest extends BaseTestCase
* @param string $description Description of test * @param string $description Description of test
* @param Size $size Size to get width * @param Size $size Size to get width
* @param bool $withUnit If is set to true, width is returned with unit ("px"). Otherwise - without. * @param bool $withUnit If is set to true, width is returned with unit ("px"). Otherwise - without.
* @param string|int $expected Expected width * @param int|string $expected Expected width
* *
* @dataProvider provideSizeToGetWidth * @dataProvider provideSizeToGetWidth
*/ */
@@ -70,7 +73,7 @@ class SizeTest extends BaseTestCase
* @param string $description Description of test * @param string $description Description of test
* @param Size $size Size to set width * @param Size $size Size to set width
* @param int|string $width The width * @param int|string $width The width
* @param string|int $expected Expected width * @param int|string $expected Expected width
* *
* @dataProvider provideSizeToSetWidth * @dataProvider provideSizeToSetWidth
*/ */
@@ -86,7 +89,7 @@ class SizeTest extends BaseTestCase
* @param string $description Description of test * @param string $description Description of test
* @param Size $size Size to get width * @param Size $size Size to get width
* @param bool $withUnit If is set to true, width is returned with unit ("px"). Otherwise - without. * @param bool $withUnit If is set to true, width is returned with unit ("px"). Otherwise - without.
* @param string|int $expected Expected width * @param int|string $expected Expected width
* *
* @dataProvider provideSizeToGetHeight * @dataProvider provideSizeToGetHeight
*/ */
@@ -99,7 +102,7 @@ class SizeTest extends BaseTestCase
* @param string $description Description of test * @param string $description Description of test
* @param Size $size Size to set height * @param Size $size Size to set height
* @param int|string $height The height * @param int|string $height The height
* @param string|int $expected Expected height * @param int|string $expected Expected height
* *
* @dataProvider provideSizeToSetHeight * @dataProvider provideSizeToSetHeight
*/ */
@@ -167,7 +170,7 @@ class SizeTest extends BaseTestCase
* @param string $size The size represented as string (width and height separated by "x") * @param string $size The size represented as string (width and height separated by "x")
* @param string $unit Unit used when width or height should be returned with unit * @param string $unit Unit used when width or height should be returned with unit
* @param string $separator Separator used to split width and height * @param string $separator Separator used to split width and height
* @param Size|null $expected Expected result * @param null|Size $expected Expected result
* *
* @dataProvider provideSizeForFromString * @dataProvider provideSizeForFromString
*/ */

View File

@@ -19,6 +19,9 @@ use Meritoo\Common\ValueObject\Version;
* *
* @author Meritoo <github@meritoo.pl> * @author Meritoo <github@meritoo.pl>
* @copyright Meritoo <http://www.meritoo.pl> * @copyright Meritoo <http://www.meritoo.pl>
*
* @internal
* @covers \Meritoo\Common\ValueObject\Version
*/ */
class VersionTest extends BaseTestCase class VersionTest extends BaseTestCase
{ {