From 9c62115d8856731bea8515e17c44d8b6aaa9b919 Mon Sep 17 00:00:00 2001 From: Hendrik Bugdoll Date: Mon, 12 Feb 2024 12:22:28 +0100 Subject: [PATCH 1/2] Fixed typos and more --- README.md | 6 +- src/helpers/ArrayHelper.php | 34 +++++----- src/helpers/ExportHelper.php | 20 +++--- src/helpers/FileHelper.php | 42 ++++++------ src/helpers/ImportHelper.php | 22 +++---- src/helpers/Inflector.php | 6 +- src/helpers/Json.php | 16 ++--- src/helpers/RestHelper.php | 12 ++-- src/helpers/StringHelper.php | 92 +++++++++++++-------------- src/helpers/Url.php | 64 +++++++++---------- src/helpers/ZipHelper.php | 10 +-- tests/helpers/ExportHelperTest.php | 2 +- tests/helpers/FileHelperTest.php | 2 +- tests/helpers/InflectorHelperTest.php | 4 +- tests/helpers/JsonTest.php | 4 +- tests/helpers/StringHelperTest.php | 11 ++-- 16 files changed, 173 insertions(+), 174 deletions(-) diff --git a/README.md b/README.md index 5996f24..39676ec 100644 --- a/README.md +++ b/README.md @@ -9,7 +9,7 @@ A set of helper classes for the Yii Framework which are used as LUYA Helpers. ## Installation -In order to install the LUYA Yii Framework Helpers use composer: +In order to install the LUYA Yii Framework Helpers use Composer: ```sh composer require luyadev/yii-helpers @@ -20,10 +20,10 @@ composer require luyadev/yii-helpers The LUYA Yii Framework Helpers library provides the following classes: + ArrayHelper - Working with Arrays -+ ExportHelper - Export Data into a given Format (f.e. CSV, XLS) ++ ExportHelper - Export Data into a given Format (e.g. CSV, XLS) + ImportHelper - Import Data + FileHelper - Working with Filesystem -+ Json = Working with Json Data ++ Json = Working with JSON Data + RestHelper - Yii Framework REST API Output + StringHelper - Working with Strings + ZipHelper - Create ZIP Archives \ No newline at end of file diff --git a/src/helpers/ArrayHelper.php b/src/helpers/ArrayHelper.php index 4e5925c..5ef9a65 100644 --- a/src/helpers/ArrayHelper.php +++ b/src/helpers/ArrayHelper.php @@ -7,7 +7,7 @@ /** * Helper methods when dealing with Arrays. * - * Extends the {{yii\helpers\ArrayHelper}} class by some usefull functions like: + * Extends the {{yii\helpers\ArrayHelper}} class by some useful functions like: * * + {{luya\yii\helpers\ArrayHelper::toObject()}} * + {{luya\yii\helpers\ArrayHelper::arrayUnshiftAssoc()}} @@ -39,9 +39,9 @@ public static function toObject(array $array) } /** - * Cover senstive values from a given list of keys. + * Cover sensitive values from a given list of keys. * - * The main purpose is to remove passwords transferd to api when existing in post, get or session. + * The main purpose is to remove passwords transferred to API when existing in POST, GET or SESSION. * * Example: * @@ -73,12 +73,12 @@ public static function coverSensitiveValues(array $data, array $keys = []) } } - // the later overrides the former + // the latter overrides the former return array_replace($data, $clean); } /** - * Prepend an assoc array item as first entry for a given array. + * Prepend an associative array item as first entry for a given array. * * Adds the given key with value as first entry to $arr * @@ -97,7 +97,7 @@ public static function arrayUnshiftAssoc(&$arr, $key, $val) /** * TypeCast values from a mixed array source. numeric values will be casted as integer. * - * This method is often used to convert corect json respons arrays + * This method is often used to convert correct JSON response arrays * * @param array $array The array which should be type casted * @return array An array with type casted values @@ -120,7 +120,7 @@ public static function typeCast(array $array) } /** - * Search trough all keys inside of an array, any occurence will return the rest of the array. + * Search through all keys inside of an array, any occurrence will return the rest of the array. * * ```php * $data = [ @@ -137,7 +137,7 @@ public static function typeCast(array $array) * ]; * ``` * - * Searching for the string `Bar` would return the the orignal array is bar would be found in both. + * Searching for the string `Bar` would return the original array if bar would be found in both. * * In order to search only in certain keys defined $keys attribute: * @@ -149,7 +149,7 @@ public static function typeCast(array $array) * * @param array $array The multidimensional array keys. * @param string $searchText The text you where search inside the rows. - * @param boolean $sensitive Whether to use strict sensitive search (true) or case insenstivie search (false). + * @param boolean $sensitive Whether to use strict sensitive search (`true`) or case insensitive search (`false`). * @param array $keys A list of array keys which should be taken to search in, if empty or not provided it will lookup all array keys by default. * @return array The modified array depending on the search result hits. */ @@ -176,9 +176,9 @@ public static function search(array $array, $searchText, $sensitive = false, arr } /** - * Search for a Column Value inside a Multidimension array and return the array with the found key. + * Search for a column value inside a multidimensional array and return the array with the found key. * - * Compare to searchColumns() this function return will return the first found result. + * Compared to `searchColumns()` this function return will return the first found result. * * ```php * $array = [ @@ -192,7 +192,7 @@ public static function search(array $array, $searchText, $sensitive = false, arr * // array ('name' => 'nadar', 'userId' => 2); * ``` * - * > This will not work with assoc keys + * > This will not work with associative keys * * @param array $array The array with the multimensional array values. * @param string $column The column to lookup and compare with the $search string. @@ -210,9 +210,9 @@ public static function searchColumn(array $array, $column, $search) /** * Search for columns with the given search value, returns the full array with all valid items. * - * Compare to searchColumn() this function return will return all found results. + * Compared to `searchColumn()` this function return will return all found results. * - * > This function is not casesensitive, which means FOO will match Foo, foo and FOO + * > This function is not case-sensitive, which means `FOO` will match `Foo`, `foo` and `FOO`. * * ```php * $array = [ @@ -244,9 +244,9 @@ public static function searchColumns(array $array, $column, $search) } /** - * Generate an Array from a Rang with an appending optional Text. + * Generate an array from a range with an appending optional text. * - * This is commonly used when generate dropDowns in forms to select a number of something. + * This is commonly used when generate dropdowns in forms to select a number of something. * * When $text is an array, the first key is the singular value to use, the second is the pluralized value. * @@ -262,7 +262,7 @@ public static function searchColumns(array $array, $column, $search) * // array (1 => "1 ticket", 2 => "2 tickets", 3 => "3 tickets") * ``` * - * In php range() function is used to generate the array range. + * PHP's `range()` function is used to generate the array range. * * @param string|integer $from The range starts from * @param string|integer $to The range ends diff --git a/src/helpers/ExportHelper.php b/src/helpers/ExportHelper.php index dfb15aa..0dba3cb 100644 --- a/src/helpers/ExportHelper.php +++ b/src/helpers/ExportHelper.php @@ -15,13 +15,13 @@ class ExportHelper { /** - * Export an Array or QueryInterface instance into a CSV formated string. + * Export an array or QueryInterface instance into a CSV-formatted string. * - * @param array|QueryInterface $input The data to export into a csv - * @param array $keys Defines which keys should be packed into the generated CSV. The defined keys does not change the sort behavior of the generated csv. - * @param boolean $header Whether the column name should be set as header inside the csv or not. + * @param array|QueryInterface $input The data to export into a CSV + * @param array $keys Defines which keys should be packed into the generated CSV. The defined keys does not change the sort behavior of the generated CSV. + * @param boolean $header Whether the column name should be set as header inside the CSV or not. * @param array $options Options - * + `sort`: boolean, whether they row should be sorted by its keys, default is true. + * + `sort`: boolean, whether they row should be sorted by its keys, default is `true`. * @return string The generated CSV as string. */ public static function csv($input, array $keys = [], $header = true, array $options = []) @@ -34,13 +34,13 @@ public static function csv($input, array $keys = [], $header = true, array $opti } /** - * Export an Array or QueryInterface instance into a Excel formatted string. + * Export an array or QueryInterface instance into an Excel-formatted string. * * @param array|QueryInterface $input - * @param array $keys Defines which keys should be packed into the generated xlsx. The defined keys does not change the sort behavior of the generated xls. + * @param array $keys Defines which keys should be packed into the generated XLSX. The defined keys does not change the sort behavior of the generated XLS. * @param bool $header * @param array $options Options - * + `sort`: boolean, whether they row should be sorted by its keys, default is true. + * + `sort`: boolean, whether they row should be sorted by its keys, default is `true`. * @return mixed * @throws Exception */ @@ -78,7 +78,7 @@ protected static function transformInput($input) * @param array $keys * @param bool $generateHeader * @param array $options Options - * + `sort`: boolean, whether they row should be sorted by its keys, default is true. + * + `sort`: boolean, whether they row should be sorted by its keys, default is `true`. * @return array * @throws Exception */ @@ -185,7 +185,7 @@ protected static function generateRow(array $row, $delimiter, $enclose) } /** - * Sanitize Certain Values to increase security from user generated output. + * Sanitize certain values to increase security from user generated output. * * @param string $value * @return string diff --git a/src/helpers/FileHelper.php b/src/helpers/FileHelper.php index 6883cfa..ddbb809 100644 --- a/src/helpers/FileHelper.php +++ b/src/helpers/FileHelper.php @@ -8,7 +8,7 @@ /** * Helper methods when dealing with Files. * - * Extends the {{yii\helpers\FileHelper}} class by some usefull functions like: + * Extends the {{yii\helpers\FileHelper}} class by some useful functions like: * * + {{luya\yii\helpers\FileHelper::humanReadableFilesize()}} * + {{luya\yii\helpers\FileHelper::ensureExtension()}} @@ -23,7 +23,7 @@ class FileHelper extends \yii\helpers\BaseFileHelper { /** - * Generate a human readable size informations from provided Byte/s size + * Generate a human readable size informations from provided Byte/s size. * * @param integer $size The size to convert in Byte * @return string The readable size definition @@ -60,12 +60,12 @@ public static function ensureExtension($file, $extension) /** * Provide class informations from a file path or file content. * - * This is used when working with file paths from composer, in order to detect class and namespace from a given file. + * This is used when working with file paths from Composer, in order to detect class and namespace from a given file. * * @param string $file The file path to the class into order to get infos from, could also be the content directly from a given file. - * @return array If the given filepath is a file, it will return an array with the keys: - * + namespace: the namespace of the file, if false no namespace could have been determined. - * + class: the class name of the file, if false no class could have been determined. + * @return array If the given file path is a file, it will return an array with the keys: + * + `namespace`: the namespace of the file, `false` if no namespace could have been determined. + * + `class`: the class name of the file, `false` if no class could have been determined. */ public static function classInfo($file) { @@ -87,9 +87,9 @@ public static function classInfo($file) } /** - * Tokenize the php code from a given class in in order to determine the class name. + * Tokenize the PHP code from a given class in in order to determine the class name. * - * @param string $phpCode The php code to tokenize and find the clas name from + * @param string $phpCode The PHP code to tokenize and find the class name from * @return array */ private static function classNameByTokens($phpCode) @@ -110,10 +110,10 @@ private static function classNameByTokens($phpCode) * Create a unique hash name from a given file. * * Warning - * Because PHP's integer type is signed many crc32 checksums will result in negative integers on 32bit platforms. On 64bit installations all crc32() results will be positive integers though. - * So you need to use the "%u" formatter of sprintf() or printf() to get the string representation of the unsigned crc32() checksum in decimal format. + * Because PHP's integer type is signed many `crc32()` checksums will result in negative integers on 32-bit platforms. On 64-bit installations all `crc32()` results will be positive integers though. + * So you need to use the `%u` formatter of `sprintf()` or `printf()` to get the string representation of the unsigned `crc32()` checksum in decimal format. * - * @param string $fileName The file name which should be hashed + * @param string $fileName The file name which should be hashed. * @return string */ public static function hashName($fileName) @@ -129,7 +129,7 @@ public static function hashName($fileName) */ public static function getFileInfo($sourceFile) { - // pathinfo always returns an array event the path does not exists + // pathinfo() always returns an array event the path does not exists $path = pathinfo($sourceFile); return (object) [ @@ -141,10 +141,10 @@ public static function getFileInfo($sourceFile) } /** - * Generate a md5 hash of a file. This is eqauls to `md5sum` command + * Generate a MD5 hash of a file. This is equal to `md5sum` command. * * @param string $sourceFile The path to the file - * @return false|string Returns false or the md5 hash of this file + * @return false|string Returns false or the MD5 hash of this file */ public static function md5sum($sourceFile) { @@ -152,11 +152,11 @@ public static function md5sum($sourceFile) } /** - * Basic helper method to write files with exception capture. The fileName will auto wrapped - * trough the Yii::getAlias function. + * Basic helper method to write files with exception capture. The filename will auto-wrapped + * through the `Yii::getAlias()` function. * - * @param string $fileName The path to the file with file name - * @param string $content The content to store in this File + * @param string $fileName The path to the file with filename + * @param string $content The content to store in this file * @return boolean */ public static function writeFile($fileName, $content) @@ -174,8 +174,8 @@ public static function writeFile($fileName, $content) } /** - * Basic helper to retreive the content of a file and catched exception. The filename - * will auto alias encode by Yii::getAlias function. + * Basic helper to retrieve the content of a file and catched exception. The filename + * will auto-alias encoded by `Yii::getAlias()` function. * * @param string $fileName The path to the file to get the content * @return string|boolean @@ -215,7 +215,7 @@ public static function unlink($file) } } - // try to use realpath + // try to use realpath() if (realpath($file) && realpath($file) !== $file) { if (@unlink(realpath($file))) { return true; diff --git a/src/helpers/ImportHelper.php b/src/helpers/ImportHelper.php index 34e9787..86581fe 100644 --- a/src/helpers/ImportHelper.php +++ b/src/helpers/ImportHelper.php @@ -15,25 +15,25 @@ class ImportHelper /** * Import a CSV from a string or filename and return array. * - * The filename can be either a resource from fopen() or a string containing the csv data. Filenames will be wrapped trough {{Yii::getAlias()}} method. + * The filename can be either a resource from `fopen()` or a string containing the CSV data. Filenames will be wrapped through {{`Yii::getAlias()`}} method. * - * @param string $filename Can be either a filename which is parsed by {{luya\yii\helpers\FileHelper::getFileContent()}} or a string with the contained csv data. - * @param array $options Provide options to the csv - * + removeHeader: boolean, Whether the import csv contains a header in the first row to skip or not. Default value is false. - * + delimiter: string, The delimiter which is used to explode the columns. Default value is `,`. - * + enclosure: string, The encloser which is used betweend the columns. Default value is `"`. - * + fields: array, An array with fielnames (based on the array header if any, or position) which should be parsed into the final export. + * @param string $filename Can be either a filename which is parsed by {{luya\yii\helpers\FileHelper::getFileContent()}} or a string with the contained CSV data. + * @param array $options Provide options to the CSV + * + `removeHeader`: boolean, Whether the import CSV contains a header in the first row to skip or not. Default value is false. + * + `delimiter`: string, The delimiter which is used to explode the columns. Default value is `,`. + * + `enclosure`: string, The enclosure which is used between the columns. Default value is `"`. + * + `fields`: array, An array with filenames (based on the array header if any, or position) which should be parsed into the final export. * ```php * 'fields' => ['firstname', 'lastname'] // will only parse those fields based on table header (row 0) - * 'fields' => [0,1,3] // will only parse fields by those positions if no table header is present. Positions starts at 0 + * 'fields' => [0,1,3] // will only parse fields by those positions if no table header is present. Positions starts at 0. * ``` - * @return array an array with the csv data. + * @return array an array with the CSV data. */ public static function csv($filename, array $options = []) { $filename = Yii::getAlias($filename); - // check if a given file name is provided or a csv based on the content + // check if a given file name is provided or a CSV based on the content if (FileHelper::getFileInfo($filename)->extension) { $resource = fopen($filename, 'r'); } else { @@ -66,7 +66,7 @@ public static function csv($filename, array $options = []) unset($filteredData); } - // if the option to remove a header is provide. remove the first key and reset and array keys + // if the option to remove a header is provided, remove the first key and re-set array keys if (ArrayHelper::getValue($options, 'removeHeader', false)) { unset($data[0]); $data = array_values($data); diff --git a/src/helpers/Inflector.php b/src/helpers/Inflector.php index a5fca0c..09ce66a 100644 --- a/src/helpers/Inflector.php +++ b/src/helpers/Inflector.php @@ -5,7 +5,7 @@ use yii\helpers\BaseInflector; /** - * Helper methods which can be used for string transformations + * Helper methods which can be used for String transformations * * Extends the {{yii\helpers\BaseInflector}} class by: * @@ -20,7 +20,7 @@ class Inflector extends BaseInflector * From yii/helpers/BaseInflector: * * Returns a string with all spaces converted to given replacement, - * non word characters removed and the rest of characters transliterated. + * non-word characters removed and the rest of characters transliterated. * * If intl extension isn't available uses fallback that converts latin characters only * and removes the rest. You may customize characters map via $transliteration property @@ -29,7 +29,7 @@ class Inflector extends BaseInflector * @param string $string An arbitrary string to convert * @param string $replacement The replacement to use for spaces * @param bool $lowercase whether to return the string in lowercase or not. Defaults to `true`. - * @param bool $transliterate whether to use a transliteration transformation or not. Defaults to `true` (=BaseInflector implementation) + * @param bool $transliterate whether to use a transliteration transformation or not. Defaults to `true` (=`BaseInflector` implementation) * @return string The converted string. */ public static function slug($string, $replacement = '-', $lowercase = true, $transliterate = true) diff --git a/src/helpers/Json.php b/src/helpers/Json.php index 3819e4d..39ef9ab 100644 --- a/src/helpers/Json.php +++ b/src/helpers/Json.php @@ -5,9 +5,9 @@ use yii\helpers\BaseJson; /** - * Json Helper. + * JSON Helper. * - * Extends the {{yii\helpers\Json}} class by some usefull functions like: + * Extends the {{yii\helpers\Json}} class by some useful functions like: * * + {{luya\yii\helpers\Json::isJson()}} * @@ -17,9 +17,9 @@ class Json extends BaseJson { /** - * Checks if a string is a json or not. + * Checks if a string is a JSON or not. * - * Example values which return true: + * Example values which return `true`: * * ```php * Json::isJson('{"123":"456"}'); @@ -28,8 +28,8 @@ class Json extends BaseJson * Json::isJson('[{"123":"456"}]'); * ``` * - * @param mixed $value The value to test if its a json or not. - * @return boolean Whether the string is a json or not. + * @param mixed $value The value to test if it's a JSON or not. + * @return boolean Whether the string is a JSON or not. */ public static function isJson($value) { @@ -49,9 +49,9 @@ public static function isJson($value) } /** - * Decode Json without Exception + * Decode JSON without Exception * - * Since Json::decode('foo') would throw an exception, this method will return a default value + * Since `Json::decode('foo')` would throw an exception, this method will return a default value * defined instead of an exception. * * @param string $json diff --git a/src/helpers/RestHelper.php b/src/helpers/RestHelper.php index 47d09d7..cede6f4 100644 --- a/src/helpers/RestHelper.php +++ b/src/helpers/RestHelper.php @@ -15,7 +15,7 @@ class RestHelper { /** - * Send Model errors with correct headers. + * Send model errors with correct headers. * * Helper method to correctly send model errors with the correct response headers. * @@ -27,7 +27,7 @@ class RestHelper * [0] => Array * ( * [field] => firstname - * [message] => Firstname cannot be blank. + * [message] => First name cannot be blank. * ) * [1] => Array * ( @@ -39,12 +39,12 @@ class RestHelper * * @param \yii\base\Model $model The model to find the first error. * @throws \yii\base\InvalidParamException - * @return array If the model has errors InvalidParamException will be thrown, otherwise an array with message and field key. + * @return array If the model has errors `InvalidParamException` will be thrown, otherwise an array with message and field key. */ public static function sendModelError(Model $model) { if (!$model->hasErrors()) { - throw new InvalidParamException('The model as thrown an uknown Error.'); + throw new InvalidParamException('The model has thrown an unknown error.'); } Yii::$app->response->setStatusCode(422, 'Data Validation Failed.'); @@ -65,7 +65,7 @@ public static function sendModelError(Model $model) * Example input: * * ```php - * return $this->sendArrayError(['firstname' => 'Firstname cannot be blank']); + * return $this->sendArrayError(['firstname' => 'First name cannot be blank']); * ``` * * Example return value: @@ -76,7 +76,7 @@ public static function sendModelError(Model $model) * [0] => Array * ( * [field] => firstname - * [message] => Firstname cannot be blank. + * [message] => First name cannot be blank. * ) * ) * ``` diff --git a/src/helpers/StringHelper.php b/src/helpers/StringHelper.php index e040520..6b1e4e4 100644 --- a/src/helpers/StringHelper.php +++ b/src/helpers/StringHelper.php @@ -7,7 +7,7 @@ /** * Helper methods when dealing with Strings. * - * Extends the {{yii\helpers\StringHelper}} class by some usefull functions like: + * Extends the {{yii\helpers\StringHelper}} class by some useful functions like: * * + {{luya\yii\helpers\StringHelper::typeCast()}} * + {{luya\yii\helpers\StringHelper::isFloat()}} @@ -22,9 +22,9 @@ class StringHelper extends BaseStringHelper { /** - * Convert a YouTube link to an Embedable Video URL. + * Convert a YouTube link to an embeddable video URL. * - * If the given input url is invalid, false is returned. + * If the given input URL is invalid, `false` is returned. * * @param string $url * @return string|boolean @@ -43,9 +43,9 @@ public static function toYouTubeEmbed($url) /** * TypeCast a string to its specific types. * - * Arrays will passed to to the {{luya\yii\helpers\ArrayHelper::typeCast()}} class. + * Arrays will passed to the {{luya\yii\helpers\ArrayHelper::typeCast()}} class. * - * @param mixed $string The input string to type cast. Arrays will be passted to {{luya\yii\helpers\ArrayHelper::typeCast()}}. + * @param mixed $string The input string to type cast. Arrays will be passed to {{luya\yii\helpers\ArrayHelper::typeCast()}}. * @return mixed The new type casted value, if the input is an array the output is the typecasted array. */ public static function typeCast($string) @@ -62,15 +62,15 @@ public static function typeCast($string) /** * String Wildcard Check. * - * Checks whether a strings starts with the wildcard symbole and compares the string before the wild card symbol * - * with the string provided, if there is NO wildcard symbold it always return false. + * Checks whether a strings starts with the wildcard symbol and compares the string before the wild card symbol `*` + * with the string provided. If there is NO wildcard symbol it always returns `false`. * * - * @param string $string The string which should be checked with $with comperator - * @param string $with The with string which must end with the wildcard symbol * e.g. `foo*` would match string `foobar`. - * @param boolean $caseSensitive Whether to compare the starts with string as case sensitive or not, defaults to true. + * @param string $string The string which should be checked with $with comparator + * @param string $with The with string which must end with the wildcard symbol `*` e.g. `foo*` would match string `foobar`. + * @param boolean $caseSensitive Whether to compare the starts with string as case-sensitive or not, defaults to `true`. * @return boolean Whether the string starts with the wildcard marked string or not, if no wildcard symbol is contained. - * in the $with it always returns false. + * in the $with it always returns `false`. */ public static function startsWithWildcard($string, $with, $caseSensitive = true) { @@ -110,7 +110,7 @@ public static function startsWithWildcard($string, $with, $caseSensitive = true) * @param $value The value on which the filter conditions should be applied on. * @param array|string $conditions An array of filter conditions, if a string is given he will be exploded by commas. * @param boolean $caseSensitive Whether to match value even when lower/upper case is not correct/same. - * @return bool Returns true if one of the given filter conditions matches. + * @return bool Returns `true` if one of the given filter conditions matches. */ public static function filterMatch($value, $conditions, $caseSensitive = true) { @@ -140,7 +140,7 @@ public static function filterMatch($value, $conditions, $caseSensitive = true) /** * TypeCast a numeric value to float or integer. * - * If the given value is not a numeric or float value it will be returned as it is. In order to find out whether its float + * If the given value is not a numeric or float value it will be returned as it is. In order to find out whether it's float * or not use {{luya\yii\helpers\StringHelper::isFloat()}}. * * @param mixed $value The given value to parse. @@ -162,10 +162,10 @@ public static function typeCastNumeric($value) /** * Checks whether a string is a float value. * - * Compared to `is_float` function of php, it only ensures whether the input variable is type float. + * Compared to `is_float()` function of PHP, it only ensures whether the input variable is type float. * - * @param mixed $value The value to check whether its float or not. - * @return boolean Whether its a float value or not. + * @param mixed $value The value to check whether it's float or not. + * @return boolean Whether it's a float value or not. */ public static function isFloat($value) { @@ -182,9 +182,9 @@ public static function isFloat($value) } /** - * Replace only the first occurance found inside the string. + * Replace only the first occurrence found inside the string. * - * The replace first method is *case sensitive*. + * The replace first method is *case-sensitive*. * * ```php * StringHelper::replaceFirst('abc', '123', 'abc abc abc'); // returns "123 abc abc" @@ -203,7 +203,7 @@ public static function replaceFirst($search, $replace, $subject) /** * Check whether a char or word exists in a string or not. * - * This method is case sensitive. The need can be an array with multiple chars or words who + * This method is case-sensitive. The need can be an array with multiple chars or words who * are going to look up in the haystack string. * * If an array of needle words is provided the $strict parameter defines whether all need keys must be found @@ -225,7 +225,7 @@ public static function replaceFirst($search, $replace, $subject) * * @param string|array $needle The char or word to find in the $haystack. Can be an array to multi find words or char in the string. * @param string $haystack The haystack where the $needle string should be looked up. A string or phrase with words. - * @param boolean $strict If an array of needles is provided the $strict parameter defines whether all keys must be found ($strict = true) or just one result must be found ($strict = false). + * @param boolean $strict If an array of needles is provided the $strict parameter defines whether all keys must be found ($strict = `true`) or just one result must be found ($strict = `false`). * @return boolean If an array of values is provided the response may change depending on $findAll. */ public static function contains($needle, $haystack, $strict = false) @@ -255,11 +255,11 @@ public static function contains($needle, $haystack, $strict = false) * + remove space * + remove tabs * + remove newlines - * + remove html comments + * + remove HTML comments * * @param string $content The content to minify. * @param array $options Optional arguments to provide for minification: - * - comments: boolean, where html comments should be removed or not. defaults to false + * - comments: boolean, where HTML comments should be removed or not, defaults to `false`. * @return mixed Returns the minified content. */ public static function minify($content, array $options = []) @@ -275,9 +275,9 @@ public static function minify($content, array $options = []) } /** - * Cut the given word/string from the content. Its truncates to the left side and to the right side of the word. + * Cut the given word/string from the content. It's truncated to the left side and to the right side of the word. * - * An example of how a sentenced is cut: + * An example of how a sentence is cutted: * * ```php * $cut = StringHelper::truncateMiddle('the quick fox jumped over the lazy dog', 'jumped', 12); @@ -285,9 +285,9 @@ public static function minify($content, array $options = []) * ``` * * @param string $content The content to cut the words from. - * @param string $word The word which should be in the middle of the string - * @param integer $length The amount of the chars to cut on the left and right side from the word. - * @param string $affix The chars which should be used for prefix and suffix when string is cuted. + * @param string $word The word which should be in the middle of the string. + * @param integer $length The amount of chars to cut on the left and right side from the word. + * @param string $affix The chars which should be used for prefix and suffix when string is cutted. * @param boolean $caseSensitive Whether the search word in the string even when lower/upper case is not correct. */ public static function truncateMiddle($content, $word, $length, $affix = '..', $caseSensitive = false) @@ -298,7 +298,7 @@ public static function truncateMiddle($content, $word, $length, $affix = '..', $ // we could not find any match, therefore use casual truncate method. if ($first === false) { - // as the length value in truncate middle stands for to the left and to the right, we multiple this value with 2 + // as the length value in truncate middle stands for to the left and to the right, we multiply this value with 2 return self::truncate($content, ($length * 2), $affix); } @@ -319,9 +319,9 @@ public static function truncateMiddle($content, $word, $length, $affix = '..', $ /** * Highlight a word within a content. * - * Since version 1.0.14 its possible to provide an array with words to highlight + * Since version 1.0.14 it's possible to provide an array with words to highlight. * - * > This function IS NOT case sensitive! + * > This function IS NOT case-sensitive! * * ```php * StringHelper::highlightWord('Hello John!', 'john'); @@ -330,7 +330,7 @@ public static function truncateMiddle($content, $word, $length, $affix = '..', $ * The above example would return `Hello John!`. * * @param string $content The content to find the word. - * @param string|array $word The word to find within the content. It can be an array. If a word exists already in the list of words, this one will be stripped. f.e. `['test', 'testfoobar'] would remove `test` from the list as it exists in `testfoobar` + * @param string|array $word The word to find within the content. It can be an array. If a word exists already in the list of words, this one will be stripped. e.g. `['test', 'testfoobar']` would remove `test` from the list as it exists in `testfoobar`. * @param string $markup The markup used wrap the word to highlight. */ public static function highlightWord($content, $word, $markup = '%s') @@ -360,14 +360,14 @@ public static function highlightWord($content, $word, $markup = '%s') break; } - // search in transliated content if not yet breaked from previous results + // search in transliterated content if not yet breaked from previous results preg_match_all("/".preg_quote($word, '/')."+/i", $transliterateContent, $matches); foreach ($matches[0] as $word) { $highlights[] = self::sliceTransliteratedWord($word, $transliterateContent, $content); } } - // hightlight all results in text with [[$word]] + // highlight all results in text with [[$word]] foreach (array_unique($highlights) as $highlight) { $content = str_replace($highlight, '[['.$highlight.']]', $content); } @@ -391,7 +391,7 @@ public static function highlightWord($content, $word, $markup = '%s') /** * Search a word within a transliterated text and cut out the original word in the original text. * - * For example when you search for the transliaterad word in text and want to return the original: + * For example when you search for the transliterated word in text and want to return the original: * * ```php * StringHelper::sliceTransliteratedWord('frederic', 'Hello frederic', 'Hello fréderic'); @@ -411,9 +411,9 @@ public static function sliceTransliteratedWord($word, $transliteratedText, $orig } /** - * Multibyte-safe str_split funciton. + * Multibyte-safe `str_split()` function. * - * @param string $string The string to split into an array + * @param string $string The string to split into an array. * @param integer $length The length of the chars to cut. * @see https://www.php.net/manual/de/function.str-split.php#115703 */ @@ -425,11 +425,11 @@ public static function mb_str_split($string, $length = 1) /** * Check whether a value is numeric or not. * - * There are situations where is_numeric does not provide the desried result, - * like for example `is_numeric('3e30')` would return true, as e can be considered + * There are situations where `is_numeric()` does not provide the desired result, + * like for example `is_numeric('3e30')` would return true, as `e` can be considered * as exponential operator. * - * Therfore this function checks with regex whether values or 0-9 if strict is enabled, + * Therefore this function checks with regex whether values or 0-9 if strict is enabled, * which is default behavior. * * @param mixed $value The value to check. @@ -466,7 +466,7 @@ public static function isNummeric($value, $strict = true) * // output:

