Skip to content

Commit

Permalink
add new methods
Browse files Browse the repository at this point in the history
  • Loading branch information
Leonid74 committed Feb 6, 2022
1 parent 5ffa4cc commit c6cdaf1
Show file tree
Hide file tree
Showing 4 changed files with 270 additions and 13 deletions.
138 changes: 131 additions & 7 deletions src/ArrayHelper.php
Original file line number Diff line number Diff line change
Expand Up @@ -3,12 +3,13 @@
/**
* Helper class for processing arrays
*
* This file is part of the project.
* Вспомогательный класс для обработки массивов
*
* @author Leonid Sheikman (leonid74)
* @copyright 2019-2021 Leonid Sheikman
* @copyright 2019-2022 Leonid Sheikman
* @see https://github.com/Leonid74/helpers-php
*
* This file is part of the project.
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
Expand All @@ -18,11 +19,14 @@
class ArrayHelper
{
/**
* Checks if the given KEY or INDEX exists in the one- or multi-dimensional array
*
* Checks if the given KEY or INDEX exists in the one- or multi-dimensional array.
* Arrays in PHP handle an integer key and a string integer key identically, so it is
* pointless to specify a type match for keys
*
* Проверяет, существует ли данный КЛЮЧ или ИНДЕКС в одно- или многомерном массиве.
* Массивы в PHP обрабатывают целочисленный ключ и строковый целочисленный ключ одинаково, поэтому
* бессмысленно указывать соответствие типов для ключей
*
* @param mixed $mNeedle
* @param array $aHaystack
* @param bool $bCaseInsensitive (optional, defaults to false)
Expand Down Expand Up @@ -62,7 +66,9 @@ public static function arrayKeyExists(
}

/**
* Checks if the given VALUE exists in the one- or multi-dimensional array
* Checks if the given VALUE exists in the one- or multi-dimensional array.
*
* Проверяет, существует ли данное ЗНАЧЕНИЕ в одно- или многомерном массиве.
*
* @param mixed $mNeedle
* @param array $aHaystack
Expand Down Expand Up @@ -108,9 +114,42 @@ public static function arrayValueExists(
return $result;
}

/**
* Checks whether any of the values from the aNeedles array are contained in the sHaystack.
*
* Проверяет, содержатся ли какие-либо значения из массива aNeedles в строке sHaystack.
*
* @param string $sHaystack
* @param array $aNeedles
* @param int $iOffset (optional, defaults to 0)
* @param bool $bCaseInSensitive (optional, defaults to false)
*
* @return bool
*/
public static function arrayNeedlesExists(
string $sHaystack,
array $aNeedles,
?int $iOffset,
?bool $bCaseInSensitive
): bool {
$iOffset = $iOffset ?? 0;
$bCaseInsensitive = $bCaseInsensitive ?? false;

foreach ( $aNeedles as $needle ) {
if ( ( $bCaseInSensitive ? \stripos( $sHaystack, $needle, $iOffset ) : \strpos( $sHaystack, $needle, $iOffset ) ) !== false ) {
return true;
}
}

return false;
}

/**
* Searches in the one- or multi-dimensional array for a given VALUE and returns the first
* corresponding key if successful
* corresponding key if successful.
*
* Выполняет поиск в одно- или многомерном массиве заданного ЗНАЧЕНИЯ и возвращает первый
* соответствующий ключ в случае успеха.
*
* @param mixed $mNeedle
* @param array $aHaystack
Expand Down Expand Up @@ -163,7 +202,10 @@ public static function arraySearch(

/**
* Searches in the one- or multi-dimensional array for a given SUBSTRING in the VALUE and returns the first
* corresponding key if successful
* corresponding key if successful.
*
* Выполняет поиск в одно- или многомерном массиве заданной ПОДСТРОКИ в ЗНАЧЕНИИ и возвращает первый
* соответствующий ключ в случае успеха.
*
* @param mixed $mNeedle
* @param array $aHaystack
Expand Down Expand Up @@ -204,4 +246,86 @@ public static function arrayStrPos(

return $result;
}

/**
* An array combined into a string (for example, to save to CSV).
* Nested subarrays will also be combined into a string with a subseparator.
*
* Массив объединённый в строку (к примеру, для сохранения в CSV).
* Вложенные подмассивы будут также объединены в строку с разделителем subseparator.
*
* @param array $aHaystack
* @param string $default
* @param string $separator
* @param string $subseparator
* @param bool $isRecursion (service parameter)
*
* @return string converted array to string
*/
public static function arrayToCsvString(
array $aHaystack,
?string $default = '',
?string $separator = ';',
?string $subseparator = '|',
?bool $isRecursion = false
): string {
if ( empty( $aHaystack ) || ( !\is_array( $aHaystack ) && !\is_object( $aHaystack ) ) ) {
return $default;
}

$separator = $isRecursion ? $separator : '"' . $separator . '"';

$res = [];
foreach ( $aHaystack as $row ) {
$res[] = \is_array( $row ) ? \trim( self::arrayToCsvString( $row, $default, $subseparator, '||', true ), "\"\n\r" ) : \trim( $row );
}

return '"' . \implode( $separator, $res ) . '"' . PHP_EOL;
}

