From 924e492e111ccd01b6be8195e88e06e1b797dea5 Mon Sep 17 00:00:00 2001 From: Meritoo Date: Sat, 23 Feb 2019 19:41:37 +0100 Subject: [PATCH 1/8] Arrays > refactoring & more tests --- CHANGELOG.md | 4 + VERSION | 2 +- src/Utilities/Arrays.php | 527 +++++++++++++++---------- tests/Utilities/ArraysTest.php | 687 ++++++++++++++++++++++++++++++--- 4 files changed, 956 insertions(+), 264 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 5a7bf20..e2355e9 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,10 @@ Common and useful classes, methods, exceptions etc. +# 0.1.6 + +1. Arrays > refactoring & more tests + # 0.1.5 1. Tests > Date > one more test case diff --git a/VERSION b/VERSION index 9faa1b7..c946ee6 100644 --- a/VERSION +++ b/VERSION @@ -1 +1 @@ -0.1.5 +0.1.6 diff --git a/src/Utilities/Arrays.php b/src/Utilities/Arrays.php index 7bce3f2..8149741 100644 --- a/src/Utilities/Arrays.php +++ b/src/Utilities/Arrays.php @@ -27,102 +27,137 @@ class Arrays * Converts given array's column to string. * Recursive call is made for multi-dimensional arrays. * - * @param array $array Array data to be converted - * @param string|int $arrayColumnKey (optional) Column name - * @param string $separator (optional) Separator used in resultant string - * @return string + * @param array $array Data to be converted + * @param string|int $arrayColumnKey (optional) Column name. Default: "". + * @param string $separator (optional) Separator used between values. Default: ",". + * @return string|null */ public static function values2string(array $array, $arrayColumnKey = '', $separator = ',') { - $effect = ''; - - if (!empty($array)) { - foreach ($array as $key => $value) { - if (!empty($effect) && - ( - 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]; - } - } + /* + * No elements? + * Nothing to do + */ + if (empty($array)) { + return null; } - 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" * - * @param array $array Array data to be converted - * @param string $separator (optional) Separator used between name-value pairs in resultant string - * @param string $valuesKeysSeparator (optional) Separator used between name and value in resultant string - * @param string $valuesWrapper (optional) Wrapper used to wrap values, e.g. double-quote: key="value" - * @return string + * @param array $array Data to be converted + * @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: "". + * @return string|null */ - public static function valuesKeys2string($array, $separator = ',', $valuesKeysSeparator = '=', $valuesWrapper = '') - { - $effect = ''; - - if (is_array($array) && !empty($array)) { - foreach ($array as $key => $value) { - if (!empty($effect)) { - $effect .= $separator; - } - - if (!empty($valuesWrapper)) { - $value = sprintf('%s%s%s', $valuesWrapper, $value, $valuesWrapper); - } - - $effect .= $key . $valuesKeysSeparator . $value; - } + public static function valuesKeys2string( + array $array, + $separator = ',', + $valuesKeysSeparator = '=', + $valuesWrapper = '' + ) { + /* + * No elements? + * Nothing to do + */ + if (empty($array)) { + return null; } - 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 * - * @param array $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 - * @return 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: ",". + * @return string|null */ - public static function values2csv($array, $separator = ',') + public static function values2csv(array $array, $separator = ',') { - if (is_array($array) && !empty($array)) { - $rows = []; - $lineSeparator = "\n"; + /* + * No elements? + * Nothing to do + */ + if (empty($array)) { + return null; + } - foreach ($array as $row) { - /* - * 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 = []; + $lineSeparator = "\n"; - if (is_array($row) && !empty($row)) { - foreach ($row as $key => $value) { - $row[$key] = html_entity_decode($value); - } + foreach ($array as $row) { + /* + * 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)) { - return implode($lineSeparator, $rows); + $rows[] = implode($separator, $row); } } - 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 * - * @param array $array The array to get the breadcrumb - * @param string $separator (optional) Separator used to stick the elements - * @return string + * @param array $array Data to get the breadcrumb + * @param string $separator (optional) Separator used to stick the elements. Default: "/". + * @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); $keysCount = count($keys); @@ -350,7 +393,7 @@ class Arrays return null; } - $effect = ''; + $result = ''; $counter = 0; $arrayCount = count($array); @@ -366,14 +409,14 @@ class Arrays } 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) { - $effect .= $arrayCount; - $effect .= ');'; + $result .= $arrayCount; + $result .= ');'; } foreach ($array as $index => $value) { @@ -397,20 +440,20 @@ class Arrays * autoGeneratedVariable[1] = new Array(...); */ if (1 === $counter) { - $effect .= "\n"; + $result .= "\n"; } - $effect .= $value . "\n"; - $effect .= sprintf('%s[%s] = %s;', $jsVariableName, Miscellaneous::quoteValue($index), $variable); + $result .= $value . "\n"; + $result .= sprintf('%s[%s] = %s;', $jsVariableName, Miscellaneous::quoteValue($index), $variable); if ($counter !== $arrayCount) { - $effect .= "\n"; + $result .= "\n"; } } } elseif ($preserveIndexes) { if (!empty($jsVariableName)) { $index = Miscellaneous::quoteValue($index); - $effect .= sprintf("\n%s[%s] = %s;", $jsVariableName, $index, $value); + $result .= sprintf("\n%s[%s] = %s;", $jsVariableName, $index, $value); } } else { $format = '%s'; @@ -419,44 +462,48 @@ class Arrays $format .= ', '; } - $effect .= sprintf($format, $value); + $result .= sprintf($format, $value); } } 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 - * @return array + * @return array|null */ - public static function quoteStrings($array) + public static function quoteStrings(array $array) { - $effect = $array; - - if (is_array($array) && !empty($array)) { - $effect = []; - - foreach ($array as $index => $value) { - if (is_array($value)) { - $value = self::quoteStrings($value); - } elseif (is_string($value)) { - if (!Regex::isQuoted($value)) { - $value = '\'' . $value . '\''; - } - } - - $effect[$index] = $value; - } + /* + * No elements? + * Nothing to do + */ + if (empty($array)) { + return null; } - 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) { + /* + * No elements? + * Nothing to do + */ + if (empty($array)) { + return null; + } + $keys = array_keys($array); 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 * 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) { $array = array_reverse($array, true); } @@ -587,7 +642,7 @@ class Arrays * value will be used with it's key, because other will be overridden. * Otherwise - values are preserved and keys assigned to that values are * returned as an array. - * @return array + * @return array|null * * Example of $ignoreDuplicatedValues = false: * - provided array @@ -613,7 +668,7 @@ class Arrays * Nothing to do */ if (empty($array)) { - return []; + return null; } $replaced = []; @@ -724,8 +779,9 @@ class Arrays * ] * * @param string $string The string to be converted - * @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 + * @param string $separator (optional) Separator used between name-value pairs in the string. + * Default: "|". + * @param string $valuesKeysSeparator (optional) Separator used between name and value in the string. Default: ":". * @return array */ public static function string2array($string, $separator = '|', $valuesKeysSeparator = ':') @@ -759,52 +815,52 @@ class Arrays * Returns information if given keys exist in given array * * @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. * @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; foreach ($keys as $key) { $exists = array_key_exists($key, $array); if ($firstKey) { - $effect = $exists; + $result = $exists; $firstKey = false; } elseif ($explicit) { - $effect = $effect && $exists; + $result = $result && $exists; - if (!$effect) { + if (!$result) { break; } } else { - $effect = $effect || $exists; + $result = $result || $exists; - if ($effect) { + if ($result) { break; } } } } - return $effect; + return $result; } /** * Returns paths of the last 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|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 - * will not be used for keys in lower level of given array) - * @return array + * will not be used for keys in lower level of given array). Default: "". + * @return array|null * * Examples - $stopIfMatchedBy argument: * a) "\d+" @@ -820,7 +876,7 @@ class Arrays * Nothing to do */ if (empty($array)) { - return []; + return null; } if (!empty($stopIfMatchedBy)) { @@ -906,12 +962,13 @@ class Arrays * first level only. * @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; } @@ -955,10 +1012,10 @@ class Arrays * * @param array $array The array to check * @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 */ - public static function areAllKeysIntegers($array, $firstLevelOnly = false) + public static function areAllKeysIntegers(array $array, $firstLevelOnly = false) { $pattern = '\d+'; @@ -996,9 +1053,17 @@ class Arrays */ public static function getValueByKeysPath(array $array, array $keys) { + /* + * No elements? + * Nothing to do + */ + if (empty($array)) { + return null; + } + $value = null; - if (!empty($array) && self::issetRecursive($array, $keys)) { + if (self::issetRecursive($array, $keys)) { foreach ($keys as $key) { $value = $array[$key]; array_shift($keys); @@ -1042,23 +1107,29 @@ class Arrays */ public static function issetRecursive(array $array, array $keys) { + /* + * No elements? + * Nothing to do + */ + if (empty($array)) { + return false; + } + $isset = false; - if (!empty($array)) { - foreach ($keys as $key) { - $isset = isset($array[$key]); + foreach ($keys as $key) { + $isset = isset($array[$key]); - if ($isset) { - $newArray = $array[$key]; - array_shift($keys); + if ($isset) { + $newArray = $array[$key]; + array_shift($keys); - if (is_array($newArray) && !empty($keys)) { - $isset = self::issetRecursive($newArray, $keys); - } + if (is_array($newArray) && !empty($keys)) { + $isset = self::issetRecursive($newArray, $keys); } - - break; } + + break; } return $isset; @@ -1113,22 +1184,28 @@ class Arrays * @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 * children - * @return array + * @return array|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) { - $array[$keyName] = $startPosition; - } + $childPosition = 1; - foreach ($array as &$value) { - if (is_array($value)) { - $value = self::setPositions($value, $keyName, $childPosition); - ++$childPosition; - } + if (null !== $startPosition) { + $array[$keyName] = $startPosition; + } + + 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) { - $effect = $array; - - if (!empty($array)) { - $effect = []; - - foreach ($array as $key => $value) { - if (is_array($value)) { - $effect[$key] = self::trimRecursive($value); - continue; - } - - if (is_string($value)) { - $value = trim($value); - } - - $effect[$key] = $value; - } + /* + * No elements? + * Nothing to do + */ + if (empty($array)) { + return []; } - 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 string $separator Separator used to stick together elements of given array - * @return string + * @return string|null */ public static function implodeSmart(array $array, $separator) { @@ -1264,7 +1345,7 @@ class Arrays * Nothing to do */ if (empty($array)) { - return ''; + return null; } 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, * the first index / key will be used. * @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) { - 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? - * Let's look for the first index / key of given array + * 1st step: + * Get values which indexes should be incremented and remove those values from given array */ - if (null === $startIndex) { - $startIndex = self::getFirstKey($array); + foreach ($array as $index => $value) { + if ($index < $startIndex) { + continue; + } + + $valuesToIncrement[$index] = $value; + unset($array[$index]); } /* - * Is the start index a numeric value? - * Other indexes / keys cannot be incremented + * 2nd step: + * Increment indexes of gathered values */ - if (is_numeric($startIndex)) { - /* - * 1st step: - * Get values which indexes should be incremented and remove those values from given array - */ - 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; - } + 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) { + /* + * No elements? + * Nothing to do + */ + if (empty($array)) { + return 0; + } + $dimensionsCount = 1; foreach ($array as $value) { @@ -1577,7 +1672,7 @@ class Arrays * Returns non-empty values, e.g. without "" (empty string), null or [] * * @param array $values The values to filter - * @return array + * @return array|null */ public static function getNonEmptyValues(array $values) { @@ -1586,7 +1681,7 @@ class Arrays * Nothing to do */ if (empty($values)) { - return []; + return null; } return array_filter($values, function ($value) { @@ -1602,10 +1697,18 @@ class Arrays * * @param array $values The values to filter * @param string $separator (optional) Separator used to implode the values. Default: ", ". - * @return string + * @return string|null */ public static function getNonEmptyValuesAsString(array $values, $separator = ', ') { + /* + * No elements? + * Nothing to do + */ + if (empty($values)) { + return null; + } + $nonEmpty = self::getNonEmptyValues($values); /* @@ -1629,6 +1732,14 @@ class Arrays */ 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); $noPrevious = !$next && self::isFirstElement($array, $element); diff --git a/tests/Utilities/ArraysTest.php b/tests/Utilities/ArraysTest.php index 71d9583..3c1aa6d 100644 --- a/tests/Utilities/ArraysTest.php +++ b/tests/Utilities/ArraysTest.php @@ -31,50 +31,95 @@ class ArraysTest extends BaseTestCase 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 = ',') { - /* - * 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([])); + self::assertSame($expected, Arrays::values2string($array, $arrayColumnKey, $separator), $description); } - public function testValuesKeys2string() - { - self::assertEquals('0=Lorem,1=ipsum,2=dolor,3=sit,4=amet', Arrays::valuesKeys2string($this->simpleArray)); - self::assertEquals('0=Lorem;1=ipsum;2=dolor;3=sit;4=amet', Arrays::valuesKeys2string($this->simpleArray, ';')); - self::assertEquals('0=Lorem 1=ipsum 2=dolor 3=sit 4=amet', Arrays::valuesKeys2string($this->simpleArray, ' ')); + /** + * @param string $description Description of test + * @param string $expected Expected array converted to string + * @param array $array Data to be converted + * @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::assertEquals('0="Lorem", 1="ipsum", 2="dolor", 3="sit", 4="amet"', Arrays::valuesKeys2string($this->simpleArray, ', ', '=', '"')); + self::assertSame( + '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" - . 'donec,sagittis,fringilla,eleifend', Arrays::values2csv($this->twoDimensionsArray)); + . 'donec,sagittis,fringilla,eleifend', + Arrays::values2csv($this->twoDimensionsArray), + 'Two dimensions array' + ); } public function testGetFirstKey() @@ -93,6 +138,7 @@ class ArraysTest extends BaseTestCase public function testGetLastKey() { + self::assertNull(Arrays::getLastKey([])); self::assertEquals(4, Arrays::getLastKey($this->simpleArray)); self::assertEquals('amet', Arrays::getLastKey($this->complexArray)); } @@ -146,6 +192,7 @@ class ArraysTest extends BaseTestCase public function testGetLastElementBreadCrumb() { + self::assertNull(Arrays::getLastElementBreadCrumb([])); self::assertEquals('4/amet', Arrays::getLastElementBreadCrumb($this->simpleArray)); self::assertEquals('2/3/eleifend', Arrays::getLastElementBreadCrumb($this->twoDimensionsArray)); 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)); } + /** + * @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() { $array = $this->simpleArray; @@ -343,7 +402,7 @@ letsTest[2] = value_2;'; public function testSetKeysAsValuesEmptyArray() { - self::assertEquals([], Arrays::setKeysAsValues([])); + self::assertNull(Arrays::setKeysAsValues([])); } public function testSetKeysAsValuesSameKeysValues() @@ -456,6 +515,7 @@ letsTest[2] = value_2;'; /* * Negative cases */ + self::assertFalse(Arrays::areKeysInArray([], [])); self::assertFalse(Arrays::areKeysInArray([null], $this->simpleArray)); self::assertFalse(Arrays::areKeysInArray([''], $this->simpleArray)); self::assertFalse(Arrays::areKeysInArray(['dolorrr'], $this->simpleArrayWithKeys)); @@ -520,7 +580,7 @@ letsTest[2] = value_2;'; public function testGetLastElementsPathsUsingEmptyArray() { - self::assertSame([], Arrays::getLastElementsPaths([])); + self::assertNull(Arrays::getLastElementsPaths([])); } public function testGetLastElementsPathsUsingDefaults() @@ -585,9 +645,9 @@ letsTest[2] = value_2;'; $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 @@ -595,9 +655,9 @@ letsTest[2] = value_2;'; 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 = [ 'a' => 'b', @@ -638,6 +698,7 @@ letsTest[2] = value_2;'; public function testAreAllKeysIntegers() { + self::assertFalse(Arrays::areAllKeysIntegers([])); self::assertEquals(1, Arrays::areAllKeysIntegers($this->simpleArray)); self::assertEquals(2, Arrays::areAllKeysIntegers($this->simpleArray)); self::assertEquals('', Arrays::areAllKeysIntegers($this->complexArray)); @@ -885,8 +946,7 @@ letsTest[2] = value_2;'; /* * Negative cases */ - self::assertEmpty(Arrays::setPositions([])); - self::assertEquals([], Arrays::setPositions([])); + self::assertNull(Arrays::setPositions([])); /* * Positive case - 1-dimension array @@ -983,7 +1043,7 @@ letsTest[2] = value_2;'; /* * Negative cases */ - self::assertEquals([], Arrays::trimRecursive([])); + self::assertSame([], Arrays::trimRecursive([])); /* * Positive cases @@ -1125,7 +1185,7 @@ letsTest[2] = value_2;'; /* * Empty array */ - self::assertEmpty(Arrays::implodeSmart([], $separator)); + self::assertNull(Arrays::implodeSmart([], $separator)); /* * Simple, one-dimension array @@ -1214,7 +1274,7 @@ letsTest[2] = value_2;'; /* * Negative cases */ - self::assertEquals([], Arrays::incrementIndexes([])); + self::assertNull(Arrays::incrementIndexes([])); /* * Positive cases @@ -1454,7 +1514,7 @@ letsTest[2] = value_2;'; /* * Basic cases */ - self::assertEquals(1, Arrays::getDimensionsCount([])); + self::assertEquals(0, Arrays::getDimensionsCount([])); self::assertEquals(1, Arrays::getDimensionsCount([''])); /* @@ -1487,6 +1547,11 @@ letsTest[2] = value_2;'; self::assertTrue(Arrays::isMultiDimensional($this->complexArray)); } + public function testGetNonEmptyValuesUsingEmptyArray() + { + self::assertNull(Arrays::getNonEmptyValues([])); + } + /** * @param string $description Description of test case * @param array $values The values to filter @@ -1854,12 +1919,6 @@ letsTest[2] = value_2;'; { $simpleObject = new SimpleToString('1234'); - yield[ - 'An empty array (no values to filter)', - [], - [], - ]; - yield[ 'All values are empty', [ @@ -1955,7 +2014,7 @@ letsTest[2] = value_2;'; yield[ 'An empty array (no values to filter)', [], - '', + null, ]; yield[ @@ -2032,7 +2091,7 @@ letsTest[2] = value_2;'; 'An empty array (no values to filter)', [], ' | ', - '', + null, ]; 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} */ From 2247000a8a58086cfa9ba3899d28d11af9d7cdf5 Mon Sep 17 00:00:00 2001 From: Meritoo Date: Mon, 4 Mar 2019 18:52:07 +0100 Subject: [PATCH 2/8] Documentation > Value Objects > add missing information --- docs/Value-Objects.md | 13 ++++++++++++- 1 file changed, 12 insertions(+), 1 deletion(-) diff --git a/docs/Value-Objects.md b/docs/Value-Objects.md index 90b41e4..171947f 100644 --- a/docs/Value-Objects.md +++ b/docs/Value-Objects.md @@ -67,7 +67,7 @@ $asString = (string)$address; // "4th Avenue 10/200, 00123, New York" Represents bank account. Contains properties: 1. `$bankName` - name of bank -2. $accountNumber` - number of bank's account +2. `$accountNumber` - number of bank's account ##### New instance @@ -173,6 +173,17 @@ New instance can be created using: Version::fromString('1.0.2'); ``` +##### Conversion to string (the `__toString()` method) + +Instance of `Version` may be represented as string that contains all properties separated by `.` (`$majorPart`.`$minorPart`.`$patchPart`). + +Example: + +```php +$version = new Version(1, 0, 2); +$asString = (string)$version; // "1.0.2" +``` + # More 1. [Base test case (with common methods and data providers)](Base-test-case.md) From c175fcd1266e6a43bde1016c0156b1b8a1e90e11 Mon Sep 17 00:00:00 2001 From: Meritoo Date: Mon, 4 Mar 2019 18:52:56 +0100 Subject: [PATCH 3/8] Minor refactoring --- src/Collection/Collection.php | 2 +- src/ValueObject/Version.php | 2 +- tests/Collection/CollectionTest.php | 98 +++++++++---------- .../Date/UnknownDatePartTypeExceptionTest.php | 2 +- .../Exception/File/EmptyFileExceptionTest.php | 2 +- .../File/EmptyFilePathExceptionTest.php | 2 +- .../File/NotExistingFileExceptionTest.php | 2 +- .../Method/DisabledMethodExceptionTest.php | 2 +- .../CannotResolveClassNameExceptionTest.php | 2 +- .../MissingChildClassesExceptionTest.php | 2 +- .../TooManyChildClassesExceptionTest.php | 2 +- .../IncorrectColorHexLengthExceptionTest.php | 2 +- .../InvalidColorHexValueExceptionTest.php | 2 +- .../InvalidHtmlAttributesExceptionTest.php | 2 +- .../Regex/InvalidUrlExceptionTest.php | 2 +- .../UnknownOopVisibilityTypeExceptionTest.php | 2 +- tests/Utilities/Arrays/SimpleToString.php | 4 +- tests/Utilities/ReflectionTest.php | 8 +- tests/Utilities/RepositoryTest.php | 22 ++--- 19 files changed, 82 insertions(+), 80 deletions(-) diff --git a/src/Collection/Collection.php b/src/Collection/Collection.php index ebc3f42..0062c57 100644 --- a/src/Collection/Collection.php +++ b/src/Collection/Collection.php @@ -263,7 +263,7 @@ class Collection implements Countable, ArrayAccess, IteratorAggregate } /** - * Returns an array representation of the collection + * Returns representation of object as array * * @return array */ diff --git a/src/ValueObject/Version.php b/src/ValueObject/Version.php index 8684da0..688dae7 100644 --- a/src/ValueObject/Version.php +++ b/src/ValueObject/Version.php @@ -88,7 +88,7 @@ class Version } /** - * Returns string representation of instance of this class + * Returns representation of object as string * * @return string */ diff --git a/tests/Collection/CollectionTest.php b/tests/Collection/CollectionTest.php index 26a40ff..b2df4aa 100644 --- a/tests/Collection/CollectionTest.php +++ b/tests/Collection/CollectionTest.php @@ -45,12 +45,12 @@ class CollectionTest extends BaseTestCase public function testEmptyCollection() { - static::assertEquals(0, $this->emptyCollection->count()); + static::assertSame(0, $this->emptyCollection->count()); static::assertCount(0, $this->emptyCollection); static::assertEmpty($this->emptyCollection); static::assertTrue($this->emptyCollection->isEmpty()); - static::assertEquals([], $this->emptyCollection->toArray()); + static::assertSame([], $this->emptyCollection->toArray()); static::assertEmpty($this->emptyCollection->toArray()); static::assertNull($this->emptyCollection->getFirst()); @@ -61,23 +61,23 @@ class CollectionTest extends BaseTestCase public function testNotEmptyCollection() { - static::assertEquals(4, $this->simpleCollection->count()); + static::assertSame(4, $this->simpleCollection->count()); static::assertCount(4, $this->simpleCollection); static::assertNotEmpty($this->simpleCollection); static::assertFalse($this->simpleCollection->isEmpty()); - static::assertEquals($this->simpleElements, $this->simpleCollection->toArray()); + static::assertSame($this->simpleElements, $this->simpleCollection->toArray()); static::assertNotEmpty($this->simpleCollection->toArray()); - static::assertEquals('lorem', $this->simpleCollection->getFirst()); - static::assertEquals('sit', $this->simpleCollection->getLast()); - static::assertEquals('dolor', $this->simpleCollection[123]); + static::assertSame('lorem', $this->simpleCollection->getFirst()); + static::assertSame('sit', $this->simpleCollection->getLast()); + static::assertSame('dolor', $this->simpleCollection[123]); } public function testCount() { - static::assertEquals(0, $this->emptyCollection->count()); - static::assertEquals(4, $this->simpleCollection->count()); + static::assertSame(0, $this->emptyCollection->count()); + static::assertSame(4, $this->simpleCollection->count()); } public function testOffsetExists() @@ -94,8 +94,8 @@ class CollectionTest extends BaseTestCase static::assertNull($this->emptyCollection['abc']); static::assertNull($this->simpleCollection['abc']); - static::assertEquals('lorem', $this->simpleCollection[0]); - static::assertEquals('sit', $this->simpleCollection[345]); + static::assertSame('lorem', $this->simpleCollection[0]); + static::assertSame('sit', $this->simpleCollection[345]); } public function testOffsetSet() @@ -104,10 +104,10 @@ class CollectionTest extends BaseTestCase $this->simpleCollection['test2'] = 5678; static::assertTrue($this->emptyCollection->has(1234)); - static::assertEquals(1234, $this->emptyCollection['test1']); + static::assertSame(1234, $this->emptyCollection['test1']); static::assertTrue($this->simpleCollection->has(5678)); - static::assertEquals(5678, $this->simpleCollection['test2']); + static::assertSame(5678, $this->simpleCollection['test2']); } public function testOffsetUnset() @@ -115,14 +115,14 @@ class CollectionTest extends BaseTestCase unset($this->simpleCollection[0]); static::assertFalse($this->simpleCollection->has('lorem')); - static::assertEquals('ipsum', $this->simpleCollection[1]); - static::assertEquals(3, $this->simpleCollection->count()); + static::assertSame('ipsum', $this->simpleCollection[1]); + static::assertSame(3, $this->simpleCollection->count()); unset($this->simpleCollection[123]); static::assertFalse($this->simpleCollection->has('dolor')); - static::assertEquals('ipsum', $this->simpleCollection[1]); - static::assertEquals(2, $this->simpleCollection->count()); + static::assertSame('ipsum', $this->simpleCollection[1]); + static::assertSame(2, $this->simpleCollection->count()); } public function testGetIterator() @@ -143,8 +143,8 @@ class CollectionTest extends BaseTestCase $collection->add($element); static::assertTrue($collection->has($element)); - static::assertEquals($expectedCount, $collection->count()); - static::assertEquals($element, $collection[$expectedIndex]); + static::assertSame($expectedCount, $collection->count()); + static::assertSame($element, $collection[$expectedIndex]); } /** @@ -161,15 +161,15 @@ class CollectionTest extends BaseTestCase $collection->add($element, $index); static::assertTrue($collection->has($element)); - static::assertEquals($expectedCount, $collection->count()); - static::assertEquals($element, $collection[$expectedIndex]); + static::assertSame($expectedCount, $collection->count()); + static::assertSame($element, $collection[$expectedIndex]); } public function testAddMultipleUsingEmptyArray() { $this->emptyCollection->addMultiple([]); - static::assertEquals(0, $this->emptyCollection->count()); + static::assertSame(0, $this->emptyCollection->count()); static::assertTrue($this->emptyCollection->isEmpty()); } @@ -185,12 +185,12 @@ class CollectionTest extends BaseTestCase $this->emptyCollection->addMultiple($elements); static::assertFalse($this->emptyCollection->isEmpty()); - static::assertEquals(4, $this->emptyCollection->count()); + static::assertSame(4, $this->emptyCollection->count()); - static::assertEquals('test1', $this->emptyCollection[0]); - static::assertEquals('test2', $this->emptyCollection[1]); - static::assertEquals('test3', $this->emptyCollection[2]); - static::assertEquals('test4', $this->emptyCollection[3]); + static::assertSame('test1', $this->emptyCollection[0]); + static::assertSame('test2', $this->emptyCollection[1]); + static::assertSame('test3', $this->emptyCollection[2]); + static::assertSame('test4', $this->emptyCollection[3]); } public function testAddMultipleUsingIndexes() @@ -205,12 +205,12 @@ class CollectionTest extends BaseTestCase $this->emptyCollection->addMultiple($elements, true); static::assertFalse($this->emptyCollection->isEmpty()); - static::assertEquals(4, $this->emptyCollection->count()); + static::assertSame(4, $this->emptyCollection->count()); - static::assertEquals('test1', $this->emptyCollection[0]); - static::assertEquals('test2', $this->emptyCollection[1]); - static::assertEquals('test3', $this->emptyCollection[1234]); - static::assertEquals('test4', $this->emptyCollection[5678]); + static::assertSame('test1', $this->emptyCollection[0]); + static::assertSame('test2', $this->emptyCollection[1]); + static::assertSame('test3', $this->emptyCollection[1234]); + static::assertSame('test4', $this->emptyCollection[5678]); } public function testPrepend() @@ -218,14 +218,14 @@ class CollectionTest extends BaseTestCase $this->emptyCollection->prepend('lorem-ipsum'); static::assertFalse($this->emptyCollection->isEmpty()); - static::assertEquals(1, $this->emptyCollection->count()); - static::assertEquals('lorem-ipsum', $this->emptyCollection[0]); + static::assertSame(1, $this->emptyCollection->count()); + static::assertSame('lorem-ipsum', $this->emptyCollection[0]); $this->simpleCollection->prepend('lorem-ipsum'); static::assertFalse($this->simpleCollection->isEmpty()); - static::assertEquals(5, $this->simpleCollection->count()); - static::assertEquals('lorem-ipsum', $this->simpleCollection[0]); + static::assertSame(5, $this->simpleCollection->count()); + static::assertSame('lorem-ipsum', $this->simpleCollection[0]); } public function testRemoveNotExistingElement() @@ -233,24 +233,24 @@ class CollectionTest extends BaseTestCase $this->emptyCollection->remove('abc'); static::assertTrue($this->emptyCollection->isEmpty()); - static::assertEquals(0, $this->emptyCollection->count()); + static::assertSame(0, $this->emptyCollection->count()); $this->simpleCollection->remove('abc'); static::assertFalse($this->simpleCollection->isEmpty()); - static::assertEquals(4, $this->simpleCollection->count()); + static::assertSame(4, $this->simpleCollection->count()); } public function testRemove() { static::assertFalse($this->simpleCollection->isEmpty()); - static::assertEquals(4, $this->simpleCollection->count()); - static::assertEquals('ipsum', $this->simpleCollection[1]); + static::assertSame(4, $this->simpleCollection->count()); + static::assertSame('ipsum', $this->simpleCollection[1]); $this->simpleCollection->remove('ipsum'); static::assertFalse($this->simpleCollection->isEmpty()); - static::assertEquals(3, $this->simpleCollection->count()); + static::assertSame(3, $this->simpleCollection->count()); static::assertNull($this->simpleCollection[1]); } @@ -290,8 +290,8 @@ class CollectionTest extends BaseTestCase static::assertNull($this->simpleCollection->getPrevious('abc')); static::assertNull($this->simpleCollection->getPrevious('lorem')); - static::assertEquals('lorem', $this->simpleCollection->getPrevious('ipsum')); - static::assertEquals('dolor', $this->simpleCollection->getPrevious('sit')); + static::assertSame('lorem', $this->simpleCollection->getPrevious('ipsum')); + static::assertSame('dolor', $this->simpleCollection->getPrevious('sit')); } public function testGetNext() @@ -300,26 +300,26 @@ class CollectionTest extends BaseTestCase static::assertNull($this->simpleCollection->getNext('abc')); static::assertNull($this->simpleCollection->getNext('sit')); - static::assertEquals('dolor', $this->simpleCollection->getNext('ipsum')); - static::assertEquals('sit', $this->simpleCollection->getNext('dolor')); + static::assertSame('dolor', $this->simpleCollection->getNext('ipsum')); + static::assertSame('sit', $this->simpleCollection->getNext('dolor')); } public function testGetFirst() { static::assertNull($this->emptyCollection->getFirst()); - static::assertEquals('lorem', $this->simpleCollection->getFirst()); + static::assertSame('lorem', $this->simpleCollection->getFirst()); } public function testGetLast() { static::assertNull($this->emptyCollection->getLast()); - static::assertEquals('sit', $this->simpleCollection->getLast()); + static::assertSame('sit', $this->simpleCollection->getLast()); } public function testToArray() { - static::assertEquals([], $this->emptyCollection->toArray()); - static::assertEquals($this->simpleElements, $this->simpleCollection->toArray()); + static::assertSame([], $this->emptyCollection->toArray()); + static::assertSame($this->simpleElements, $this->simpleCollection->toArray()); } public function testExistsVisibilityAndArguments() diff --git a/tests/Exception/Date/UnknownDatePartTypeExceptionTest.php b/tests/Exception/Date/UnknownDatePartTypeExceptionTest.php index 745c481..d60bd4c 100644 --- a/tests/Exception/Date/UnknownDatePartTypeExceptionTest.php +++ b/tests/Exception/Date/UnknownDatePartTypeExceptionTest.php @@ -37,7 +37,7 @@ class UnknownDatePartTypeExceptionTest extends BaseTestCase public function testMessage($unknownDatePart, $value, $expectedMessage) { $exception = UnknownDatePartTypeException::createException($unknownDatePart, $value); - static::assertEquals($expectedMessage, $exception->getMessage()); + static::assertSame($expectedMessage, $exception->getMessage()); } /** diff --git a/tests/Exception/File/EmptyFileExceptionTest.php b/tests/Exception/File/EmptyFileExceptionTest.php index 88aae84..531e0b0 100644 --- a/tests/Exception/File/EmptyFileExceptionTest.php +++ b/tests/Exception/File/EmptyFileExceptionTest.php @@ -35,7 +35,7 @@ class EmptyFileExceptionTest extends BaseTestCase public function testMessage($emptyFilePath, $expectedMessage) { $exception = EmptyFileException::create($emptyFilePath); - static::assertEquals($expectedMessage, $exception->getMessage()); + static::assertSame($expectedMessage, $exception->getMessage()); } /** diff --git a/tests/Exception/File/EmptyFilePathExceptionTest.php b/tests/Exception/File/EmptyFilePathExceptionTest.php index 93cd7ee..35d24d9 100644 --- a/tests/Exception/File/EmptyFilePathExceptionTest.php +++ b/tests/Exception/File/EmptyFilePathExceptionTest.php @@ -28,6 +28,6 @@ class EmptyFilePathExceptionTest extends BaseTestCase public function testConstructorMessage() { $exception = EmptyFilePathException::create(); - static::assertEquals('Path of the file is empty. Did you provide path of proper file?', $exception->getMessage()); + static::assertSame('Path of the file is empty. Did you provide path of proper file?', $exception->getMessage()); } } diff --git a/tests/Exception/File/NotExistingFileExceptionTest.php b/tests/Exception/File/NotExistingFileExceptionTest.php index 21d7999..f0b0dd5 100644 --- a/tests/Exception/File/NotExistingFileExceptionTest.php +++ b/tests/Exception/File/NotExistingFileExceptionTest.php @@ -35,7 +35,7 @@ class NotExistingFileExceptionTest extends BaseTestCase public function testConstructorMessage($notExistingFilePath, $expectedMessage) { $exception = NotExistingFileException::create($notExistingFilePath); - static::assertEquals($expectedMessage, $exception->getMessage()); + static::assertSame($expectedMessage, $exception->getMessage()); } /** diff --git a/tests/Exception/Method/DisabledMethodExceptionTest.php b/tests/Exception/Method/DisabledMethodExceptionTest.php index 81854ce..b2b33cd 100644 --- a/tests/Exception/Method/DisabledMethodExceptionTest.php +++ b/tests/Exception/Method/DisabledMethodExceptionTest.php @@ -37,7 +37,7 @@ class DisabledMethodExceptionTest extends BaseTestCase public function testConstructorMessage($disabledMethod, $alternativeMethod, $expectedMessage) { $exception = DisabledMethodException::create($disabledMethod, $alternativeMethod); - static::assertEquals($expectedMessage, $exception->getMessage()); + static::assertSame($expectedMessage, $exception->getMessage()); } /** diff --git a/tests/Exception/Reflection/CannotResolveClassNameExceptionTest.php b/tests/Exception/Reflection/CannotResolveClassNameExceptionTest.php index 880f09e..b165e12 100644 --- a/tests/Exception/Reflection/CannotResolveClassNameExceptionTest.php +++ b/tests/Exception/Reflection/CannotResolveClassNameExceptionTest.php @@ -38,7 +38,7 @@ class CannotResolveClassNameExceptionTest extends BaseTestCase public function testConstructorMessage($source, $forClass, $expectedMessage) { $exception = CannotResolveClassNameException::create($source, $forClass); - static::assertEquals($expectedMessage, $exception->getMessage()); + static::assertSame($expectedMessage, $exception->getMessage()); } /** diff --git a/tests/Exception/Reflection/MissingChildClassesExceptionTest.php b/tests/Exception/Reflection/MissingChildClassesExceptionTest.php index 3ec9f3a..3771d8b 100644 --- a/tests/Exception/Reflection/MissingChildClassesExceptionTest.php +++ b/tests/Exception/Reflection/MissingChildClassesExceptionTest.php @@ -36,7 +36,7 @@ class MissingChildClassesExceptionTest extends BaseTestCase public function testConstructorMessage($parentClass, $expectedMessage) { $exception = MissingChildClassesException::create($parentClass); - static::assertEquals($expectedMessage, $exception->getMessage()); + static::assertSame($expectedMessage, $exception->getMessage()); } /** diff --git a/tests/Exception/Reflection/TooManyChildClassesExceptionTest.php b/tests/Exception/Reflection/TooManyChildClassesExceptionTest.php index 3360c4c..49cab93 100644 --- a/tests/Exception/Reflection/TooManyChildClassesExceptionTest.php +++ b/tests/Exception/Reflection/TooManyChildClassesExceptionTest.php @@ -37,7 +37,7 @@ class TooManyChildClassesExceptionTest extends BaseTestCase public function testConstructorMessage($parentClass, array $childClasses, $expectedMessage) { $exception = TooManyChildClassesException::create($parentClass, $childClasses); - static::assertEquals($expectedMessage, $exception->getMessage()); + static::assertSame($expectedMessage, $exception->getMessage()); } /** diff --git a/tests/Exception/Regex/IncorrectColorHexLengthExceptionTest.php b/tests/Exception/Regex/IncorrectColorHexLengthExceptionTest.php index 1200995..9abef1b 100644 --- a/tests/Exception/Regex/IncorrectColorHexLengthExceptionTest.php +++ b/tests/Exception/Regex/IncorrectColorHexLengthExceptionTest.php @@ -35,7 +35,7 @@ class IncorrectColorHexLengthExceptionTest extends BaseTestCase public function testConstructorMessage($color, $expectedMessage) { $exception = IncorrectColorHexLengthException::create($color); - static::assertEquals($expectedMessage, $exception->getMessage()); + static::assertSame($expectedMessage, $exception->getMessage()); } /** diff --git a/tests/Exception/Regex/InvalidColorHexValueExceptionTest.php b/tests/Exception/Regex/InvalidColorHexValueExceptionTest.php index 6153f0d..87ce62d 100644 --- a/tests/Exception/Regex/InvalidColorHexValueExceptionTest.php +++ b/tests/Exception/Regex/InvalidColorHexValueExceptionTest.php @@ -35,7 +35,7 @@ class InvalidColorHexValueExceptionTest extends BaseTestCase public function testConstructorMessage($color, $expectedMessage) { $exception = InvalidColorHexValueException::create($color); - static::assertEquals($expectedMessage, $exception->getMessage()); + static::assertSame($expectedMessage, $exception->getMessage()); } /** diff --git a/tests/Exception/Regex/InvalidHtmlAttributesExceptionTest.php b/tests/Exception/Regex/InvalidHtmlAttributesExceptionTest.php index f343830..8319283 100644 --- a/tests/Exception/Regex/InvalidHtmlAttributesExceptionTest.php +++ b/tests/Exception/Regex/InvalidHtmlAttributesExceptionTest.php @@ -35,7 +35,7 @@ class InvalidHtmlAttributesExceptionTest extends BaseTestCase public function testConstructorMessage($htmlAttributes, $expectedMessage) { $exception = InvalidHtmlAttributesException::create($htmlAttributes); - static::assertEquals($expectedMessage, $exception->getMessage()); + static::assertSame($expectedMessage, $exception->getMessage()); } /** diff --git a/tests/Exception/Regex/InvalidUrlExceptionTest.php b/tests/Exception/Regex/InvalidUrlExceptionTest.php index 1670aca..16bc8f5 100644 --- a/tests/Exception/Regex/InvalidUrlExceptionTest.php +++ b/tests/Exception/Regex/InvalidUrlExceptionTest.php @@ -35,7 +35,7 @@ class InvalidUrlExceptionTest extends BaseTestCase public function testConstructorMessage($url, $expectedMessage) { $exception = InvalidUrlException::create($url); - static::assertEquals($expectedMessage, $exception->getMessage()); + static::assertSame($expectedMessage, $exception->getMessage()); } /** diff --git a/tests/Exception/Type/UnknownOopVisibilityTypeExceptionTest.php b/tests/Exception/Type/UnknownOopVisibilityTypeExceptionTest.php index e958a97..df508e2 100644 --- a/tests/Exception/Type/UnknownOopVisibilityTypeExceptionTest.php +++ b/tests/Exception/Type/UnknownOopVisibilityTypeExceptionTest.php @@ -36,7 +36,7 @@ class UnknownOopVisibilityTypeExceptionTest extends BaseTestCase public function testConstructorMessage($unknownType, $expectedMessage) { $exception = UnknownOopVisibilityTypeException::createException($unknownType); - static::assertEquals($expectedMessage, $exception->getMessage()); + static::assertSame($expectedMessage, $exception->getMessage()); } /** diff --git a/tests/Utilities/Arrays/SimpleToString.php b/tests/Utilities/Arrays/SimpleToString.php index 04bec45..16ec4d0 100644 --- a/tests/Utilities/Arrays/SimpleToString.php +++ b/tests/Utilities/Arrays/SimpleToString.php @@ -35,7 +35,9 @@ class SimpleToString } /** - * {@inheritdoc} + * Returns representation of object as string + * + * @return string */ public function __toString() { diff --git a/tests/Utilities/ReflectionTest.php b/tests/Utilities/ReflectionTest.php index 8763716..f4c5261 100644 --- a/tests/Utilities/ReflectionTest.php +++ b/tests/Utilities/ReflectionTest.php @@ -410,7 +410,7 @@ class ReflectionTest extends BaseTestCase public function testGetMaxNumberConstant() { - static::assertEquals(5, Reflection::getMaxNumberConstant(H::class)); + static::assertSame(5, Reflection::getMaxNumberConstant(H::class)); } public function testHasMethodUsingClassWithoutMethod() @@ -450,7 +450,7 @@ class ReflectionTest extends BaseTestCase public function testGetConstantValue() { - static::assertEquals(H::LOREM, Reflection::getConstantValue(H::class, 'LOREM')); + static::assertSame(H::LOREM, Reflection::getConstantValue(H::class, 'LOREM')); } public function testIsInterfaceImplementedUsingClassWithoutInterface() @@ -484,7 +484,7 @@ class ReflectionTest extends BaseTestCase static::assertInstanceOf(ReflectionProperty::class, $property); static::assertTrue($property->isPrivate()); - static::assertEquals('count', $property->getName()); + static::assertSame('count', $property->getName()); } public function testGetPropertyUsingClassWithProtectedProperty() @@ -493,7 +493,7 @@ class ReflectionTest extends BaseTestCase static::assertInstanceOf(ReflectionProperty::class, $property); static::assertTrue($property->isProtected()); - static::assertEquals('name', $property->getName()); + static::assertSame('name', $property->getName()); } /** diff --git a/tests/Utilities/RepositoryTest.php b/tests/Utilities/RepositoryTest.php index 0ccedd4..97a7b2b 100644 --- a/tests/Utilities/RepositoryTest.php +++ b/tests/Utilities/RepositoryTest.php @@ -36,7 +36,7 @@ class RepositoryTest extends BaseTestCase $items = []; Repository::replenishPositions($items); - static::assertEquals([], $items); + static::assertSame([], $items); } public function testReplenishPositionsUsingNotSortableObjects() @@ -85,10 +85,10 @@ class RepositoryTest extends BaseTestCase public function testReplenishPositionsUsingArraysWithoutExtremePosition(array $items) { Repository::replenishPositions($items); - static::assertEquals($items, $items); + static::assertSame($items, $items); Repository::replenishPositions($items, false); - static::assertEquals($items, $items); + static::assertSame($items, $items); } /** @@ -101,7 +101,7 @@ class RepositoryTest extends BaseTestCase public function testReplenishPositionsUsingArraysWithoutExtremePositionForce(array $items, $asLast, array $expected) { Repository::replenishPositions($items, $asLast, true); - static::assertEquals($expected, $items); + static::assertSame($expected, $items); } /** @@ -114,7 +114,7 @@ class RepositoryTest extends BaseTestCase public function testReplenishPositionsUsingArraysWithExtremePositionForce(array $items, $asLast, array $expected) { Repository::replenishPositions($items, $asLast, true); - static::assertEquals($expected, $items); + static::assertSame($expected, $items); } /** @@ -124,10 +124,10 @@ class RepositoryTest extends BaseTestCase public function testReplenishPositionsUsingObjectsWithoutExtremePosition(array $items) { Repository::replenishPositions($items); - static::assertEquals($items, $items); + static::assertSame($items, $items); Repository::replenishPositions($items, false); - static::assertEquals($items, $items); + static::assertSame($items, $items); } /** @@ -171,7 +171,7 @@ class RepositoryTest extends BaseTestCase */ public function testGetExtremePositionUsingArraysWithoutExtremePosition(array $items, $max, $expected) { - static::assertEquals($expected, Repository::getExtremePosition($items, $max)); + static::assertSame($expected, Repository::getExtremePosition($items, $max)); } /** @@ -183,7 +183,7 @@ class RepositoryTest extends BaseTestCase */ public function testGetExtremePositionUsingArraysWithExtremePosition(array $items, $max, $expected) { - static::assertEquals($expected, Repository::getExtremePosition($items, $max)); + static::assertSame($expected, Repository::getExtremePosition($items, $max)); } /** @@ -195,7 +195,7 @@ class RepositoryTest extends BaseTestCase */ public function testGetExtremePositionUsingObjectsWithoutExtremePosition(array $items, $max, $expected) { - static::assertEquals($expected, Repository::getExtremePosition($items, $max)); + static::assertSame($expected, Repository::getExtremePosition($items, $max)); } /** @@ -207,7 +207,7 @@ class RepositoryTest extends BaseTestCase */ public function testGetExtremePositionUsingObjectsWithExtremePosition(array $items, $max, $expected) { - static::assertEquals($expected, Repository::getExtremePosition($items, $max)); + static::assertSame($expected, Repository::getExtremePosition($items, $max)); } public function testGetEntityOrderedQueryBuilderUsingDefaults() From ba6c185ed9b3a8f5d0602cecf8001ae83b1de422 Mon Sep 17 00:00:00 2001 From: Meritoo Date: Mon, 4 Mar 2019 19:24:23 +0100 Subject: [PATCH 4/8] Tests > missing tests --- .../IncorrectBundleNameExceptionTest.php | 74 ++++++++++++++++++ .../NotExistingPropertyExceptionTest.php | 78 +++++++++++++++++++ 2 files changed, 152 insertions(+) create mode 100644 tests/Exception/Bundle/IncorrectBundleNameExceptionTest.php create mode 100644 tests/Exception/Reflection/NotExistingPropertyExceptionTest.php diff --git a/tests/Exception/Bundle/IncorrectBundleNameExceptionTest.php b/tests/Exception/Bundle/IncorrectBundleNameExceptionTest.php new file mode 100644 index 0000000..3899331 --- /dev/null +++ b/tests/Exception/Bundle/IncorrectBundleNameExceptionTest.php @@ -0,0 +1,74 @@ + + * @copyright Meritoo + */ +class IncorrectBundleNameExceptionTest extends BaseTestCase +{ + public function testConstructor() + { + static::assertConstructorVisibilityAndArguments( + IncorrectBundleNameException::class, + OopVisibilityType::IS_PUBLIC, + 3 + ); + } + + /** + * @param string $description Description of test + * @param string $bundleName Incorrect name of bundle + * @param string $expectedMessage Expected exception's message + * + * @dataProvider provideBundleNameAndMessage + */ + public function testCreate($description, $bundleName, $expectedMessage) + { + $exception = IncorrectBundleNameException::create($bundleName); + static::assertSame($expectedMessage, $exception->getMessage(), $description); + } + + public function provideBundleNameAndMessage() + { + $template = 'Name of bundle \'%s\' is incorrect. It should start with big letter and end with "Bundle". Is' + . ' there everything ok?'; + + yield[ + 'An empty string as name of bundle', + '', + sprintf($template, ''), + ]; + + yield[ + 'Null as name of bundle', + null, + sprintf($template, ''), + ]; + + yield[ + 'String with spaces as name of bundle', + 'This is test', + sprintf($template, 'This is test'), + ]; + + yield[ + 'String without spaces as name of bundle', + 'ThisIsTest', + sprintf($template, 'ThisIsTest'), + ]; + } +} diff --git a/tests/Exception/Reflection/NotExistingPropertyExceptionTest.php b/tests/Exception/Reflection/NotExistingPropertyExceptionTest.php new file mode 100644 index 0000000..502a248 --- /dev/null +++ b/tests/Exception/Reflection/NotExistingPropertyExceptionTest.php @@ -0,0 +1,78 @@ + + * @copyright Meritoo + */ +class NotExistingPropertyExceptionTest extends BaseTestCase +{ + public function testConstructor() + { + static::assertConstructorVisibilityAndArguments( + NotExistingPropertyException::class, + OopVisibilityType::IS_PUBLIC, + 3 + ); + } + + /** + * @param string $description Description of test + * @param mixed $object Object that should contains given property + * @param string $property Name of the property + * @param string $expectedMessage Expected exception's message + * + * @dataProvider provideObjectPropertyAndMessage + */ + public function testCreate($description, $object, $property, $expectedMessage) + { + $exception = NotExistingPropertyException::create($object, $property); + static::assertSame($expectedMessage, $exception->getMessage(), $description); + } + + public function provideObjectPropertyAndMessage() + { + $template = 'Property \'%s\' does not exist in instance of class \'%s\'. Did you use proper name of property?'; + + yield[ + 'An empty string as name of property', + new \stdClass(), + '', + sprintf($template, '', get_class(new \stdClass())), + ]; + + yield[ + 'Null as name of property', + new \stdClass(), + null, + sprintf($template, '', get_class(new \stdClass())), + ]; + + yield[ + 'String with spaces as name of property', + new \stdClass(), + 'This is test', + sprintf($template, 'This is test', get_class(new \stdClass())), + ]; + + yield[ + 'String without spaces as name of property', + new \stdClass(), + 'ThisIsTest', + sprintf($template, 'ThisIsTest', get_class(new \stdClass())), + ]; + } +} From fe40d9caee49abe769de03ab8ceaf7d94c39b64e Mon Sep 17 00:00:00 2001 From: Meritoo Date: Mon, 4 Mar 2019 19:25:25 +0100 Subject: [PATCH 5/8] ValueObject > Human > represents a human --- CHANGELOG.md | 1 + docs/Value-Objects.md | 40 ++++++++ src/Traits/ValueObject/HumanTrait.php | 137 ++++++++++++++++++++++++++ src/ValueObject/Human.php | 22 +++++ tests/ValueObject/HumanTest.php | 116 ++++++++++++++++++++++ 5 files changed, 316 insertions(+) create mode 100644 src/Traits/ValueObject/HumanTrait.php create mode 100644 src/ValueObject/Human.php create mode 100644 tests/ValueObject/HumanTest.php diff --git a/CHANGELOG.md b/CHANGELOG.md index e2355e9..ba62097 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,6 +5,7 @@ Common and useful classes, methods, exceptions etc. # 0.1.6 1. Arrays > refactoring & more tests +2. ValueObject > Human > represents a human # 0.1.5 diff --git a/docs/Value-Objects.md b/docs/Value-Objects.md index 171947f..e6a8c79 100644 --- a/docs/Value-Objects.md +++ b/docs/Value-Objects.md @@ -137,6 +137,46 @@ $company = new Company( $asString = (string)$company; // "Test 1, 4th Avenue 10/200, 00123, New York, Bank 1, 12345" ``` +### Human + +##### Namespace + +`Meritoo\Common\ValueObject\Human` + +##### Info + +Represents human. Based on `\Meritoo\Common\Traits\ValueObject\HumanTrait` trait. Contains properties same as `HumanTrait` trait: +1. `$firstName` - first name +2. `$lastName` - last name +3. `$email` - email address +4. `$birthDate` - birth date + +##### New instance + +New instance can be created using constructor: + +```php +new Human('John', 'Scott', 'john@scott.com', new \DateTime('2001-01-01')); +``` + +##### Methods + +Has getters for each property, e.g. `getFirstName()`, `getEmail()` etc. + +##### Conversion to string (the `__toString()` method) + +Instance of `Human` may be represented as string that contains first name, last name and email address (if provided). + +Example: + +```php +$human1 = new Human('John', 'Scott'); +$asString1 = (string)$human1; // "John Scott" + +$human2 = new Human('John', 'Scott', 'john@scott.com', new \DateTime('2001-01-01')); +$asString2 = (string)$human2; // "John Scott " +``` + ### Version ##### Namespace diff --git a/src/Traits/ValueObject/HumanTrait.php b/src/Traits/ValueObject/HumanTrait.php new file mode 100644 index 0000000..b8b7cd8 --- /dev/null +++ b/src/Traits/ValueObject/HumanTrait.php @@ -0,0 +1,137 @@ + + * @copyright Meritoo + */ +trait HumanTrait +{ + /** + * First name + * + * @var string + */ + protected $firstName; + + /** + * Last name + * + * @var string + */ + protected $lastName; + + /** + * Email address + * + * @var string + */ + protected $email; + + /** + * Birth date + * + * @var \DateTime + */ + protected $birthDate; + + /** + * Class constructor + * + * @param string $firstName First name + * @param string $lastName Last name + * @param string $email (optional) Email address + * @param \DateTime $birthDate (optional) Birth date + */ + public function __construct($firstName, $lastName, $email = null, \DateTime $birthDate = null) + { + $this->firstName = $firstName; + $this->lastName = $lastName; + $this->email = $email; + $this->birthDate = $birthDate; + } + + /** + * Returns representation of object as string + * + * @return string + */ + public function __toString() + { + $template = '%s'; + + if ('' !== $this->email && null !== $this->email) { + $template .= ' <%s>'; + } + + return sprintf($template, $this->getFullName(), $this->email); + } + + /** + * Returns first name + * + * @return string + */ + public function getFirstName() + { + return $this->firstName; + } + + /** + * Returns last name + * + * @return string + */ + public function getLastName() + { + return $this->lastName; + } + + /** + * Returns email address + * + * @return string|null + */ + public function getEmail() + { + return $this->email; + } + + /** + * Returns birth date + * + * @return \DateTime|null + */ + public function getBirthDate() + { + return $this->birthDate; + } + + /** + * Returns the full name + * + * @param bool $firstNameFirst (optional) If is set to true, first name is the first part. Otherwise - last name. + * @return string + */ + public function getFullName($firstNameFirst = true) + { + $beginning = $this->lastName; + $finish = $this->firstName; + + if ($firstNameFirst) { + $beginning = $this->firstName; + $finish = $this->lastName; + } + + return trim(sprintf('%s %s', $beginning, $finish)); + } +} diff --git a/src/ValueObject/Human.php b/src/ValueObject/Human.php new file mode 100644 index 0000000..ad21c06 --- /dev/null +++ b/src/ValueObject/Human.php @@ -0,0 +1,22 @@ + + * @copyright Meritoo + */ +class Human +{ + use HumanTrait; +} diff --git a/tests/ValueObject/HumanTest.php b/tests/ValueObject/HumanTest.php new file mode 100644 index 0000000..0480b80 --- /dev/null +++ b/tests/ValueObject/HumanTest.php @@ -0,0 +1,116 @@ + + * @copyright Meritoo + */ +class HumanTest extends BaseTestCase +{ + public function testConstructor() + { + static::assertConstructorVisibilityAndArguments( + Human::class, + OopVisibilityType::IS_PUBLIC, + 4, + 2 + ); + } + + /** + * @param string $description Description of test + * @param Human $human Human to verify + * @param string $expected Expected string + * + * @dataProvider provideHuman + */ + public function testToString($description, Human $human, $expected) + { + static::assertSame($expected, (string)$human, $description); + } + + public function testGetFirstName() + { + $empty = new Human('', ''); + static::assertSame('', $empty->getFirstName()); + + $human = new Human('John', 'Scott'); + static::assertSame('John', $human->getFirstName()); + } + + public function testGetLastName() + { + $empty = new Human('', ''); + static::assertSame('', $empty->getLastName()); + + $human = new Human('John', 'Scott'); + static::assertSame('Scott', $human->getLastName()); + } + + public function testGetBirthDate() + { + $empty = new Human('', ''); + static::assertNull($empty->getBirthDate()); + + $human = new Human('John', 'Scott', '', new \DateTime('2001-01-01')); + static::assertEquals(new \DateTime('2001-01-01'), $human->getBirthDate()); + } + + public function testGetFullName() + { + $empty = new Human('', ''); + static::assertSame('', $empty->getFullName()); + + $human = new Human('John', 'Scott', '', new \DateTime('2001-01-01')); + static::assertSame('John Scott', $human->getFullName()); + } + + public function testGetEmail() + { + $empty = new Human('', ''); + static::assertNull($empty->getEmail()); + + $human = new Human('John', 'Scott', 'john@scott.com'); + static::assertSame('john@scott.com', $human->getEmail()); + } + + public function provideHuman() + { + yield[ + 'Without any data (an empty human)', + new Human('', ''), + '', + ]; + + yield[ + 'With first and last name only', + new Human('John', 'Scott'), + 'John Scott', + ]; + + yield[ + 'With first name, last name and email', + new Human('John', 'Scott', 'john@scott.com'), + 'John Scott ', + ]; + + yield[ + 'With whole/complete data', + new Human('John', 'Scott', 'john@scott.com', new \DateTime('2001-01-01')), + 'John Scott ', + ]; + } +} From 5ebde806461c94bc52a0ce04d59e5bb0e28ead91 Mon Sep 17 00:00:00 2001 From: Meritoo Date: Mon, 4 Mar 2019 19:35:42 +0100 Subject: [PATCH 6/8] Tests > use "Meritoo\Test\Common" namespace (instead of "Meritoo\Common\Test") --- CHANGELOG.md | 1 + composer.json | 2 +- tests/Collection/CollectionTest.php | 2 +- .../Base/UnknownTypeExceptionTest.php | 2 +- .../IncorrectBundleNameExceptionTest.php | 2 +- .../Date/UnknownDatePartTypeExceptionTest.php | 2 +- .../Exception/File/EmptyFileExceptionTest.php | 2 +- .../File/EmptyFilePathExceptionTest.php | 2 +- .../File/NotExistingFileExceptionTest.php | 2 +- .../Method/DisabledMethodExceptionTest.php | 2 +- .../CannotResolveClassNameExceptionTest.php | 2 +- .../MissingChildClassesExceptionTest.php | 2 +- .../NotExistingPropertyExceptionTest.php | 2 +- .../TooManyChildClassesExceptionTest.php | 2 +- .../IncorrectColorHexLengthExceptionTest.php | 2 +- .../InvalidColorHexValueExceptionTest.php | 2 +- .../InvalidHtmlAttributesExceptionTest.php | 2 +- .../Regex/InvalidUrlExceptionTest.php | 2 +- .../UnknownOopVisibilityTypeExceptionTest.php | 2 +- tests/Test/Base/BaseTestCaseTest.php | 2 +- tests/Type/Base/BaseTypeTest.php | 2 +- tests/Type/DatePartTypeTest.php | 48 +++++++-------- tests/Type/DatePeriodTest.php | 58 +++++++++---------- tests/Utilities/Arrays/SimpleToString.php | 2 +- tests/Utilities/ArraysTest.php | 4 +- tests/Utilities/Bootstrap4CssSelectorTest.php | 2 +- tests/Utilities/BundleTest.php | 2 +- tests/Utilities/ComposerTest.php | 2 +- tests/Utilities/CssSelectorTest.php | 2 +- tests/Utilities/DateTest.php | 9 ++- tests/Utilities/GeneratorUtilityTest.php | 2 +- tests/Utilities/LocaleTest.php | 6 +- tests/Utilities/MimeTypesTest.php | 2 +- tests/Utilities/MiscellaneousTest.php | 2 +- tests/Utilities/QueryBuilderUtilityTest.php | 5 +- tests/Utilities/Reflection/A.php | 2 +- tests/Utilities/Reflection/B.php | 2 +- tests/Utilities/Reflection/C.php | 2 +- tests/Utilities/Reflection/D.php | 2 +- tests/Utilities/Reflection/E.php | 2 +- tests/Utilities/Reflection/F.php | 2 +- tests/Utilities/Reflection/G.php | 2 +- tests/Utilities/Reflection/H.php | 2 +- tests/Utilities/Reflection/I.php | 2 +- tests/Utilities/ReflectionTest.php | 22 +++---- tests/Utilities/Repository/Sortable.php | 2 +- tests/Utilities/RepositoryTest.php | 16 +++-- tests/Utilities/UriTest.php | 2 +- tests/Utilities/XmlTest.php | 2 +- tests/ValueObject/AddressTest.php | 2 +- tests/ValueObject/BankAccountTest.php | 2 +- tests/ValueObject/CompanyTest.php | 2 +- tests/ValueObject/HumanTest.php | 2 +- tests/ValueObject/VersionTest.php | 2 +- 54 files changed, 134 insertions(+), 125 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index ba62097..9306157 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,7 @@ Common and useful classes, methods, exceptions etc. 1. Arrays > refactoring & more tests 2. ValueObject > Human > represents a human +3. Tests > use `Meritoo\Test\Common` namespace (instead of `Meritoo\Common\Test`) # 0.1.5 diff --git a/composer.json b/composer.json index 1206a5a..bf18bd2 100644 --- a/composer.json +++ b/composer.json @@ -36,7 +36,7 @@ }, "autoload-dev": { "psr-4": { - "Meritoo\\Common\\Test\\": "tests/" + "Meritoo\\Test\\Common\\": "tests/" } }, "config": { diff --git a/tests/Collection/CollectionTest.php b/tests/Collection/CollectionTest.php index b2df4aa..5b789c7 100644 --- a/tests/Collection/CollectionTest.php +++ b/tests/Collection/CollectionTest.php @@ -6,7 +6,7 @@ * file that was distributed with this source code. */ -namespace Meritoo\Common\Test\Collection; +namespace Meritoo\Test\Common\Collection; use ArrayIterator; use Generator; diff --git a/tests/Exception/Base/UnknownTypeExceptionTest.php b/tests/Exception/Base/UnknownTypeExceptionTest.php index c453db6..ce910d3 100644 --- a/tests/Exception/Base/UnknownTypeExceptionTest.php +++ b/tests/Exception/Base/UnknownTypeExceptionTest.php @@ -6,7 +6,7 @@ * file that was distributed with this source code. */ -namespace Meritoo\Common\Test\Exception\Base; +namespace Meritoo\Test\Common\Exception\Base; use Meritoo\Common\Exception\Base\UnknownTypeException; use Meritoo\Common\Test\Base\BaseTestCase; diff --git a/tests/Exception/Bundle/IncorrectBundleNameExceptionTest.php b/tests/Exception/Bundle/IncorrectBundleNameExceptionTest.php index 3899331..5c2d420 100644 --- a/tests/Exception/Bundle/IncorrectBundleNameExceptionTest.php +++ b/tests/Exception/Bundle/IncorrectBundleNameExceptionTest.php @@ -6,7 +6,7 @@ * file that was distributed with this source code. */ -namespace Meritoo\Common\Test\Exception\Bundle; +namespace Meritoo\Test\Common\Exception\Bundle; use Meritoo\Common\Exception\Bundle\IncorrectBundleNameException; use Meritoo\Common\Test\Base\BaseTestCase; diff --git a/tests/Exception/Date/UnknownDatePartTypeExceptionTest.php b/tests/Exception/Date/UnknownDatePartTypeExceptionTest.php index d60bd4c..f694ef1 100644 --- a/tests/Exception/Date/UnknownDatePartTypeExceptionTest.php +++ b/tests/Exception/Date/UnknownDatePartTypeExceptionTest.php @@ -6,7 +6,7 @@ * file that was distributed with this source code. */ -namespace Meritoo\Common\Test\Exception\Date; +namespace Meritoo\Test\Common\Exception\Date; use Generator; use Meritoo\Common\Exception\Type\UnknownDatePartTypeException; diff --git a/tests/Exception/File/EmptyFileExceptionTest.php b/tests/Exception/File/EmptyFileExceptionTest.php index 531e0b0..a2ee08d 100644 --- a/tests/Exception/File/EmptyFileExceptionTest.php +++ b/tests/Exception/File/EmptyFileExceptionTest.php @@ -6,7 +6,7 @@ * file that was distributed with this source code. */ -namespace Meritoo\Common\Test\Exception\File; +namespace Meritoo\Test\Common\Exception\File; use Generator; use Meritoo\Common\Exception\File\EmptyFileException; diff --git a/tests/Exception/File/EmptyFilePathExceptionTest.php b/tests/Exception/File/EmptyFilePathExceptionTest.php index 35d24d9..b582579 100644 --- a/tests/Exception/File/EmptyFilePathExceptionTest.php +++ b/tests/Exception/File/EmptyFilePathExceptionTest.php @@ -6,7 +6,7 @@ * file that was distributed with this source code. */ -namespace Meritoo\Common\Test\Exception\File; +namespace Meritoo\Test\Common\Exception\File; use Meritoo\Common\Exception\File\EmptyFilePathException; use Meritoo\Common\Test\Base\BaseTestCase; diff --git a/tests/Exception/File/NotExistingFileExceptionTest.php b/tests/Exception/File/NotExistingFileExceptionTest.php index f0b0dd5..08f8868 100644 --- a/tests/Exception/File/NotExistingFileExceptionTest.php +++ b/tests/Exception/File/NotExistingFileExceptionTest.php @@ -6,7 +6,7 @@ * file that was distributed with this source code. */ -namespace Meritoo\Common\Test\Exception\File; +namespace Meritoo\Test\Common\Exception\File; use Generator; use Meritoo\Common\Exception\File\NotExistingFileException; diff --git a/tests/Exception/Method/DisabledMethodExceptionTest.php b/tests/Exception/Method/DisabledMethodExceptionTest.php index b2b33cd..a815b4e 100644 --- a/tests/Exception/Method/DisabledMethodExceptionTest.php +++ b/tests/Exception/Method/DisabledMethodExceptionTest.php @@ -6,7 +6,7 @@ * file that was distributed with this source code. */ -namespace Meritoo\Common\Test\Exception\Method; +namespace Meritoo\Test\Common\Exception\Method; use Generator; use Meritoo\Common\Exception\Method\DisabledMethodException; diff --git a/tests/Exception/Reflection/CannotResolveClassNameExceptionTest.php b/tests/Exception/Reflection/CannotResolveClassNameExceptionTest.php index b165e12..c6f9082 100644 --- a/tests/Exception/Reflection/CannotResolveClassNameExceptionTest.php +++ b/tests/Exception/Reflection/CannotResolveClassNameExceptionTest.php @@ -6,7 +6,7 @@ * file that was distributed with this source code. */ -namespace Meritoo\Common\Test\Exception\Reflection; +namespace Meritoo\Test\Common\Exception\Reflection; use Generator; use Meritoo\Common\Exception\Reflection\CannotResolveClassNameException; diff --git a/tests/Exception/Reflection/MissingChildClassesExceptionTest.php b/tests/Exception/Reflection/MissingChildClassesExceptionTest.php index 3771d8b..900d6e2 100644 --- a/tests/Exception/Reflection/MissingChildClassesExceptionTest.php +++ b/tests/Exception/Reflection/MissingChildClassesExceptionTest.php @@ -6,7 +6,7 @@ * file that was distributed with this source code. */ -namespace Meritoo\Common\Test\Exception\Reflection; +namespace Meritoo\Test\Common\Exception\Reflection; use Generator; use Meritoo\Common\Exception\Reflection\MissingChildClassesException; diff --git a/tests/Exception/Reflection/NotExistingPropertyExceptionTest.php b/tests/Exception/Reflection/NotExistingPropertyExceptionTest.php index 502a248..e172003 100644 --- a/tests/Exception/Reflection/NotExistingPropertyExceptionTest.php +++ b/tests/Exception/Reflection/NotExistingPropertyExceptionTest.php @@ -6,7 +6,7 @@ * file that was distributed with this source code. */ -namespace Meritoo\Common\Test\Exception\Reflection; +namespace Meritoo\Test\Common\Exception\Reflection; use Meritoo\Common\Exception\Reflection\NotExistingPropertyException; use Meritoo\Common\Test\Base\BaseTestCase; diff --git a/tests/Exception/Reflection/TooManyChildClassesExceptionTest.php b/tests/Exception/Reflection/TooManyChildClassesExceptionTest.php index 49cab93..3c19cad 100644 --- a/tests/Exception/Reflection/TooManyChildClassesExceptionTest.php +++ b/tests/Exception/Reflection/TooManyChildClassesExceptionTest.php @@ -6,7 +6,7 @@ * file that was distributed with this source code. */ -namespace Meritoo\Common\Test\Exception\Reflection; +namespace Meritoo\Test\Common\Exception\Reflection; use Generator; use Meritoo\Common\Exception\Reflection\TooManyChildClassesException; diff --git a/tests/Exception/Regex/IncorrectColorHexLengthExceptionTest.php b/tests/Exception/Regex/IncorrectColorHexLengthExceptionTest.php index 9abef1b..9482dbd 100644 --- a/tests/Exception/Regex/IncorrectColorHexLengthExceptionTest.php +++ b/tests/Exception/Regex/IncorrectColorHexLengthExceptionTest.php @@ -6,7 +6,7 @@ * file that was distributed with this source code. */ -namespace Meritoo\Common\Test\Exception\Regex; +namespace Meritoo\Test\Common\Exception\Regex; use Generator; use Meritoo\Common\Exception\Regex\IncorrectColorHexLengthException; diff --git a/tests/Exception/Regex/InvalidColorHexValueExceptionTest.php b/tests/Exception/Regex/InvalidColorHexValueExceptionTest.php index 87ce62d..ec32268 100644 --- a/tests/Exception/Regex/InvalidColorHexValueExceptionTest.php +++ b/tests/Exception/Regex/InvalidColorHexValueExceptionTest.php @@ -6,7 +6,7 @@ * file that was distributed with this source code. */ -namespace Meritoo\Common\Test\Exception\Regex; +namespace Meritoo\Test\Common\Exception\Regex; use Generator; use Meritoo\Common\Exception\Regex\InvalidColorHexValueException; diff --git a/tests/Exception/Regex/InvalidHtmlAttributesExceptionTest.php b/tests/Exception/Regex/InvalidHtmlAttributesExceptionTest.php index 8319283..6772791 100644 --- a/tests/Exception/Regex/InvalidHtmlAttributesExceptionTest.php +++ b/tests/Exception/Regex/InvalidHtmlAttributesExceptionTest.php @@ -6,7 +6,7 @@ * file that was distributed with this source code. */ -namespace Meritoo\Common\Test\Exception\Regex; +namespace Meritoo\Test\Common\Exception\Regex; use Generator; use Meritoo\Common\Exception\Regex\InvalidHtmlAttributesException; diff --git a/tests/Exception/Regex/InvalidUrlExceptionTest.php b/tests/Exception/Regex/InvalidUrlExceptionTest.php index 16bc8f5..0e36d77 100644 --- a/tests/Exception/Regex/InvalidUrlExceptionTest.php +++ b/tests/Exception/Regex/InvalidUrlExceptionTest.php @@ -6,7 +6,7 @@ * file that was distributed with this source code. */ -namespace Meritoo\Common\Test\Exception\Regex; +namespace Meritoo\Test\Common\Exception\Regex; use Generator; use Meritoo\Common\Exception\Regex\InvalidUrlException; diff --git a/tests/Exception/Type/UnknownOopVisibilityTypeExceptionTest.php b/tests/Exception/Type/UnknownOopVisibilityTypeExceptionTest.php index df508e2..3f8377b 100644 --- a/tests/Exception/Type/UnknownOopVisibilityTypeExceptionTest.php +++ b/tests/Exception/Type/UnknownOopVisibilityTypeExceptionTest.php @@ -6,7 +6,7 @@ * file that was distributed with this source code. */ -namespace Meritoo\Common\Test\Exception\Type; +namespace Meritoo\Test\Common\Exception\Type; use Generator; use Meritoo\Common\Exception\Type\UnknownOopVisibilityTypeException; diff --git a/tests/Test/Base/BaseTestCaseTest.php b/tests/Test/Base/BaseTestCaseTest.php index 1136686..71dc496 100644 --- a/tests/Test/Base/BaseTestCaseTest.php +++ b/tests/Test/Base/BaseTestCaseTest.php @@ -6,7 +6,7 @@ * file that was distributed with this source code. */ -namespace Meritoo\Common\Test\Test\Base; +namespace Meritoo\Test\Common\Test\Base; use DateTime; use Generator; diff --git a/tests/Type/Base/BaseTypeTest.php b/tests/Type/Base/BaseTypeTest.php index 1b9b962..f21a1dc 100644 --- a/tests/Type/Base/BaseTypeTest.php +++ b/tests/Type/Base/BaseTypeTest.php @@ -6,7 +6,7 @@ * file that was distributed with this source code. */ -namespace Meritoo\Common\Test\Type\Base; +namespace Meritoo\Test\Common\Type\Base; use Generator; use Meritoo\Common\Test\Base\BaseTestCase; diff --git a/tests/Type/DatePartTypeTest.php b/tests/Type/DatePartTypeTest.php index 541aa15..782c259 100644 --- a/tests/Type/DatePartTypeTest.php +++ b/tests/Type/DatePartTypeTest.php @@ -6,7 +6,7 @@ * file that was distributed with this source code. */ -namespace Meritoo\Common\Test\Type; +namespace Meritoo\Test\Common\Type; use Meritoo\Common\Test\Base\BaseTypeTestCase; use Meritoo\Common\Type\DatePartType; @@ -19,29 +19,6 @@ use Meritoo\Common\Type\DatePartType; */ class DatePartTypeTest extends BaseTypeTestCase { - /** - * {@inheritdoc} - */ - protected function getAllExpectedTypes() - { - return [ - 'DAY' => DatePartType::DAY, - 'HOUR' => DatePartType::HOUR, - 'MINUTE' => DatePartType::MINUTE, - 'MONTH' => DatePartType::MONTH, - 'SECOND' => DatePartType::SECOND, - 'YEAR' => DatePartType::YEAR, - ]; - } - - /** - * {@inheritdoc} - */ - protected function getTestedTypeInstance() - { - return new DatePartType(); - } - /** * {@inheritdoc} */ @@ -97,4 +74,27 @@ class DatePartTypeTest extends BaseTypeTestCase true, ]; } + + /** + * {@inheritdoc} + */ + protected function getAllExpectedTypes() + { + return [ + 'DAY' => DatePartType::DAY, + 'HOUR' => DatePartType::HOUR, + 'MINUTE' => DatePartType::MINUTE, + 'MONTH' => DatePartType::MONTH, + 'SECOND' => DatePartType::SECOND, + 'YEAR' => DatePartType::YEAR, + ]; + } + + /** + * {@inheritdoc} + */ + protected function getTestedTypeInstance() + { + return new DatePartType(); + } } diff --git a/tests/Type/DatePeriodTest.php b/tests/Type/DatePeriodTest.php index fc6557f..a73ceaf 100644 --- a/tests/Type/DatePeriodTest.php +++ b/tests/Type/DatePeriodTest.php @@ -6,7 +6,7 @@ * file that was distributed with this source code. */ -namespace Meritoo\Common\Test\Type; +namespace Meritoo\Test\Common\Type; use DateTime; use Generator; @@ -214,34 +214,6 @@ class DatePeriodTest extends BaseTypeTestCase ]; } - /** - * Returns all expected types of the tested type - * - * @return array - */ - protected function getAllExpectedTypes() - { - return [ - 'LAST_MONTH' => DatePeriod::LAST_MONTH, - 'LAST_WEEK' => DatePeriod::LAST_WEEK, - 'LAST_YEAR' => DatePeriod::LAST_YEAR, - 'NEXT_MONTH' => DatePeriod::NEXT_MONTH, - 'NEXT_WEEK' => DatePeriod::NEXT_WEEK, - 'NEXT_YEAR' => DatePeriod::NEXT_YEAR, - 'THIS_MONTH' => DatePeriod::THIS_MONTH, - 'THIS_WEEK' => DatePeriod::THIS_WEEK, - 'THIS_YEAR' => DatePeriod::THIS_YEAR, - ]; - } - - /** - * {@inheritdoc} - */ - protected function getTestedTypeInstance() - { - return new DatePeriod(); - } - /** * {@inheritdoc} */ @@ -277,4 +249,32 @@ class DatePeriodTest extends BaseTypeTestCase true, ]; } + + /** + * Returns all expected types of the tested type + * + * @return array + */ + protected function getAllExpectedTypes() + { + return [ + 'LAST_MONTH' => DatePeriod::LAST_MONTH, + 'LAST_WEEK' => DatePeriod::LAST_WEEK, + 'LAST_YEAR' => DatePeriod::LAST_YEAR, + 'NEXT_MONTH' => DatePeriod::NEXT_MONTH, + 'NEXT_WEEK' => DatePeriod::NEXT_WEEK, + 'NEXT_YEAR' => DatePeriod::NEXT_YEAR, + 'THIS_MONTH' => DatePeriod::THIS_MONTH, + 'THIS_WEEK' => DatePeriod::THIS_WEEK, + 'THIS_YEAR' => DatePeriod::THIS_YEAR, + ]; + } + + /** + * {@inheritdoc} + */ + protected function getTestedTypeInstance() + { + return new DatePeriod(); + } } diff --git a/tests/Utilities/Arrays/SimpleToString.php b/tests/Utilities/Arrays/SimpleToString.php index 16ec4d0..dd51827 100644 --- a/tests/Utilities/Arrays/SimpleToString.php +++ b/tests/Utilities/Arrays/SimpleToString.php @@ -6,7 +6,7 @@ * file that was distributed with this source code. */ -namespace Meritoo\Common\Test\Utilities\Arrays; +namespace Meritoo\Test\Common\Utilities\Arrays; /** * Simple class convertible to string. diff --git a/tests/Utilities/ArraysTest.php b/tests/Utilities/ArraysTest.php index 3c1aa6d..168fac7 100644 --- a/tests/Utilities/ArraysTest.php +++ b/tests/Utilities/ArraysTest.php @@ -6,11 +6,11 @@ * file that was distributed with this source code. */ -namespace Meritoo\Common\Test\Utilities; +namespace Meritoo\Test\Common\Utilities; use Meritoo\Common\Test\Base\BaseTestCase; -use Meritoo\Common\Test\Utilities\Arrays\SimpleToString; use Meritoo\Common\Utilities\Arrays; +use Meritoo\Test\Common\Utilities\Arrays\SimpleToString; /** * Test case of the useful arrays methods diff --git a/tests/Utilities/Bootstrap4CssSelectorTest.php b/tests/Utilities/Bootstrap4CssSelectorTest.php index c2aa462..ee6787d 100644 --- a/tests/Utilities/Bootstrap4CssSelectorTest.php +++ b/tests/Utilities/Bootstrap4CssSelectorTest.php @@ -6,7 +6,7 @@ * file that was distributed with this source code. */ -namespace Meritoo\Common\Test\Utilities; +namespace Meritoo\Test\Common\Utilities; use Meritoo\Common\Test\Base\BaseTestCase; use Meritoo\Common\Utilities\Bootstrap4CssSelector; diff --git a/tests/Utilities/BundleTest.php b/tests/Utilities/BundleTest.php index a8fe474..92dd655 100644 --- a/tests/Utilities/BundleTest.php +++ b/tests/Utilities/BundleTest.php @@ -6,7 +6,7 @@ * file that was distributed with this source code. */ -namespace Meritoo\Common\Test\Utilities; +namespace Meritoo\Test\Common\Utilities; use Generator; use Meritoo\Common\Exception\Bundle\IncorrectBundleNameException; diff --git a/tests/Utilities/ComposerTest.php b/tests/Utilities/ComposerTest.php index b526c5e..10e4177 100644 --- a/tests/Utilities/ComposerTest.php +++ b/tests/Utilities/ComposerTest.php @@ -6,7 +6,7 @@ * file that was distributed with this source code. */ -namespace Meritoo\Common\Test\Utilities; +namespace Meritoo\Test\Common\Utilities; use Generator; use Meritoo\Common\Test\Base\BaseTestCase; diff --git a/tests/Utilities/CssSelectorTest.php b/tests/Utilities/CssSelectorTest.php index f85fa53..0ab9535 100644 --- a/tests/Utilities/CssSelectorTest.php +++ b/tests/Utilities/CssSelectorTest.php @@ -6,7 +6,7 @@ * file that was distributed with this source code. */ -namespace Meritoo\Common\Test\Utilities; +namespace Meritoo\Test\Common\Utilities; use Meritoo\Common\Test\Base\BaseTestCase; use Meritoo\Common\Utilities\CssSelector; diff --git a/tests/Utilities/DateTest.php b/tests/Utilities/DateTest.php index 94a7813..5fca3fe 100644 --- a/tests/Utilities/DateTest.php +++ b/tests/Utilities/DateTest.php @@ -6,7 +6,7 @@ * file that was distributed with this source code. */ -namespace Meritoo\Common\Test\Utilities; +namespace Meritoo\Test\Common\Utilities; use DateInterval; use DateTime; @@ -680,7 +680,8 @@ class DateTest extends BaseTestCase } /** - * @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. * @param DatePeriod $expected Expected start and end date for given period * * @dataProvider provideCorrectPeriod @@ -982,7 +983,9 @@ class DateTest extends BaseTestCase DatePeriod::NEXT_WEEK, new DatePeriod( (new DateTime('this week'))->add(new DateInterval('P7D'))->setTime(0, 0, 0), - (new DateTime('this week'))->add(new DateInterval('P7D'))->add(new DateInterval('P6D'))->setTime(23, 59, 59) + (new DateTime('this week'))->add(new DateInterval('P7D')) + ->add(new DateInterval('P6D')) + ->setTime(23, 59, 59) ), ]; diff --git a/tests/Utilities/GeneratorUtilityTest.php b/tests/Utilities/GeneratorUtilityTest.php index 27cf5d7..7642c87 100644 --- a/tests/Utilities/GeneratorUtilityTest.php +++ b/tests/Utilities/GeneratorUtilityTest.php @@ -6,7 +6,7 @@ * file that was distributed with this source code. */ -namespace Meritoo\Common\Test\Utilities; +namespace Meritoo\Test\Common\Utilities; use Meritoo\Common\Test\Base\BaseTestCase; use Meritoo\Common\Utilities\GeneratorUtility; diff --git a/tests/Utilities/LocaleTest.php b/tests/Utilities/LocaleTest.php index 5ad4d90..6a2c9ea 100644 --- a/tests/Utilities/LocaleTest.php +++ b/tests/Utilities/LocaleTest.php @@ -6,7 +6,7 @@ * file that was distributed with this source code. */ -namespace Meritoo\Common\Test\Utilities; +namespace Meritoo\Test\Common\Utilities; use Generator; use Meritoo\Common\Test\Base\BaseTestCase; @@ -80,8 +80,8 @@ class LocaleTest extends BaseTestCase } /** - * @param int $category Named constant specifying the category of the functions affected by the locale setting. - * It's the same constant as required by setlocale() function. + * @param int $category Named constant specifying the category of the functions affected by the locale + * setting. It's the same constant as required by setlocale() function. * @param string $languageCode Language code, in ISO 639-1 format. Short form of the locale, e.g. "fr". * @param string $countryCode Country code, in ISO 3166-1 alpha-2 format, e.g. "FR" * @param string $expectedLocale Expected locale diff --git a/tests/Utilities/MimeTypesTest.php b/tests/Utilities/MimeTypesTest.php index b51e7f2..ee0e85e 100644 --- a/tests/Utilities/MimeTypesTest.php +++ b/tests/Utilities/MimeTypesTest.php @@ -6,7 +6,7 @@ * file that was distributed with this source code. */ -namespace Meritoo\Common\Test\Utilities; +namespace Meritoo\Test\Common\Utilities; use Generator; use Meritoo\Common\Test\Base\BaseTestCase; diff --git a/tests/Utilities/MiscellaneousTest.php b/tests/Utilities/MiscellaneousTest.php index c5cfed2..38aec86 100644 --- a/tests/Utilities/MiscellaneousTest.php +++ b/tests/Utilities/MiscellaneousTest.php @@ -6,7 +6,7 @@ * file that was distributed with this source code. */ -namespace Meritoo\Common\Test\Utilities; +namespace Meritoo\Test\Common\Utilities; use Generator; use Meritoo\Common\Exception\Regex\IncorrectColorHexLengthException; diff --git a/tests/Utilities/QueryBuilderUtilityTest.php b/tests/Utilities/QueryBuilderUtilityTest.php index ece2b21..0451ef8 100644 --- a/tests/Utilities/QueryBuilderUtilityTest.php +++ b/tests/Utilities/QueryBuilderUtilityTest.php @@ -6,7 +6,7 @@ * file that was distributed with this source code. */ -namespace Meritoo\Common\Test\Utilities; +namespace Meritoo\Test\Common\Utilities; use Doctrine\Common\Collections\ArrayCollection; use Doctrine\ORM\EntityManager; @@ -260,7 +260,8 @@ class QueryBuilderUtilityTest extends BaseTestCase $entityManager ->expects(static::any()) ->method('getExpressionBuilder') - ->willReturn(new Expr()); + ->willReturn(new Expr()) + ; yield[ (new QueryBuilder($entityManager))->from('lorem_ipsum', 'lm'), diff --git a/tests/Utilities/Reflection/A.php b/tests/Utilities/Reflection/A.php index d3c5e0c..f20ca1a 100644 --- a/tests/Utilities/Reflection/A.php +++ b/tests/Utilities/Reflection/A.php @@ -6,7 +6,7 @@ * file that was distributed with this source code. */ -namespace Meritoo\Common\Test\Utilities\Reflection; +namespace Meritoo\Test\Common\Utilities\Reflection; /** * The A class. diff --git a/tests/Utilities/Reflection/B.php b/tests/Utilities/Reflection/B.php index 0ada1d0..101cdce 100644 --- a/tests/Utilities/Reflection/B.php +++ b/tests/Utilities/Reflection/B.php @@ -6,7 +6,7 @@ * file that was distributed with this source code. */ -namespace Meritoo\Common\Test\Utilities\Reflection; +namespace Meritoo\Test\Common\Utilities\Reflection; /** * The B class. diff --git a/tests/Utilities/Reflection/C.php b/tests/Utilities/Reflection/C.php index 8807a35..3c4d598 100644 --- a/tests/Utilities/Reflection/C.php +++ b/tests/Utilities/Reflection/C.php @@ -6,7 +6,7 @@ * file that was distributed with this source code. */ -namespace Meritoo\Common\Test\Utilities\Reflection; +namespace Meritoo\Test\Common\Utilities\Reflection; /** * The C class. diff --git a/tests/Utilities/Reflection/D.php b/tests/Utilities/Reflection/D.php index d031a08..06f6550 100644 --- a/tests/Utilities/Reflection/D.php +++ b/tests/Utilities/Reflection/D.php @@ -6,7 +6,7 @@ * file that was distributed with this source code. */ -namespace Meritoo\Common\Test\Utilities\Reflection; +namespace Meritoo\Test\Common\Utilities\Reflection; /** * The D class. diff --git a/tests/Utilities/Reflection/E.php b/tests/Utilities/Reflection/E.php index 177e94d..7a72efc 100644 --- a/tests/Utilities/Reflection/E.php +++ b/tests/Utilities/Reflection/E.php @@ -6,7 +6,7 @@ * file that was distributed with this source code. */ -namespace Meritoo\Common\Test\Utilities\Reflection; +namespace Meritoo\Test\Common\Utilities\Reflection; /** * The E trait. diff --git a/tests/Utilities/Reflection/F.php b/tests/Utilities/Reflection/F.php index f563db7..7206544 100644 --- a/tests/Utilities/Reflection/F.php +++ b/tests/Utilities/Reflection/F.php @@ -6,7 +6,7 @@ * file that was distributed with this source code. */ -namespace Meritoo\Common\Test\Utilities\Reflection; +namespace Meritoo\Test\Common\Utilities\Reflection; /** * The F class. diff --git a/tests/Utilities/Reflection/G.php b/tests/Utilities/Reflection/G.php index 0fb8ff6..d7f2c54 100644 --- a/tests/Utilities/Reflection/G.php +++ b/tests/Utilities/Reflection/G.php @@ -6,7 +6,7 @@ * file that was distributed with this source code. */ -namespace Meritoo\Common\Test\Utilities\Reflection; +namespace Meritoo\Test\Common\Utilities\Reflection; /** * The G class. diff --git a/tests/Utilities/Reflection/H.php b/tests/Utilities/Reflection/H.php index 68fa525..a5ce14d 100644 --- a/tests/Utilities/Reflection/H.php +++ b/tests/Utilities/Reflection/H.php @@ -6,7 +6,7 @@ * file that was distributed with this source code. */ -namespace Meritoo\Common\Test\Utilities\Reflection; +namespace Meritoo\Test\Common\Utilities\Reflection; /** * The H class. diff --git a/tests/Utilities/Reflection/I.php b/tests/Utilities/Reflection/I.php index d6a2063..020b149 100644 --- a/tests/Utilities/Reflection/I.php +++ b/tests/Utilities/Reflection/I.php @@ -6,7 +6,7 @@ * file that was distributed with this source code. */ -namespace Meritoo\Common\Test\Utilities\Reflection; +namespace Meritoo\Test\Common\Utilities\Reflection; /** * The H interface. diff --git a/tests/Utilities/ReflectionTest.php b/tests/Utilities/ReflectionTest.php index f4c5261..2507d7e 100644 --- a/tests/Utilities/ReflectionTest.php +++ b/tests/Utilities/ReflectionTest.php @@ -6,7 +6,7 @@ * file that was distributed with this source code. */ -namespace Meritoo\Common\Test\Utilities; +namespace Meritoo\Test\Common\Utilities; use DateTime; use Generator; @@ -16,16 +16,16 @@ use Meritoo\Common\Exception\Reflection\MissingChildClassesException; use Meritoo\Common\Exception\Reflection\NotExistingPropertyException; use Meritoo\Common\Exception\Reflection\TooManyChildClassesException; use Meritoo\Common\Test\Base\BaseTestCase; -use Meritoo\Common\Test\Utilities\Reflection\A; -use Meritoo\Common\Test\Utilities\Reflection\B; -use Meritoo\Common\Test\Utilities\Reflection\C; -use Meritoo\Common\Test\Utilities\Reflection\D; -use Meritoo\Common\Test\Utilities\Reflection\E; -use Meritoo\Common\Test\Utilities\Reflection\F; -use Meritoo\Common\Test\Utilities\Reflection\G; -use Meritoo\Common\Test\Utilities\Reflection\H; -use Meritoo\Common\Test\Utilities\Reflection\I; use Meritoo\Common\Utilities\Reflection; +use Meritoo\Test\Common\Utilities\Reflection\A; +use Meritoo\Test\Common\Utilities\Reflection\B; +use Meritoo\Test\Common\Utilities\Reflection\C; +use Meritoo\Test\Common\Utilities\Reflection\D; +use Meritoo\Test\Common\Utilities\Reflection\E; +use Meritoo\Test\Common\Utilities\Reflection\F; +use Meritoo\Test\Common\Utilities\Reflection\G; +use Meritoo\Test\Common\Utilities\Reflection\H; +use Meritoo\Test\Common\Utilities\Reflection\I; use ReflectionProperty; /** @@ -107,7 +107,7 @@ class ReflectionTest extends BaseTestCase /* * Existing class */ - self::assertEquals('Meritoo\Common\Test\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([ diff --git a/tests/Utilities/Repository/Sortable.php b/tests/Utilities/Repository/Sortable.php index c4b0413..fc877b6 100644 --- a/tests/Utilities/Repository/Sortable.php +++ b/tests/Utilities/Repository/Sortable.php @@ -6,7 +6,7 @@ * file that was distributed with this source code. */ -namespace Meritoo\Common\Test\Utilities\Repository; +namespace Meritoo\Test\Common\Utilities\Repository; /** * Sortable object/entity. diff --git a/tests/Utilities/RepositoryTest.php b/tests/Utilities/RepositoryTest.php index 97a7b2b..72d58a7 100644 --- a/tests/Utilities/RepositoryTest.php +++ b/tests/Utilities/RepositoryTest.php @@ -6,7 +6,7 @@ * file that was distributed with this source code. */ -namespace Meritoo\Common\Test\Utilities; +namespace Meritoo\Test\Common\Utilities; use Doctrine\ORM\EntityManagerInterface; use Doctrine\ORM\EntityRepository; @@ -14,8 +14,8 @@ use Doctrine\ORM\Query\Expr\OrderBy; use Doctrine\ORM\QueryBuilder; use Generator; use Meritoo\Common\Test\Base\BaseTestCase; -use Meritoo\Common\Test\Utilities\Repository\Sortable; use Meritoo\Common\Utilities\Repository; +use Meritoo\Test\Common\Utilities\Repository\Sortable; use stdClass; /** @@ -220,7 +220,8 @@ class RepositoryTest extends BaseTestCase ->setMethods([ 'createQueryBuilder', ]) - ->getMock(); + ->getMock() + ; $expectedQueryBuilder = new QueryBuilder($entityManager); $expectedQueryBuilder->from('any_table_name', 'qb'); @@ -228,7 +229,8 @@ class RepositoryTest extends BaseTestCase $entityRepository ->expects(static::once()) ->method('createQueryBuilder') - ->willReturn($expectedQueryBuilder); + ->willReturn($expectedQueryBuilder) + ; $queryBuilder = Repository::getEntityOrderedQueryBuilder($entityRepository); $selectDQLPart = $queryBuilder->getDQLPart('select'); @@ -262,7 +264,8 @@ class RepositoryTest extends BaseTestCase ->setMethods([ 'createQueryBuilder', ]) - ->getMock(); + ->getMock() + ; $expectedQueryBuilder = new QueryBuilder($entityManager); $expectedQueryBuilder->from('any_table_name', 'qb'); @@ -270,7 +273,8 @@ class RepositoryTest extends BaseTestCase $entityRepository ->expects(static::once()) ->method('createQueryBuilder') - ->willReturn($expectedQueryBuilder); + ->willReturn($expectedQueryBuilder) + ; $queryBuilder = Repository::getEntityOrderedQueryBuilder($entityRepository, $property, $direction); $selectDQLPart = $queryBuilder->getDQLPart('select'); diff --git a/tests/Utilities/UriTest.php b/tests/Utilities/UriTest.php index e341d65..20b1eaf 100644 --- a/tests/Utilities/UriTest.php +++ b/tests/Utilities/UriTest.php @@ -6,7 +6,7 @@ * file that was distributed with this source code. */ -namespace Meritoo\Common\Test\Utilities; +namespace Meritoo\Test\Common\Utilities; use Generator; use Meritoo\Common\Test\Base\BaseTestCase; diff --git a/tests/Utilities/XmlTest.php b/tests/Utilities/XmlTest.php index 804d77a..494aabf 100644 --- a/tests/Utilities/XmlTest.php +++ b/tests/Utilities/XmlTest.php @@ -6,7 +6,7 @@ * file that was distributed with this source code. */ -namespace Meritoo\Common\Test\Utilities; +namespace Meritoo\Test\Common\Utilities; use Meritoo\Common\Test\Base\BaseTestCase; use Meritoo\Common\Utilities\Xml; diff --git a/tests/ValueObject/AddressTest.php b/tests/ValueObject/AddressTest.php index e07db25..5cd1899 100644 --- a/tests/ValueObject/AddressTest.php +++ b/tests/ValueObject/AddressTest.php @@ -6,7 +6,7 @@ * file that was distributed with this source code. */ -namespace Meritoo\Common\Test\ValueObject; +namespace Meritoo\Test\Common\ValueObject; use Meritoo\Common\Test\Base\BaseTestCase; use Meritoo\Common\Type\OopVisibilityType; diff --git a/tests/ValueObject/BankAccountTest.php b/tests/ValueObject/BankAccountTest.php index 9dc6ab4..ac38dbc 100644 --- a/tests/ValueObject/BankAccountTest.php +++ b/tests/ValueObject/BankAccountTest.php @@ -6,7 +6,7 @@ * file that was distributed with this source code. */ -namespace Meritoo\Common\Test\ValueObject; +namespace Meritoo\Test\Common\ValueObject; use Meritoo\Common\Test\Base\BaseTestCase; use Meritoo\Common\Type\OopVisibilityType; diff --git a/tests/ValueObject/CompanyTest.php b/tests/ValueObject/CompanyTest.php index d6da00b..383b012 100644 --- a/tests/ValueObject/CompanyTest.php +++ b/tests/ValueObject/CompanyTest.php @@ -6,7 +6,7 @@ * file that was distributed with this source code. */ -namespace Meritoo\Common\Test\ValueObject; +namespace Meritoo\Test\Common\ValueObject; use Meritoo\Common\Test\Base\BaseTestCase; use Meritoo\Common\Type\OopVisibilityType; diff --git a/tests/ValueObject/HumanTest.php b/tests/ValueObject/HumanTest.php index 0480b80..1a58e35 100644 --- a/tests/ValueObject/HumanTest.php +++ b/tests/ValueObject/HumanTest.php @@ -6,7 +6,7 @@ * file that was distributed with this source code. */ -namespace Meritoo\Common\Test\ValueObject; +namespace Meritoo\Test\Common\ValueObject; use Meritoo\Common\Test\Base\BaseTestCase; use Meritoo\Common\Type\OopVisibilityType; diff --git a/tests/ValueObject/VersionTest.php b/tests/ValueObject/VersionTest.php index 7876798..fb0e783 100644 --- a/tests/ValueObject/VersionTest.php +++ b/tests/ValueObject/VersionTest.php @@ -6,7 +6,7 @@ * file that was distributed with this source code. */ -namespace Meritoo\Common\Test\ValueObject; +namespace Meritoo\Test\Common\ValueObject; use Generator; use Meritoo\Common\Test\Base\BaseTestCase; From d88ead92feaa353840cfaa7c5fd828061ff76254 Mon Sep 17 00:00:00 2001 From: Meritoo Date: Tue, 5 Mar 2019 10:11:48 +0100 Subject: [PATCH 7/8] Tests > use @dataProvider --- CHANGELOG.md | 1 + src/Utilities/Miscellaneous.php | 48 +-- tests/Utilities/MiscellaneousTest.php | 422 +++++++++++++++++++++++--- 3 files changed, 403 insertions(+), 68 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 9306157..a44377d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,7 @@ Common and useful classes, methods, exceptions etc. 1. Arrays > refactoring & more tests 2. ValueObject > Human > represents a human 3. Tests > use `Meritoo\Test\Common` namespace (instead of `Meritoo\Common\Test`) +4. Tests > use @dataProvider # 0.1.5 diff --git a/src/Utilities/Miscellaneous.php b/src/Utilities/Miscellaneous.php index 283e929..7dd7e61 100644 --- a/src/Utilities/Miscellaneous.php +++ b/src/Utilities/Miscellaneous.php @@ -425,6 +425,14 @@ class Miscellaneous */ public static function replace($subject, $search, $replacement, $quoteStrings = false) { + /* + * Unknown source or item to find or replacement is an empty array? + * Nothing to do + */ + if (empty($subject) || empty($search) || [] === $replacement) { + return $subject; + } + $effect = $subject; $searchIsString = is_string($search); @@ -444,14 +452,24 @@ class Miscellaneous $bothAreStrings = $searchIsString && $replacementIsString; $bothAreArrays = $searchIsArray && $replacementIsArray; + if ($quoteStrings) { + if ($replacementIsString) { + $replacement = '\'' . $replacement . '\''; + } elseif ($replacementIsArray) { + foreach ($replacement as &$item) { + if (is_string($item)) { + $item = '\'' . $item . '\''; + } + } + + unset($item); + } + } + /* * First step: replace strings, simple operation with strings */ - if ($searchIsString && $replacementIsString) { - if ($quoteStrings) { - $replacement = '\'' . $replacement . '\''; - } - + if ($bothAreStrings) { $effect = str_replace($search, $replacement, $subject); } @@ -460,16 +478,16 @@ class Miscellaneous * Attention. Searched and replacement value should be the same type: strings or arrays. */ if ($effect === $subject && ($bothAreStrings || $bothAreArrays)) { - if ($quoteStrings && $replacementIsString) { - $replacement = '\'' . $replacement . '\''; - } - /* * I have to avoid string that contains spaces only, e.g. " ". * It's required to avoid bug: preg_replace(): Empty regular expression. */ if ($searchIsArray || ($searchIsString && !empty(trim($search)))) { - $effect = preg_replace($search, $replacement, $subject); + $replaced = @preg_replace($search, $replacement, $subject); + + if (null !== $replaced && [] !== $replaced) { + $effect = $replaced; + } } } @@ -500,16 +518,6 @@ class Miscellaneous $exploded = explode($search, $subSubject); $explodedCount = count($exploded); - if ($quoteStrings) { - foreach ($replacement as &$item) { - if (is_string($item)) { - $item = '\'' . $item . '\''; - } - } - - unset($item); - } - foreach ($exploded as $key => $item) { $subEffect .= $item; diff --git a/tests/Utilities/MiscellaneousTest.php b/tests/Utilities/MiscellaneousTest.php index 38aec86..c2ed2bb 100644 --- a/tests/Utilities/MiscellaneousTest.php +++ b/tests/Utilities/MiscellaneousTest.php @@ -14,7 +14,6 @@ use Meritoo\Common\Exception\Regex\InvalidColorHexValueException; use Meritoo\Common\Test\Base\BaseTestCase; use Meritoo\Common\Utilities\Locale; use Meritoo\Common\Utilities\Miscellaneous; -use ReflectionException; use stdClass; /** @@ -226,57 +225,68 @@ class MiscellaneousTest extends BaseTestCase self::assertEquals($this->stringSmall, Miscellaneous::replace($this->stringSmall, $search, $replacement3, true)); } - public function testReplace() + /** + * @param string $description Description of test + * @param string|array $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 + * 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 + * of strings. + * @param mixed $result Result of replacing + * + * @dataProvider provideEmptyValuesToReplace + */ + public function testReplaceUsingEmptyValues($description, $subject, $search, $replacement, $result) { - /* - * Common variables - */ - $quoteStrings = true; + static::assertSame($result, Miscellaneous::replace($subject, $search, $replacement), $description); + } - $subject = [ - $this->stringSmall, - $this->stringDotSeparated, - ]; + /** + * @param string $description Description of test + * @param string $subject The string or an array of strings to search and replace + * @param string $search String or pattern or array of patterns to find. It may be: string, an array of + * strings or an array of patterns. + * @param string $replacement The string or an array of strings to replace. It may be: string or an array of + * strings. + * @param mixed $result Result of replacing + * + * @dataProvider provideStringsToReplace + */ + public function testReplaceUsingStrings($description, $subject, $search, $replacement, $result) + { + static::assertSame($result, Miscellaneous::replace($subject, $search, $replacement), $description); + } - /* - * Testing replace with an array - */ - $search = [ - '|ipsum|', - '|pellentesque|', - ]; + /** + * @param string $description Description of test + * @param string $subject The string or an array of strings to search and replace + * @param string $search String or pattern or array of patterns to find. It may be: string, an array of + * strings or an array of patterns. + * @param string $replacement The string or an array of strings to replace. It may be: string or an array of + * strings. + * @param mixed $result Result of replacing + * + * @dataProvider provideRegexToReplace + */ + public function testReplaceUsingRegex($description, $subject, $search, $replacement, $result) + { + static::assertSame($result, Miscellaneous::replace($subject, $search, $replacement), $description); + } - $replacement = [ - 'commodo', - 'interdum', - ]; - - $replaced1 = Miscellaneous::replace($subject, $search, $replacement); - $replaced2 = Miscellaneous::replace($subject, $search, $replacement, true); - - self::assertEquals('Lorem commodo dolor sit amet.', $replaced1[0]); - self::assertEquals('Etiam ullamcorper. Suspendisse a interdum dui, non felis.', $replaced1[1]); - - self::assertEquals('Lorem commodo dolor sit amet.', $replaced2[0]); - self::assertEquals('Etiam ullamcorper. Suspendisse a interdum dui, non felis.', $replaced2[1]); - - /* - * Testing replace with string - */ - $searchString = 'ipsum'; - $replacementString = 'commodo'; - - $replaced = Miscellaneous::replace($subject, $searchString, $replacementString, $quoteStrings); - self::assertEquals('Lorem \'commodo\' dolor sit amet.', $replaced[0]); - - /* - * Testing replace with mixed values: - * - subject: array - * - search: string - * - replacement: string - */ - $replacedMixed = Miscellaneous::replace($subject, $searchString, $replacement, $quoteStrings); - self::assertEquals('Lorem \'commodo\' dolor sit amet.', $replacedMixed[0]); + /** + * @param string $description Description of test + * @param string $subject The string or an array of strings to search and replace + * @param string $search String or pattern or array of patterns to find. It may be: string, an array of + * strings or an array of patterns. + * @param string $replacement The string or an array of strings to replace. It may be: string or an array of + * strings. + * @param mixed $result Result of replacing + * + * @dataProvider provideDataToReplaceWithQuoteStrings + */ + public function testReplaceWithQuoteStrings($description, $subject, $search, $replacement, $result) + { + static::assertSame($result, Miscellaneous::replace($subject, $search, $replacement, true), $description); } public function testUppercaseFirst() @@ -1156,6 +1166,322 @@ class MiscellaneousTest extends BaseTestCase ]; } + public function provideEmptyValuesToReplace() + { + yield[ + 'An empty string as subject', + '', + 'test', + 'another test', + '', + ]; + + yield[ + 'An empty array as subject', + [], + 'test', + 'another test', + [], + ]; + + yield[ + 'Null as subject', + null, + 'test', + 'another test', + null, + ]; + + yield[ + 'An empty string to search', + 'test', + '', + 'another test', + 'test', + ]; + + yield[ + 'An empty array to search', + 'test', + [], + 'another test', + 'test', + ]; + + yield[ + 'Null to search', + 'test', + null, + 'another test', + 'test', + ]; + + yield[ + 'An empty string as replacement', + 'test', + 'another test', + '', + 'test', + ]; + + yield[ + 'An empty array as replacement', + 'test', + 'another test', + [], + 'test', + ]; + + yield[ + 'Null as replacement', + 'test', + 'another test', + null, + 'test', + ]; + } + + public function provideStringsToReplace() + { + yield[ + 'Different count of strings to search and replace - 1st part', + 'Lorem ipsum dolor sit amet', + [ + 'ipsum', + ], + 'commodo', + 'Lorem ipsum dolor sit amet', + ]; + + yield[ + 'Different count of strings to search and replace - 2nd part', + 'Lorem ipsum dolor sit amet', + 'ipsum', + [ + 'commodo', + ], + 'Lorem commodo dolor sit amet', + ]; + + yield[ + 'Replace 1 not existing word in 1 sentence (nothing to replace)', + 'Lorem ipsum dolor sit amet', + 'plum', + 'commodo', + 'Lorem ipsum dolor sit amet', + ]; + + yield[ + 'Replace 1 word in 1 sentence', + 'Lorem ipsum dolor sit amet', + 'ipsum', + 'commodo', + 'Lorem commodo dolor sit amet', + ]; + + yield[ + 'Replace 1 not existing word in 2 sentences (nothing to replace)', + [ + 'Lorem ipsum dolor sit amet', + 'Maecenas sed diam eget risus varius blandit sit amet', + ], + 'plum', + 'commodo', + [ + 'Lorem ipsum dolor sit amet', + 'Maecenas sed diam eget risus varius blandit sit amet', + ], + ]; + + yield[ + 'Replace 1 word in 2 sentences', + [ + 'Lorem ipsum dolor sit amet', + 'Maecenas sed diam eget risus varius blandit sit amet', + ], + 'amet', + 'commodo', + [ + 'Lorem ipsum dolor sit commodo', + 'Maecenas sed diam eget risus varius blandit sit commodo', + ], + ]; + } + + public function provideRegexToReplace() + { + yield[ + 'Different count of strings to search and replace - 1st part', + 'Lorem ipsum dolor sit amet', + [ + '|ipsum|', + ], + 'commodo', + 'Lorem ipsum dolor sit amet', + ]; + + yield[ + 'Different count of strings to search and replace - 2nd part', + 'Lorem ipsum dolor sit amet', + '|ipsum|', + [ + 'commodo', + ], + 'Lorem ipsum dolor sit amet', + ]; + + yield[ + '1 pattern (word -> "")', + 'Lorem ipsum dolor sit amet', + '|ipsum|', + '', + 'Lorem dolor sit amet', + ]; + + yield[ + '1 pattern (word -> word)', + 'Lorem ipsum dolor sit amet', + '|ipsum|', + 'commodo', + 'Lorem commodo dolor sit amet', + ]; + + yield[ + '2 patterns (word -> word)', + 'Lorem ipsum dolor sit amet', + [ + '|ipsum|', + '|amet|', + ], + [ + 'commodo', + 'egestas', + ], + 'Lorem commodo dolor sit egestas', + ]; + + yield[ + '1 word in 2 sentences', + [ + 'Lorem ipsum dolor sit amet', + 'Maecenas sed diam eget risus varius blandit sit amet', + ], + '|amet|', + 'commodo', + [ + 'Lorem ipsum dolor sit commodo', + 'Maecenas sed diam eget risus varius blandit sit commodo', + ], + ]; + + yield[ + '2 words in 2 sentences', + [ + 'Lorem ipsum dolor sit amet', + 'Maecenas sed diam eget risus varius blandit sit amet', + ], + [ + '|ipsum|', + '|amet|', + ], + [ + 'commodo', + 'egestas', + ], + [ + 'Lorem commodo dolor sit egestas', + 'Maecenas sed diam eget risus varius blandit sit egestas', + ], + ]; + } + + public function provideDataToReplaceWithQuoteStrings() + { + yield[ + 'An empty string as subject', + '', + 'test', + 'another test', + '', + ]; + + yield[ + 'An empty string to search', + 'test', + '', + 'another test', + 'test', + ]; + + yield[ + 'An empty string as replacement', + 'test', + 'another test', + '', + 'test', + ]; + + yield[ + 'Replace 1 not existing word in 1 sentence (nothing to replace)', + 'Lorem ipsum dolor sit amet', + 'plum', + 'commodo', + 'Lorem ipsum dolor sit amet', + ]; + + yield[ + 'Replace 1 word in 1 sentence', + 'Lorem ipsum dolor sit amet', + 'ipsum', + 'commodo', + 'Lorem \'commodo\' dolor sit amet', + ]; + + yield[ + 'Replace 1 word in 2 sentences', + [ + 'Lorem ipsum dolor sit amet', + 'Maecenas sed diam eget risus varius blandit sit amet', + ], + 'amet', + 'commodo', + [ + 'Lorem ipsum dolor sit \'commodo\'', + 'Maecenas sed diam eget risus varius blandit sit \'commodo\'', + ], + ]; + + yield[ + '1 pattern (word -> "")', + 'Lorem ipsum dolor sit amet', + '|ipsum|', + '', + 'Lorem \'\' dolor sit amet', + ]; + + yield[ + '1 pattern (word -> word)', + 'Lorem ipsum dolor sit amet', + '|ipsum|', + 'commodo', + 'Lorem \'commodo\' dolor sit amet', + ]; + + yield[ + '2 patterns (word -> word)', + 'Lorem ipsum dolor sit amet', + [ + '|ipsum|', + '|amet|', + ], + [ + 'commodo', + 'egestas', + ], + 'Lorem \'commodo\' dolor sit \'egestas\'', + ]; + } + /** * {@inheritdoc} */ From a021870ebd6032b0994cd652daf118eb333c6258 Mon Sep 17 00:00:00 2001 From: Meritoo Date: Tue, 5 Mar 2019 10:18:45 +0100 Subject: [PATCH 8/8] Minor refactoring --- src/Utilities/Miscellaneous.php | 6 +++--- tests/Utilities/MiscellaneousTest.php | 23 ++--------------------- 2 files changed, 5 insertions(+), 24 deletions(-) diff --git a/src/Utilities/Miscellaneous.php b/src/Utilities/Miscellaneous.php index 7dd7e61..cdc1ef7 100644 --- a/src/Utilities/Miscellaneous.php +++ b/src/Utilities/Miscellaneous.php @@ -467,14 +467,14 @@ class Miscellaneous } /* - * First step: replace strings, simple operation with strings + * 1st step: replace strings, simple operation with strings */ if ($bothAreStrings) { $effect = str_replace($search, $replacement, $subject); } /* - * Second step: replace with regular expressions. + * 2nd step: replace with regular expressions. * Attention. Searched and replacement value should be the same type: strings or arrays. */ if ($effect === $subject && ($bothAreStrings || $bothAreArrays)) { @@ -492,7 +492,7 @@ class Miscellaneous } /* - * Third step: complex replace of the replacement defined as an array. + * 3rd step: complex replace of the replacement defined as an array. * It may be useful when you want to search for a one string and replace the string with multiple values. */ if ($effect === $subject && $searchIsString && $replacementIsArray) { diff --git a/tests/Utilities/MiscellaneousTest.php b/tests/Utilities/MiscellaneousTest.php index c2ed2bb..70c36c7 100644 --- a/tests/Utilities/MiscellaneousTest.php +++ b/tests/Utilities/MiscellaneousTest.php @@ -29,9 +29,6 @@ class MiscellaneousTest extends BaseTestCase private $stringDotSeparated; private $stringWithoutSpaces; - /** - * @throws ReflectionException - */ public function testConstructor() { static::assertHasNoConstructor(Miscellaneous::class); @@ -382,7 +379,7 @@ class MiscellaneousTest extends BaseTestCase mkdir($directory1Path, 0777, true); mkdir($directory2Path, 0777, true); - self::assertTrue(Miscellaneous::removeDirectory(sys_get_temp_dir() . '/lorem', false)); + self::assertTrue(Miscellaneous::removeDirectory(sys_get_temp_dir() . '/lorem')); } /** @@ -651,10 +648,6 @@ class MiscellaneousTest extends BaseTestCase self::assertEquals(255, Miscellaneous::getValidColorComponent(255, false)); } - /** - * @throws IncorrectColorHexLengthException - * @throws InvalidColorHexValueException - */ public function testGetInvertedColorWithIncorrectLength() { $this->setExpectedException(IncorrectColorHexLengthException::class); @@ -669,10 +662,6 @@ class MiscellaneousTest extends BaseTestCase Miscellaneous::getInvertedColor('1234567'); } - /** - * @throws IncorrectColorHexLengthException - * @throws InvalidColorHexValueException - */ public function testGetInvertedColorWithInvalidValue() { $this->setExpectedException(InvalidColorHexValueException::class); @@ -684,10 +673,6 @@ class MiscellaneousTest extends BaseTestCase Miscellaneous::getInvertedColor('00ppqq'); } - /** - * @throws IncorrectColorHexLengthException - * @throws InvalidColorHexValueException - */ public function testGetInvertedColor() { /* @@ -1501,10 +1486,6 @@ class MiscellaneousTest extends BaseTestCase protected function tearDown() { parent::tearDown(); - - unset($this->stringSmall); - unset($this->stringCommaSeparated); - unset($this->stringDotSeparated); - unset($this->stringWithoutSpaces); + unset($this->stringSmall, $this->stringCommaSeparated, $this->stringDotSeparated, $this->stringWithoutSpaces); } }