John

* ``` * - * If a variable is not found, the original curly bracktes will be returned. + * If a variable is not found, the original curly brackets will be returned. * * @param string $template The template to parse. The template may contain double curly brackets variables. * @param array $variables The variables which should be available in the template. @@ -496,10 +496,10 @@ public static function template($template, array $variables = [], $removeEmpty = } /** - * Convert a text with different seperators to an array. + * Convert a text with different separators to an array. * - * Its very common to use seperators when working with user input, for example a list of domains seperated by commas. Therefore - * this function will use common seperators the generate an array from a text string. + * It's very common to use separators when working with user input, for example a list of domains separated by commas. Therefore + * this function will use common separators the generate an array from a text string. * * Explodes the string by: "Newline", ";", "," * @@ -507,11 +507,11 @@ public static function template($template, array $variables = [], $removeEmpty = * + comma * + point comma * - * @param string $text A text which contains a list of items seperated by seperators like commas. + * @param string $text A text which contains a list of items separated by separators like commas. * @return array */ - public static function textList($text, array $seperators = [PHP_EOL, "\n", "\r", "\n\r", ";", ","]) + public static function textList($text, array $separators = [PHP_EOL, "\n", "\r", "\n\r", ";", ","]) { - return StringHelper::explode(str_replace($seperators, ';', $text), ";", true, true); + return StringHelper::explode(str_replace($separators, ';', $text), ";", true, true); } } diff --git a/src/helpers/Url.php b/src/helpers/Url.php index d482a06..4212008 100644 --- a/src/helpers/Url.php +++ b/src/helpers/Url.php @@ -9,14 +9,14 @@ /** * Helper methods when dealing with URLs and Links. * - * Extends the {{yii\helpers\BaseUrl}} class by some usefull functions like: + * Extends the {{yii\helpers\BaseUrl}} class by some useful functions like: * * + {{luya\yii\helpers\Url::trailing()}} * + {{luya\yii\helpers\Url::toInternal()}} * + {{luya\yii\helpers\Url::toAjax()}} * + {{luya\yii\helpers\Url::ensureHttp()}} * - * An example of create an URL based on Route in the UrlManager: + * An example of create an URL based on route in the UrlManager: * * ```php * Url::toRoute(['/module/controller/action']); @@ -28,11 +28,11 @@ class Url extends BaseUrl { /** - * Add a trailing slash to an url if there is no trailing slash at the end of the url. + * Add a trailing slash to an URL if there is no trailing slash at the end of the URL. * - * @param string $url The url which a trailing slash should be appended - * @param string $slash If you want to trail a file on a windows system it gives you the ability to add forward slashes. - * @return string The url with added trailing slash, if requred. + * @param string $url The URL which a trailing slash should be appended + * @param string $slash If you want to trail a file on a Windows system it gives you the ability to add forward slashes. + * @return string The URL with added trailing slash, if required. */ public static function trailing($url, $slash = '/') { @@ -43,8 +43,8 @@ public static function trailing($url, $slash = '/') * This helper method will not concern any context informations * * @param array $routeParams Example array to route `['/module/controller/action']`. - * @param boolean $scheme Whether to return the absolute url or not - * @return string The created url. + * @param boolean $scheme Whether to return the absolute URL or not. + * @return string The created URL. */ public static function toInternal(array $routeParams, $scheme = false) { @@ -58,11 +58,11 @@ public static function toInternal(array $routeParams, $scheme = false) } /** - * Create a link to use when point to an ajax script. + * Create a link to use when point to an AJAX script. * - * @param string $route The base routing path defined in yii. module/controller/action - * @param array $params Optional array containing get parameters with key value pairing - * @return string The ajax url link. + * @param string $route The base routing path defined in Yii (module/controller/action). + * @param array $params Optional array containing get parameters with key-value pairing. + * @return string The AJAX URL link. */ public static function toAjax($route, array $params = []) { @@ -75,8 +75,8 @@ public static function toAjax($route, array $params = []) } /** - * Apply the http protcol to an url to make sure valid clickable links. Commonly used when provide link where user could have added urls - * in an administration area. For Example: + * Apply the HTTP protocol to an URL to make sure valid clickable links. Commonly used when provide link where user could have added URLs + * in an administration area. For example: * * ```php * Url::ensureHttp('luya.io'); // return https://luya.io @@ -84,8 +84,8 @@ public static function toAjax($route, array $params = []) * Url::ensureHttp('luya.io', true); // return https://luya.io * ``` * - * @param string $url The url where the http protcol should be applied to if missing - * @param boolean $https Whether the ensured url should be returned as https or not. + * @param string $url The URL where the HTTP protocol should be applied to if missing. + * @param boolean $https Whether the ensured URL should be returned as https or not. * @return string */ public static function ensureHttp($url, $https = false) @@ -102,8 +102,8 @@ public static function ensureHttp($url, $https = false) * * For example `https://luya.io/path` would return `luya.io/path`. * - * @param string $url The url to extract - * @return string returns the url without protocol or www. subdomain + * @param string $url The URL to extract + * @return string returns the URL without protocol or www. subdomain */ public static function cleanHost($url) { @@ -114,8 +114,8 @@ public static function cleanHost($url) * * For example `https://luya.io/path` would return `luya.io` without path informations. * - * @param string $url The url to extract - * @return string Returns only the domain from the url. + * @param string $url The URL to extract + * @return string Returns only the domain from the URL. */ public static function domain($url) { @@ -123,12 +123,12 @@ public static function domain($url) } /** - * Append a query to the current url. + * Append a query to the current URL. * * See {{luya\yii\helpers\Url::appendToUrl()}} * - * @param string|array $append A string with url fragments or an array which will be processed by http_build_query. - * @param boolean $scheme Add full path schema to the url, by default false. Otherwise absolute paths are used (including domain). + * @param string|array $append A string with URL fragments or an array which will be processed by `http_build_query()`. + * @param boolean $scheme Add full path schema to the URL, by default `false`. Otherwise absolute paths are used (including domain). * @return string */ public static function appendQuery($append, $scheme = false) @@ -139,31 +139,31 @@ public static function appendQuery($append, $scheme = false) } /** - * Append an url part to an url + * Append an URL part to an URL. * - * @param string $url The url where the data should be appended. - * @param string|array $append The query param to append, if an array is given http_build_query() will taken to build the query string. - * @return string Returns the url with appended query string + * @param string $url The URL where the data should be appended. + * @param string|array $append The query parameters to append, if an array is given `http_build_query()` will taken to build the query string. + * @return string Returns the URL with appended query string. */ public static function appendQueryToUrl($url, $append) { if (is_array($append)) { $append = http_build_query($append); } - // remove starting & and ? chars + // remove starting '&' and '?' chars $append = ltrim($append, '&?'); - // use &: Do we have already a ? in the url + // use '&': Do we have already a '?' in the URL if (StringHelper::contains('?', $url)) { - // seperator already existing + // separator already existing if (StringHelper::endsWith($url, '&') || StringHelper::endsWith($url, '?')) { return $url . $append; } - // add seperator + // add separator return $url . '&' . $append; } - // use ? + // use '?' return $url . '?' . $append; } } diff --git a/src/helpers/ZipHelper.php b/src/helpers/ZipHelper.php index d20fa1e..62f5303 100644 --- a/src/helpers/ZipHelper.php +++ b/src/helpers/ZipHelper.php @@ -13,11 +13,11 @@ class ZipHelper { /** - * Add files and sub-directories in a folder to zip file. + * Add files and sub-directories in a folder to ZIP file. * * @param string $folder * @param \ZipArchive $zipFile - * @param integer $exclusiveLength Number of text to be exclusived from the file path. + * @param integer $exclusiveLength Length of text to be exclusived from the file path. */ private static function folderToZip($folder, &$zipFile, $exclusiveLength) { @@ -25,7 +25,7 @@ private static function folderToZip($folder, &$zipFile, $exclusiveLength) while (false !== $f = readdir($handle)) { if ($f != '.' && $f != '..') { $filePath = "$folder/$f"; - // Remove prefix from file path before add to zip. + // Remove prefix from file path before add to ZIP. $localPath = substr($filePath, $exclusiveLength); if (is_file($filePath)) { $zipFile->addFile($filePath, $localPath); @@ -46,8 +46,8 @@ private static function folderToZip($folder, &$zipFile, $exclusiveLength) * ZipHelper::dir('/path/to/sourceDir', '/path/to/out.zip'); * ``` * - * @param string $sourcePath Path of directory to be zip. - * @param string $outZipPath Path of output zip file. + * @param string $sourcePath Path of directory to be zipped. + * @param string $outZipPath Path of output ZIP file. */ public static function dir($sourcePath, $outZipPath) { diff --git a/tests/helpers/ExportHelperTest.php b/tests/helpers/ExportHelperTest.php index 17571e0..050266a 100644 --- a/tests/helpers/ExportHelperTest.php +++ b/tests/helpers/ExportHelperTest.php @@ -88,7 +88,7 @@ public function testActiveRecordCsv() $m->save(); } - // active query find + // ActiveQuery find $this->assertEquals('"Id","Name"'.PHP_EOL.'"1","John"'.PHP_EOL.'"2","Jane"'. PHP_EOL, ExportHelper::csv(CsvModelStub::find())); $this->assertEquals('"1","John"'.PHP_EOL.'"2","Jane"'. PHP_EOL, ExportHelper::csv(CsvModelStub::find(), [], false)); $this->assertEquals('"1"'.PHP_EOL.'"2"'. PHP_EOL, ExportHelper::csv(CsvModelStub::find(), ['id'], false)); diff --git a/tests/helpers/FileHelperTest.php b/tests/helpers/FileHelperTest.php index b8642f8..651eb8e 100644 --- a/tests/helpers/FileHelperTest.php +++ b/tests/helpers/FileHelperTest.php @@ -31,7 +31,7 @@ public function testEnsureExtension() { $this->assertSame('path/to/image.png', FileHelper::ensureExtension('path/to/image.png', 'gif')); $this->assertSame('path/to/image.gif', FileHelper::ensureExtension('path/to/image', 'gif')); - // twig example as used in element component + // Twig example as used in element component $this->assertSame('file.twig', FileHelper::ensureExtension('file', 'twig')); $this->assertSame('path/to/file.twig', FileHelper::ensureExtension('path/to/file', 'twig')); $this->assertSame('path/to/file.twig', FileHelper::ensureExtension('path/to/file.', 'twig')); diff --git a/tests/helpers/InflectorHelperTest.php b/tests/helpers/InflectorHelperTest.php index 5b68cff..340b98f 100644 --- a/tests/helpers/InflectorHelperTest.php +++ b/tests/helpers/InflectorHelperTest.php @@ -21,11 +21,11 @@ public function testSlug() // testing without transliteration and without lowercase transformation $this->assertEquals('新-新-新-新', Inflector::slug('新-新-新-新', '-', true, false)); $this->assertEquals('這是-luya', Inflector::slug('這是 LUYA ', '-', true, false)); - // filter critical string elements whithout inflection + // filter critical string elements without inflection $this->assertEquals('這是-luya', Inflector::slug('<這是> {LUYA} ', '-', true, false)); $this->assertEquals('a1Zあ新~!@#$^&*()[];\',:?', Inflector::slug('a1Zあ新`~!@#$%^&*()_+[]\;\\\',./{}|:<>?', '-', false, false)); - // test lowercase and german special char + // test lowercase and german special chars $this->assertEquals('ÖöÜäüü-!?Hallo-hH', Inflector::slug('ÖöÜäüü !?Hallo hH ', '-', false, false)); $this->assertEquals('ööüäüü-!?hallo-hh', Inflector::slug('ÖöÜäüü !?Hallo hH ', '-', true, false)); $this->assertEquals('ööüäüü-新新新', Inflector::slug('ÖöÜäüü 新新新 ', '-', true, false)); diff --git a/tests/helpers/JsonTest.php b/tests/helpers/JsonTest.php index 514a6ed..a378ab1 100644 --- a/tests/helpers/JsonTest.php +++ b/tests/helpers/JsonTest.php @@ -10,7 +10,7 @@ class JsonTest extends HelpersTestCase { public function testIsJson() { - // not a json + // not a JSON $this->assertFalse(Json::isJson(['foo' => 'bar'])); $this->assertFalse(Json::isJson('12312312')); $this->assertFalse(Json::isJson(12312312)); @@ -18,7 +18,7 @@ public function testIsJson() $this->assertFalse(Json::isJson('{"123":\'123}')); $this->assertFalse(Json::isJson('{"1233}')); $this->assertFalse(Json::isJson('{"1232"3}')); - // is a json + // is a JSON $this->assertTrue(Json::isJson('{"123":"456"}')); $this->assertTrue(Json::isJson('{"123":456}')); $this->assertTrue(Json::isJson('[{"123":"456"}]')); diff --git a/tests/helpers/StringHelperTest.php b/tests/helpers/StringHelperTest.php index 6778ad4..7f1f12f 100644 --- a/tests/helpers/StringHelperTest.php +++ b/tests/helpers/StringHelperTest.php @@ -84,7 +84,7 @@ public function testArrayContains() $this->assertTrue(StringHelper::contains(['foo', 'bar'], 'hello foo bar')); // disabled $strict mode $this->assertTrue(StringHelper::contains(['notexistings', 'bar'], 'hello bar foo')); // disabled $strict mode $this->assertTrue(StringHelper::contains(['bar', 'notexistings'], 'hello bar foo')); // disabled $strict mode - $this->assertFalse(StringHelper::contains(['notexistings'], 'hello bar foo')); + $this->assertFalse(StringHelper::contains(['notexistings'], 'hello bar foo')); // disabled $strict mode } public function testArrayStrictContains() @@ -92,8 +92,8 @@ public function testArrayStrictContains() $this->assertTrue(StringHelper::contains(['foo', 'bar'], 'hello foo bar', true)); // enabled $strict mode $this->assertFalse(StringHelper::contains(['notexistings', 'bar'], 'hello bar foo', true)); // enabled $strict mode $this->assertFalse(StringHelper::contains(['bar', 'notexistings'], 'hello bar foo', true)); // enabled $strict mode - $this->assertFalse(StringHelper::contains(['notexistings'], 'hello bar foo', true)); // enabled strict mode - $this->assertTrue(StringHelper::contains(['a', 'b', 'c'], 'thesmallabc', true)); + $this->assertFalse(StringHelper::contains(['notexistings'], 'hello bar foo', true)); // enabled $strict mode + $this->assertTrue(StringHelper::contains(['a', 'b', 'c'], 'thesmallabc', true)); // enabled $strict mode } public function testStartsWithWildcard() @@ -186,7 +186,7 @@ public function testCutAndHighlightWord() $this->assertSame('Не следует, однако, забывать, что высокое ка', $text); $this->assertSame('Не следует, однако, забывать, что высокое ка', StringHelper::highlightWord($text, $word)); } - public function testHightlightWithItsOwnWord() + public function testHighlightWithItsOwnWord() { $this->assertSame('Die attraktivste Gemeinde Damonisu Skadalitus. Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ..', StringHelper::highlightWord('Die attraktivste Gemeinde Damonisu Skadalitus. Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ..', 'lor', '%s')); @@ -212,7 +212,7 @@ public function testIsNumeric() $this->assertFalse(StringHelper::isNummeric('abc', false)); $this->assertFalse(StringHelper::isNummeric('xyz2', false)); - // none scalar + // non-scalar $this->assertFalse(StringHelper::isNummeric(true)); $this->assertFalse(StringHelper::isNummeric(true, false)); $this->assertFalse(StringHelper::isNummeric(false)); @@ -220,7 +220,6 @@ public function testIsNumeric() $this->assertFalse(StringHelper::isNummeric([])); $this->assertFalse(StringHelper::isNummeric([], false)); - // exponent number case $this->assertFalse(StringHelper::isNummeric('3e30')); $this->assertTrue(StringHelper::isNummeric('3e30', false)); From 457e9e33c52fde5cdd40d1072d2f5c113392313a Mon Sep 17 00:00:00 2001 From: Hendrik Bugdoll Date: Mon, 12 Feb 2024 12:47:46 +0100 Subject: [PATCH 2/2] Apply a php-cs-fixer change --- src/helpers/Url.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/helpers/Url.php b/src/helpers/Url.php index 4212008..f62b89f 100644 --- a/src/helpers/Url.php +++ b/src/helpers/Url.php @@ -75,7 +75,7 @@ public static function toAjax($route, array $params = []) } /** - * Apply the HTTP protocol to an URL to make sure valid clickable links. Commonly used when provide link where user could have added URLs + * Apply the HTTP protocol to an URL to make sure valid clickable links. Commonly used when provide link where user could have added URLs. * in an administration area. For example: * * ```php