This commit is contained in:
Manish Verma
2016-12-13 18:18:25 +05:30
parent fc98add11c
commit 2d8e640e9b
2314 changed files with 97798 additions and 75664 deletions

View File

@@ -2,29 +2,6 @@
All notable changes to this project will be documented in this file, in reverse chronological order by release.
## 3.1.0 - 2016-09-13
### Added
- [#63](https://github.com/zendframework/zend-stdlib/pull/63) adds a new
`Zend\Stdlib\ConsoleHelper` class, providing minimal support for writing
output to `STDOUT` and `STDERR`, with optional colorization, when the console
supports that feature.
### Deprecated
- [#38](https://github.com/zendframework/zend-stdlib/pull/38) deprecates
`Zend\Stdlib\JsonSerializable`, as all supported version of PHP now support
it.
### Removed
- Nothing.
### Fixed
- Nothing.
## 3.0.1 - 2016-04-12
### Added

View File

@@ -7,6 +7,7 @@
class for different scopes like:
- array utilities functions;
- json serializable interfaces;
- general messaging systems;
- string wrappers;
- etc.
@@ -14,4 +15,4 @@ class for different scopes like:
---
- File issues at https://github.com/zendframework/zend-stdlib/issues
- Documentation is at https://docs.zendframework.com/zend-stdlib/
- Documentation is at http://framework.zend.com/manual/current/en/index.html#zend-stdlib

View File

@@ -13,17 +13,17 @@
}
},
"require": {
"php": "^5.6 || ^7.0"
"php": "^5.5 || ^7.0"
},
"require-dev": {
"athletic/athletic": "~0.1",
"fabpot/php-cs-fixer": "1.7.*",
"phpunit/PHPUnit": "~4.0",
"squizlabs/php_codesniffer": "^2.6.2"
"athletic/athletic": "~0.1"
},
"extra": {
"branch-alias": {
"dev-master": "3.1-dev",
"dev-develop": "3.2-dev"
"dev-master": "3.0-dev",
"dev-develop": "3.1-dev"
}
},
"autoload-dev": {
@@ -31,12 +31,5 @@
"ZendTest\\Stdlib\\": "test/",
"ZendBench\\Stdlib\\": "benchmark/"
}
},
"scripts": {
"cs-check": "phpcs --colors",
"cs-fix": "phpcbf --colors",
"test": "phpunit --colors=always",
"test-coverage": "phpunit --colors=always --coverage-clover clover.xml",
"upload-coverage": "coveralls -v"
}
}

View File

