Arrays > refactoring & more tests

This commit is contained in:
Meritoo
2019-02-23 19:41:37 +01:00
parent ede9a182b4
commit 924e492e11
4 changed files with 956 additions and 264 deletions

View File

@@ -2,6 +2,10 @@
Common and useful classes, methods, exceptions etc. Common and useful classes, methods, exceptions etc.
# 0.1.6
1. Arrays > refactoring & more tests
# 0.1.5 # 0.1.5
1. Tests > Date > one more test case 1. Tests > Date > one more test case

View File

@@ -1 +1 @@
0.1.5 0.1.6

View File

@@ -27,102 +27,137 @@ class Arrays
* 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 Array data to be converted * @param array $array Data to be converted
* @param string|int $arrayColumnKey (optional) Column name * @param string|int $arrayColumnKey (optional) Column name. Default: "".
* @param string $separator (optional) Separator used in resultant string * @param string $separator (optional) Separator used between values. Default: ",".
* @return string * @return string|null
*/ */
public static function values2string(array $array, $arrayColumnKey = '', $separator = ',') public static function values2string(array $array, $arrayColumnKey = '', $separator = ',')
{ {
$effect = ''; /*
* No elements?
if (!empty($array)) { * Nothing to do
foreach ($array as $key => $value) { */
if (!empty($effect) && if (empty($array)) {
( return null;
empty($arrayColumnKey) || (!is_array($value) && $key === $arrayColumnKey)
)
) {
$effect .= $separator;
}
if (is_array($value)) {
$effect .= self::values2string($value, $arrayColumnKey, $separator);
} elseif (empty($arrayColumnKey)) {
$effect .= $value;
} elseif ($key === $arrayColumnKey) {
$effect .= $array[$arrayColumnKey];
}
}
} }
return $effect; $values = [];
foreach ($array as $key => $value) {
$appendMe = null;
if (is_array($value)) {
$appendMe = self::values2string($value, $arrayColumnKey, $separator);
} elseif (empty($arrayColumnKey)) {
$appendMe = $value;
} elseif ($key === $arrayColumnKey) {
$appendMe = $array[$arrayColumnKey];
}
/*
* Part to append is unknown?
* Let's go to next part
*/
if (null === $appendMe) {
continue;
}
$values[] = $appendMe;
}
/*
* No values found?
* Nothing to do
*/
if (empty($values)) {
return null;
}
return implode($separator, $values);
} }
/** /**
* Converts given array to string with keys, e.g. abc=1&def=2 or abc="1" def="2" * Converts given array to string with keys, e.g. abc=1&def=2 or abc="1" def="2"
* *
* @param array $array Array data to be converted * @param array $array Data to be converted
* @param string $separator (optional) Separator used between name-value pairs in resultant string * @param string $separator (optional) Separator used between name-value pairs. Default: ",".
* @param string $valuesKeysSeparator (optional) Separator used between name and value in resultant string * @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".
* @return string * Default: "".
* @return string|null
*/ */
public static function valuesKeys2string($array, $separator = ',', $valuesKeysSeparator = '=', $valuesWrapper = '') public static function valuesKeys2string(
{ array $array,
$effect = ''; $separator = ',',
$valuesKeysSeparator = '=',
if (is_array($array) && !empty($array)) { $valuesWrapper = ''
foreach ($array as $key => $value) { ) {
if (!empty($effect)) { /*
$effect .= $separator; * No elements?
} * Nothing to do
*/
if (!empty($valuesWrapper)) { if (empty($array)) {
$value = sprintf('%s%s%s', $valuesWrapper, $value, $valuesWrapper); return null;
}
$effect .= $key . $valuesKeysSeparator . $value;
}
} }
return $effect; $result = '';
foreach ($array as $key => $value) {
if (!empty($result)) {
$result .= $separator;
}
if (!empty($valuesWrapper)) {
$value = sprintf('%s%s%s', $valuesWrapper, $value, $valuesWrapper);
}
$result .= $key . $valuesKeysSeparator . $value;
}
return $result;
} }
/** /**
* Converts given array's rows to csv string * Converts given array's rows to csv string
* *
* @param array $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 in resultant string * @param string $separator (optional) Separator used between values. Default: ",".
* @return string * @return string|null
*/ */
public static function values2csv($array, $separator = ',') public static function values2csv(array $array, $separator = ',')
{ {
if (is_array($array) && !empty($array)) { /*
$rows = []; * No elements?
$lineSeparator = "\n"; * Nothing to do
*/
if (empty($array)) {
return null;
}
foreach ($array as $row) { $rows = [];
/* $lineSeparator = "\n";
* I have to use html_entity_decode() function here, because some string values can contain
* entities with semicolon and this can destroy the CSV column order.
*/
if (is_array($row) && !empty($row)) { foreach ($array as $row) {
foreach ($row as $key => $value) { /*
$row[$key] = html_entity_decode($value); * I have to use html_entity_decode() function here, because some string values can contain
} * entities with semicolon and this can destroy the CSV column order.
*/
$rows[] = implode($separator, $row); if (is_array($row) && !empty($row)) {
foreach ($row as $key => $value) {
$row[$key] = html_entity_decode($value);
} }
}
if (!empty($rows)) { $rows[] = implode($separator, $row);
return implode($lineSeparator, $rows);
} }
} }
return ''; if (empty($rows)) {
return '';
}
return implode($lineSeparator, $rows);
} }
/** /**
@@ -242,12 +277,20 @@ class Arrays
/** /**
* Returns breadcrumb (a path) to the last element of array * Returns breadcrumb (a path) to the last element of array
* *
* @param array $array The array to get the breadcrumb * @param array $array Data to get the breadcrumb
* @param string $separator (optional) Separator used to stick the elements * @param string $separator (optional) Separator used to stick the elements. Default: "/".
* @return string * @return string|null
*/ */
public static function getLastElementBreadCrumb($array, $separator = '/') public static function getLastElementBreadCrumb(array $array, $separator = '/')
{ {
/*
* No elements?
* Nothing to do
*/
if (empty($array)) {
return null;
}
$keys = array_keys($array); $keys = array_keys($array);
$keysCount = count($keys); $keysCount = count($keys);
@@ -350,7 +393,7 @@ class Arrays
return null; return null;
} }
$effect = ''; $result = '';
$counter = 0; $counter = 0;
$arrayCount = count($array); $arrayCount = count($array);
@@ -366,14 +409,14 @@ class Arrays
} }
if (!empty($jsVariableName) && is_string($jsVariableName)) { if (!empty($jsVariableName) && is_string($jsVariableName)) {
$effect .= sprintf('var %s = ', $jsVariableName); $result .= sprintf('var %s = ', $jsVariableName);
} }
$effect .= 'new Array('; $result .= 'new Array(';
if ($preserveIndexes || $isMultiDimensional) { if ($preserveIndexes || $isMultiDimensional) {
$effect .= $arrayCount; $result .= $arrayCount;
$effect .= ');'; $result .= ');';
} }
foreach ($array as $index => $value) { foreach ($array as $index => $value) {
@@ -397,20 +440,20 @@ class Arrays
* autoGeneratedVariable[1] = new Array(...); * autoGeneratedVariable[1] = new Array(...);
*/ */
if (1 === $counter) { if (1 === $counter) {
$effect .= "\n"; $result .= "\n";
} }
$effect .= $value . "\n"; $result .= $value . "\n";
$effect .= sprintf('%s[%s] = %s;', $jsVariableName, Miscellaneous::quoteValue($index), $variable); $result .= sprintf('%s[%s] = %s;', $jsVariableName, Miscellaneous::quoteValue($index), $variable);
if ($counter !== $arrayCount) { if ($counter !== $arrayCount) {
$effect .= "\n"; $result .= "\n";
} }
} }
} elseif ($preserveIndexes) { } elseif ($preserveIndexes) {
if (!empty($jsVariableName)) { if (!empty($jsVariableName)) {
$index = Miscellaneous::quoteValue($index); $index = Miscellaneous::quoteValue($index);
$effect .= sprintf("\n%s[%s] = %s;", $jsVariableName, $index, $value); $result .= sprintf("\n%s[%s] = %s;", $jsVariableName, $index, $value);
} }
} else { } else {
$format = '%s'; $format = '%s';
@@ -419,44 +462,48 @@ class Arrays
$format .= ', '; $format .= ', ';
} }
$effect .= sprintf($format, $value); $result .= sprintf($format, $value);
} }
} }
if (!$preserveIndexes && !$isMultiDimensional) { if (!$preserveIndexes && !$isMultiDimensional) {
$effect .= ');'; $result .= ');';
} }
return $effect; return $result;
} }
/** /**
* Quotes (adds quotes) to elements of an array that are strings * 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 * @return array|null
*/ */
public static function quoteStrings($array) public static function quoteStrings(array $array)
{ {
$effect = $array; /*
* No elements?
if (is_array($array) && !empty($array)) { * Nothing to do
$effect = []; */
if (empty($array)) {
foreach ($array as $index => $value) { return null;
if (is_array($value)) {
$value = self::quoteStrings($value);
} elseif (is_string($value)) {
if (!Regex::isQuoted($value)) {
$value = '\'' . $value . '\'';
}
}
$effect[$index] = $value;
}
} }
return $effect; $result = [];
foreach ($array as $index => $value) {
if (is_array($value)) {
$value = self::quoteStrings($value);
} elseif (is_string($value)) {
if (!Regex::isQuoted($value)) {
$value = '\'' . $value . '\'';
}
}
$result[$index] = $value;
}
return $result;
} }
/** /**
@@ -495,6 +542,14 @@ class Arrays
*/ */
public static function getLastKey(array $array) public static function getLastKey(array $array)
{ {
/*
* No elements?
* Nothing to do
*/
if (empty($array)) {
return null;
}
$keys = array_keys($array); $keys = array_keys($array);
return end($keys); return end($keys);
@@ -543,9 +598,9 @@ class Arrays
* @param bool $before (optional) If is set to true, all elements before given needle are removed. Otherwise - all * @param bool $before (optional) If is set to true, all elements before given needle are removed. Otherwise - all
* after needle. * after needle.
*/ */
public static function removeElements(&$array, $needle, $before = true) public static function removeElements(array &$array, $needle, $before = true)
{ {
if (is_array($array) && !empty($array)) { if (!empty($array)) {
if (!$before) { if (!$before) {
$array = array_reverse($array, true); $array = array_reverse($array, true);
} }
@@ -587,7 +642,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 * @return array|null
* *
* Example of $ignoreDuplicatedValues = false: * Example of $ignoreDuplicatedValues = false:
* - provided array * - provided array
@@ -613,7 +668,7 @@ class Arrays
* Nothing to do * Nothing to do
*/ */
if (empty($array)) { if (empty($array)) {
return []; return null;
} }
$replaced = []; $replaced = [];
@@ -724,8 +779,9 @@ class Arrays
* ] * ]
* *
* @param string $string The string to be converted * @param string $string The string to be converted
* @param string $separator (optional) Separator used between name-value pairs in the string * @param string $separator (optional) Separator used between name-value pairs in the string.
* @param string $valuesKeysSeparator (optional) Separator used between name and value in the string * Default: "|".
* @param string $valuesKeysSeparator (optional) Separator used between name and value in the string. Default: ":".
* @return array * @return array
*/ */
public static function string2array($string, $separator = '|', $valuesKeysSeparator = ':') public static function string2array($string, $separator = '|', $valuesKeysSeparator = ':')
@@ -759,52 +815,52 @@ class Arrays
* Returns information if given keys exist in given array * Returns information if given keys exist in given array
* *
* @param array $keys The keys to find * @param array $keys The keys to find
* @param array $array The array which maybe contains keys * @param array $array The array that maybe contains keys
* @param bool $explicit (optional) If is set to true, all keys should exist in given array. Otherwise - not all. * @param bool $explicit (optional) If is set to true, all keys should exist in given array. Otherwise - not all.
* @return bool * @return bool
*/ */
public static function areKeysInArray($keys, $array, $explicit = true) public static function areKeysInArray(array $keys, array $array, $explicit = true)
{ {
$effect = false; $result = false;
if (is_array($array) && !empty($array)) { if (!empty($array)) {
$firstKey = true; $firstKey = true;
foreach ($keys as $key) { foreach ($keys as $key) {
$exists = array_key_exists($key, $array); $exists = array_key_exists($key, $array);
if ($firstKey) { if ($firstKey) {
$effect = $exists; $result = $exists;
$firstKey = false; $firstKey = false;
} elseif ($explicit) { } elseif ($explicit) {
$effect = $effect && $exists; $result = $result && $exists;
if (!$effect) { if (!$result) {
break; break;
} }
} else { } else {
$effect = $effect || $exists; $result = $result || $exists;
if ($effect) { if ($result) {
break; break;
} }
} }
} }
} }
return $effect; return $result;
} }
/** /**
* Returns paths of the last elements * Returns paths of the last elements
* *
* @param array $array The array with elements * @param array $array The array with elements
* @param string $separator (optional) Separator used in resultant strings. 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 string|array $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) * will not be used for keys in lower level of given array). Default: "".
* @return array * @return array|null
* *
* Examples - $stopIfMatchedBy argument: * Examples - $stopIfMatchedBy argument:
* a) "\d+" * a) "\d+"
@@ -820,7 +876,7 @@ class Arrays
* Nothing to do * Nothing to do
*/ */
if (empty($array)) { if (empty($array)) {
return []; return null;
} }
if (!empty($stopIfMatchedBy)) { if (!empty($stopIfMatchedBy)) {
@@ -906,12 +962,13 @@ class Arrays
* first level only. * first level only.
* @return bool * @return bool
*/ */
public static function areAllKeysMatchedByPattern($array, $pattern, $firstLevelOnly = false) public static function areAllKeysMatchedByPattern(array $array, $pattern, $firstLevelOnly = false)
{ {
/* /*
* It's not an array or it's empty array? * No elements?
* Nothing to do
*/ */
if (!is_array($array) || (is_array($array) && empty($array))) { if (empty($array)) {
return false; return false;
} }
@@ -955,10 +1012,10 @@ class Arrays
* *
* @param array $array The array to check * @param array $array The array to check
* @param bool $firstLevelOnly (optional) If is set to true, all keys / indexes are checked. Otherwise - from the * @param bool $firstLevelOnly (optional) If is set to true, all keys / indexes are checked. Otherwise - from the
* first level only. * first level only (default behaviour).
* @return bool * @return bool
*/ */
public static function areAllKeysIntegers($array, $firstLevelOnly = false) public static function areAllKeysIntegers(array $array, $firstLevelOnly = false)
{ {
$pattern = '\d+'; $pattern = '\d+';
@@ -996,9 +1053,17 @@ class Arrays
*/ */
public static function getValueByKeysPath(array $array, array $keys) public static function getValueByKeysPath(array $array, array $keys)
{ {
/*
* No elements?
* Nothing to do
*/
if (empty($array)) {
return null;
}
$value = null; $value = null;
if (!empty($array) && self::issetRecursive($array, $keys)) { if (self::issetRecursive($array, $keys)) {
foreach ($keys as $key) { foreach ($keys as $key) {
$value = $array[$key]; $value = $array[$key];
array_shift($keys); array_shift($keys);
@@ -1042,23 +1107,29 @@ class Arrays
*/ */
public static function issetRecursive(array $array, array $keys) public static function issetRecursive(array $array, array $keys)
{ {
/*
* No elements?
* Nothing to do
*/
if (empty($array)) {
return false;
}
$isset = false; $isset = false;
if (!empty($array)) { foreach ($keys as $key) {
foreach ($keys as $key) { $isset = isset($array[$key]);
$isset = isset($array[$key]);
if ($isset) { if ($isset) {
$newArray = $array[$key]; $newArray = $array[$key];
array_shift($keys); array_shift($keys);
if (is_array($newArray) && !empty($keys)) { if (is_array($newArray) && !empty($keys)) {
$isset = self::issetRecursive($newArray, $keys); $isset = self::issetRecursive($newArray, $keys);
}
} }
break;
} }
break;
} }
return $isset; return $isset;
@@ -1113,22 +1184,28 @@ 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 * @return array|null
*/ */
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)
{ {
if (!empty($array)) { /*
$childPosition = 1; * No elements?
* Nothing to do
*/
if (empty($array)) {
return null;
}
if (null !== $startPosition) { $childPosition = 1;
$array[$keyName] = $startPosition;
}
foreach ($array as &$value) { if (null !== $startPosition) {
if (is_array($value)) { $array[$keyName] = $startPosition;
$value = self::setPositions($value, $keyName, $childPosition); }
++$childPosition;
} foreach ($array as &$value) {
if (is_array($value)) {
$value = self::setPositions($value, $keyName, $childPosition);
++$childPosition;
} }
} }
@@ -1143,26 +1220,30 @@ class Arrays
*/ */
public static function trimRecursive(array $array) public static function trimRecursive(array $array)
{ {
$effect = $array; /*
* No elements?
if (!empty($array)) { * Nothing to do
$effect = []; */
if (empty($array)) {
foreach ($array as $key => $value) { return [];
if (is_array($value)) {
$effect[$key] = self::trimRecursive($value);
continue;
}
if (is_string($value)) {
$value = trim($value);
}
$effect[$key] = $value;
}
} }
return $effect; $result = [];
foreach ($array as $key => $value) {
if (is_array($value)) {
$result[$key] = self::trimRecursive($value);
continue;
}
if (is_string($value)) {
$value = trim($value);
}
$result[$key] = $value;
}
return $result;
} }
/** /**
@@ -1255,7 +1336,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 * @return string|null
*/ */
public static function implodeSmart(array $array, $separator) public static function implodeSmart(array $array, $separator)
{ {
@@ -1264,7 +1345,7 @@ class Arrays
* Nothing to do * Nothing to do
*/ */
if (empty($array)) { if (empty($array)) {
return ''; return null;
} }
foreach ($array as &$element) { foreach ($array as &$element) {
@@ -1454,48 +1535,54 @@ class Arrays
* @param int|null $startIndex (optional) Index from which incrementation should be started. If not provided, * @param int|null $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 * @return array|null
*/ */
public static function incrementIndexes(array $array, $startIndex = null, $incrementStep = 1) public static function incrementIndexes(array $array, $startIndex = null, $incrementStep = 1)
{ {
if (!empty($array)) { /*
$valuesToIncrement = []; * No elements?
* Nothing to do
*/
if (empty($array)) {
return null;
}
$valuesToIncrement = [];
/*
* Start index not provided?
* Let's look for the first index / key of given array
*/
if (null === $startIndex) {
$startIndex = self::getFirstKey($array);
}
/*
* Is the start index a numeric value?
* Other indexes / keys cannot be incremented
*/
if (is_numeric($startIndex)) {
/* /*
* Start index not provided? * 1st step:
* Let's look for the first index / key of given array * Get values which indexes should be incremented and remove those values from given array
*/ */
if (null === $startIndex) { foreach ($array as $index => $value) {
$startIndex = self::getFirstKey($array); if ($index < $startIndex) {
continue;
}
$valuesToIncrement[$index] = $value;
unset($array[$index]);
} }
/* /*
* Is the start index a numeric value? * 2nd step:
* Other indexes / keys cannot be incremented * Increment indexes of gathered values
*/ */
if (is_numeric($startIndex)) { if (!empty($valuesToIncrement)) {
/* foreach ($valuesToIncrement as $oldIndex => $value) {
* 1st step: $newIndex = $oldIndex + $incrementStep;
* Get values which indexes should be incremented and remove those values from given array $array[$newIndex] = $value;
*/
foreach ($array as $index => $value) {
if ($index < $startIndex) {
continue;
}
$valuesToIncrement[$index] = $value;
unset($array[$index]);
}
/*
* 2nd step:
* Increment indexes of gathered values
*/
if (!empty($valuesToIncrement)) {
foreach ($valuesToIncrement as $oldIndex => $value) {
$newIndex = $oldIndex + $incrementStep;
$array[$newIndex] = $value;
}
} }
} }
} }
@@ -1554,6 +1641,14 @@ class Arrays
*/ */
public static function getDimensionsCount(array $array) public static function getDimensionsCount(array $array)
{ {
/*
* No elements?
* Nothing to do
*/
if (empty($array)) {
return 0;
}
$dimensionsCount = 1; $dimensionsCount = 1;
foreach ($array as $value) { foreach ($array as $value) {
@@ -1577,7 +1672,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 * @return array|null
*/ */
public static function getNonEmptyValues(array $values) public static function getNonEmptyValues(array $values)
{ {
@@ -1586,7 +1681,7 @@ class Arrays
* Nothing to do * Nothing to do
*/ */
if (empty($values)) { if (empty($values)) {
return []; return null;
} }
return array_filter($values, function ($value) { return array_filter($values, function ($value) {
@@ -1602,10 +1697,18 @@ 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 * @return string|null
*/ */
public static function getNonEmptyValuesAsString(array $values, $separator = ', ') public static function getNonEmptyValuesAsString(array $values, $separator = ', ')
{ {
/*
* No elements?
* Nothing to do
*/
if (empty($values)) {
return null;
}
$nonEmpty = self::getNonEmptyValues($values); $nonEmpty = self::getNonEmptyValues($values);
/* /*
@@ -1629,6 +1732,14 @@ class Arrays
*/ */
private static function getNeighbour(array $array, $element, $next = true) private static function getNeighbour(array $array, $element, $next = true)
{ {
/*
* No elements?
* Nothing to do
*/
if (empty($array)) {
return null;
}
$noNext = $next && self::isLastElement($array, $element); $noNext = $next && self::isLastElement($array, $element);
$noPrevious = !$next && self::isFirstElement($array, $element); $noPrevious = !$next && self::isFirstElement($array, $element);

View File

@@ -31,50 +31,95 @@ class ArraysTest extends BaseTestCase
static::assertHasNoConstructor(Arrays::class); static::assertHasNoConstructor(Arrays::class);
} }
public function testValues2string() /**
* @param string $description Description of test
* @param string $expected Expected array converted to string
* @param array $array Data to be converted
* @param string $arrayColumnKey (optional) Column name. Default: "".
* @param string $separator (optional) Separator used between values. Default: ",".
*
* @dataProvider provideArrayValues2string
*/
public function testValues2string($description, $expected, array $array, $arrayColumnKey = '', $separator = ',')
{ {
/* self::assertSame($expected, Arrays::values2string($array, $arrayColumnKey, $separator), $description);
* Simple array / string
*/
$simpleString = 'Lorem,ipsum,dolor,sit,amet';
$simpleStringWithDots = str_replace(',', '.', $simpleString);
self::assertEquals($simpleString, Arrays::values2string($this->simpleArray));
self::assertEquals('ipsum', Arrays::values2string($this->simpleArray, 1));
self::assertEquals($simpleStringWithDots, Arrays::values2string($this->simpleArray, '', '.'));
/*
* Complex array / string
*/
$complexString = 'sit,egestas,adipiscing,1234,,donec,quis,elit,iaculis,primis';
$complexStringWithDots = str_replace(',', '.', $complexString);
self::assertEquals($complexString, Arrays::values2string($this->complexArray));
self::assertEquals($complexStringWithDots, Arrays::values2string($this->complexArray, '', '.'));
/*
* Other cases
*/
self::assertEquals('', Arrays::values2string([]));
} }
public function testValuesKeys2string() /**
{ * @param string $description Description of test
self::assertEquals('0=Lorem,1=ipsum,2=dolor,3=sit,4=amet', Arrays::valuesKeys2string($this->simpleArray)); * @param string $expected Expected array converted to string
self::assertEquals('0=Lorem;1=ipsum;2=dolor;3=sit;4=amet', Arrays::valuesKeys2string($this->simpleArray, ';')); * @param array $array Data to be converted
self::assertEquals('0=Lorem 1=ipsum 2=dolor 3=sit 4=amet', Arrays::valuesKeys2string($this->simpleArray, ' ')); * @param string $separator (optional) Separator used between name-value pairs. 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".
* Default: "".
*
* @dataProvider provideArrayValuesKeysConverted2string
*/
public function testValuesKeys2string(
$description,
$expected,
array $array,
$separator = ',',
$valuesKeysSeparator = '=',
$valuesWrapper = ''
) {
self::assertSame(
$expected,
Arrays::valuesKeys2string($array, $separator, $valuesKeysSeparator, $valuesWrapper),
$description
);
self::assertEquals('0="Lorem" 1="ipsum" 2="dolor" 3="sit" 4="amet"', Arrays::valuesKeys2string($this->simpleArray, ' ', '=', '"')); self::assertSame(
self::assertEquals('0="Lorem", 1="ipsum", 2="dolor", 3="sit", 4="amet"', Arrays::valuesKeys2string($this->simpleArray, ', ', '=', '"')); '0=Lorem,1=ipsum,2=dolor,3=sit,4=amet',
Arrays::valuesKeys2string($this->simpleArray),
'Simple array'
);
self::assertSame(
'0=Lorem;1=ipsum;2=dolor;3=sit;4=amet',
Arrays::valuesKeys2string($this->simpleArray, ';'),
'Simple array (with custom separator)'
);
self::assertSame(
'0=Lorem 1=ipsum 2=dolor 3=sit 4=amet',
Arrays::valuesKeys2string($this->simpleArray, ' '),
'Simple array (with custom separator)'
);
self::assertSame(
'0="Lorem" 1="ipsum" 2="dolor" 3="sit" 4="amet"',
Arrays::valuesKeys2string($this->simpleArray, ' ', '=', '"'),
'Simple array (with custom separators)'
);
self::assertSame(
'0="Lorem", 1="ipsum", 2="dolor", 3="sit", 4="amet"',
Arrays::valuesKeys2string($this->simpleArray, ', ', '=', '"'),
'Simple array (with custom separators)'
);
} }
public function testValues2csv() /**
* @param string $description Description of test
* @param string $expected Expected array converted to csv string
* @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: ",".
*
* @dataProvider provideArrayValues2csv
*/
public function testValues2csv($description, $expected, array $array, $separator = ',')
{ {
self::assertEquals('', Arrays::values2csv($this->simpleArray)); self::assertSame($expected, Arrays::values2csv($array, $separator), $description);
self::assertSame('', Arrays::values2csv($this->simpleArray), 'Simple array');
self::assertEquals("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', Arrays::values2csv($this->twoDimensionsArray)); . 'donec,sagittis,fringilla,eleifend',
Arrays::values2csv($this->twoDimensionsArray),
'Two dimensions array'
);
} }
public function testGetFirstKey() public function testGetFirstKey()
@@ -93,6 +138,7 @@ class ArraysTest extends BaseTestCase
public function testGetLastKey() public function testGetLastKey()
{ {
self::assertNull(Arrays::getLastKey([]));
self::assertEquals(4, Arrays::getLastKey($this->simpleArray)); self::assertEquals(4, Arrays::getLastKey($this->simpleArray));
self::assertEquals('amet', Arrays::getLastKey($this->complexArray)); self::assertEquals('amet', Arrays::getLastKey($this->complexArray));
} }
@@ -146,6 +192,7 @@ class ArraysTest extends BaseTestCase
public function testGetLastElementBreadCrumb() public function testGetLastElementBreadCrumb()
{ {
self::assertNull(Arrays::getLastElementBreadCrumb([]));
self::assertEquals('4/amet', Arrays::getLastElementBreadCrumb($this->simpleArray)); self::assertEquals('4/amet', Arrays::getLastElementBreadCrumb($this->simpleArray));
self::assertEquals('2/3/eleifend', Arrays::getLastElementBreadCrumb($this->twoDimensionsArray)); self::assertEquals('2/3/eleifend', Arrays::getLastElementBreadCrumb($this->twoDimensionsArray));
self::assertEquals('amet/1/primis', Arrays::getLastElementBreadCrumb($this->complexArray)); self::assertEquals('amet/1/primis', Arrays::getLastElementBreadCrumb($this->complexArray));
@@ -279,6 +326,18 @@ letsTest[2] = value_2;';
self::assertEquals($effect, Arrays::array2JavaScript($this->twoDimensionsArray, 'letsTest', true)); self::assertEquals($effect, Arrays::array2JavaScript($this->twoDimensionsArray, 'letsTest', true));
} }
/**
* @param string $description Description of test case
* @param array|null $expected Expected new array (with quoted elements)
* @param array $array The array to check for string values
*
* @dataProvider provideArrayToQuoteStrings
*/
public function testQuoteStrings($description, $expected, array $array)
{
self::assertSame($expected, Arrays::quoteStrings($array), $description);
}
public function testRemoveMarginalElement() public function testRemoveMarginalElement()
{ {
$array = $this->simpleArray; $array = $this->simpleArray;
@@ -343,7 +402,7 @@ letsTest[2] = value_2;';
public function testSetKeysAsValuesEmptyArray() public function testSetKeysAsValuesEmptyArray()
{ {
self::assertEquals([], Arrays::setKeysAsValues([])); self::assertNull(Arrays::setKeysAsValues([]));
} }
public function testSetKeysAsValuesSameKeysValues() public function testSetKeysAsValuesSameKeysValues()
@@ -456,6 +515,7 @@ letsTest[2] = value_2;';
/* /*
* Negative cases * Negative cases
*/ */
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));
self::assertFalse(Arrays::areKeysInArray(['dolorrr'], $this->simpleArrayWithKeys)); self::assertFalse(Arrays::areKeysInArray(['dolorrr'], $this->simpleArrayWithKeys));
@@ -520,7 +580,7 @@ letsTest[2] = value_2;';
public function testGetLastElementsPathsUsingEmptyArray() public function testGetLastElementsPathsUsingEmptyArray()
{ {
self::assertSame([], Arrays::getLastElementsPaths([])); self::assertNull(Arrays::getLastElementsPaths([]));
} }
public function testGetLastElementsPathsUsingDefaults() public function testGetLastElementsPathsUsingDefaults()
@@ -585,9 +645,9 @@ letsTest[2] = value_2;';
$pattern = '\d+'; $pattern = '\d+';
/* /*
* Complex array with strings and integers as keys * Empty array
*/ */
self::assertFalse(Arrays::areAllKeysMatchedByPattern($this->complexArray, $pattern)); self::assertFalse(Arrays::areAllKeysMatchedByPattern([], $pattern));
/* /*
* Simple array with integers as keys only * Simple array with integers as keys only
@@ -595,9 +655,9 @@ letsTest[2] = value_2;';
self::assertTrue(Arrays::areAllKeysMatchedByPattern($this->simpleArray, $pattern)); self::assertTrue(Arrays::areAllKeysMatchedByPattern($this->simpleArray, $pattern));
/* /*
* Empty array * Complex array with strings and integers as keys
*/ */
self::assertFalse(Arrays::areAllKeysMatchedByPattern([], $pattern)); self::assertFalse(Arrays::areAllKeysMatchedByPattern($this->complexArray, $pattern));
$array = [ $array = [
'a' => 'b', 'a' => 'b',
@@ -638,6 +698,7 @@ letsTest[2] = value_2;';
public function testAreAllKeysIntegers() public function testAreAllKeysIntegers()
{ {
self::assertFalse(Arrays::areAllKeysIntegers([]));
self::assertEquals(1, Arrays::areAllKeysIntegers($this->simpleArray)); self::assertEquals(1, Arrays::areAllKeysIntegers($this->simpleArray));
self::assertEquals(2, Arrays::areAllKeysIntegers($this->simpleArray)); self::assertEquals(2, Arrays::areAllKeysIntegers($this->simpleArray));
self::assertEquals('', Arrays::areAllKeysIntegers($this->complexArray)); self::assertEquals('', Arrays::areAllKeysIntegers($this->complexArray));
@@ -885,8 +946,7 @@ letsTest[2] = value_2;';
/* /*
* Negative cases * Negative cases
*/ */
self::assertEmpty(Arrays::setPositions([])); self::assertNull(Arrays::setPositions([]));
self::assertEquals([], Arrays::setPositions([]));
/* /*
* Positive case - 1-dimension array * Positive case - 1-dimension array
@@ -983,7 +1043,7 @@ letsTest[2] = value_2;';
/* /*
* Negative cases * Negative cases
*/ */
self::assertEquals([], Arrays::trimRecursive([])); self::assertSame([], Arrays::trimRecursive([]));
/* /*
* Positive cases * Positive cases
@@ -1125,7 +1185,7 @@ letsTest[2] = value_2;';
/* /*
* Empty array * Empty array
*/ */
self::assertEmpty(Arrays::implodeSmart([], $separator)); self::assertNull(Arrays::implodeSmart([], $separator));
/* /*
* Simple, one-dimension array * Simple, one-dimension array
@@ -1214,7 +1274,7 @@ letsTest[2] = value_2;';
/* /*
* Negative cases * Negative cases
*/ */
self::assertEquals([], Arrays::incrementIndexes([])); self::assertNull(Arrays::incrementIndexes([]));
/* /*
* Positive cases * Positive cases
@@ -1454,7 +1514,7 @@ letsTest[2] = value_2;';
/* /*
* Basic cases * Basic cases
*/ */
self::assertEquals(1, Arrays::getDimensionsCount([])); self::assertEquals(0, Arrays::getDimensionsCount([]));
self::assertEquals(1, Arrays::getDimensionsCount([''])); self::assertEquals(1, Arrays::getDimensionsCount(['']));
/* /*
@@ -1487,6 +1547,11 @@ letsTest[2] = value_2;';
self::assertTrue(Arrays::isMultiDimensional($this->complexArray)); self::assertTrue(Arrays::isMultiDimensional($this->complexArray));
} }
public function testGetNonEmptyValuesUsingEmptyArray()
{
self::assertNull(Arrays::getNonEmptyValues([]));
}
/** /**
* @param string $description Description of test case * @param string $description Description of test case
* @param array $values The values to filter * @param array $values The values to filter
@@ -1854,12 +1919,6 @@ letsTest[2] = value_2;';
{ {
$simpleObject = new SimpleToString('1234'); $simpleObject = new SimpleToString('1234');
yield[
'An empty array (no values to filter)',
[],
[],
];
yield[ yield[
'All values are empty', 'All values are empty',
[ [
@@ -1955,7 +2014,7 @@ letsTest[2] = value_2;';
yield[ yield[
'An empty array (no values to filter)', 'An empty array (no values to filter)',
[], [],
'', null,
]; ];
yield[ yield[
@@ -2032,7 +2091,7 @@ letsTest[2] = value_2;';
'An empty array (no values to filter)', 'An empty array (no values to filter)',
[], [],
' | ', ' | ',
'', null,
]; ];
yield[ yield[
@@ -2103,6 +2162,524 @@ letsTest[2] = value_2;';
]; ];
} }
public function provideArrayValuesKeysConverted2string()
{
yield[
'An empty array',
null,
[],
];
yield[
'Empty string and null as value',
'test_1=,test_2=,test_3=3',
[
'test_1' => null,
'test_2' => '',
'test_3' => '3',
],
];
yield[
'Empty string and null as value (with custom separators)',
'test_1="" test_2="" test_3="3"',
[
'test_1' => null,
'test_2' => '',
'test_3' => '3',
],
' ',
'=',
'"',
];
yield[
'Empty string as key',
'1=test_1,=test_2,3=test_3',
[
1 => 'test_1',
'' => 'test_2',
'3' => 'test_3',
],
];
yield[
'Empty string as key (with custom separators)',
'1 => "test_1"; => "test_2"; 3 => "test_3"',
[
1 => 'test_1',
'' => 'test_2',
'3' => 'test_3',
],
'; ',
' => ',
'"',
];
yield[
'Mixed types of keys and values',
'test_1=test test,test_2=2,test_3=3.45',
[
'test_1' => 'test test',
'test_2' => 2,
'test_3' => 3.45,
],
];
yield[
'Mixed types of keys and values (with custom separators)',
'test_1 --> *test test* | test_2 --> *2* | test_3 --> *3.45*',
[
'test_1' => 'test test',
'test_2' => 2,
'test_3' => 3.45,
],
' | ',
' --> ',
'*',
];
}
public function provideArrayValues2csv()
{
yield[
'An empty array',
null,
[],
];
yield[
'Empty string, and empty array and null as row',
"1,2,3\n5,6,",
[
'test_1' => '',
'test_2' => [],
'test_3' => null,
'test_4' => [
'aa' => 1,
'bb' => 2,
'cc' => 3,
],
[
'dd' => 5,
'ee' => 6,
'ff' => '',
],
],
];
yield[
'Empty string, and empty array and null as row (with custom separator)',
"1, 2, 3\n5, 6, ",
[
'test_1' => '',
'test_2' => [],
'test_3' => null,
'test_4' => [
'aa' => 1,
'bb' => 2,
'cc' => 3,
],
[
'dd' => 5,
'ee' => 6,
'ff' => '',
],
],
', ',
];
yield[
'Empty string as key, non-array as value',
"1,2,3\n5,6,",
[
'' => 'test_1',
1 => 'test_2',
'3' => [
'aa' => 1,
'bb' => 2,
'cc' => 3,
],
[
'dd' => 5,
'ee' => 6,
'ff' => '',
],
],
];
yield[
'Empty string as key, non-array as value (with custom separator)',
"1 | 2 | 3\n5 | 6 | ",
[
'' => 'test_1',
1 => 'test_2',
'3' => [
'aa' => 1,
'bb' => 2,
'cc' => 3,
],
[
'dd' => 5,
'ee' => 6,
'ff' => '',
],
],
' | ',
];
yield[
'Invalid structure, not like database table',
"1,2,3\n5,6\n7,8,9,10",
[
[
'aa' => 1,
'bb' => 2,
'cc' => 3,
],
[
'dd' => 5,
'ee' => 6,
],
[
7,
8,
9,
10,
],
],
];
yield[
'Invalid structure, not like database table (with custom separator)',
"1 <-> 2 <-> 3\n5 <-> 6\n7 <-> 8 <-> 9 <-> 10",
[
[
'aa' => 1,
'bb' => 2,
'cc' => 3,
],
[
'dd' => 5,
'ee' => 6,
],
[
7,
8,
9,
10,
],
],
' <-> ',
];
yield[
'Mixed types of keys and values',
"1,2,3.45\n5,6,\n7,8,9,,10",
[
[
'aa' => 1,
'bb' => 2,
'cc' => 3.45,
],
[
'dd' => 5,
'ee' => 6,
null,
],
[
7,
8,
'qq' => 9,
'',
10,
],
],
];
yield[
'Mixed types of keys and values (with custom separator)',
"1 // 2 // 3.45\n5 // 6 // \n7 // 8 // 9 // // 10",
[
[
'aa' => 1,
'bb' => 2,
'cc' => 3.45,
],
[
'dd' => 5,
'ee' => 6,
null,
],
[
7,
8,
'qq' => 9,
'',
10,
],
],
' // ',
];
}
public function provideArrayValues2string()
{
yield[
'An empty array',
null,
[],
];
yield[
'Simple array',
'Test 1,Test 2,Test 3',
[
1 => 'Test 1',
2 => 'Test 2',
3 => 'Test 3',
],
];
yield[
'Simple array (with custom separator)',
'Test 1.Test 2.Test 3',
[
1 => 'Test 1',
2 => 'Test 2',
3 => 'Test 3',
],
'',
'.',
];
yield[
'Simple array (concrete column)',
'Test 2',
[
1 => 'Test 1',
2 => 'Test 2',
3 => 'Test 3',
],
2,
];
yield[
'Simple array (concrete column with custom separator)',
'Test 2',
[
1 => 'Test 1',
2 => 'Test 2',
3 => 'Test 3',
],
2,
'.',
];
yield[
'Complex array',
'1,2,3,test 1,test 2,test 3,,test 4,,bbb,3.45',
[
[
1,
2,
3,
],
[
'test 1',
'test 2',
[
'test 3',
'',
'test 4',
],
],
[],
[
'a' => '',
'b' => 'bbb',
[],
'c' => 3.45,
],
],
];
yield[
'1st complex array (concrete column)',
'2,test 2,',
[
[
1,
2,
3,
],
[
'test 1',
'test 2',
[
'test 3',
'',
'test 4',
],
],
[],
[
'a' => '',
'b' => 'bbb',
[],
'c' => 3.45,
],
],
1,
];
yield[
'2nd complex array (concrete column)',
'bb,1234,0xb',
[
[
1,
2,
3,
],
[
'a' => 'aa',
'b' => 'bb',
'c' => 'cc',
],
[
'a',
'b',
'c',
],
[
'a' => '',
'b' => 1234,
],
[
'c' => 5678,
'b' => '0xb',
],
],
'b',
];
yield[
'3rd complex array (concrete column with custom separator)',
'bb - 1234 - 3xb - bbb',
[
[
1,
2,
3,
],
[
'a' => 'aa',
'b' => 'bb',
'c' => 'cc',
],
[
'a',
'b' => [],
'c',
],
[
'a' => '',
'b' => 1234,
],
[
'c' => 5678,
'b' => [
'b1' => '0xb',
'b2' => '1xb',
'b' => '3xb',
],
[
1,
2,
'a' => 'aaa',
'b' => 'bbb',
],
],
],
'b',
' - ',
];
}
public function provideArrayToQuoteStrings()
{
yield[
'An empty array',
null,
[],
];
yield[
'Simple array',
[
1,
2,
3,
'\'1\'',
'\'2\'',
],
[
1,
2,
3,
'1',
'2',
],
];
yield[
'Complex array',
[
123,
'\'456\'',
[
'x' => [
0,
'\'0\'',
1 => '\'1\'',
2 => 2,
],
'\'y\'',
],
444 => '\'\'',
[
[
[
'\'test\'',
],
],
],
],
[
123,
'456',
[
'x' => [
0,
'0',
1 => '1',
2 => 2,
],
'y',
],
444 => '',
[
[
[
'test',
],
],
],
],
];
}
/** /**
* {@inheritdoc} * {@inheritdoc}
*/ */