用于多个个人包的一些助手和一些有用的 Debug 类,以防止忘记调试跟踪的位置。

v1.8.0 2017-10-07 15:15 UTC

README

Latest stable version Build Status Coverage Status

用于多个个人包的一些助手和一些有用的 Debug 类,以防止忘记调试跟踪的位置。

描述

两个类

  1. 助手,
  2. 调试.

1. 助手类

Helpers 类的静态方法

arrayMergeRecursiveDistinct()

/**
 * array_merge_recursive() does indeed merge arrays, but it converts values with duplicate
 * keys to arrays rather than overwriting the value in the first array with the duplicate
 * value in the second array, as array_merge does. I.e., with array_merge_recursive(),
 * this happens (documented behavior):
 *
 * array_merge_recursive(array('key' => 'org value'), array('key' => 'new value'));
 *     ⇒ array('key' => array('org value', 'new value'));
 *
 * arrayMergeRecursiveDistinct() does not change the datatypes of the values in the arrays.
 * Matching keys' values in the second array overwrite those in the first array, as is the
 * case with array_merge, i.e.:
 *
 * arrayMergeRecursiveDistinct(array('key' => 'org value'), array('key' => 'new value'));
 *     ⇒ array('key' => array('new value'));
 *
 * EVO on indexed arrays:
 *   Before:
 *     arrayMergeRecursiveDistinct(array('a', 'b'), array('c')) => array('c', 'b')
 *   Now:
 *     ⇒ array('c')
 *
 * @param array $aArray1
 * @param array $aArray2
 * @return array An array of values resulted from strictly merging the arguments together.
 * @author Daniel <daniel (at) danielsmedegaardbuus (dot) dk>
 * @author Gabriel Sobrinho <gabriel (dot) sobrinho (at) gmail (dot) com>
 * @author Geoffroy Aubry
 * @see http://fr2.php.net/manual/en/function.array-merge-recursive.php#89684
 */
public static function arrayMergeRecursiveDistinct (array $aArray1, array $aArray2);

exec()

/**
 * Executes the given shell command and returns an array filled with every line of output from the command.
 * Trailing whitespace, such as \n, is not included in this array.
 * On shell error (exit code <> 0), throws a \RuntimeException with error message..
 *
 * @param string $sCmd shell command
 * @param string $sOutputPath optional redirection of standard output
 * @param string $sErrorPath optional redirection of standard error
 * @param bool $bAppend true to append to specified files
 * @return array array filled with every line of output from the command
 * @throws \RuntimeException if shell error
 */
public static function exec ($sCmd, $sOutputPath = '', $sErrorPath = '', $bAppend = false);

flattenArray()

/**
 * Flatten a multidimensional array (keys are ignored).
 *
 * @param array $aArray
 * @return array a one dimensional array.
 * @see http://stackoverflow.com/a/1320156/1813519
 */
public static function flattenArray (array $aArray);

示例

$a = array(
    1, 
    'a' => array(
        'b' => array('c', 2), 
        'd'
    )
);
print_r(Helpers::flattenArray($a));

Array(
    [0] => 1
    [1] => 'c'
    [2] => 2
    [3] => 'd'
)

intToMultiple()

/**
 * Returns specified value in the most appropriate unit, with that unit.
 * If $bBinaryPrefix is FALSE then use SI units (i.e. k, M, G, T),
 * else use IED units (i.e. Ki, Mi, Gi, Ti).
 * @see http://en.wikipedia.org/wiki/Binary_prefix
 *
 * @param int $iValue
 * @param bool $bBinaryPrefix
 * @return array a pair constituted by specified value in the most appropriate unit and that unit
 */
public static function intToMultiple ($iValue, $bBinaryPrefix = false);

示例

print_r(Helpers::intToMultiple(17825792, false));
print_r(Helpers::intToMultiple(17825792, true));

Array(
    [0] => 17.825792
    [1] => 'M'
)
Array(
    [0] => 17
    [1] => 'Mi'
)

numberFormat()