@@ -1,126 +0,0 @@
# Console Helper
Writing one-off scripts or vendor binaries for a package is often problematic:
- You need to parse arguments manually.
- You need to send output to the console in a meaningful fashion:
- Using `STDOUT` for meaningful, expected output
- Using `STDERR` for error messages
- Ensuring any line breaks are converted to `PHP_EOL`
- Optionally, using console colors to provide context, which means:
- Detecting whether or not the console supports colors in the first place
- Providing appropriate escape sequences to produce color
`Zend\Stdlib\ConsoleHelper` helps to address the second major bullet point and
all beneath it in a minimal fashion.
## Usage
Typical usage is to instantiate a `ConsoleHelper`, and call one of its methods:
```php
use Zend\Stdlib\ConsoleHelper;
$helper = new ConsoleHelper();
$helper->writeLine('This is output');
```
You can optionally pass a PHP stream resource to the constructor, which will be
used to determine whether or not color support is available:
```php
$helper = new ConsoleHelper($stream);
```
By default, it assumes `STDOUT`, and tests against that.
## Available methods
`ConsoleHelper` provides the following methods.
### colorize
- `colorize(string $string) : string`
`colorize()` accepts a formatted string, and will then apply ANSI color
sequences to them, if color support is detected.
The following sequences are currently supported:
- `<info>...</info>` will apply a green color sequence around the provided text.
- `<error>...</error>` will apply a red color sequence around the provided text.
You may mix multiple sequences within the same stream.
### write
- `write(string $string, bool $colorize = true, resource $stream = STDOUT) : void`
Emits the provided `$string` to the provided `$stream` (which defaults to
`STDOUT` if not provided). Any EOL sequences are convered to `PHP_EOL`. If
`$colorize` is `true`, the string is first passed to `colorize()` as well.
### writeline
- `writeLine(string $string, bool $colorize = true, resource $stream = STDOUT) : void`
Same as `write()`, except it also appends a `PHP_EOL` sequence to the `$string`.
### writeErrorMessage
- `writeErrorMessage(string $message)`
Wraps `$message` in an `<error></error>` sequence, and passes it to
`writeLine()`, using `STDERR` as the `$stream`.
## Example
Below is an example class that accepts an argument list, and determines how and
what to emit.
```php
namespace Foo;
use Zend\Stdlib\ConsoleHelper;
class HelloWorld
{
private $helper;
public function __construct(ConsoleHelper $helper = null)
{
$this->helper = $helper ?: new ConsoleHelper();
}
public function __invoke(array $args)
{
if (! count($args)) {
$this->helper->writeErrorMessage('Missing arguments!');
return;
}
if (count($args) > 1) {
$this->helper->writeErrorMessage('Too many arguments!');
return;
}
$target = array_shift($args);
$this->helper->writeLine(sprintf(
'<info>Hello</info> %s',
$target
));
}
}
```
## When to upgrade
`ConsoleHelper` is deliberately simple, and assumes that your primary need for
console tooling is for output considerations.
If you need to parse complex argument strings, we recommend using
[zend-console](https://docs.zendframework.com/zend-console/)/[zf-console](https://github.com/zfcampus/zf-console)
or [symfony/console](http://symfony.com/doc/current/components/console.html),
as these packages provide those capabilities, as well as far more colorization
and console feature detection facilities.

View File

@@ -2,8 +2,6 @@ docs_dir: doc/book
site_dir: doc/html
pages:
- index.md
- Reference:
- "Console Helper": console-helper.md
- Migration: migration.md
site_name: zend-stdlib
site_description: Zend\Stdlib

View File

@@ -1,27 +0,0 @@
<?xml version="1.0"?>
<ruleset name="Zend Framework coding standard">
<description>Zend Framework coding standard</description>
<!-- display progress -->
<arg value="p"/>
<arg name="colors"/>
<!-- inherit rules from: -->
<rule ref="PSR2"/>
<rule ref="Generic.Arrays.DisallowLongArraySyntax"/>
<rule ref="Generic.Formatting.SpaceAfterNot"/>
<rule ref="Squiz.WhiteSpace.OperatorSpacing">
<properties>
<property name="ignoreNewlines" value="true"/>
</properties>
</rule>
<rule ref="Squiz.WhiteSpace.SuperfluousWhitespace">
<properties>
<property name="ignoreBlankLines" value="false"/>
</properties>
</rule>
<!-- Paths to check -->
<file>src</file>
<file>test</file>
</ruleset>

View File

@@ -13,7 +13,6 @@ use Traversable;
abstract class AbstractOptions implements ParameterObjectInterface
{
// @codingStandardsIgnoreStart
/**
* We use the __ prefix to avoid collisions with properties in
* user-implementations.
@@ -21,7 +20,6 @@ abstract class AbstractOptions implements ParameterObjectInterface
* @var bool
*/
protected $__strictMode__ = true;
// @codingStandardsIgnoreEnd
/**
* Constructor
@@ -48,7 +46,7 @@ abstract class AbstractOptions implements ParameterObjectInterface
$options = $options->toArray();
}
if (! is_array($options) && ! $options instanceof Traversable) {
if (!is_array($options) && !$options instanceof Traversable) {
throw new Exception\InvalidArgumentException(
sprintf(
'Parameter provided to %s must be an %s, %s or %s',

View File

@@ -180,16 +180,14 @@ class ArrayObject implements IteratorAggregate, ArrayAccess, Serializable, Count
*/
public function exchangeArray($data)
{
if (! is_array($data) && ! is_object($data)) {
throw new Exception\InvalidArgumentException(
'Passed variable is not an array or object, using empty array instead'
);
if (!is_array($data) && !is_object($data)) {
throw new Exception\InvalidArgumentException('Passed variable is not an array or object, using empty array instead');
}
if (is_object($data) && ($data instanceof self || $data instanceof \ArrayObject)) {
$data = $data->getArrayCopy();
}
if (! is_array($data)) {
if (!is_array($data)) {
$data = (array) $data;
}
@@ -292,7 +290,7 @@ class ArrayObject implements IteratorAggregate, ArrayAccess, Serializable, Count
public function &offsetGet($key)
{
$ret = null;
if (! $this->offsetExists($key)) {
if (!$this->offsetExists($key)) {
return $ret;
}
$ret =& $this->storage[$key];

View File

@@ -39,11 +39,11 @@ abstract class ArrayUtils
*/
public static function hasStringKeys($value, $allowEmpty = false)
{
if (! is_array($value)) {
if (!is_array($value)) {
return false;
}
if (! $value) {
if (!$value) {
return $allowEmpty;
}
@@ -59,11 +59,11 @@ abstract class ArrayUtils
*/
public static function hasIntegerKeys($value, $allowEmpty = false)
{
if (! is_array($value)) {
if (!is_array($value)) {
return false;
}
if (! $value) {
if (!$value) {
return $allowEmpty;
}
@@ -86,11 +86,11 @@ abstract class ArrayUtils
*/
public static function hasNumericKeys($value, $allowEmpty = false)
{
if (! is_array($value)) {
if (!is_array($value)) {
return false;
}
if (! $value) {
if (!$value) {
return $allowEmpty;
}
@@ -119,11 +119,11 @@ abstract class ArrayUtils
*/
public static function isList($value, $allowEmpty = false)
{
if (! is_array($value)) {
if (!is_array($value)) {
return false;
}
if (! $value) {
if (!$value) {
return $allowEmpty;
}
@@ -161,11 +161,11 @@ abstract class ArrayUtils
*/
public static function isHashTable($value, $allowEmpty = false)
{
if (! is_array($value)) {
if (!is_array($value)) {
return false;
}
if (! $value) {
if (!$value) {
return $allowEmpty;
}
@@ -187,7 +187,7 @@ abstract class ArrayUtils
*/
public static function inArray($needle, array $haystack, $strict = false)
{
if (! $strict) {
if (!$strict) {
if (is_int($needle) || is_float($needle)) {
$needle = (string) $needle;
}
@@ -215,11 +215,11 @@ abstract class ArrayUtils
*/
public static function iteratorToArray($iterator, $recursive = true)
{
if (! is_array($iterator) && ! $iterator instanceof Traversable) {
if (!is_array($iterator) && !$iterator instanceof Traversable) {
throw new Exception\InvalidArgumentException(__METHOD__ . ' expects an array or Traversable object');
}
if (! $recursive) {
if (!$recursive) {
if (is_array($iterator)) {
return $iterator;
}
@@ -274,7 +274,7 @@ abstract class ArrayUtils
} elseif (isset($a[$key]) || array_key_exists($key, $a)) {
if ($value instanceof MergeRemoveKey) {
unset($a[$key]);
} elseif (! $preserveNumericKeys && is_int($key)) {
} elseif (!$preserveNumericKeys && is_int($key)) {
$a[] = $value;
} elseif (is_array($value) && is_array($a[$key])) {
$a[$key] = static::merge($a[$key], $value, $preserveNumericKeys);
@@ -282,7 +282,7 @@ abstract class ArrayUtils
$a[$key] = $value;
}
} else {
if (! $value instanceof MergeRemoveKey) {
if (!$value instanceof MergeRemoveKey) {
$a[$key] = $value;
}
}

View File

@@ -1,158 +0,0 @@
<?php
/**
* @link http://github.com/zendframework/zend-stdlib for the canonical source repository
* @copyright Copyright (c) 2016 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
namespace Zend\Stdlib;
/**
* Utilities for console tooling.
*
* Provides the following facilities:
*
* - Colorize strings using markup (e.g., `<info>message</info>`,
* `<error>message</error>`)
* - Write output to a specified stream, optionally with colorization.
* - Write a line of output to a specified stream, optionally with
* colorization, using the system EOL sequence..
* - Write an error message to STDERR.
*
* Colorization will only occur when expected sequences are discovered, and
* then, only if the console terminal allows it.
*
* Essentially, provides the bare minimum to allow you to provide messages to
* the current console.
*/
class ConsoleHelper
{
const COLOR_GREEN = "\033[32m";
const COLOR_RED = "\033[31m";
const COLOR_RESET = "\033[0m";
const HIGHLIGHT_INFO = 'info';
const HIGHLIGHT_ERROR = 'error';
private $highlightMap = [
self::HIGHLIGHT_INFO => self::COLOR_GREEN,
self::HIGHLIGHT_ERROR => self::COLOR_RED,
];
/**
* @var string Exists only for testing.
*/
private $eol = PHP_EOL;
/**
* @var resource Exists only for testing.
*/
private $stderr = STDERR;
/**
* @var bool
*/
private $supportsColor;
/**
* @param resource $resource
*/
public function __construct($resource = STDOUT)
{
$this->supportsColor = $this->detectColorCapabilities($resource);
}
/**
* Colorize a string for use with the terminal.
*
* Takes strings formatted as `<key>string</key>` and formats them per the
* $highlightMap; if color support is disabled, simply removes the formatting
* tags.
*
* @param string $string
* @return string
*/
public function colorize($string)
{
$reset = $this->supportsColor ? self::COLOR_RESET : '';
foreach ($this->highlightMap as $key => $color) {
$pattern = sprintf('#<%s>(.*?)</%s>#s', $key, $key);
$color = $this->supportsColor ? $color : '';
$string = preg_replace($pattern, $color . '$1' . $reset, $string);
}
return $string;
}
/**
* @param string $string
* @param bool $colorize Whether or not to colorize the string
* @param resource $resource Defaults to STDOUT
* @return void
*/
public function write($string, $colorize = true, $resource = STDOUT)
{
if ($colorize) {
$string = $this->colorize($string);
}
$string = $this->formatNewlines($string);
fwrite($resource, $string);
}
/**
* @param string $string
* @param bool $colorize Whether or not to colorize the line
* @param resource $resource Defaults to STDOUT
* @return void
*/
public function writeLine($string, $colorize = true, $resource = STDOUT)
{
$this->write($string . $this->eol, $colorize, $resource);
}
/**
* Emit an error message.
*
* Wraps the message in `<error></error>`, and passes it to `writeLine()`,
* using STDERR as the resource; emits an additional empty line when done,
* also to STDERR.
*
* @param string $message
* @return void
*/
public function writeErrorMessage($message)
{
$this->writeLine(sprintf('<error>%s</error>', $message), true, $this->stderr);
$this->writeLine('', false, $this->stderr);
}
/**
* @param resource $resource
* @return bool
*/
private function detectColorCapabilities($resource = STDOUT)
{
if ('\\' === DIRECTORY_SEPARATOR) {
// Windows
return false !== getenv('ANSICON')
|| 'ON' === getenv('ConEmuANSI')
|| 'xterm' === getenv('TERM');
}
return function_exists('posix_isatty') && posix_isatty($resource);
}
/**
* Ensure newlines are appropriate for the current terminal.
*
* @param string
* @return string
*/
private function formatNewlines($string)
{
$string = str_replace($this->eol, "\0PHP_EOL\0", $string);
$string = preg_replace("/(\r\n|\n|\r)/", $this->eol, $string);
return str_replace("\0PHP_EOL\0", $this->eol, $string);
}
}

View File

@@ -51,7 +51,7 @@ abstract class ErrorHandler
*/
public static function start($errorLevel = \E_WARNING)
{
if (! static::$stack) {
if (!static::$stack) {
set_error_handler([get_called_class(), 'addError'], $errorLevel);
}
@@ -72,7 +72,7 @@ abstract class ErrorHandler
if (static::$stack) {
$errorException = array_pop(static::$stack);
if (! static::$stack) {
if (!static::$stack) {
restore_error_handler();
}

View File

@@ -38,7 +38,7 @@ abstract class Glob
*/
public static function glob($pattern, $flags = 0, $forceFallback = false)
{
if (! defined('GLOB_BRACE') || $forceFallback) {
if (!defined('GLOB_BRACE') || $forceFallback) {
return static::fallbackGlob($pattern, $flags);
}
@@ -96,7 +96,7 @@ abstract class Glob
*/
protected static function fallbackGlob($pattern, $flags)
{
if (! $flags & self::GLOB_BRACE) {
if (!$flags & self::GLOB_BRACE) {
return static::systemGlob($pattern, $flags);
}
@@ -182,7 +182,7 @@ abstract class Glob
$current = $begin;
while ($current < $length) {
if (! $flags & self::GLOB_NOESCAPE && $pattern[$current] === '\\') {
if (!$flags & self::GLOB_NOESCAPE && $pattern[$current] === '\\') {
if (++$current === $length) {
break;
}

View File

@@ -29,7 +29,7 @@ trait ArrayOrTraversableGuardTrait
$dataName = 'Argument',
$exceptionClass = 'Zend\Stdlib\Exception\InvalidArgumentException'
) {
if (! is_array($data) && ! ($data instanceof Traversable)) {
if (!is_array($data) && !($data instanceof Traversable)) {
$message = sprintf(
"%s must be an array or Traversable, [%s] given",
$dataName,

View File

@@ -9,9 +9,6 @@
namespace Zend\Stdlib;
/**
* @deprecated Since 3.1.0; use the native JsonSerializable interface
*/
interface JsonSerializable extends \JsonSerializable
{
}

View File

@@ -40,7 +40,7 @@ class Message implements MessageInterface
$this->metadata[$spec] = $value;
return $this;
}
if (! is_array($spec) && ! $spec instanceof Traversable) {
if (!is_array($spec) && !$spec instanceof Traversable) {
throw new Exception\InvalidArgumentException(sprintf(
'Expected a string, array, or Traversable argument in first position; received "%s"',
(is_object($spec) ? get_class($spec) : gettype($spec))
@@ -66,7 +66,7 @@ class Message implements MessageInterface
return $this->metadata;
}
if (! is_scalar($key)) {
if (!is_scalar($key)) {
throw new Exception\InvalidArgumentException('Non-scalar argument provided for key');
}

View File

@@ -70,7 +70,7 @@ class Parameters extends PhpArrayObject implements ParametersInterface
*/
public function toString()
{
return http_build_query($this->toArray());
return http_build_query($this);
}
/**

View File

@@ -62,7 +62,7 @@ class PriorityList implements Iterator, Countable
*/
public function insert($name, $value, $priority = 0)
{
if (! isset($this->items[$name])) {
if (!isset($this->items[$name])) {
$this->count++;
}
@@ -85,7 +85,7 @@ class PriorityList implements Iterator, Countable
*/
public function setPriority($name, $priority)
{
if (! isset($this->items[$name])) {
if (!isset($this->items[$name])) {
throw new \Exception("item $name not found");
}
@@ -131,7 +131,7 @@ class PriorityList implements Iterator, Countable
*/
public function get($name)
{
if (! isset($this->items[$name])) {
if (!isset($this->items[$name])) {
return;
}
@@ -145,7 +145,7 @@ class PriorityList implements Iterator, Countable
*/
protected function sort()
{
if (! $this->sorted) {
if (!$this->sorted) {
uasort($this->items, [$this, 'compare']);
$this->sorted = true;
}
@@ -161,7 +161,7 @@ class PriorityList implements Iterator, Countable
protected function compare(array $item1, array $item2)
{
return ($item1['priority'] === $item2['priority'])
? ($item1['serial'] > $item2['serial'] ? -1 : 1) * $this->isLIFO
? ($item1['serial'] > $item2['serial'] ? -1 : 1) * $this->isLIFO
: ($item1['priority'] > $item2['priority'] ? -1 : 1);
}

View File

@@ -99,7 +99,7 @@ class PriorityQueue implements Countable, IteratorAggregate, Serializable
unset($this->items[$key]);
$this->queue = null;
if (! $this->isEmpty()) {
if (!$this->isEmpty()) {
$queue = $this->getQueue();
foreach ($this->items as $item) {
$queue->insert($item['data'], $item['priority']);
@@ -277,7 +277,7 @@ class PriorityQueue implements Countable, IteratorAggregate, Serializable
{
if (null === $this->queue) {
$this->queue = new $this->queueClass();
if (! $this->queue instanceof \SplPriorityQueue) {
if (!$this->queue instanceof \SplPriorityQueue) {
throw new Exception\DomainException(sprintf(
'PriorityQueue expects an internal queue of type SplPriorityQueue; received "%s"',
get_class($this->queue)

View File

@@ -36,7 +36,7 @@ class SplPriorityQueue extends \SplPriorityQueue implements Serializable
*/
public function insert($datum, $priority)
{
if (! is_array($priority)) {
if (!is_array($priority)) {
$priority = [$priority, $this->serial--];
}
parent::insert($datum, $priority);

View File

@@ -84,7 +84,7 @@ abstract class StringUtils
public static function registerWrapper($wrapper)
{
$wrapper = (string) $wrapper;
if (! in_array($wrapper, static::$wrapperRegistry, true)) {
if (!in_array($wrapper, static::$wrapperRegistry, true)) {
static::$wrapperRegistry[] = $wrapper;
}
}

View File

@@ -38,11 +38,11 @@ abstract class AbstractStringWrapper implements StringWrapperInterface
{
$supportedEncodings = static::getSupportedEncodings();
if (! in_array(strtoupper($encoding), $supportedEncodings)) {
if (!in_array(strtoupper($encoding), $supportedEncodings)) {
return false;
}
if ($convertEncoding !== null && ! in_array(strtoupper($convertEncoding), $supportedEncodings)) {
if ($convertEncoding !== null && !in_array(strtoupper($convertEncoding), $supportedEncodings)) {
return false;
}
@@ -61,7 +61,7 @@ abstract class AbstractStringWrapper implements StringWrapperInterface
$supportedEncodings = static::getSupportedEncodings();
$encodingUpper = strtoupper($encoding);
if (! in_array($encodingUpper, $supportedEncodings)) {
if (!in_array($encodingUpper, $supportedEncodings)) {
throw new Exception\InvalidArgumentException(
'Wrapper doesn\'t support character encoding "' . $encoding . '"'
);
@@ -69,7 +69,7 @@ abstract class AbstractStringWrapper implements StringWrapperInterface
if ($convertEncoding !== null) {
$convertEncodingUpper = strtoupper($convertEncoding);
if (! in_array($convertEncodingUpper, $supportedEncodings)) {
if (!in_array($convertEncodingUpper, $supportedEncodings)) {
throw new Exception\InvalidArgumentException(
'Wrapper doesn\'t support character encoding "' . $convertEncoding . '"'
);

View File

@@ -214,7 +214,7 @@ class Iconv extends AbstractStringWrapper
*/
public function __construct()
{
if (! extension_loaded('iconv')) {
if (!extension_loaded('iconv')) {
throw new Exception\ExtensionNotLoadedException(
'PHP extension "iconv" is required for this wrapper'
);

View File

@@ -37,7 +37,7 @@ class Intl extends AbstractStringWrapper
*/
public function __construct()
{
if (! extension_loaded('intl')) {
if (!extension_loaded('intl')) {
throw new Exception\ExtensionNotLoadedException(
'PHP extension "intl" is required for this wrapper'
);

View File

@@ -48,7 +48,7 @@ class MbString extends AbstractStringWrapper
*/
public function __construct()
{
if (! extension_loaded('mbstring')) {
if (!extension_loaded('mbstring')) {
throw new Exception\ExtensionNotLoadedException(
'PHP extension "mbstring" is required for this wrapper'
);

View File

@@ -35,7 +35,7 @@ class Native extends AbstractStringWrapper
$encodingUpper = strtoupper($encoding);
$supportedEncodings = static::getSupportedEncodings();
if (! in_array($encodingUpper, $supportedEncodings)) {
if (!in_array($encodingUpper, $supportedEncodings)) {
return false;
}
@@ -69,7 +69,7 @@ class Native extends AbstractStringWrapper
$supportedEncodings = static::getSupportedEncodings();
$encodingUpper = strtoupper($encoding);
if (! in_array($encodingUpper, $supportedEncodings)) {
if (!in_array($encodingUpper, $supportedEncodings)) {
throw new Exception\InvalidArgumentException(
'Wrapper doesn\'t support character encoding "' . $encoding . '"'
);