/**
* Flatten Multidimensional Array.
*
* Превратить Многомерный Массив в одномерный.
*
* @param array $aHaystack
* @param string|bool $prefix
*
* @return array
*
* @author https://github.com/php-curl-class/php-curl-class
* @edit Leonid Sheikman (leonid74)
*/
public static function arrayFlattenMulti(
array $aHaystack,
$prefix = false
): array {
$return = [];
if ( \is_array( $aHaystack ) || \is_object( $aHaystack ) ) {
if ( empty( $aHaystack ) ) {
$return[$prefix] = '';
} else {
foreach ( $aHaystack as $key => $val ) {
if ( \is_scalar( $val ) ) {
if ( $prefix ) {
$return[$prefix . '[' . $key . ']'] = $val;
} else {
$return[$key] = $val;
}
} else {
$return = \array_merge(
$return,
self::arrayFlattenMulti(
$val,
$prefix ? $prefix . '[' . $key . ']' : $key
)
);
}
}
}
} elseif ( $aHaystack === null ) {
$return[$prefix] = $aHaystack;
}
return $return;
}
}
8 changes: 4 additions & 4 deletions src/ConfigHelper.php
Original file line number Diff line number Diff line change
Expand Up @@ -68,8 +68,8 @@ public static function loadFile( string $sPath, ?bool $bPrefixFilename = false,
}

// Load file content
$mixContent = static::getFileContent( $sPath, $aPathinfo );
static::loadArray( $mixContent, $sPrefix );
$mixContent = self::getFileContent( $sPath, $aPathinfo );
self::loadArray( $mixContent, $sPrefix );
}

/**
Expand All @@ -87,7 +87,7 @@ public static function loadArray( array $aData, ?string $sPrefix = null ): void
$key = $sPrefix . '.' . $key;
}

static::set( $key, $val );
self::set( $key, $val );
}
}

Expand Down Expand Up @@ -181,7 +181,7 @@ protected static function set( string $key, $value ): void
if ( \is_array( $value ) ) {
foreach ( $value as $key2 => $val2 ) {
$key_path = $key . '.' . $key2;
static::set( $key_path, $val2 );
self::set( $key_path, $val2 );
}
}

Expand Down
4 changes: 2 additions & 2 deletions src/PhoneHelper.php
Original file line number Diff line number Diff line change
Expand Up @@ -111,10 +111,10 @@ public static function isPhoneExist( ?string $sString = '', ?string $apiToken =
$oResult->errors[] = $json->status_code . ': ' . $json->status_text;
}
} else {
// The request was not executed (the connection with the server could not be established)
// The request was not executed (Error decoding the response or Failed to establish connection with the server)
$oResult->phone_exists = 'unknown';
$oResult->is_error = true;
$oResult->errors[] = 'Failed to establish connection with the server or error decoding the response';
$oResult->errors[] = 'Error decoding the response or Failed to establish connection with the server';
}

\usleep( 500000 );
Expand Down
133 changes: 133 additions & 0 deletions src/StringHelper.php
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,139 @@

class StringHelper
{
/**
* Set the encoding by default
*/
public static $encoding = 'UTF-8';

/**
* Most used common php functions.
*/
// @codingStandardsIgnoreLine
public static function mb_stristr( string $haystack, string $needle, bool $before_needle = false )
{
return function_exists( 'mb_stristr' )
? \mb_stristr( $haystack, $needle, $before_needle, static::$encoding )
: \stristr( $haystack, $needle, $before_needle );
}