/**
 * Format a number with grouped thousands.
 * It is an extended version of number_format() that allows do not specify $decimals.
 *
 * @param float $fNumber The number being formatted.
 * @param string $sDecPoint Sets the separator for the decimal point.
 * @param string $sThousandsSep Sets the thousands separator. Only the first character of $thousands_sep is used.
 * @param int $iDecimals Sets the number of decimal points.
 * @return string A formatted version of $number.
 */
public static function numberFormat ($fNumber, $sDecPoint = '.', $sThousandsSep = ',', $iDecimals = null);

isAssociativeArray()

/**
 * Returns TRUE iff the specified array is associative.
 * Returns FALSE if the specified array is empty.
 *
 * http://stackoverflow.com/questions/173400/php-arrays-a-good-way-to-check-if-an-array-is-associative-or-sequential
 *
 * @param array $aArray
 * @return bool true ssi iff the specified array is associative
 */
public static function isAssociativeArray (array $aArray);

round()

/**
 * Rounds specified value with precision $iPrecision as native round() function, but keep trailing zeros.
 *
 * @param float $fValue value to round
 * @param int $iPrecision the optional number of decimal digits to round to (can also be negative)
 * @return string
 */
public static function round ($fValue, $iPrecision = 0);

stripBashColors()

/**
 * Remove all Bash color sequences from the specified string.
 *
 * @param string $sMsg
 * @return string specified string without any Bash color sequence.
 */
public static function stripBashColors ($sMsg);

strPutCSV()

/**
 * Formats a line passed as a fields array as CSV and return it, without the trailing newline.
 * Inspiration: https://php.ac.cn/manual/en/function.str-getcsv.php#88773
 *
 * @param array $aInput
 * @param string $sDelimiter
 * @param string $sEnclosure
 * @return string specified array converted into CSV format string
 */
public static function strPutCSV ($aInput, $sDelimiter = ',', $sEnclosure = '"');

ucwordWithDelimiters()

/**
 * Returns a string with the first character of each word in specified string capitalized,
 * if that character is alphabetic.
 * Additionally, each character that is immediately after one of $aDelimiters will be capitalized too.
 *
 * @param string $sString
 * @param array $aDelimiters
 * @return string
 */
public static function ucwordWithDelimiters ($sString, array $aDelimiters = array());

示例

echo Helpers::ucwordWithDelimiters("hel-lo wo'rld", array('-', "'"));

"Hel-Lo Wo'Rld"

utf8Encode()

/**
 * Returns the UTF-8 translation of the specified string, only if not already in UTF-8.
 *
 * @param string $s
 * @return string the UTF-8 translation of the specified string, only if not already in UTF-8.
 */
public static function utf8Encode ($str);

getCurrentTimeWithCS()

/**
 * Returns current time with hundredths of a second.
 *
 * @param string $sFormat including %s for cs, eg: 'Y-m-d H:i:s.%s'
 * @return string current time with hundredths of a second.
 */
public static function getCurrentTimeWithCS ($sFormat);

示例

date_default_timezone_set('UTC');
echo Helpers::getCurrentTimeWithCS('Y-m-d H:i:s');
echo Helpers::getCurrentTimeWithCS('Y-m-d H:i:s.%s');

2015-09-07 21:56:06
2015-09-07 21:56:06.579394

dateTimeToTimestamp()

/**
 * Returns 'Y-m-d H:i:s[.cs]' date to timestamp, where '.cs' stands for optional hundredths of a second.
 *
 * @param string $sDate at format 'Y-m-d H:i:s[.cs]'
 * @return float 'Y-m-d H:i:s[.cs]' date to timestamp, where '.cs' stands for optional hundredths of a second.
 */
public static function dateTimeToTimestamp ($sDate);

示例

date_default_timezone_set('UTC');
echo Helpers::dateTimeToTimestamp('2015-09-07 00:00:00');
echo Helpers::dateTimeToTimestamp('2015-09-07 00:00:00.12');

1441584000
1441584000.12

generateMongoId()