// @codingStandardsIgnoreLine
public static function mb_strstr( string $haystack, string $needle, bool $before_needle = false )
{
return function_exists( 'mb_strstr' )
? \mb_strstr( $haystack, $needle, $before_needle, static::$encoding )
: \strstr( $haystack, $needle, $before_needle );
}

// @codingStandardsIgnoreLine
public static function mb_stripos( string $haystack, string $needle, int $start = 0 )
{
return function_exists( 'mb_stripos' )
? \mb_stripos( $haystack, $needle, $start, static::$encoding )
: \stripos( $haystack, $needle, $start );
}

// @codingStandardsIgnoreLine
public static function mb_strripos( string $haystack, string $needle, int $start = 0 )
{
return function_exists( 'mb_strripos' )
? \mb_strripos( $haystack, $needle, $start, static::$encoding )
: \strripos( $haystack, $needle, $start );
}

// @codingStandardsIgnoreLine
public static function mb_strpos( string $haystack, string $needle, int $start = 0 )
{
return function_exists( 'mb_strpos' )
? \mb_strpos( $haystack, $needle, $start, static::$encoding )
: \strpos( $haystack, $needle, $start );
}

// @codingStandardsIgnoreLine
public static function mb_strrpos( string $haystack, string $needle, int $start = 0 )
{
return function_exists( 'mb_strrpos' )
? \mb_strrpos( $haystack, $needle, $start, static::$encoding )
: \strrpos( $haystack, $needle, $start );
}

// @codingStandardsIgnoreLine
public static function mb_substr( string $string, int $start, int $length = null ): string
{
return function_exists( 'mb_substr' )
? \mb_substr( $string, $start, $length, static::$encoding )
: \substr( $string, $start, $length );
}

// @codingStandardsIgnoreLine
public static function mb_strlen( string $string ): int
{
return function_exists( 'mb_strlen' )
? \mb_strlen( $string, static::$encoding )
: \strlen( $string );
}

// @codingStandardsIgnoreLine
public static function mb_strtolower( string $string ): string
{
return function_exists( 'mb_strtolower' )
? \mb_strtolower( $string, static::$encoding )
: \strtolower( $string );
}

// @codingStandardsIgnoreLine
public static function mb_strtoupper( string $string ): string
{
return function_exists( 'mb_strtoupper' )
? \mb_strtoupper( $string, static::$encoding )
: \strtoupper( $string );
}

// @codingStandardsIgnoreLine
public static function mb_ucfirst( string $string ): string
{
return self::mb_strtoupper( self::mb_substr( $string, 0, 1 ) ) . self::mb_substr( $string, 1 );
}

// @codingStandardsIgnoreLine
public static function mb_convert_case( string $string ): string
{
return function_exists( 'mb_convert_case' )
? \mb_convert_case( $string, MB_CASE_TITLE, static::$encoding )
: \ucfirst( $string );
}

// @codingStandardsIgnoreLine
public static function htmlspecialchars( string $string ): string
{
return \htmlspecialchars( $string, ENT_COMPAT | ENT_SUBSTITUTE | ENT_HTML5, static::$encoding );
}

// @codingStandardsIgnoreLine
public static function htmlspecialchars_decode( string $string ): string
{
return \htmlspecialchars_decode( $string, ENT_COMPAT | ENT_HTML5 );
}

// @codingStandardsIgnoreLine
public static function htmlentities( string $string ): string
{
return \htmlentities( $string, ENT_COMPAT | ENT_SUBSTITUTE | ENT_HTML5, static::$encoding );
}

// @codingStandardsIgnoreLine
public static function html_entity_decode( string $string ): string
{
return \html_entity_decode( $string, ENT_COMPAT | ENT_HTML5, static::$encoding );
}

// @codingStandardsIgnoreLine
public static function utf8_urldecode( string $string ): string
{
$string = \preg_replace( "/%u([0-9a-f]{3,4})/i", "&#x\\1;", \urldecode( $string ) );
return self::html_entity_decode( $string );
}

/**
* Add BOM to the beginning of the string
*
Expand Down

0 comments on commit c6cdaf1

Please sign in to comment.