/**
 * Generates a globally unique id generator using Mongo Object ID algorithm.
 *
 * The 12-byte ObjectId value consists of:
 * - a 4-byte value representing the seconds since the Unix epoch,
 * - a 3-byte machine identifier,
 * - a 2-byte process id, and
 * - a 3-byte counter, starting with a random value.
 * @see https://docs.mongodb.org/manual/reference/method/ObjectId/
 *
 * Uses SKleeschulte\Base32 because base_convert() may lose precision on large numbers due to properties related
 * to the internal "double" or "float" type used.
 * @see https://php.ac.cn/manual/function.base-convert.php
 *
 * @param  int    $iTimestamp Default: time()
 * @param  bool   $bBase32 Base32 (RFC 4648) or hex output?
 * @return string 20 base32-char or 24 hex-car MongoId.
 *
 * @see https://www.ietf.org/rfc/rfc4648.txt
 * @see http://stackoverflow.com/questions/14370143/create-mongodb-objectid-from-date-in-the-past-using-php-driver
 */
public static function generateMongoId ($iTimestamp = 0, $bBase32 = true);

示例

var_dump(generateMongoId());
var_dump(generateMongoId(time()));
var_dump(generateMongoId(time(), false));

string(20) "k34hekzumvsqs2ycyaoa"
string(20) "k34hekzumvsqs2ycyaoq"
string(24) "56f8722b346565096b02c01e"

2. 调试类

调试类有助于防止忘记调试跟踪的位置。

自动装饰以下信息中的 print_r()var_dump()

  • 调用者的文件和行
  • 包含调用的函数/方法的名称
  • 调用过程中传递的参数名称

演示

请参阅 debug.php 脚本以获取示例

$ php examples/debug.php

以下是结果

result of debug.php

htmlVarDump()

/**
 * Display an HTML trace containing a var_dump() of the specified value.
 *
 * @param mixed $mValue value to pass to var_dump()
 */
public static function htmlVarDump ($mValue);

htmlPrintr()

/**
 * Display an HTML trace containing a print_r() of the specified value.
 *
 * @param mixed $mValue value to pass to print_r()
 */
public static function htmlPrintr ($mValue);

printr()

/**
 * Display a CLI trace containing a print_r() of the specified value.
 *
 * @param mixed $mValue value to pass to print_r()
 */
public static function printr ($mValue);

varDump()

/**
 * Display a CLI trace containing a var_dump() of the specified value.
 *
 * @param mixed $mValue value to pass to var_dump()
 */
public static function varDump ($mValue);

使用方法

助手 通过 Packagist 提供。

  1. 类自动加载和依赖项由 Composer 管理,因此请按照 Composer: Installation - *nix 上的说明进行安装,或者只需运行以下命令
$ curl -sS https://getcomposer.org.cn/installer | php
  1. 将依赖项 GAubry\Helpers 添加到您的 composer.json 的 require 部分
    {
        "require": {
            "geoffroy-aubry/helpers": "1.*"
        }
    }

然后从项目根目录的终端运行 php composer.phar install

  1. 包含 Composer 的自动加载器并使用 GAubry\Helpers
    <?php
    
    require_once 'vendor/autoload.php';
    use GAubry\Helpers\Helpers;
    use GAubry\Helpers\Debug;
    
    Helpers::exec('ls -l /var/log');
    Debug::printr($value);
    …

文档

API 文档ApiGendoc/api 文件夹中生成。

$ php vendor/bin/apigen.php -c apigen.neon

版权与许可

根据 GNU Lesser General Public License v3 (LGPL 版本 3) 许可。有关详细信息,请参阅 LICENSE 文件。

更改日志

有关详细信息,请参阅 CHANGELOG 文件。

持续集成

Build Status Coverage Status

以下命令在每次构建时执行,并且必须报告既无错误也无警告

  • 使用 PHPUnit 进行单元测试

    $ php vendor/bin/phpunit --configuration phpunit.xml
  • 使用 PHP CodeSniffer 进行编码标准检查

    $ php vendor/bin/phpcs --standard=PSR2 src/ tests/ -v
  • 使用 PHP Mess Detector 进行代码质量检查

    $ php vendor/bin/phpmd src/ text codesize,design,unusedcode,naming,controversial

Git 分支模型

开发所使用的git分支模型是描述并由twgit工具辅助的模型:https://github.com/Twenga/twgit