ALPHA 3.0.2a

This commit is contained in:
TheGamecraft
2018-09-10 08:51:18 -04:00
parent 7fe13ae0a7
commit 0e0ef86b71
1404 changed files with 10604 additions and 33714 deletions

0
vendor/psy/psysh/bin/build-stub vendored Normal file → Executable file
View File

0
vendor/psy/psysh/bin/psysh vendored Normal file → Executable file
View File

View File

@@ -14,6 +14,8 @@
],
"require": {
"php": ">=5.4.0",
"ext-json": "*",
"ext-tokenizer": "*",
"symfony/console": "~2.3.10|^2.4.2|~3.0|~4.0",
"symfony/var-dumper": "~2.7|~3.0|~4.0",
"nikic/php-parser": "~1.3|~2.0|~3.0|~4.0",

View File

@@ -138,7 +138,7 @@ class CodeCleaner
}
try {
$code = @file_get_contents($file);
$code = @\file_get_contents($file);
if (!$code) {
return;
}
@@ -169,15 +169,15 @@ class CodeCleaner
*/
private static function getDebugFile()
{
$trace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS);
$trace = \debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS);
foreach (array_reverse($trace) as $stackFrame) {
foreach (\array_reverse($trace) as $stackFrame) {
if (!self::isDebugCall($stackFrame)) {
continue;
}
if (preg_match('/eval\(/', $stackFrame['file'])) {
preg_match_all('/([^\(]+)\((\d+)/', $stackFrame['file'], $matches);
if (\preg_match('/eval\(/', $stackFrame['file'])) {
\preg_match_all('/([^\(]+)\((\d+)/', $stackFrame['file'], $matches);
return $matches[1][0];
}
@@ -214,7 +214,7 @@ class CodeCleaner
*/
public function clean(array $codeLines, $requireSemicolons = false)
{
$stmts = $this->parse('<?php ' . implode(PHP_EOL, $codeLines) . PHP_EOL, $requireSemicolons);
$stmts = $this->parse('<?php ' . \implode(PHP_EOL, $codeLines) . PHP_EOL, $requireSemicolons);
if ($stmts === false) {
return false;
}
@@ -223,13 +223,13 @@ class CodeCleaner
$stmts = $this->traverser->traverse($stmts);
// Work around https://github.com/nikic/PHP-Parser/issues/399
$oldLocale = setlocale(LC_NUMERIC, 0);
setlocale(LC_NUMERIC, 'C');
$oldLocale = \setlocale(LC_NUMERIC, 0);
\setlocale(LC_NUMERIC, 'C');
$code = $this->printer->prettyPrint($stmts);
// Now put the locale back
setlocale(LC_NUMERIC, $oldLocale);
\setlocale(LC_NUMERIC, $oldLocale);
return $code;
}
@@ -307,7 +307,7 @@ class CodeCleaner
{
$msg = $e->getRawMessage();
return ($msg === 'Unexpected token EOF') || (strpos($msg, 'Syntax error, unexpected EOF') !== false);
return ($msg === 'Unexpected token EOF') || (\strpos($msg, 'Syntax error, unexpected EOF') !== false);
}
/**
@@ -344,6 +344,6 @@ class CodeCleaner
private function parseErrorIsTrailingComma(\PhpParser\Error $e, $code)
{
return ($e->getRawMessage() === 'A trailing comma is not allowed here') && (substr(rtrim($code), -1) === ',');
return ($e->getRawMessage() === 'A trailing comma is not allowed here') && (\substr(\rtrim($code), -1) === ',');
}
}

View File

@@ -36,11 +36,11 @@ class AbstractClassPass extends CodeCleanerPass
$this->abstractMethods = [];
} elseif ($node instanceof ClassMethod) {
if ($node->isAbstract()) {
$name = sprintf('%s::%s', $this->class->name, $node->name);
$name = \sprintf('%s::%s', $this->class->name, $node->name);
$this->abstractMethods[] = $name;
if ($node->stmts !== null) {
$msg = sprintf('Abstract function %s cannot contain body', $name);
$msg = \sprintf('Abstract function %s cannot contain body', $name);
throw new FatalErrorException($msg, 0, E_ERROR, null, $node->getLine());
}
}
@@ -55,14 +55,14 @@ class AbstractClassPass extends CodeCleanerPass
public function leaveNode(Node $node)
{
if ($node instanceof Class_) {
$count = count($this->abstractMethods);
$count = \count($this->abstractMethods);
if ($count > 0 && !$node->isAbstract()) {
$msg = sprintf(
$msg = \sprintf(
'Class %s contains %d abstract method%s must therefore be declared abstract or implement the remaining methods (%s)',
$node->name,
$count,
($count === 1) ? '' : 's',
implode(', ', $this->abstractMethods)
\implode(', ', $this->abstractMethods)
);
throw new FatalErrorException($msg, 0, E_ERROR, null, $node->getLine());
}

View File

@@ -58,9 +58,9 @@ class CalledClassPass extends CodeCleanerPass
return;
}
$name = strtolower($node->name);
if (in_array($name, ['get_class', 'get_called_class'])) {
$msg = sprintf('%s() called without object from outside a class', $name);
$name = \strtolower($node->name);
if (\in_array($name, ['get_class', 'get_called_class'])) {
$msg = \sprintf('%s() called without object from outside a class', $name);
throw new ErrorException($msg, 0, E_USER_WARNING, null, $node->getLine());
}
}
@@ -78,6 +78,6 @@ class CalledClassPass extends CodeCleanerPass
private function isNull(Node $node)
{
return $node->value instanceof ConstFetch && strtolower($node->value->name) === 'null';
return $node->value instanceof ConstFetch && \strtolower($node->value->name) === 'null';
}
}

View File

@@ -41,13 +41,13 @@ class FinalClassPass extends CodeCleanerPass
if ($node->extends) {
$extends = (string) $node->extends;
if ($this->isFinalClass($extends)) {
$msg = sprintf('Class %s may not inherit from final class (%s)', $node->name, $extends);
$msg = \sprintf('Class %s may not inherit from final class (%s)', $node->name, $extends);
throw new FatalErrorException($msg, 0, E_ERROR, null, $node->getLine());
}
}
if ($node->isFinal()) {
$this->finalClasses[strtolower($node->name)] = true;
$this->finalClasses[\strtolower($node->name)] = true;
}
}
}
@@ -59,8 +59,8 @@ class FinalClassPass extends CodeCleanerPass
*/
private function isFinalClass($name)
{
if (!class_exists($name)) {
return isset($this->finalClasses[strtolower($name)]);
if (!\class_exists($name)) {
return isset($this->finalClasses[\strtolower($name)]);
}
$refl = new \ReflectionClass($name);

View File

@@ -36,7 +36,7 @@ class FunctionReturnInWriteContextPass extends CodeCleanerPass
public function __construct()
{
$this->atLeastPhp55 = version_compare(PHP_VERSION, '5.5', '>=');
$this->atLeastPhp55 = \version_compare(PHP_VERSION, '5.5', '>=');
}
/**

View File

@@ -49,7 +49,7 @@ class ImplicitReturnPass extends CodeCleanerPass
return [new Return_(NoReturnValue::create())];
}
$last = end($nodes);
$last = \end($nodes);
// Special case a few types of statements to add an implicit return
// value (even though they technically don't have any return value)
@@ -68,22 +68,22 @@ class ImplicitReturnPass extends CodeCleanerPass
} elseif ($last instanceof Switch_) {
foreach ($last->cases as $case) {
// only add an implicit return to cases which end in break
$caseLast = end($case->stmts);
$caseLast = \end($case->stmts);
if ($caseLast instanceof Break_) {
$case->stmts = $this->addImplicitReturn(array_slice($case->stmts, 0, -1));
$case->stmts = $this->addImplicitReturn(\array_slice($case->stmts, 0, -1));
$case->stmts[] = $caseLast;
}
}
} elseif ($last instanceof Expr && !($last instanceof Exit_)) {
// @codeCoverageIgnoreStart
$nodes[count($nodes) - 1] = new Return_($last, [
$nodes[\count($nodes) - 1] = new Return_($last, [
'startLine' => $last->getLine(),
'endLine' => $last->getLine(),
]);
// @codeCoverageIgnoreEnd
} elseif ($last instanceof Expression && !($last->expr instanceof Exit_)) {
// For PHP Parser 4.x
$nodes[count($nodes) - 1] = new Return_($last->expr, [
$nodes[\count($nodes) - 1] = new Return_($last->expr, [
'startLine' => $last->getLine(),
'endLine' => $last->getLine(),
]);

View File

@@ -28,7 +28,7 @@ class LegacyEmptyPass extends CodeCleanerPass
public function __construct()
{
$this->atLeastPhp55 = version_compare(PHP_VERSION, '5.5', '>=');
$this->atLeastPhp55 = \version_compare(PHP_VERSION, '5.5', '>=');
}
/**
@@ -49,7 +49,7 @@ class LegacyEmptyPass extends CodeCleanerPass
}
if (!$node->expr instanceof Variable) {
$msg = sprintf('syntax error, unexpected %s', $this->getUnexpectedThing($node->expr));
$msg = \sprintf('syntax error, unexpected %s', $this->getUnexpectedThing($node->expr));
throw new ParseErrorException($msg, $node->expr->getLine());
}
@@ -61,7 +61,7 @@ class LegacyEmptyPass extends CodeCleanerPass
case 'Scalar_String':
case 'Scalar_LNumber':
case 'Scalar_DNumber':
return json_encode($node->value);
return \json_encode($node->value);
case 'Expr_ConstFetch':
return (string) $node->name;

View File

@@ -12,10 +12,13 @@
namespace Psy\CodeCleaner;
use PhpParser\Node;
use PhpParser\Node\Expr;
use PhpParser\Node\Expr\Array_;
use PhpParser\Node\Expr\ArrayDimFetch;
use PhpParser\Node\Expr\ArrayItem;
use PhpParser\Node\Expr\Assign;
use PhpParser\Node\Expr\List_;
use PhpParser\Node\Expr\PropertyFetch;
use PhpParser\Node\Expr\Variable;
use Psy\Exception\ParseErrorException;
@@ -28,7 +31,7 @@ class ListPass extends CodeCleanerPass
public function __construct()
{
$this->atLeastPhp71 = version_compare(PHP_VERSION, '7.1', '>=');
$this->atLeastPhp71 = \version_compare(PHP_VERSION, '7.1', '>=');
}
/**
@@ -74,9 +77,7 @@ class ListPass extends CodeCleanerPass
throw new ParseErrorException($msg, $item->key->getLine());
}
$value = ($item instanceof ArrayItem) ? $item->value : $item;
if (!$value instanceof Variable) {
if (!self::isValidArrayItem($item)) {
$msg = 'Assignments can only happen to writable values';
throw new ParseErrorException($msg, $item->getLine());
}
@@ -86,4 +87,26 @@ class ListPass extends CodeCleanerPass
throw new ParseErrorException('Cannot use empty list');
}
}
/**
* Validate whether a given item in an array is valid for short assignment.
*
* @param Expr $item
*
* @return bool
*/
private static function isValidArrayItem(Expr $item)
{
$value = ($item instanceof ArrayItem) ? $item->value : $item;
if ($value instanceof Variable) {
return true;
}
if ($value instanceof ArrayDimFetch || $value instanceof PropertyFetch) {
return isset($value->var) && $value->var instanceof Variable;
}
return false;
}
}

View File

@@ -62,23 +62,23 @@ class LoopContextPass extends CodeCleanerPass
$operator = $node instanceof Break_ ? 'break' : 'continue';
if ($this->loopDepth === 0) {
$msg = sprintf("'%s' not in the 'loop' or 'switch' context", $operator);
$msg = \sprintf("'%s' not in the 'loop' or 'switch' context", $operator);
throw new FatalErrorException($msg, 0, E_ERROR, null, $node->getLine());
}
if ($node->num instanceof LNumber || $node->num instanceof DNumber) {
$num = $node->num->value;
if ($node->num instanceof DNumber || $num < 1) {
$msg = sprintf("'%s' operator accepts only positive numbers", $operator);
$msg = \sprintf("'%s' operator accepts only positive numbers", $operator);
throw new FatalErrorException($msg, 0, E_ERROR, null, $node->getLine());
}
if ($num > $this->loopDepth) {
$msg = sprintf("Cannot '%s' %d levels", $operator, $num);
$msg = \sprintf("Cannot '%s' %d levels", $operator, $num);
throw new FatalErrorException($msg, 0, E_ERROR, null, $node->getLine());
}
} elseif ($node->num) {
$msg = sprintf("'%s' operator with non-constant operand is no longer supported", $operator);
$msg = \sprintf("'%s' operator with non-constant operand is no longer supported", $operator);
throw new FatalErrorException($msg, 0, E_ERROR, null, $node->getLine());
}
break;

View File

@@ -59,13 +59,13 @@ abstract class NamespaceAwarePass extends CodeCleanerPass
protected function getFullyQualifiedName($name)
{
if ($name instanceof FullyQualifiedName) {
return implode('\\', $name->parts);
return \implode('\\', $name->parts);
} elseif ($name instanceof Name) {
$name = $name->parts;
} elseif (!is_array($name)) {
} elseif (!\is_array($name)) {
$name = [$name];
}
return implode('\\', array_merge($this->namespace, $name));
return \implode('\\', \array_merge($this->namespace, $name));
}
}

View File

@@ -53,7 +53,7 @@ class NamespacePass extends CodeCleanerPass
return $nodes;
}
$last = end($nodes);
$last = \end($nodes);
if ($last instanceof Namespace_) {
$kind = $last->getAttribute('kind');

View File

@@ -56,7 +56,7 @@ class PassableByReferencePass extends CodeCleanerPass
}
foreach ($refl->getParameters() as $key => $param) {
if (array_key_exists($key, $node->args)) {
if (\array_key_exists($key, $node->args)) {
$arg = $node->args[$key];
if ($param->isPassedByReference() && !$this->isPassableByReference($arg)) {
throw new FatalErrorException(self::EXCEPTION_MESSAGE, 0, E_ERROR, null, $node->getLine());

View File

@@ -79,16 +79,15 @@ class RequirePass extends CodeCleanerPass
// @todo Shell::handleError would be better here, because we could
// fake the file and line number, but we can't call it statically.
// So we're duplicating some of the logics here.
if (E_WARNING & error_reporting()) {
if (E_WARNING & \error_reporting()) {
ErrorException::throwException(E_WARNING, 'Filename cannot be empty', null, $lineNumber);
} else {
// @todo trigger an error as fallback? this is pretty ugly…
// trigger_error('Filename cannot be empty', E_USER_WARNING);
}
// @todo trigger an error as fallback? this is pretty ugly…
// trigger_error('Filename cannot be empty', E_USER_WARNING);
}
if ($file === '' || !stream_resolve_include_path($file)) {
$msg = sprintf("Failed opening required '%s'", $file);
if ($file === '' || !\stream_resolve_include_path($file)) {
$msg = \sprintf("Failed opening required '%s'", $file);
throw new FatalErrorException($msg, 0, E_ERROR, null, $lineNumber);
}
@@ -97,6 +96,6 @@ class RequirePass extends CodeCleanerPass
private function isRequireNode(Node $node)
{
return $node instanceof Include_ && in_array($node->type, self::$requireTypes);
return $node instanceof Include_ && \in_array($node->type, self::$requireTypes);
}
}

View File

@@ -36,7 +36,7 @@ class StrictTypesPass extends CodeCleanerPass
public function __construct()
{
$this->atLeastPhp7 = version_compare(PHP_VERSION, '7.0', '>=');
$this->atLeastPhp7 = \version_compare(PHP_VERSION, '7.0', '>=');
}
/**
@@ -75,10 +75,10 @@ class StrictTypesPass extends CodeCleanerPass
}
if ($prependStrictTypes) {
$first = reset($nodes);
$first = \reset($nodes);
if (!$first instanceof Declare_) {
$declare = new Declare_([new DeclareDeclare('strict_types', new LNumber(1))]);
array_unshift($nodes, $declare);
\array_unshift($nodes, $declare);
}
}

View File

@@ -49,7 +49,7 @@ class UseStatementPass extends CodeCleanerPass
if ($node instanceof Namespace_) {
// If this is the same namespace as last namespace, let's do ourselves
// a favor and reload all the aliases...
if (strtolower($node->name) === strtolower($this->lastNamespace)) {
if (\strtolower($node->name) === \strtolower($this->lastNamespace)) {
$this->aliases = $this->lastAliases;
}
}
@@ -69,8 +69,8 @@ class UseStatementPass extends CodeCleanerPass
// Store a reference to every "use" statement, because we'll need
// them in a bit.
foreach ($node->uses as $use) {
$alias = $use->alias ?: end($use->name->parts);
$this->aliases[strtolower($alias)] = $use->name;
$alias = $use->alias ?: \end($use->name->parts);
$this->aliases[\strtolower($alias)] = $use->name;
}
return NodeTraverser::REMOVE_NODE;
@@ -78,8 +78,8 @@ class UseStatementPass extends CodeCleanerPass
// Expand every "use" statement in the group into a full, standalone
// "use" and store 'em with the others.
foreach ($node->uses as $use) {
$alias = $use->alias ?: end($use->name->parts);
$this->aliases[strtolower($alias)] = Name::concat($node->prefix, $use->name, [
$alias = $use->alias ?: \end($use->name->parts);
$this->aliases[\strtolower($alias)] = Name::concat($node->prefix, $use->name, [
'startLine' => $node->prefix->getAttribute('startLine'),
'endLine' => $use->name->getAttribute('endLine'),
]);
@@ -114,12 +114,12 @@ class UseStatementPass extends CodeCleanerPass
*/
private function findAlias(Name $name)
{
$that = strtolower($name);
$that = \strtolower($name);
foreach ($this->aliases as $alias => $prefix) {
if ($that === $alias) {
return new FullyQualifiedName($prefix->toString());
} elseif (substr($that, 0, strlen($alias) + 1) === $alias . '\\') {
return new FullyQualifiedName($prefix->toString() . substr($name, strlen($alias)));
} elseif (\substr($that, 0, \strlen($alias) + 1) === $alias . '\\') {
return new FullyQualifiedName($prefix->toString() . \substr($name, \strlen($alias)));
}
}
}

View File

@@ -43,7 +43,7 @@ class ValidClassNamePass extends NamespaceAwarePass
public function __construct()
{
$this->atLeastPhp55 = version_compare(PHP_VERSION, '5.5', '>=');
$this->atLeastPhp55 = \version_compare(PHP_VERSION, '5.5', '>=');
}
/**
@@ -164,7 +164,7 @@ class ValidClassNamePass extends NamespaceAwarePass
protected function validateClassConstFetchExpression(ClassConstFetch $stmt)
{
// there is no need to check exists for ::class const for php 5.5 or newer
if (strtolower($stmt->name) === 'class' && $this->atLeastPhp55) {
if (\strtolower($stmt->name) === 'class' && $this->atLeastPhp55) {
return;
}
@@ -210,12 +210,12 @@ class ValidClassNamePass extends NamespaceAwarePass
}
if ($errorType !== null) {
throw $this->createError(sprintf('%s named %s already exists', ucfirst($errorType), $name), $stmt);
throw $this->createError(\sprintf('%s named %s already exists', \ucfirst($errorType), $name), $stmt);
}
// Store creation for the rest of this code snippet so we can find local
// issue too
$this->currentScope[strtolower($name)] = $scopeType;
$this->currentScope[\strtolower($name)] = $scopeType;
}
/**
@@ -229,7 +229,7 @@ class ValidClassNamePass extends NamespaceAwarePass
protected function ensureClassExists($name, $stmt)
{
if (!$this->classExists($name)) {
throw $this->createError(sprintf('Class \'%s\' not found', $name), $stmt);
throw $this->createError(\sprintf('Class \'%s\' not found', $name), $stmt);
}
}
@@ -244,7 +244,22 @@ class ValidClassNamePass extends NamespaceAwarePass
protected function ensureClassOrInterfaceExists($name, $stmt)
{
if (!$this->classExists($name) && !$this->interfaceExists($name)) {
throw $this->createError(sprintf('Class \'%s\' not found', $name), $stmt);
throw $this->createError(\sprintf('Class \'%s\' not found', $name), $stmt);
}
}
/**
* Ensure that a referenced class _or trait_ exists.
*
* @throws FatalErrorException
*
* @param string $name
* @param Stmt $stmt
*/
protected function ensureClassOrTraitExists($name, $stmt)
{
if (!$this->classExists($name) && !$this->traitExists($name)) {
throw $this->createError(\sprintf('Class \'%s\' not found', $name), $stmt);
}
}
@@ -259,10 +274,10 @@ class ValidClassNamePass extends NamespaceAwarePass
*/
protected function ensureMethodExists($class, $name, $stmt)
{
$this->ensureClassExists($class, $stmt);
$this->ensureClassOrTraitExists($class, $stmt);
// let's pretend all calls to self, parent and static are valid
if (in_array(strtolower($class), ['self', 'parent', 'static'])) {
if (\in_array(\strtolower($class), ['self', 'parent', 'static'])) {
return;
}
@@ -276,8 +291,8 @@ class ValidClassNamePass extends NamespaceAwarePass
return;
}
if (!method_exists($class, $name) && !method_exists($class, '__callStatic')) {
throw $this->createError(sprintf('Call to undefined method %s::%s()', $class, $name), $stmt);
if (!\method_exists($class, $name) && !\method_exists($class, '__callStatic')) {
throw $this->createError(\sprintf('Call to undefined method %s::%s()', $class, $name), $stmt);
}
}
@@ -295,7 +310,7 @@ class ValidClassNamePass extends NamespaceAwarePass
/** @var string $name */
$name = $this->getFullyQualifiedName($interface);
if (!$this->interfaceExists($name)) {
throw $this->createError(sprintf('Interface \'%s\' not found', $name), $stmt);
throw $this->createError(\sprintf('Interface \'%s\' not found', $name), $stmt);
}
}
}
@@ -335,11 +350,11 @@ class ValidClassNamePass extends NamespaceAwarePass
// Give `self`, `static` and `parent` a pass. This will actually let
// some errors through, since we're not checking whether the keyword is
// being used in a class scope.
if (in_array(strtolower($name), ['self', 'static', 'parent'])) {
if (\in_array(\strtolower($name), ['self', 'static', 'parent'])) {
return true;
}
return class_exists($name) || $this->findInScope($name) === self::CLASS_TYPE;
return \class_exists($name) || $this->findInScope($name) === self::CLASS_TYPE;
}
/**
@@ -351,7 +366,7 @@ class ValidClassNamePass extends NamespaceAwarePass
*/
protected function interfaceExists($name)
{
return interface_exists($name) || $this->findInScope($name) === self::INTERFACE_TYPE;
return \interface_exists($name) || $this->findInScope($name) === self::INTERFACE_TYPE;
}
/**
@@ -363,7 +378,7 @@ class ValidClassNamePass extends NamespaceAwarePass
*/
protected function traitExists($name)
{
return trait_exists($name) || $this->findInScope($name) === self::TRAIT_TYPE;
return \trait_exists($name) || $this->findInScope($name) === self::TRAIT_TYPE;
}
/**
@@ -375,7 +390,7 @@ class ValidClassNamePass extends NamespaceAwarePass
*/
protected function findInScope($name)
{
$name = strtolower($name);
$name = \strtolower($name);
if (isset($this->currentScope[$name])) {
return $this->currentScope[$name];
}

View File

@@ -43,10 +43,10 @@ class ValidConstantPass extends NamespaceAwarePass
*/
public function leaveNode(Node $node)
{
if ($node instanceof ConstFetch && count($node->name->parts) > 1) {
if ($node instanceof ConstFetch && \count($node->name->parts) > 1) {
$name = $this->getFullyQualifiedName($node->name);
if (!defined($name)) {
$msg = sprintf('Undefined constant %s', $name);
if (!\defined($name)) {
$msg = \sprintf('Undefined constant %s', $name);
throw new FatalErrorException($msg, 0, E_ERROR, null, $node->getLine());
}
} elseif ($node instanceof ClassConstFetch) {
@@ -77,11 +77,11 @@ class ValidConstantPass extends NamespaceAwarePass
// if the class doesn't exist, don't throw an exception… it might be
// defined in the same line it's used or something stupid like that.
if (class_exists($className) || interface_exists($className)) {
if (\class_exists($className) || \interface_exists($className)) {
$refl = new \ReflectionClass($className);
if (!$refl->hasConstant($constName)) {
$constType = class_exists($className) ? 'Class' : 'Interface';
$msg = sprintf('%s constant \'%s::%s\' not found', $constType, $className, $constName);
$constType = \class_exists($className) ? 'Class' : 'Interface';
$msg = \sprintf('%s constant \'%s::%s\' not found', $constType, $className, $constName);
throw new FatalErrorException($msg, 0, E_ERROR, null, $stmt->getLine());
}
}

View File

@@ -57,14 +57,14 @@ class ValidConstructorPass extends CodeCleanerPass
foreach ($node->stmts as $stmt) {
if ($stmt instanceof ClassMethod) {
// If we find a new-style constructor, no need to look for the old-style
if ('__construct' === strtolower($stmt->name)) {
if ('__construct' === \strtolower($stmt->name)) {
$this->validateConstructor($stmt, $node);
return;
}
// We found a possible old-style constructor (unless there is also a __construct method)
if (empty($this->namespace) && strtolower($node->name) === strtolower($stmt->name)) {
if (empty($this->namespace) && \strtolower($node->name) === \strtolower($stmt->name)) {
$constructor = $stmt;
}
}
@@ -89,21 +89,21 @@ class ValidConstructorPass extends CodeCleanerPass
// For PHP Parser 4.x
$className = $classNode->name instanceof Identifier ? $classNode->name->toString() : $classNode->name;
$msg = sprintf(
$msg = \sprintf(
'Constructor %s::%s() cannot be static',
implode('\\', array_merge($this->namespace, (array) $className)),
\implode('\\', \array_merge($this->namespace, (array) $className)),
$constructor->name
);
throw new FatalErrorException($msg, 0, E_ERROR, null, $classNode->getLine());
}
if (method_exists($constructor, 'getReturnType') && $constructor->getReturnType()) {
if (\method_exists($constructor, 'getReturnType') && $constructor->getReturnType()) {
// For PHP Parser 4.x
$className = $classNode->name instanceof Identifier ? $classNode->name->toString() : $classNode->name;
$msg = sprintf(
$msg = \sprintf(
'Constructor %s::%s() cannot declare a return type',
implode('\\', array_merge($this->namespace, (array) $className)),
\implode('\\', \array_merge($this->namespace, (array) $className)),
$constructor->name
);
throw new FatalErrorException($msg, 0, E_ERROR, null, $classNode->getLine());

View File

@@ -49,14 +49,14 @@ class ValidFunctionNamePass extends NamespaceAwarePass
// @todo add an "else" here which adds a runtime check for instances where we can't tell
// whether a function is being redefined by static analysis alone.
if ($this->conditionalScopes === 0) {
if (function_exists($name) ||
isset($this->currentScope[strtolower($name)])) {
$msg = sprintf('Cannot redeclare %s()', $name);
if (\function_exists($name) ||
isset($this->currentScope[\strtolower($name)])) {
$msg = \sprintf('Cannot redeclare %s()', $name);
throw new FatalErrorException($msg, 0, E_ERROR, null, $node->getLine());
}
}
$this->currentScope[strtolower($name)] = true;
$this->currentScope[\strtolower($name)] = true;
}
}
@@ -76,11 +76,11 @@ class ValidFunctionNamePass extends NamespaceAwarePass
// if function name is an expression or a variable, give it a pass for now.
$name = $node->name;
if (!$name instanceof Expr && !$name instanceof Variable) {
$shortName = implode('\\', $name->parts);
$shortName = \implode('\\', $name->parts);
$fullName = $this->getFullyQualifiedName($name);
$inScope = isset($this->currentScope[strtolower($fullName)]);
if (!$inScope && !function_exists($shortName) && !function_exists($fullName)) {
$message = sprintf('Call to undefined function %s()', $name);
$inScope = isset($this->currentScope[\strtolower($fullName)]);
if (!$inScope && !\function_exists($shortName) && !\function_exists($fullName)) {
$message = \sprintf('Call to undefined function %s()', $name);
throw new FatalErrorException($message, 0, E_ERROR, null, $node->getLine());
}
}

View File

@@ -68,10 +68,10 @@ HELP
*/
protected function formatLines(array $lines, $type = 'return')
{
$template = sprintf('<%s>%%s</%s>', $type, $type);
$template = \sprintf('<%s>%%s</%s>', $type, $type);
return array_map(function ($line) use ($template) {
return sprintf($template, $line);
return \array_map(function ($line) use ($template) {
return \sprintf($template, $line);
}, $lines);
}
}

View File

@@ -44,6 +44,6 @@ HELP
*/
protected function execute(InputInterface $input, OutputInterface $output)
{
$output->write(sprintf('%c[2J%c[0;0f', 27, 27));
$output->write(\sprintf('%c[2J%c[0;0f', 27, 27));
}
}

View File

@@ -65,10 +65,10 @@ abstract class Command extends BaseCommand
if ($help = $this->getProcessedHelp()) {
$messages[] = '<comment>Help:</comment>';
$messages[] = ' ' . str_replace("\n", "\n ", $help) . "\n";
$messages[] = ' ' . \str_replace("\n", "\n ", $help) . "\n";
}
return implode("\n", $messages);
return \implode("\n", $messages);
}
/**
@@ -78,8 +78,8 @@ abstract class Command extends BaseCommand
{
$hidden = $this->getHiddenArguments();
return array_filter($this->getNativeDefinition()->getArguments(), function ($argument) use ($hidden) {
return !in_array($argument->getName(), $hidden);
return \array_filter($this->getNativeDefinition()->getArguments(), function ($argument) use ($hidden) {
return !\in_array($argument->getName(), $hidden);
});
}
@@ -100,8 +100,8 @@ abstract class Command extends BaseCommand
{
$hidden = $this->getHiddenOptions();
return array_filter($this->getNativeDefinition()->getOptions(), function ($option) use ($hidden) {
return !in_array($option->getName(), $hidden);
return \array_filter($this->getNativeDefinition()->getOptions(), function ($option) use ($hidden) {
return !\in_array($option->getName(), $hidden);
});
}
@@ -122,7 +122,7 @@ abstract class Command extends BaseCommand
*/
private function aliasesAsText()
{
return '<comment>Aliases:</comment> <info>' . implode(', ', $this->getAliases()) . '</info>' . PHP_EOL;
return '<comment>Aliases:</comment> <info>' . \implode(', ', $this->getAliases()) . '</info>' . PHP_EOL;
}
/**
@@ -139,21 +139,21 @@ abstract class Command extends BaseCommand
if (!empty($arguments)) {
$messages[] = '<comment>Arguments:</comment>';
foreach ($arguments as $argument) {
if (null !== $argument->getDefault() && (!is_array($argument->getDefault()) || count($argument->getDefault()))) {
$default = sprintf('<comment> (default: %s)</comment>', $this->formatDefaultValue($argument->getDefault()));
if (null !== $argument->getDefault() && (!\is_array($argument->getDefault()) || \count($argument->getDefault()))) {
$default = \sprintf('<comment> (default: %s)</comment>', $this->formatDefaultValue($argument->getDefault()));
} else {
$default = '';
}
$description = str_replace("\n", "\n" . str_pad('', $max + 2, ' '), $argument->getDescription());
$description = \str_replace("\n", "\n" . \str_pad('', $max + 2, ' '), $argument->getDescription());
$messages[] = sprintf(" <info>%-${max}s</info> %s%s", $argument->getName(), $description, $default);
$messages[] = \sprintf(" <info>%-${max}s</info> %s%s", $argument->getName(), $description, $default);
}
$messages[] = '';
}
return implode(PHP_EOL, $messages);
return \implode(PHP_EOL, $messages);
}
/**
@@ -171,20 +171,20 @@ abstract class Command extends BaseCommand
$messages[] = '<comment>Options:</comment>';
foreach ($options as $option) {
if ($option->acceptValue() && null !== $option->getDefault() && (!is_array($option->getDefault()) || count($option->getDefault()))) {
$default = sprintf('<comment> (default: %s)</comment>', $this->formatDefaultValue($option->getDefault()));
if ($option->acceptValue() && null !== $option->getDefault() && (!\is_array($option->getDefault()) || \count($option->getDefault()))) {
$default = \sprintf('<comment> (default: %s)</comment>', $this->formatDefaultValue($option->getDefault()));
} else {
$default = '';
}
$multiple = $option->isArray() ? '<comment> (multiple values allowed)</comment>' : '';
$description = str_replace("\n", "\n" . str_pad('', $max + 2, ' '), $option->getDescription());
$description = \str_replace("\n", "\n" . \str_pad('', $max + 2, ' '), $option->getDescription());
$optionMax = $max - strlen($option->getName()) - 2;
$messages[] = sprintf(
$optionMax = $max - \strlen($option->getName()) - 2;
$messages[] = \sprintf(
" <info>%s</info> %-${optionMax}s%s%s%s",
'--' . $option->getName(),
$option->getShortcut() ? sprintf('(-%s) ', $option->getShortcut()) : '',
$option->getShortcut() ? \sprintf('(-%s) ', $option->getShortcut()) : '',
$description,
$default,
$multiple
@@ -194,7 +194,7 @@ abstract class Command extends BaseCommand
$messages[] = '';
}
return implode(PHP_EOL, $messages);
return \implode(PHP_EOL, $messages);
}
/**
@@ -207,16 +207,16 @@ abstract class Command extends BaseCommand
$max = 0;
foreach ($this->getOptions() as $option) {
$nameLength = strlen($option->getName()) + 2;
$nameLength = \strlen($option->getName()) + 2;
if ($option->getShortcut()) {
$nameLength += strlen($option->getShortcut()) + 3;
$nameLength += \strlen($option->getShortcut()) + 3;
}
$max = max($max, $nameLength);
$max = \max($max, $nameLength);
}
foreach ($this->getArguments() as $argument) {
$max = max($max, strlen($argument->getName()));
$max = \max($max, \strlen($argument->getName()));
}
return ++$max;
@@ -231,11 +231,11 @@ abstract class Command extends BaseCommand
*/
private function formatDefaultValue($default)
{
if (is_array($default) && $default === array_values($default)) {
return sprintf("array('%s')", implode("', '", $default));
if (\is_array($default) && $default === \array_values($default)) {
return \sprintf("array('%s')", \implode("', '", $default));
}
return str_replace("\n", '', var_export($default, true));
return \str_replace("\n", '', \var_export($default, true));
}
/**
@@ -247,7 +247,7 @@ abstract class Command extends BaseCommand
*/
protected function getTable(OutputInterface $output)
{
if (!class_exists('Symfony\Component\Console\Helper\Table')) {
if (!\class_exists('Symfony\Component\Console\Helper\Table')) {
return $this->getTableHelper();
}

View File

@@ -14,7 +14,6 @@ namespace Psy\Command;
use Psy\Formatter\DocblockFormatter;
use Psy\Formatter\SignatureFormatter;
use Psy\Input\CodeArgument;
use Psy\Reflection\ReflectionClassConstant;
use Psy\Reflection\ReflectionLanguageConstruct;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
@@ -87,7 +86,7 @@ HELP
private function getManualDoc($reflector)
{
switch (get_class($reflector)) {
switch (\get_class($reflector)) {
case 'ReflectionClass':
case 'ReflectionObject':
case 'ReflectionFunction':
@@ -125,7 +124,7 @@ HELP
{
if ($db = $this->getApplication()->getManualDb()) {
return $db
->query(sprintf('SELECT doc FROM php_manual WHERE id = %s', $db->quote($id)))
->query(\sprintf('SELECT doc FROM php_manual WHERE id = %s', $db->quote($id)))
->fetchColumn(0);
}
}

View File

@@ -73,7 +73,7 @@ HELP
$target = $this->resolveCode($input->getArgument('target'));
$output->page($this->presenter->present($target, $depth, $input->getOption('all') ? Presenter::VERBOSE : 0));
if (is_object($target)) {
if (\is_object($target)) {
$this->setCommandScopeVariables(new \ReflectionObject($target));
}
}
@@ -87,7 +87,7 @@ HELP
*/
protected function resolveTarget($name)
{
@trigger_error('`resolveTarget` is deprecated; use `resolveCode` instead.', E_USER_DEPRECATED);
@\trigger_error('`resolveTarget` is deprecated; use `resolveCode` instead.', E_USER_DEPRECATED);
return $this->resolveCode($name);
}

View File

@@ -95,7 +95,7 @@ class EditCommand extends Command implements ContextAware
$shouldRemoveFile = false;
if ($filePath === null) {
$filePath = tempnam($this->runtimeDir, 'psysh-edit-command');
$filePath = \tempnam($this->runtimeDir, 'psysh-edit-command');
$shouldRemoveFile = true;
}
@@ -138,9 +138,9 @@ class EditCommand extends Command implements ContextAware
{
// If the file argument was a variable, get it from the context
if ($fileArgument !== null &&
strlen($fileArgument) > 0 &&
\strlen($fileArgument) > 0 &&
$fileArgument[0] === '$') {
$fileArgument = $this->context->get(preg_replace('/^\$/', '', $fileArgument));
$fileArgument = $this->context->get(\preg_replace('/^\$/', '', $fileArgument));
}
return $fileArgument;
@@ -156,16 +156,16 @@ class EditCommand extends Command implements ContextAware
*/
private function editFile($filePath, $shouldRemoveFile)
{
$escapedFilePath = escapeshellarg($filePath);
$escapedFilePath = \escapeshellarg($filePath);
$pipes = [];
$proc = proc_open((getenv('EDITOR') ?: 'nano') . " {$escapedFilePath}", [STDIN, STDOUT, STDERR], $pipes);
proc_close($proc);
$proc = \proc_open((\getenv('EDITOR') ?: 'nano') . " {$escapedFilePath}", [STDIN, STDOUT, STDERR], $pipes);
\proc_close($proc);
$editedContent = @file_get_contents($filePath);
$editedContent = @\file_get_contents($filePath);
if ($shouldRemoveFile) {
@unlink($filePath);
@\unlink($filePath);
}
if ($editedContent === false) {

View File

@@ -74,13 +74,13 @@ class HelpCommand extends Command
}
if ($command->getAliases()) {
$aliases = sprintf('<comment>Aliases:</comment> %s', implode(', ', $command->getAliases()));
$aliases = \sprintf('<comment>Aliases:</comment> %s', \implode(', ', $command->getAliases()));
} else {
$aliases = '';
}
$table->addRow([
sprintf('<info>%s</info>', $name),
\sprintf('<info>%s</info>', $name),
$command->getDescription(),
$aliases,
]);

View File

@@ -110,11 +110,11 @@ HELP
foreach ($history as $i => $line) {
if ($this->filter->match($line, $matches)) {
if (isset($matches[0])) {
$chunks = explode($matches[0], $history[$i]);
$chunks = array_map([__CLASS__, 'escape'], $chunks);
$glue = sprintf('<urgent>%s</urgent>', self::escape($matches[0]));
$chunks = \explode($matches[0], $history[$i]);
$chunks = \array_map([__CLASS__, 'escape'], $chunks);
$glue = \sprintf('<urgent>%s</urgent>', self::escape($matches[0]));
$highlighted[$i] = implode($glue, $chunks);
$highlighted[$i] = \implode($glue, $chunks);
}
} else {
unset($history[$i]);
@@ -123,16 +123,16 @@ HELP
}
if ($save = $input->getOption('save')) {
$output->writeln(sprintf('Saving history in %s...', $save));
file_put_contents($save, implode(PHP_EOL, $history) . PHP_EOL);
$output->writeln(\sprintf('Saving history in %s...', $save));
\file_put_contents($save, \implode(PHP_EOL, $history) . PHP_EOL);
$output->writeln('<info>History saved.</info>');
} elseif ($input->getOption('replay')) {
if (!($input->getOption('show') || $input->getOption('head') || $input->getOption('tail'))) {
throw new \InvalidArgumentException('You must limit history via --head, --tail or --show before replaying');
}
$count = count($history);
$output->writeln(sprintf('Replaying %d line%s of history', $count, ($count !== 1) ? 's' : ''));
$count = \count($history);
$output->writeln(\sprintf('Replaying %d line%s of history', $count, ($count !== 1) ? 's' : ''));
$this->getApplication()->addInput($history);
} elseif ($input->getOption('clear')) {
$this->clearHistory();
@@ -156,14 +156,14 @@ HELP
*/
private function extractRange($range)
{
if (preg_match('/^\d+$/', $range)) {
if (\preg_match('/^\d+$/', $range)) {
return [$range, $range + 1];
}
$matches = [];
if ($range !== '..' && preg_match('/^(\d*)\.\.(\d*)$/', $range, $matches)) {
$start = $matches[1] ? intval($matches[1]) : 0;
$end = $matches[2] ? intval($matches[2]) + 1 : PHP_INT_MAX;
if ($range !== '..' && \preg_match('/^(\d*)\.\.(\d*)$/', $range, $matches)) {
$start = $matches[1] ? \intval($matches[1]) : 0;
$end = $matches[2] ? \intval($matches[2]) + 1 : PHP_INT_MAX;
return [$start, $end];
}
@@ -185,30 +185,30 @@ HELP
$history = $this->readline->listHistory();
// don't show the current `history` invocation
array_pop($history);
\array_pop($history);
if ($show) {
list($start, $end) = $this->extractRange($show);
$length = $end - $start;
} elseif ($head) {
if (!preg_match('/^\d+$/', $head)) {
if (!\preg_match('/^\d+$/', $head)) {
throw new \InvalidArgumentException('Please specify an integer argument for --head');
}
$start = 0;
$length = intval($head);
$length = \intval($head);
} elseif ($tail) {
if (!preg_match('/^\d+$/', $tail)) {
if (!\preg_match('/^\d+$/', $tail)) {
throw new \InvalidArgumentException('Please specify an integer argument for --tail');
}
$start = count($history) - $tail;
$length = intval($tail) + 1;
$start = \count($history) - $tail;
$length = \intval($tail) + 1;
} else {
return $history;
}
return array_slice($history, $start, $length, true);
return \array_slice($history, $start, $length, true);
}
/**
@@ -227,7 +227,7 @@ HELP
}
if ($count > 1) {
throw new \InvalidArgumentException('Please specify only one of --' . implode(', --', $options));
throw new \InvalidArgumentException('Please specify only one of --' . \implode(', --', $options));
}
}

View File

@@ -178,8 +178,8 @@ HELP
}
foreach ($result as $label => $items) {
$names = array_map([$this, 'formatItemName'], $items);
$output->writeln(sprintf('<strong>%s</strong>: %s', $label, implode(', ', $names)));
$names = \array_map([$this, 'formatItemName'], $items);
$output->writeln(\sprintf('<strong>%s</strong>: %s', $label, \implode(', ', $names)));
}
}
@@ -201,7 +201,7 @@ HELP
foreach ($result as $label => $items) {
$output->writeln('');
$output->writeln(sprintf('<strong>%s:</strong>', $label));
$output->writeln(\sprintf('<strong>%s:</strong>', $label));
$table->setRows([]);
foreach ($items as $item) {
@@ -225,7 +225,7 @@ HELP
*/
private function formatItemName($item)
{
return sprintf('<%s>%s</%s>', $item['style'], OutputFormatter::escape($item['name']), $item['style']);
return \sprintf('<%s>%s</%s>', $item['style'], OutputFormatter::escape($item['name']), $item['style']);
}
/**

View File

@@ -68,7 +68,7 @@ class ClassConstantEnumerator extends Enumerator
$constants = [];
foreach ($reflector->getConstants() as $name => $constant) {
$constReflector = ReflectionClassConstant::create($reflector, $name);
$constReflector = ReflectionClassConstant::create($reflector->name, $name);
if ($noInherit && $constReflector->getDeclaringClass()->getName() !== $className) {
continue;
@@ -77,7 +77,7 @@ class ClassConstantEnumerator extends Enumerator
$constants[$name] = $constReflector;
}
ksort($constants, SORT_NATURAL | SORT_FLAG_CASE);
\ksort($constants, SORT_NATURAL | SORT_FLAG_CASE);
return $constants;
}
@@ -118,7 +118,7 @@ class ClassConstantEnumerator extends Enumerator
{
if ($reflector->isInterface()) {
return 'Interface Constants';
} elseif (method_exists($reflector, 'isTrait') && $reflector->isTrait()) {
} elseif (\method_exists($reflector, 'isTrait') && $reflector->isTrait()) {
return 'Trait Constants';
} else {
return 'Class Constants';

View File

@@ -43,18 +43,18 @@ class ClassEnumerator extends Enumerator
// only list classes, interfaces and traits if we are specifically asked
if ($input->getOption('classes')) {
$ret = array_merge($ret, $this->filterClasses('Classes', get_declared_classes(), $internal, $user));
$ret = \array_merge($ret, $this->filterClasses('Classes', \get_declared_classes(), $internal, $user));
}
if ($input->getOption('interfaces')) {
$ret = array_merge($ret, $this->filterClasses('Interfaces', get_declared_interfaces(), $internal, $user));
$ret = \array_merge($ret, $this->filterClasses('Interfaces', \get_declared_interfaces(), $internal, $user));
}
if ($input->getOption('traits')) {
$ret = array_merge($ret, $this->filterClasses('Traits', get_declared_traits(), $internal, $user));
$ret = \array_merge($ret, $this->filterClasses('Traits', \get_declared_traits(), $internal, $user));
}
return array_map([$this, 'prepareClasses'], array_filter($ret));
return \array_map([$this, 'prepareClasses'], \array_filter($ret));
}
/**
@@ -75,7 +75,7 @@ class ClassEnumerator extends Enumerator
$ret = [];
if ($internal) {
$ret['Internal ' . $key] = array_filter($classes, function ($class) {
$ret['Internal ' . $key] = \array_filter($classes, function ($class) {
$refl = new \ReflectionClass($class);
return $refl->isInternal();
@@ -83,7 +83,7 @@ class ClassEnumerator extends Enumerator
}
if ($user) {
$ret['User ' . $key] = array_filter($classes, function ($class) {
$ret['User ' . $key] = \array_filter($classes, function ($class) {
$refl = new \ReflectionClass($class);
return !$refl->isInternal();
@@ -106,7 +106,7 @@ class ClassEnumerator extends Enumerator
*/
protected function prepareClasses(array $classes)
{
natcasesort($classes);
\natcasesort($classes);
// My kingdom for a generator.
$ret = [];

View File

@@ -54,7 +54,7 @@ class ConstantEnumerator extends Enumerator
}
if ($category) {
$label = ucfirst($category) . ' Constants';
$label = \ucfirst($category) . ' Constants';
$ret[$label] = $this->getConstants($category);
}
@@ -62,7 +62,7 @@ class ConstantEnumerator extends Enumerator
$ret['Constants'] = $this->getConstants();
}
return array_map([$this, 'prepareConstants'], array_filter($ret));
return \array_map([$this, 'prepareConstants'], \array_filter($ret));
}
/**
@@ -78,15 +78,15 @@ class ConstantEnumerator extends Enumerator
protected function getConstants($category = null)
{
if (!$category) {
return get_defined_constants();
return \get_defined_constants();
}
$consts = get_defined_constants(true);
$consts = \get_defined_constants(true);
if ($category === 'internal') {
unset($consts['user']);
return call_user_func_array('array_merge', $consts);
return \call_user_func_array('array_merge', $consts);
}
return isset($consts[$category]) ? $consts[$category] : [];
@@ -104,8 +104,8 @@ class ConstantEnumerator extends Enumerator
// My kingdom for a generator.
$ret = [];
$names = array_keys($constants);
natcasesort($names);
$names = \array_keys($constants);
\natcasesort($names);
foreach ($names as $name) {
if ($this->showItem($name)) {

View File

@@ -74,12 +74,12 @@ class FunctionEnumerator extends Enumerator
*/
protected function getFunctions($type = null)
{
$funcs = get_defined_functions();
$funcs = \get_defined_functions();
if ($type) {
return $funcs[$type];
} else {
return array_merge($funcs['internal'], $funcs['user']);
return \array_merge($funcs['internal'], $funcs['user']);
}
}
@@ -92,7 +92,7 @@ class FunctionEnumerator extends Enumerator
*/
protected function prepareFunctions(array $functions)
{
natcasesort($functions);
\natcasesort($functions);
// My kingdom for a generator.
$ret = [];

View File

@@ -53,8 +53,8 @@ class GlobalVariableEnumerator extends Enumerator
{
global $GLOBALS;
$names = array_keys($GLOBALS);
natcasesort($names);
$names = \array_keys($GLOBALS);
\natcasesort($names);
$ret = [];
foreach ($names as $name) {

View File

@@ -23,7 +23,7 @@ class InterfaceEnumerator extends Enumerator
{
public function __construct(Presenter $presenter)
{
@trigger_error('InterfaceEnumerator is no longer used', E_USER_DEPRECATED);
@\trigger_error('InterfaceEnumerator is no longer used', E_USER_DEPRECATED);
parent::__construct($presenter);
}
@@ -49,7 +49,7 @@ class InterfaceEnumerator extends Enumerator
return;
}
$interfaces = $this->prepareInterfaces(get_declared_interfaces());
$interfaces = $this->prepareInterfaces(\get_declared_interfaces());
if (empty($interfaces)) {
return;
@@ -69,7 +69,7 @@ class InterfaceEnumerator extends Enumerator
*/
protected function prepareInterfaces(array $interfaces)
{
natcasesort($interfaces);
\natcasesort($interfaces);
// My kingdom for a generator.
$ret = [];

View File

@@ -77,7 +77,7 @@ class MethodEnumerator extends Enumerator
}
}
ksort($methods, SORT_NATURAL | SORT_FLAG_CASE);
\ksort($methods, SORT_NATURAL | SORT_FLAG_CASE);
return $methods;
}
@@ -118,7 +118,7 @@ class MethodEnumerator extends Enumerator
{
if ($reflector->isInterface()) {
return 'Interface Methods';
} elseif (method_exists($reflector, 'isTrait') && $reflector->isTrait()) {
} elseif (\method_exists($reflector, 'isTrait') && $reflector->isTrait()) {
return 'Trait Methods';
} else {
return 'Class Methods';

View File

@@ -77,7 +77,7 @@ class PropertyEnumerator extends Enumerator
}
}
ksort($properties, SORT_NATURAL | SORT_FLAG_CASE);
\ksort($properties, SORT_NATURAL | SORT_FLAG_CASE);
return $properties;
}
@@ -119,7 +119,7 @@ class PropertyEnumerator extends Enumerator
{
if ($reflector->isInterface()) {
return 'Interface Properties';
} elseif (method_exists($reflector, 'isTrait') && $reflector->isTrait()) {
} elseif (\method_exists($reflector, 'isTrait') && $reflector->isTrait()) {
return 'Trait Properties';
} else {
return 'Class Properties';
@@ -156,11 +156,11 @@ class PropertyEnumerator extends Enumerator
{
// If $target is a class, trait or interface (try to) get the default
// value for the property.
if (!is_object($target)) {
if (!\is_object($target)) {
try {
$refl = new \ReflectionClass($target);
$props = $refl->getDefaultProperties();
if (array_key_exists($property->name, $props)) {
if (\array_key_exists($property->name, $props)) {
$suffix = $property->isStatic() ? '' : ' <aside>(default)</aside>';
return $this->presentRef($props[$property->name]) . $suffix;

View File

@@ -23,7 +23,7 @@ class TraitEnumerator extends Enumerator
{
public function __construct(Presenter $presenter)
{
@trigger_error('TraitEnumerator is no longer used', E_USER_DEPRECATED);
@\trigger_error('TraitEnumerator is no longer used', E_USER_DEPRECATED);
parent::__construct($presenter);
}
@@ -49,7 +49,7 @@ class TraitEnumerator extends Enumerator
return;
}
$traits = $this->prepareTraits(get_declared_traits());
$traits = $this->prepareTraits(\get_declared_traits());
if (empty($traits)) {
return;
@@ -69,7 +69,7 @@ class TraitEnumerator extends Enumerator
*/
protected function prepareTraits(array $traits)
{
natcasesort($traits);
\natcasesort($traits);
// My kingdom for a generator.
$ret = [];

View File

@@ -79,9 +79,9 @@ class VariableEnumerator extends Enumerator
protected function getVariables($showAll)
{
$scopeVars = $this->context->getAll();
uksort($scopeVars, function ($a, $b) {
$aIndex = array_search($a, self::$specialNames);
$bIndex = array_search($b, self::$specialNames);
\uksort($scopeVars, function ($a, $b) {
$aIndex = \array_search($a, self::$specialNames);
$bIndex = \array_search($b, self::$specialNames);
if ($aIndex !== false) {
if ($bIndex !== false) {
@@ -95,12 +95,12 @@ class VariableEnumerator extends Enumerator
return -1;
}
return strnatcasecmp($a, $b);
return \strnatcasecmp($a, $b);
});
$ret = [];
foreach ($scopeVars as $name => $val) {
if (!$showAll && in_array($name, self::$specialNames)) {
if (!$showAll && \in_array($name, self::$specialNames)) {
continue;
}
@@ -126,7 +126,7 @@ class VariableEnumerator extends Enumerator
$fname = '$' . $name;
$ret[$fname] = [
'name' => $fname,
'style' => in_array($name, self::$specialNames) ? self::IS_PRIVATE : self::IS_PUBLIC,
'style' => \in_array($name, self::$specialNames) ? self::IS_PRIVATE : self::IS_PUBLIC,
'value' => $this->presentRef($val),
];
}

View File

@@ -97,7 +97,7 @@ class ParseCommand extends Command implements ContextAware, PresenterAware
if ($this->parserFactory->hasKindsSupport()) {
$msg = 'One of PhpParser\\ParserFactory constants: '
. implode(', ', ParserFactory::getPossibleKinds())
. \implode(', ', ParserFactory::getPossibleKinds())
. " (default is based on current interpreter's version).";
$defaultKind = $this->parserFactory->getDefaultKind();
@@ -128,7 +128,7 @@ HELP
protected function execute(InputInterface $input, OutputInterface $output)
{
$code = $input->getArgument('code');
if (strpos('<?', $code) === false) {
if (\strpos('<?', $code) === false) {
$code = '<?php ' . $code;
}
@@ -153,7 +153,7 @@ HELP
try {
return $parser->parse($code);
} catch (\PhpParser\Error $e) {
if (strpos($e->getMessage(), 'unexpected EOF') === false) {
if (\strpos($e->getMessage(), 'unexpected EOF') === false) {
throw $e;
}
@@ -171,7 +171,7 @@ HELP
*/
private function getParser($kind = null)
{
if (!array_key_exists($kind, $this->parsers)) {
if (!\array_key_exists($kind, $this->parsers)) {
$this->parsers[$kind] = $this->parserFactory->createParser($kind);
}

View File

@@ -56,19 +56,19 @@ abstract class ReflectingCommand extends Command implements ContextAware
*/
protected function getTarget($valueName)
{
$valueName = trim($valueName);
$valueName = \trim($valueName);
$matches = [];
switch (true) {
case preg_match(self::CLASS_OR_FUNC, $valueName, $matches):
case \preg_match(self::CLASS_OR_FUNC, $valueName, $matches):
return [$this->resolveName($matches[0], true), null, 0];
case preg_match(self::CLASS_MEMBER, $valueName, $matches):
case \preg_match(self::CLASS_MEMBER, $valueName, $matches):
return [$this->resolveName($matches[1]), $matches[2], Mirror::CONSTANT | Mirror::METHOD];
case preg_match(self::CLASS_STATIC, $valueName, $matches):
case \preg_match(self::CLASS_STATIC, $valueName, $matches):
return [$this->resolveName($matches[1]), $matches[2], Mirror::STATIC_PROPERTY | Mirror::PROPERTY];
case preg_match(self::INSTANCE_MEMBER, $valueName, $matches):
case \preg_match(self::INSTANCE_MEMBER, $valueName, $matches):
if ($matches[2] === '->') {
$kind = Mirror::METHOD | Mirror::PROPERTY;
} else {
@@ -97,27 +97,27 @@ abstract class ReflectingCommand extends Command implements ContextAware
$shell = $this->getApplication();
// While not *technically* 100% accurate, let's treat `self` and `static` as equivalent.
if (in_array(strtolower($name), ['self', 'static'])) {
if (\in_array(\strtolower($name), ['self', 'static'])) {
if ($boundClass = $shell->getBoundClass()) {
return $boundClass;
}
if ($boundObject = $shell->getBoundObject()) {
return get_class($boundObject);
return \get_class($boundObject);
}
$msg = sprintf('Cannot use "%s" when no class scope is active', strtolower($name));
$msg = \sprintf('Cannot use "%s" when no class scope is active', \strtolower($name));
throw new ErrorException($msg, 0, E_USER_ERROR, "eval()'d code", 1);
}
if (substr($name, 0, 1) === '\\') {
if (\substr($name, 0, 1) === '\\') {
return $name;
}
if ($namespace = $shell->getNamespace()) {
$fullName = $namespace . '\\' . $name;
if (class_exists($fullName) || interface_exists($fullName) || ($includeFunctions && function_exists($fullName))) {
if (\class_exists($fullName) || \interface_exists($fullName) || ($includeFunctions && \function_exists($fullName))) {
return $fullName;
}
}
@@ -176,7 +176,7 @@ abstract class ReflectingCommand extends Command implements ContextAware
{
$value = $this->resolveCode($code);
if (!is_object($value)) {
if (!\is_object($value)) {
throw new RuntimeException('Unable to inspect a non-object');
}
@@ -192,7 +192,7 @@ abstract class ReflectingCommand extends Command implements ContextAware
*/
protected function resolveInstance($name)
{
@trigger_error('`resolveInstance` is deprecated; use `resolveCode` instead.', E_USER_DEPRECATED);
@\trigger_error('`resolveInstance` is deprecated; use `resolveCode` instead.', E_USER_DEPRECATED);
return $this->resolveCode($name);
}
@@ -230,7 +230,7 @@ abstract class ReflectingCommand extends Command implements ContextAware
{
$vars = [];
switch (get_class($reflector)) {
switch (\get_class($reflector)) {
case 'ReflectionClass':
case 'ReflectionObject':
$vars['__class'] = $reflector->name;
@@ -240,7 +240,7 @@ abstract class ReflectingCommand extends Command implements ContextAware
break;
case 'ReflectionMethod':
$vars['__method'] = sprintf('%s::%s', $reflector->class, $reflector->name);
$vars['__method'] = \sprintf('%s::%s', $reflector->class, $reflector->name);
$vars['__class'] = $reflector->class;
$classReflector = $reflector->getDeclaringClass();
if ($classReflector->inNamespace()) {
@@ -264,7 +264,7 @@ abstract class ReflectingCommand extends Command implements ContextAware
if ($fileName = $reflector->getExecutingFile()) {
$vars['__file'] = $fileName;
$vars['__line'] = $reflector->getExecutingLine();
$vars['__dir'] = dirname($fileName);
$vars['__dir'] = \dirname($fileName);
}
break;
@@ -279,7 +279,7 @@ abstract class ReflectingCommand extends Command implements ContextAware
// no line for these, but this'll do
if ($fileName = $reflector->getDeclaringClass()->getFileName()) {
$vars['__file'] = $fileName;
$vars['__dir'] = dirname($fileName);
$vars['__dir'] = \dirname($fileName);
}
break;
@@ -294,7 +294,7 @@ abstract class ReflectingCommand extends Command implements ContextAware
if ($fileName = $reflector->getFileName()) {
$vars['__file'] = $fileName;
$vars['__line'] = $reflector->getStartLine();
$vars['__dir'] = dirname($fileName);
$vars['__dir'] = \dirname($fileName);
}
}

View File

@@ -140,16 +140,16 @@ HELP
$index = 0;
}
} else {
$index = max(0, intval($input->getOption('ex')) - 1);
$index = \max(0, \intval($input->getOption('ex')) - 1);
}
$trace = $exception->getTrace();
array_unshift($trace, [
\array_unshift($trace, [
'file' => $exception->getFile(),
'line' => $exception->getLine(),
]);
if ($index >= count($trace)) {
if ($index >= \count($trace)) {
$index = 0;
}
@@ -169,25 +169,25 @@ HELP
$file = isset($trace[$index]['file']) ? $this->replaceCwd($trace[$index]['file']) : 'n/a';
$line = isset($trace[$index]['line']) ? $trace[$index]['line'] : 'n/a';
$output->writeln(sprintf(
$output->writeln(\sprintf(
'From <info>%s:%d</info> at <strong>level %d</strong> of backtrace (of %d).',
OutputFormatter::escape($file),
OutputFormatter::escape($line),
$index + 1,
count($trace)
\count($trace)
));
}
private function replaceCwd($file)
{
if ($cwd = getcwd()) {
$cwd = rtrim($cwd, DIRECTORY_SEPARATOR) . DIRECTORY_SEPARATOR;
if ($cwd = \getcwd()) {
$cwd = \rtrim($cwd, DIRECTORY_SEPARATOR) . DIRECTORY_SEPARATOR;
}
if ($cwd === false) {
return $file;
} else {
return preg_replace('/^' . preg_quote($cwd, '/') . '/', '', $file);
return \preg_replace('/^' . \preg_quote($cwd, '/') . '/', '', $file);
}
}
@@ -208,8 +208,8 @@ HELP
$line = $trace[$index]['line'];
}
if (is_file($file)) {
$code = @file_get_contents($file);
if (\is_file($file)) {
$code = @\file_get_contents($file);
}
if (empty($code)) {
@@ -268,12 +268,12 @@ HELP
$line = $context['line'];
}
if (is_file($file)) {
if (\is_file($file)) {
$vars['__file'] = $file;
if (isset($line)) {
$vars['__line'] = $line;
}
$vars['__dir'] = dirname($file);
$vars['__dir'] = \dirname($file);
}
}
@@ -282,7 +282,7 @@ HELP
private function extractEvalFileAndLine($file)
{
if (preg_match('/(.*)\\((\\d+)\\) : eval\\(\\)\'d code$/', $file, $matches)) {
if (\preg_match('/(.*)\\((\\d+)\\) : eval\\(\\)\'d code$/', $file, $matches)) {
return [$matches[1], $matches[2]];
}
}

View File

@@ -103,13 +103,13 @@ HELP
// special case for !!
if ($code === '!!') {
$history = $this->readline->listHistory();
if (count($history) < 2) {
if (\count($history) < 2) {
throw new \InvalidArgumentException('No previous command to replay');
}
$code = $history[count($history) - 2];
$code = $history[\count($history) - 2];
}
if (strpos('<?', $code) === false) {
if (\strpos('<?', $code) === false) {
$code = '<?php ' . $code;
}
@@ -132,7 +132,7 @@ HELP
try {
return $this->parser->parse($code);
} catch (\PhpParser\Error $e) {
if (strpos($e->getMessage(), 'unexpected EOF') === false) {
if (\strpos($e->getMessage(), 'unexpected EOF') === false) {
throw $e;
}

View File

@@ -125,12 +125,12 @@ HELP
return [new Arg(new Variable('_e'))];
}
if (strpos('<?', $code) === false) {
if (\strpos('<?', $code) === false) {
$code = '<?php ' . $code;
}
$nodes = $this->parse($code);
if (count($nodes) !== 1) {
if (\count($nodes) !== 1) {
throw new \InvalidArgumentException('No idea how to throw this');
}
@@ -161,7 +161,7 @@ HELP
try {
return $this->parser->parse($code);
} catch (\PhpParser\Error $e) {
if (strpos($e->getMessage(), 'unexpected EOF') === false) {
if (\strpos($e->getMessage(), 'unexpected EOF') === false) {
throw $e;
}

View File

@@ -16,7 +16,6 @@ use PhpParser\PrettyPrinter\Standard as Printer;
use Psy\Command\TimeitCommand\TimeitVisitor;
use Psy\Input\CodeArgument;
use Psy\ParserFactory;
use Psy\Shell;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;
@@ -99,13 +98,13 @@ HELP
self::$times = [];
if ($num === 1) {
$output->writeln(sprintf(self::RESULT_MSG, $times[0]));
$output->writeln(\sprintf(self::RESULT_MSG, $times[0]));
} else {
$total = array_sum($times);
rsort($times);
$median = $times[round($num / 2)];
$total = \array_sum($times);
\rsort($times);
$median = $times[\round($num / 2)];
$output->writeln(sprintf(self::AVG_RESULT_MSG, $total / $num, $median, $total));
$output->writeln(\sprintf(self::AVG_RESULT_MSG, $total / $num, $median, $total));
}
}
@@ -118,7 +117,7 @@ HELP
*/
public static function markStart()
{
self::$start = microtime(true);
self::$start = \microtime(true);
}
/**
@@ -137,7 +136,7 @@ HELP
*/
public static function markEnd($ret = null)
{
self::$times[] = microtime(true) - self::$start;
self::$times[] = \microtime(true) - self::$start;
self::$start = null;
return $ret;
@@ -185,7 +184,7 @@ HELP
try {
return $this->parser->parse($code);
} catch (\PhpParser\Error $e) {
if (strpos($e->getMessage(), 'unexpected EOF') === false) {
if (\strpos($e->getMessage(), 'unexpected EOF') === false) {
throw $e;
}

View File

@@ -75,15 +75,15 @@ class TimeitVisitor extends NodeVisitorAbstract
public function afterTraverse(array $nodes)
{
// prepend a `markStart` call
array_unshift($nodes, $this->maybeExpression($this->getStartCall()));
\array_unshift($nodes, $this->maybeExpression($this->getStartCall()));
// append a `markEnd` call (wrapping the final node, if it's an expression)
$last = $nodes[count($nodes) - 1];
$last = $nodes[\count($nodes) - 1];
if ($last instanceof Expr) {
array_pop($nodes);
\array_pop($nodes);
$nodes[] = $this->getEndCall($last);
} elseif ($last instanceof Expression) {
array_pop($nodes);
\array_pop($nodes);
$nodes[] = new Expression($this->getEndCall($last->expr), $last->getAttributes());
} elseif ($last instanceof Return_) {
// nothing to do here, we're already ending with a return call
@@ -134,6 +134,6 @@ class TimeitVisitor extends NodeVisitorAbstract
*/
private function maybeExpression($expr, $attrs = [])
{
return class_exists('PhpParser\Node\Stmt\Expression') ? new Expression($expr, $attrs) : $expr;
return \class_exists('PhpParser\Node\Stmt\Expression') ? new Expression($expr, $attrs) : $expr;
}
}

View File

@@ -90,8 +90,8 @@ HELP
*/
protected function getBacktrace(\Exception $e, $count = null, $includePsy = true)
{
if ($cwd = getcwd()) {
$cwd = rtrim($cwd, DIRECTORY_SEPARATOR) . DIRECTORY_SEPARATOR;
if ($cwd = \getcwd()) {
$cwd = \rtrim($cwd, DIRECTORY_SEPARATOR) . DIRECTORY_SEPARATOR;
}
if ($count === null) {
@@ -101,7 +101,7 @@ HELP
$lines = [];
$trace = $e->getTrace();
array_unshift($trace, [
\array_unshift($trace, [
'function' => '',
'file' => $e->getFile() !== null ? $e->getFile() : 'n/a',
'line' => $e->getLine() !== null ? $e->getLine() : 'n/a',
@@ -109,16 +109,16 @@ HELP
]);
if (!$includePsy) {
for ($i = count($trace) - 1; $i >= 0; $i--) {
for ($i = \count($trace) - 1; $i >= 0; $i--) {
$thing = isset($trace[$i]['class']) ? $trace[$i]['class'] : $trace[$i]['function'];
if (preg_match('/\\\\?Psy\\\\/', $thing)) {
$trace = array_slice($trace, $i + 1);
if (\preg_match('/\\\\?Psy\\\\/', $thing)) {
$trace = \array_slice($trace, $i + 1);
break;
}
}
}
for ($i = 0, $count = min($count, count($trace)); $i < $count; $i++) {
for ($i = 0, $count = \min($count, \count($trace)); $i < $count; $i++) {
$class = isset($trace[$i]['class']) ? $trace[$i]['class'] : '';
$type = isset($trace[$i]['type']) ? $trace[$i]['type'] : '';
$function = $trace[$i]['function'];
@@ -126,16 +126,16 @@ HELP
$line = isset($trace[$i]['line']) ? $trace[$i]['line'] : 'n/a';
// Leave execution loop out of the `eval()'d code` lines
if (preg_match("#/src/Execution(?:Loop)?Closure.php\(\d+\) : eval\(\)'d code$#", str_replace('\\', '/', $file))) {
if (\preg_match("#/src/Execution(?:Loop)?Closure.php\(\d+\) : eval\(\)'d code$#", \str_replace('\\', '/', $file))) {
$file = "eval()'d code";
}
// Skip any lines that don't match our filter options
if (!$this->filter->match(sprintf('%s%s%s() at %s:%s', $class, $type, $function, $file, $line))) {
if (!$this->filter->match(\sprintf('%s%s%s() at %s:%s', $class, $type, $function, $file, $line))) {
continue;
}
$lines[] = sprintf(
$lines[] = \sprintf(
' <class>%s</class>%s%s() at <info>%s:%s</info>',
OutputFormatter::escape($class),
OutputFormatter::escape($type),
@@ -161,7 +161,7 @@ HELP
if ($cwd === false) {
return $file;
} else {
return preg_replace('/^' . preg_quote($cwd, '/') . '/', '', $file);
return \preg_replace('/^' . \preg_quote($cwd, '/') . '/', '', $file);
}
}
}

View File

@@ -33,7 +33,7 @@ class WhereamiCommand extends Command
public function __construct($colorMode = null)
{
$this->colorMode = $colorMode ?: Configuration::COLOR_MODE_AUTO;
$this->backtrace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS);
$this->backtrace = \debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS);
parent::__construct();
}
@@ -69,13 +69,13 @@ HELP
*/
protected function trace()
{
foreach (array_reverse($this->backtrace) as $stackFrame) {
foreach (\array_reverse($this->backtrace) as $stackFrame) {
if ($this->isDebugCall($stackFrame)) {
return $stackFrame;
}
}
return end($this->backtrace);
return \end($this->backtrace);
}
private static function isDebugCall(array $stackFrame)
@@ -84,7 +84,7 @@ HELP
$function = isset($stackFrame['function']) ? $stackFrame['function'] : null;
return ($class === null && $function === 'Psy\debug') ||
($class === 'Psy\Shell' && in_array($function, ['__construct', 'debug']));
($class === 'Psy\Shell' && \in_array($function, ['__construct', 'debug']));
}
/**
@@ -95,8 +95,8 @@ HELP
protected function fileInfo()
{
$stackFrame = $this->trace();
if (preg_match('/eval\(/', $stackFrame['file'])) {
preg_match_all('/([^\(]+)\((\d+)/', $stackFrame['file'], $matches);
if (\preg_match('/eval\(/', $stackFrame['file'])) {
\preg_match_all('/([^\(]+)\((\d+)/', $stackFrame['file'], $matches);
$file = $matches[1][0];
$line = (int) $matches[2][0];
} else {
@@ -104,7 +104,7 @@ HELP
$line = $stackFrame['line'];
}
return compact('file', 'line');
return \compact('file', 'line');
}
/**
@@ -117,11 +117,11 @@ HELP
$factory = new ConsoleColorFactory($this->colorMode);
$colors = $factory->getConsoleColor();
$highlighter = new Highlighter($colors);
$contents = file_get_contents($info['file']);
$contents = \file_get_contents($info['file']);
$output->startPaging();
$output->writeln('');
$output->writeln(sprintf('From <info>%s:%s</info>:', $this->replaceCwd($info['file']), $info['line']));
$output->writeln(\sprintf('From <info>%s:%s</info>:', $this->replaceCwd($info['file']), $info['line']));
$output->writeln('');
$output->write($highlighter->getCodeSnippet($contents, $info['line'], $num, $num), ShellOutput::OUTPUT_RAW);
$output->stopPaging();
@@ -136,13 +136,13 @@ HELP
*/
private function replaceCwd($file)
{
$cwd = getcwd();
$cwd = \getcwd();
if ($cwd === false) {
return $file;
}
$cwd = rtrim($cwd, DIRECTORY_SEPARATOR) . DIRECTORY_SEPARATOR;
$cwd = \rtrim($cwd, DIRECTORY_SEPARATOR) . DIRECTORY_SEPARATOR;
return preg_replace('/^' . preg_quote($cwd, '/') . '/', '', $file);
return \preg_replace('/^' . \preg_quote($cwd, '/') . '/', '', $file);
}
}

View File

@@ -86,26 +86,26 @@ HELP
{
$this->filter->bind($input);
$incredulity = implode('', $input->getArgument('incredulity'));
if (strlen(preg_replace('/[\\?!]/', '', $incredulity))) {
$incredulity = \implode('', $input->getArgument('incredulity'));
if (\strlen(\preg_replace('/[\\?!]/', '', $incredulity))) {
throw new \InvalidArgumentException('Incredulity must include only "?" and "!"');
}
$exception = $this->context->getLastException();
$count = $input->getOption('all') ? PHP_INT_MAX : max(3, pow(2, strlen($incredulity) + 1));
$count = $input->getOption('all') ? PHP_INT_MAX : \max(3, \pow(2, \strlen($incredulity) + 1));
$shell = $this->getApplication();
$output->startPaging();
do {
$traceCount = count($exception->getTrace());
$traceCount = \count($exception->getTrace());
$showLines = $count;
// Show the whole trace if we'd only be hiding a few lines
if ($traceCount < max($count * 1.2, $count + 2)) {
if ($traceCount < \max($count * 1.2, $count + 2)) {
$showLines = PHP_INT_MAX;
}
$trace = $this->getBacktrace($exception, $showLines);
$moreLines = $traceCount - count($trace);
$moreLines = $traceCount - \count($trace);
$output->writeln($shell->formatException($exception));
$output->writeln('--');
@@ -113,7 +113,7 @@ HELP
$output->writeln('');
if ($moreLines > 0) {
$output->writeln(sprintf(
$output->writeln(\sprintf(
'<aside>Use <return>wtf -a</return> to see %d more lines</aside>',
$moreLines
));

View File

@@ -68,7 +68,7 @@ class ConfigPaths
{
$configDirs = self::getHomeConfigDirs();
foreach ($configDirs as $configDir) {
if (@is_dir($configDir)) {
if (@\is_dir($configDir)) {
return $configDir;
}
}
@@ -136,7 +136,7 @@ class ConfigPaths
{
$xdg = new Xdg();
set_error_handler(['Psy\Exception\ErrorException', 'throwException']);
\set_error_handler(['Psy\Exception\ErrorException', 'throwException']);
try {
// XDG doesn't really work on Windows, sometimes complains about
@@ -146,34 +146,34 @@ class ConfigPaths
} catch (\Exception $e) {
// Well. That didn't work. Fall back to a boring old folder in the
// system temp dir.
$runtimeDir = sys_get_temp_dir();
$runtimeDir = \sys_get_temp_dir();
}
restore_error_handler();
\restore_error_handler();
return strtr($runtimeDir, '\\', '/') . '/psysh';
return \strtr($runtimeDir, '\\', '/') . '/psysh';
}
private static function getDirNames(array $baseDirs)
{
$dirs = array_map(function ($dir) {
return strtr($dir, '\\', '/') . '/psysh';
$dirs = \array_map(function ($dir) {
return \strtr($dir, '\\', '/') . '/psysh';
}, $baseDirs);
// Add ~/.psysh
if ($home = getenv('HOME')) {
$dirs[] = strtr($home, '\\', '/') . '/.psysh';
if ($home = \getenv('HOME')) {
$dirs[] = \strtr($home, '\\', '/') . '/.psysh';
}
// Add some Windows specific ones :)
if (defined('PHP_WINDOWS_VERSION_MAJOR')) {
if ($appData = getenv('APPDATA')) {
if (\defined('PHP_WINDOWS_VERSION_MAJOR')) {
if ($appData = \getenv('APPDATA')) {
// AppData gets preference
array_unshift($dirs, strtr($appData, '\\', '/') . '/PsySH');
\array_unshift($dirs, \strtr($appData, '\\', '/') . '/PsySH');
}
$dir = strtr(getenv('HOMEDRIVE') . '/' . getenv('HOMEPATH'), '\\', '/') . '/.psysh';
if (!in_array($dir, $dirs)) {
$dir = \strtr(\getenv('HOMEDRIVE') . '/' . \getenv('HOMEPATH'), '\\', '/') . '/.psysh';
if (!\in_array($dir, $dirs)) {
$dirs[] = $dir;
}
}
@@ -187,7 +187,7 @@ class ConfigPaths
foreach ($dirNames as $dir) {
foreach ($fileNames as $name) {
$file = $dir . '/' . $name;
if (@is_file($file)) {
if (@\is_file($file)) {
$files[] = $file;
}
}
@@ -207,30 +207,30 @@ class ConfigPaths
*/
public static function touchFileWithMkdir($file)
{
if (file_exists($file)) {
if (is_writable($file)) {
if (\file_exists($file)) {
if (\is_writable($file)) {
return $file;
}
trigger_error(sprintf('Writing to %s is not allowed.', $file), E_USER_NOTICE);
\trigger_error(\sprintf('Writing to %s is not allowed.', $file), E_USER_NOTICE);
return false;
}
$dir = dirname($file);
$dir = \dirname($file);
if (!is_dir($dir)) {
if (!\is_dir($dir)) {
// Just try making it and see if it works
@mkdir($dir, 0700, true);
@\mkdir($dir, 0700, true);
}
if (!is_dir($dir) || !is_writable($dir)) {
trigger_error(sprintf('Writing to %s is not allowed.', $dir), E_USER_NOTICE);
if (!\is_dir($dir) || !\is_writable($dir)) {
\trigger_error(\sprintf('Writing to %s is not allowed.', $dir), E_USER_NOTICE);
return false;
}
touch($file);
\touch($file);
return $file;
}

View File

@@ -114,7 +114,7 @@ class Configuration
// explicit configFile option
if (isset($config['configFile'])) {
$this->configFile = $config['configFile'];
} elseif ($configFile = getenv('PSYSH_CONFIG')) {
} elseif ($configFile = \getenv('PSYSH_CONFIG')) {
$this->configFile = $configFile;
}
@@ -145,8 +145,8 @@ class Configuration
public function init()
{
// feature detection
$this->hasReadline = function_exists('readline');
$this->hasPcntl = function_exists('pcntl_signal') && function_exists('posix_getpid');
$this->hasReadline = \function_exists('readline');
$this->hasPcntl = \function_exists('pcntl_signal') && \function_exists('posix_getpid');
if ($configFile = $this->getConfigFile()) {
$this->loadConfigFile($configFile);
@@ -180,9 +180,9 @@ class Configuration
$files = ConfigPaths::getConfigFiles(['config.php', 'rc.php'], $this->configDir);
if (!empty($files)) {
if ($this->warnOnMultipleConfigs && count($files) > 1) {
$msg = sprintf('Multiple configuration files found: %s. Using %s', implode($files, ', '), $files[0]);
trigger_error($msg, E_USER_NOTICE);
if ($this->warnOnMultipleConfigs && \count($files) > 1) {
$msg = \sprintf('Multiple configuration files found: %s. Using %s', \implode($files, ', '), $files[0]);
\trigger_error($msg, E_USER_NOTICE);
}
return $files[0];
@@ -199,9 +199,9 @@ class Configuration
*/
public function getLocalConfigFile()
{
$localConfig = getcwd() . '/.psysh.php';
$localConfig = \getcwd() . '/.psysh.php';
if (@is_file($localConfig)) {
if (@\is_file($localConfig)) {
return $localConfig;
}
}
@@ -215,7 +215,7 @@ class Configuration
{
foreach (self::$AVAILABLE_OPTIONS as $option) {
if (isset($options[$option])) {
$method = 'set' . ucfirst($option);
$method = 'set' . \ucfirst($option);
$this->$method($options[$option]);
}
}
@@ -223,14 +223,14 @@ class Configuration
// legacy `tabCompletion` option
if (isset($options['tabCompletion'])) {
$msg = '`tabCompletion` is deprecated; use `useTabCompletion` instead.';
@trigger_error($msg, E_USER_DEPRECATED);
@\trigger_error($msg, E_USER_DEPRECATED);
$this->setUseTabCompletion($options['tabCompletion']);
}
foreach (['commands', 'matchers', 'casters'] as $option) {
if (isset($options[$option])) {
$method = 'add' . ucfirst($option);
$method = 'add' . \ucfirst($option);
$this->$method($options[$option]);
}
}
@@ -238,7 +238,7 @@ class Configuration
// legacy `tabCompletionMatchers` option
if (isset($options['tabCompletionMatchers'])) {
$msg = '`tabCompletionMatchers` is deprecated; use `matchers` instead.';
@trigger_error($msg, E_USER_DEPRECATED);
@\trigger_error($msg, E_USER_DEPRECATED);
$this->addMatchers($options['tabCompletionMatchers']);
}
@@ -267,7 +267,7 @@ class Configuration
$result = $load($this);
if (!empty($result)) {
if (is_array($result)) {
if (\is_array($result)) {
$this->loadConfig($result);
} else {
throw new \InvalidArgumentException('Psy Shell configuration must return an array of options');
@@ -359,8 +359,8 @@ class Configuration
$this->runtimeDir = ConfigPaths::getRuntimeDir();
}
if (!is_dir($this->runtimeDir)) {
mkdir($this->runtimeDir, 0700, true);
if (!\is_dir($this->runtimeDir)) {
\mkdir($this->runtimeDir, 0700, true);
}
return $this->runtimeDir;
@@ -393,9 +393,9 @@ class Configuration
$files = ConfigPaths::getConfigFiles(['psysh_history', 'history'], $this->configDir);
if (!empty($files)) {
if ($this->warnOnMultipleConfigs && count($files) > 1) {
$msg = sprintf('Multiple history files found: %s. Using %s', implode($files, ', '), $files[0]);
trigger_error($msg, E_USER_NOTICE);
if ($this->warnOnMultipleConfigs && \count($files) > 1) {
$msg = \sprintf('Multiple history files found: %s. Using %s', \implode($files, ', '), $files[0]);
\trigger_error($msg, E_USER_NOTICE);
}
$this->setHistoryFile($files[0]);
@@ -462,7 +462,7 @@ class Configuration
*/
public function getTempFile($type, $pid)
{
return tempnam($this->getRuntimeDir(), $type . '_' . $pid . '_');
return \tempnam($this->getRuntimeDir(), $type . '_' . $pid . '_');
}
/**
@@ -477,7 +477,7 @@ class Configuration
*/
public function getPipe($type, $pid)
{
return sprintf('%s/%s_%s', $this->getRuntimeDir(), $type, $pid);
return \sprintf('%s/%s_%s', $this->getRuntimeDir(), $type, $pid);
}
/**
@@ -861,7 +861,7 @@ class Configuration
*/
public function setPager($pager)
{
if ($pager && !is_string($pager) && !$pager instanceof OutputPager) {
if ($pager && !\is_string($pager) && !$pager instanceof OutputPager) {
throw new \InvalidArgumentException('Unexpected pager instance');
}
@@ -879,10 +879,10 @@ class Configuration
public function getPager()
{
if (!isset($this->pager) && $this->usePcntl()) {
if ($pager = ini_get('cli.pager')) {
if ($pager = \ini_get('cli.pager')) {
// use the default pager
$this->pager = $pager;
} elseif ($less = exec('which less 2>/dev/null')) {
} elseif ($less = \exec('which less 2>/dev/null')) {
// check for the presence of less...
$this->pager = $less . ' -R -S -F -X';
}
@@ -937,7 +937,7 @@ class Configuration
*/
public function addMatchers(array $matchers)
{
$this->newMatchers = array_merge($this->newMatchers, $matchers);
$this->newMatchers = \array_merge($this->newMatchers, $matchers);
if (isset($this->shell)) {
$this->doAddMatchers();
}
@@ -977,7 +977,7 @@ class Configuration
*/
public function addCommands(array $commands)
{
$this->newCommands = array_merge($this->newCommands, $commands);
$this->newCommands = \array_merge($this->newCommands, $commands);
if (isset($this->shell)) {
$this->doAddCommands();
}
@@ -1033,9 +1033,9 @@ class Configuration
$files = ConfigPaths::getDataFiles(['php_manual.sqlite'], $this->dataDir);
if (!empty($files)) {
if ($this->warnOnMultipleConfigs && count($files) > 1) {
$msg = sprintf('Multiple manual database files found: %s. Using %s', implode($files, ', '), $files[0]);
trigger_error($msg, E_USER_NOTICE);
if ($this->warnOnMultipleConfigs && \count($files) > 1) {
$msg = \sprintf('Multiple manual database files found: %s. Using %s', \implode($files, ', '), $files[0]);
\trigger_error($msg, E_USER_NOTICE);
}
return $this->manualDbFile = $files[0];
@@ -1051,7 +1051,7 @@ class Configuration
{
if (!isset($this->manualDb)) {
$dbFile = $this->getManualDbFile();
if (is_file($dbFile)) {
if (\is_file($dbFile)) {
try {
$this->manualDb = new \PDO('sqlite:' . $dbFile);
} catch (\PDOException $e) {
@@ -1133,7 +1133,7 @@ class Configuration
self::COLOR_MODE_DISABLED,
];
if (in_array($colorMode, $validColorModes)) {
if (\in_array($colorMode, $validColorModes)) {
$this->colorMode = $colorMode;
} else {
throw new \InvalidArgumentException('invalid color mode: ' . $colorMode);
@@ -1226,7 +1226,7 @@ class Configuration
Checker::NEVER,
];
if (!in_array($interval, $validIntervals)) {
if (!\in_array($interval, $validIntervals)) {
throw new \InvalidArgumentException('invalid update check interval: ' . $interval);
}

View File

@@ -75,13 +75,13 @@ class Context
case '__file':
case '__line':
case '__dir':
if (array_key_exists($name, $this->commandScopeVariables)) {
if (\array_key_exists($name, $this->commandScopeVariables)) {
return $this->commandScopeVariables[$name];
}
break;
default:
if (array_key_exists($name, $this->scopeVariables)) {
if (\array_key_exists($name, $this->scopeVariables)) {
return $this->scopeVariables[$name];
}
break;
@@ -97,7 +97,7 @@ class Context
*/
public function getAll()
{
return array_merge($this->scopeVariables, $this->getSpecialVariables());
return \array_merge($this->scopeVariables, $this->getSpecialVariables());
}
/**
@@ -123,7 +123,7 @@ class Context
$vars['this'] = $this->boundObject;
}
return array_merge($vars, $this->commandScopeVariables);
return \array_merge($vars, $this->commandScopeVariables);
}
/**
@@ -228,7 +228,7 @@ class Context
*/
public function setBoundObject($boundObject)
{
$this->boundObject = is_object($boundObject) ? $boundObject : null;
$this->boundObject = \is_object($boundObject) ? $boundObject : null;
$this->boundClass = null;
}
@@ -251,7 +251,7 @@ class Context
*/
public function setBoundClass($boundClass)
{
$this->boundClass = (is_string($boundClass) && $boundClass !== '') ? $boundClass : null;
$this->boundClass = (\is_string($boundClass) && $boundClass !== '') ? $boundClass : null;
$this->boundObject = null;
}
@@ -275,7 +275,7 @@ class Context
$vars = [];
foreach ($commandScopeVariables as $key => $value) {
// kind of type check
if (is_scalar($value) && in_array($key, self::$commandScopeNames)) {
if (\is_scalar($value) && \in_array($key, self::$commandScopeNames)) {
$vars[$key] = $value;
}
}
@@ -303,7 +303,7 @@ class Context
*/
public function getUnusedCommandScopeVariableNames()
{
return array_diff(self::$commandScopeNames, array_keys($this->commandScopeVariables));
return \array_diff(self::$commandScopeNames, \array_keys($this->commandScopeVariables));
}
/**
@@ -315,6 +315,6 @@ class Context
*/
public static function isSpecialVariableName($name)
{
return in_array($name, self::$specialNames) || in_array($name, self::$commandScopeNames);
return \in_array($name, self::$specialNames) || \in_array($name, self::$commandScopeNames);
}
}

View File

@@ -24,7 +24,7 @@ class BreakException extends \Exception implements Exception
public function __construct($message = '', $code = 0, \Exception $previous = null)
{
$this->rawMessage = $message;
parent::__construct(sprintf('Exit: %s', $message), $code, $previous);
parent::__construct(\sprintf('Exit: %s', $message), $code, $previous);
}
/**

View File

@@ -32,7 +32,7 @@ class ErrorException extends \ErrorException implements Exception
{
$this->rawMessage = $message;
if (!empty($filename) && preg_match('{Psy[/\\\\]ExecutionLoop}', $filename)) {
if (!empty($filename) && \preg_match('{Psy[/\\\\]ExecutionLoop}', $filename)) {
$filename = '';
}
@@ -67,7 +67,7 @@ class ErrorException extends \ErrorException implements Exception
break;
}
$message = sprintf('PHP %s: %s%s on line %d', $type, $message, $filename ? ' in ' . $filename : '', $lineno);
$message = \sprintf('PHP %s: %s%s on line %d', $type, $message, $filename ? ' in ' . $filename : '', $lineno);
parent::__construct($message, $code, $severity, $filename, $lineno, $previous);
}

View File

@@ -36,7 +36,7 @@ class FatalErrorException extends \ErrorException implements Exception
}
$this->rawMessage = $message;
$message = sprintf('PHP Fatal error: %s in %s on line %d', $message, $filename ?: "eval()'d code", $lineno);
$message = \sprintf('PHP Fatal error: %s in %s on line %d', $message, $filename ?: "eval()'d code", $lineno);
parent::__construct($message, $code, $severity, $filename, $lineno, $previous);
}

View File

@@ -24,7 +24,7 @@ class ParseErrorException extends \PhpParser\Error implements Exception
*/
public function __construct($message = '', $line = -1)
{
$message = sprintf('PHP Parse error: %s', $message);
$message = \sprintf('PHP Parse error: %s', $message);
parent::__construct($message, $line);
}

View File

@@ -21,7 +21,7 @@ class ThrowUpException extends \Exception implements Exception
*/
public function __construct(\Exception $exception)
{
$message = sprintf("Throwing %s with message '%s'", get_class($exception), $exception->getMessage());
$message = \sprintf("Throwing %s with message '%s'", \get_class($exception), $exception->getMessage());
parent::__construct($message, $exception->getCode(), $exception);
}

View File

@@ -27,8 +27,8 @@ class TypeErrorException extends \Exception implements Exception
public function __construct($message = '', $code = 0)
{
$this->rawMessage = $message;
$message = preg_replace('/, called in .*?: eval\\(\\)\'d code/', '', $message);
parent::__construct(sprintf('TypeError: %s', $message), $code);
$message = \preg_replace('/, called in .*?: eval\\(\\)\'d code/', '', $message);
parent::__construct(\sprintf('TypeError: %s', $message), $code);
}
/**

View File

@@ -28,42 +28,42 @@ class ExecutionClosure
$this->setClosure($__psysh__, function () use ($__psysh__) {
try {
// Restore execution scope variables
extract($__psysh__->getScopeVariables(false));
\extract($__psysh__->getScopeVariables(false));
// Buffer stdout; we'll need it later
ob_start([$__psysh__, 'writeStdout'], 1);
\ob_start([$__psysh__, 'writeStdout'], 1);
// Convert all errors to exceptions
set_error_handler([$__psysh__, 'handleError']);
\set_error_handler([$__psysh__, 'handleError']);
// Evaluate the current code buffer
$_ = eval($__psysh__->onExecute($__psysh__->flushCode() ?: ExecutionClosure::NOOP_INPUT));
} catch (\Throwable $_e) {
// Clean up on our way out.
restore_error_handler();
if (ob_get_level() > 0) {
ob_end_clean();
\restore_error_handler();
if (\ob_get_level() > 0) {
\ob_end_clean();
}
throw $_e;
} catch (\Exception $_e) {
// Clean up on our way out.
restore_error_handler();
if (ob_get_level() > 0) {
ob_end_clean();
\restore_error_handler();
if (\ob_get_level() > 0) {
\ob_end_clean();
}
throw $_e;
}
// Won't be needing this anymore
restore_error_handler();
\restore_error_handler();
// Flush stdout (write to shell output, plus save to magic variable)
ob_end_flush();
\ob_end_flush();
// Save execution scope variables for next time
$__psysh__->setScopeVariables(get_defined_vars());
$__psysh__->setScopeVariables(\get_defined_vars());
return $_;
});
@@ -79,8 +79,8 @@ class ExecutionClosure
{
if (self::shouldBindClosure()) {
$that = $shell->getBoundObject();
if (is_object($that)) {
$closure = $closure->bindTo($that, get_class($that));
if (\is_object($that)) {
$closure = $closure->bindTo($that, \get_class($that));
} else {
$closure = $closure->bindTo(null, $shell->getBoundClass());
}
@@ -110,8 +110,8 @@ class ExecutionClosure
{
// skip binding on HHVM < 3.5.0
// see https://github.com/facebook/hhvm/issues/1203
if (defined('HHVM_VERSION')) {
return version_compare(HHVM_VERSION, '3.5.0', '>=');
if (\defined('HHVM_VERSION')) {
return \version_compare(HHVM_VERSION, '3.5.0', '>=');
}
return true;

View File

@@ -42,7 +42,7 @@ class ExecutionLoop
{
// Load user-defined includes
$load = function (Shell $__psysh__) {
set_error_handler([$__psysh__, 'handleError']);
\set_error_handler([$__psysh__, 'handleError']);
foreach ($__psysh__->getIncludes() as $__psysh_include__) {
try {
include $__psysh_include__;
@@ -52,14 +52,14 @@ class ExecutionLoop
$__psysh__->writeException($_e);
}
}
restore_error_handler();
\restore_error_handler();
unset($__psysh_include__);
// Override any new local variables with pre-defined scope variables
extract($__psysh__->getScopeVariables(false));
\extract($__psysh__->getScopeVariables(false));
// ... then add the whole mess of variables back.
$__psysh__->setScopeVariables(get_defined_vars());
$__psysh__->setScopeVariables(\get_defined_vars());
};
$load($shell);

View File

@@ -33,7 +33,7 @@ class ProcessForker extends AbstractListener
*/
public static function isSupported()
{
return function_exists('pcntl_signal') && function_exists('posix_getpid');
return \function_exists('pcntl_signal') && \function_exists('posix_getpid');
}
/**
@@ -46,20 +46,20 @@ class ProcessForker extends AbstractListener
*/
public function beforeRun(Shell $shell)
{
list($up, $down) = stream_socket_pair(STREAM_PF_UNIX, STREAM_SOCK_STREAM, STREAM_IPPROTO_IP);
list($up, $down) = \stream_socket_pair(STREAM_PF_UNIX, STREAM_SOCK_STREAM, STREAM_IPPROTO_IP);
if (!$up) {
throw new \RuntimeException('Unable to create socket pair');
}
$pid = pcntl_fork();
$pid = \pcntl_fork();
if ($pid < 0) {
throw new \RuntimeException('Unable to start execution loop');
} elseif ($pid > 0) {
// This is the main thread. We'll just wait for a while.
// We won't be needing this one.
fclose($up);
\fclose($up);
// Wait for a return value from the loop process.
$read = [$down];
@@ -67,40 +67,40 @@ class ProcessForker extends AbstractListener
$except = null;
do {
$n = @stream_select($read, $write, $except, null);
$n = @\stream_select($read, $write, $except, null);
if ($n === 0) {
throw new \RuntimeException('Process timed out waiting for execution loop');
}
if ($n === false) {
$err = error_get_last();
if (!isset($err['message']) || stripos($err['message'], 'interrupted system call') === false) {
$err = \error_get_last();
if (!isset($err['message']) || \stripos($err['message'], 'interrupted system call') === false) {
$msg = $err['message'] ?
sprintf('Error waiting for execution loop: %s', $err['message']) :
\sprintf('Error waiting for execution loop: %s', $err['message']) :
'Error waiting for execution loop';
throw new \RuntimeException($msg);
}
}
} while ($n < 1);
$content = stream_get_contents($down);
fclose($down);
$content = \stream_get_contents($down);
\fclose($down);
if ($content) {
$shell->setScopeVariables(@unserialize($content));
$shell->setScopeVariables(@\unserialize($content));
}
throw new BreakException('Exiting main thread');
}
// This is the child process. It's going to do all the work.
if (function_exists('setproctitle')) {
if (\function_exists('setproctitle')) {
setproctitle('psysh (loop)');
}
// We won't be needing this one.
fclose($down);
\fclose($down);
// Save this; we'll need to close it in `afterRun`
$this->up = $up;
@@ -125,8 +125,8 @@ class ProcessForker extends AbstractListener
{
// if there's an old savegame hanging around, let's kill it.
if (isset($this->savegame)) {
posix_kill($this->savegame, SIGKILL);
pcntl_signal_dispatch();
\posix_kill($this->savegame, SIGKILL);
\pcntl_signal_dispatch();
}
}
@@ -140,10 +140,10 @@ class ProcessForker extends AbstractListener
{
// We're a child thread. Send the scope variables back up to the main thread.
if (isset($this->up)) {
fwrite($this->up, $this->serializeReturn($shell->getScopeVariables(false)));
fclose($this->up);
\fwrite($this->up, $this->serializeReturn($shell->getScopeVariables(false)));
\fclose($this->up);
posix_kill(posix_getpid(), SIGKILL);
\posix_kill(\posix_getpid(), SIGKILL);
}
}
@@ -157,18 +157,18 @@ class ProcessForker extends AbstractListener
private function createSavegame()
{
// the current process will become the savegame
$this->savegame = posix_getpid();
$this->savegame = \posix_getpid();
$pid = pcntl_fork();
$pid = \pcntl_fork();
if ($pid < 0) {
throw new \RuntimeException('Unable to create savegame fork');
} elseif ($pid > 0) {
// we're the savegame now... let's wait and see what happens
pcntl_waitpid($pid, $status);
\pcntl_waitpid($pid, $status);
// worker exited cleanly, let's bail
if (!pcntl_wexitstatus($status)) {
posix_kill(posix_getpid(), SIGKILL);
if (!\pcntl_wexitstatus($status)) {
\posix_kill(\posix_getpid(), SIGKILL);
}
// worker didn't exit cleanly, we'll need to have another go
@@ -199,12 +199,12 @@ class ProcessForker extends AbstractListener
}
// Resources and Closures don't error, but they don't serialize well either.
if (is_resource($value) || $value instanceof \Closure) {
if (\is_resource($value) || $value instanceof \Closure) {
continue;
}
try {
@serialize($value);
@\serialize($value);
$serializable[$key] = $value;
} catch (\Throwable $e) {
// we'll just ignore this one...
@@ -214,6 +214,6 @@ class ProcessForker extends AbstractListener
}
}
return @serialize($serializable);
return @\serialize($serializable);
}
}

View File

@@ -30,7 +30,7 @@ class RunkitReloader extends AbstractListener
*/
public static function isSupported()
{
return extension_loaded('runkit');
return \extension_loaded('runkit');
}
/**
@@ -62,11 +62,11 @@ class RunkitReloader extends AbstractListener
*/
private function reload(Shell $shell)
{
clearstatcache();
\clearstatcache();
$modified = [];
foreach (get_included_files() as $file) {
$timestamp = filemtime($file);
foreach (\get_included_files() as $file) {
$timestamp = \filemtime($file);
if (!isset($this->timestamps[$file])) {
$this->timestamps[$file] = $timestamp;
@@ -78,7 +78,7 @@ class RunkitReloader extends AbstractListener
}
if (!$this->lintFile($file)) {
$msg = sprintf('Modified file "%s" could not be reloaded', $file);
$msg = \sprintf('Modified file "%s" could not be reloaded', $file);
$shell->writeException(new ParseErrorException($msg));
continue;
}
@@ -125,7 +125,7 @@ class RunkitReloader extends AbstractListener
{
// first try to parse it
try {
$this->parser->parse(file_get_contents($file));
$this->parser->parse(\file_get_contents($file));
} catch (\Exception $e) {
return false;
}

View File

@@ -31,7 +31,7 @@ class ExecutionLoopClosure extends ExecutionClosure
{
$this->setClosure($__psysh__, function () use ($__psysh__) {
// Restore execution scope variables
extract($__psysh__->getScopeVariables(false));
\extract($__psysh__->getScopeVariables(false));
do {
$__psysh__->beforeLoop();
@@ -40,40 +40,43 @@ class ExecutionLoopClosure extends ExecutionClosure
$__psysh__->getInput();
try {
// Pull in any new execution scope variables
\extract($__psysh__->getScopeVariablesDiff(\get_defined_vars()));
// Buffer stdout; we'll need it later
ob_start([$__psysh__, 'writeStdout'], 1);
\ob_start([$__psysh__, 'writeStdout'], 1);
// Convert all errors to exceptions
set_error_handler([$__psysh__, 'handleError']);
\set_error_handler([$__psysh__, 'handleError']);
// Evaluate the current code buffer
$_ = eval($__psysh__->onExecute($__psysh__->flushCode() ?: ExecutionClosure::NOOP_INPUT));
} catch (\Throwable $_e) {
// Clean up on our way out.
restore_error_handler();
if (ob_get_level() > 0) {
ob_end_clean();
\restore_error_handler();
if (\ob_get_level() > 0) {
\ob_end_clean();
}
throw $_e;
} catch (\Exception $_e) {
// Clean up on our way out.
restore_error_handler();
if (ob_get_level() > 0) {
ob_end_clean();
\restore_error_handler();
if (\ob_get_level() > 0) {
\ob_end_clean();
}
throw $_e;
}
// Won't be needing this anymore
restore_error_handler();
\restore_error_handler();
// Flush stdout (write to shell output, plus save to magic variable)
ob_end_flush();
\ob_end_flush();
// Save execution scope variables for next time
$__psysh__->setScopeVariables(get_defined_vars());
$__psysh__->setScopeVariables(\get_defined_vars());
$__psysh__->writeReturnValue($_);
} catch (BreakException $_e) {

View File

@@ -38,11 +38,11 @@ class CodeFormatter implements Formatter
$colorMode = $colorMode ?: Configuration::COLOR_MODE_AUTO;
if ($fileName = $reflector->getFileName()) {
if (!is_file($fileName)) {
if (!\is_file($fileName)) {
throw new RuntimeException('Source code unavailable');
}
$file = file_get_contents($fileName);
$file = \file_get_contents($fileName);
$start = $reflector->getStartLine();
$end = $reflector->getEndLine() - $start;

View File

@@ -45,20 +45,20 @@ class DocblockFormatter implements Formatter
if (!empty($docblock->tags)) {
foreach ($docblock::$vectors as $name => $vector) {
if (isset($docblock->tags[$name])) {
$chunks[] = sprintf('<comment>%s:</comment>', self::inflect($name));
$chunks[] = \sprintf('<comment>%s:</comment>', self::inflect($name));
$chunks[] = self::formatVector($vector, $docblock->tags[$name]);
$chunks[] = '';
}
}
$tags = self::formatTags(array_keys($docblock::$vectors), $docblock->tags);
$tags = self::formatTags(\array_keys($docblock::$vectors), $docblock->tags);
if (!empty($tags)) {
$chunks[] = $tags;
$chunks[] = '';
}
}
return rtrim(implode("\n", $chunks));
return \rtrim(\implode("\n", $chunks));
}
/**
@@ -78,7 +78,7 @@ class DocblockFormatter implements Formatter
$max = 0;
foreach ($lines as $line) {
$chunk = $line[$type];
$cur = empty($chunk) ? 0 : strlen($chunk) + 1;
$cur = empty($chunk) ? 0 : \strlen($chunk) + 1;
if ($cur > $max) {
$max = $cur;
}
@@ -86,12 +86,12 @@ class DocblockFormatter implements Formatter
$template[] = self::getVectorParamTemplate($type, $max);
}
$template = implode(' ', $template);
$template = \implode(' ', $template);
return implode("\n", array_map(function ($line) use ($template) {
$escaped = array_map(['Symfony\Component\Console\Formatter\OutputFormatter', 'escape'], $line);
return \implode("\n", \array_map(function ($line) use ($template) {
$escaped = \array_map(['Symfony\Component\Console\Formatter\OutputFormatter', 'escape'], $line);
return rtrim(vsprintf($template, $escaped));
return \rtrim(\vsprintf($template, $escaped));
}, $lines));
}
@@ -108,18 +108,18 @@ class DocblockFormatter implements Formatter
$chunks = [];
foreach ($tags as $name => $values) {
if (in_array($name, $skip)) {
if (\in_array($name, $skip)) {
continue;
}
foreach ($values as $value) {
$chunks[] = sprintf('<comment>%s%s</comment> %s', self::inflect($name), empty($value) ? '' : ':', OutputFormatter::escape($value));
$chunks[] = \sprintf('<comment>%s%s</comment> %s', self::inflect($name), empty($value) ? '' : ':', OutputFormatter::escape($value));
}
$chunks[] = '';
}
return implode("\n", $chunks);
return \implode("\n", $chunks);
}
/**
@@ -133,10 +133,10 @@ class DocblockFormatter implements Formatter
private static function getVectorParamTemplate($type, $max)
{
if (!isset(self::$vectorParamTemplates[$type])) {
return sprintf('%%-%ds', $max);
return \sprintf('%%-%ds', $max);
}
return sprintf('<%s>%%-%ds</%s>', self::$vectorParamTemplates[$type], $max, self::$vectorParamTemplates[$type]);
return \sprintf('<%s>%%-%ds</%s>', self::$vectorParamTemplates[$type], $max, self::$vectorParamTemplates[$type]);
}
/**
@@ -149,7 +149,7 @@ class DocblockFormatter implements Formatter
*/
private static function indent($text, $indent = ' ')
{
return $indent . str_replace("\n", "\n" . $indent, $text);
return $indent . \str_replace("\n", "\n" . $indent, $text);
}
/**
@@ -161,8 +161,8 @@ class DocblockFormatter implements Formatter
*/
private static function inflect($text)
{
$words = trim(preg_replace('/[\s_-]+/', ' ', preg_replace('/([a-z])([A-Z])/', '$1 $2', $text)));
$words = \trim(\preg_replace('/[\s_-]+/', ' ', \preg_replace('/([a-z])([A-Z])/', '$1 $2', $text)));
return implode(' ', array_map('ucfirst', explode(' ', $words)));
return \implode(' ', \array_map('ucfirst', \explode(' ', $words)));
}
}

View File

@@ -56,7 +56,7 @@ class SignatureFormatter implements Formatter
return self::formatConstant($reflector);
default:
throw new \InvalidArgumentException('Unexpected Reflector class: ' . get_class($reflector));
throw new \InvalidArgumentException('Unexpected Reflector class: ' . \get_class($reflector));
}
}
@@ -84,13 +84,13 @@ class SignatureFormatter implements Formatter
if ($reflector instanceof \ReflectionClass && $reflector->isTrait()) {
// For some reason, PHP 5.x returns `abstract public` modifiers for
// traits. Let's just ignore that business entirely.
if (version_compare(PHP_VERSION, '7.0.0', '<')) {
if (\version_compare(PHP_VERSION, '7.0.0', '<')) {
return [];
}
}
return implode(' ', array_map(function ($modifier) {
return sprintf('<keyword>%s</keyword>', $modifier);
return \implode(' ', \array_map(function ($modifier) {
return \sprintf('<keyword>%s</keyword>', $modifier);
}, \Reflection::getModifierNames($reflector->getModifiers())));
}
@@ -115,24 +115,24 @@ class SignatureFormatter implements Formatter
$chunks[] = $reflector->isInterface() ? 'interface' : 'class';
}
$chunks[] = sprintf('<class>%s</class>', self::formatName($reflector));
$chunks[] = \sprintf('<class>%s</class>', self::formatName($reflector));
if ($parent = $reflector->getParentClass()) {
$chunks[] = 'extends';
$chunks[] = sprintf('<class>%s</class>', $parent->getName());
$chunks[] = \sprintf('<class>%s</class>', $parent->getName());
}
$interfaces = $reflector->getInterfaceNames();
if (!empty($interfaces)) {
sort($interfaces);
\sort($interfaces);
$chunks[] = 'implements';
$chunks[] = implode(', ', array_map(function ($name) {
return sprintf('<class>%s</class>', $name);
$chunks[] = \implode(', ', \array_map(function ($name) {
return \sprintf('<class>%s</class>', $name);
}, $interfaces));
}
return implode(' ', $chunks);
return \implode(' ', $chunks);
}
/**
@@ -147,7 +147,7 @@ class SignatureFormatter implements Formatter
$value = $reflector->getValue();
$style = self::getTypeStyle($value);
return sprintf(
return \sprintf(
'<keyword>const</keyword> <const>%s</const> = <%s>%s</%s>',
self::formatName($reflector),
$style,
@@ -168,7 +168,7 @@ class SignatureFormatter implements Formatter
$value = $reflector->getValue();
$style = self::getTypeStyle($value);
return sprintf(
return \sprintf(
'<keyword>define</keyword>(<string>%s</string>, <%s>%s</%s>)',
OutputFormatter::escape(Json::encode($reflector->getName())),
$style,
@@ -186,11 +186,11 @@ class SignatureFormatter implements Formatter
*/
private static function getTypeStyle($value)
{
if (is_int($value) || is_float($value)) {
if (\is_int($value) || \is_float($value)) {
return 'number';
} elseif (is_string($value)) {
} elseif (\is_string($value)) {
return 'string';
} elseif (is_bool($value) || is_null($value)) {
} elseif (\is_bool($value) || \is_null($value)) {
return 'bool';
} else {
return 'strong'; // @codeCoverageIgnore
@@ -206,7 +206,7 @@ class SignatureFormatter implements Formatter
*/
private static function formatProperty(\ReflectionProperty $reflector)
{
return sprintf(
return \sprintf(
'%s <strong>$%s</strong>',
self::formatModifiers($reflector),
$reflector->getName()
@@ -222,11 +222,11 @@ class SignatureFormatter implements Formatter
*/
private static function formatFunction(\ReflectionFunctionAbstract $reflector)
{
return sprintf(
return \sprintf(
'<keyword>function</keyword> %s<function>%s</function>(%s)',
$reflector->returnsReference() ? '&' : '',
self::formatName($reflector),
implode(', ', self::formatFunctionParams($reflector))
\implode(', ', self::formatFunctionParams($reflector))
);
}
@@ -239,7 +239,7 @@ class SignatureFormatter implements Formatter
*/
private static function formatMethod(\ReflectionMethod $reflector)
{
return sprintf(
return \sprintf(
'%s %s',
self::formatModifiers($reflector),
self::formatFunction($reflector)
@@ -262,7 +262,7 @@ class SignatureFormatter implements Formatter
if ($param->isArray()) {
$hint = '<keyword>array</keyword> ';
} elseif ($class = $param->getClass()) {
$hint = sprintf('<class>%s</class> ', $class->getName());
$hint = \sprintf('<class>%s</class> ', $class->getName());
}
} catch (\Exception $e) {
// sometimes we just don't know...
@@ -272,11 +272,11 @@ class SignatureFormatter implements Formatter
// Hax: we'll try to extract it :P
// @codeCoverageIgnoreStart
$chunks = explode('$' . $param->getName(), (string) $param);
$chunks = explode(' ', trim($chunks[0]));
$guess = end($chunks);
$chunks = \explode('$' . $param->getName(), (string) $param);
$chunks = \explode(' ', \trim($chunks[0]));
$guess = \end($chunks);
$hint = sprintf('<urgent>%s</urgent> ', $guess);
$hint = \sprintf('<urgent>%s</urgent> ', $guess);
// @codeCoverageIgnoreEnd
}
@@ -287,14 +287,14 @@ class SignatureFormatter implements Formatter
} else {
$value = $param->getDefaultValue();
$typeStyle = self::getTypeStyle($value);
$value = is_array($value) ? 'array()' : is_null($value) ? 'null' : var_export($value, true);
$value = \is_array($value) ? 'array()' : \is_null($value) ? 'null' : \var_export($value, true);
}
$default = sprintf(' = <%s>%s</%s>', $typeStyle, OutputFormatter::escape($value), $typeStyle);
$default = \sprintf(' = <%s>%s</%s>', $typeStyle, OutputFormatter::escape($value), $typeStyle);
} else {
$default = '';
}
$params[] = sprintf(
$params[] = \sprintf(
'%s%s<strong>$%s</strong>%s',
$param->isPassedByReference() ? '&' : '',
$hint,

View File

@@ -56,7 +56,7 @@ class FilterOptions
}
if (!$this->stringIsRegex($pattern)) {
$pattern = '/' . preg_quote($pattern, '/') . '/';
$pattern = '/' . \preg_quote($pattern, '/') . '/';
}
if ($insensitive = $input->getOption('insensitive')) {
@@ -91,7 +91,7 @@ class FilterOptions
*/
public function match($string, array &$matches = null)
{
return $this->filter === false || (preg_match($this->pattern, $string, $matches) xor $this->invert);
return $this->filter === false || (\preg_match($this->pattern, $string, $matches) xor $this->invert);
}
/**
@@ -121,7 +121,7 @@ class FilterOptions
*/
private function stringIsRegex($string)
{
return substr($string, 0, 1) === '/' && substr($string, -1) === '/' && strlen($string) >= 3;
return \substr($string, 0, 1) === '/' && \substr($string, -1) === '/' && \strlen($string) >= 3;
}
/**
@@ -133,13 +133,13 @@ class FilterOptions
*/
private function validateRegex($pattern)
{
set_error_handler(['Psy\Exception\ErrorException', 'throwException']);
\set_error_handler(['Psy\Exception\ErrorException', 'throwException']);
try {
preg_match($pattern, '');
\preg_match($pattern, '');
} catch (ErrorException $e) {
restore_error_handler();
throw new RuntimeException(str_replace('preg_match(): ', 'Invalid regular expression: ', $e->getRawMessage()));
\restore_error_handler();
throw new RuntimeException(\str_replace('preg_match(): ', 'Invalid regular expression: ', $e->getRawMessage()));
}
restore_error_handler();
\restore_error_handler();
}
}

View File

@@ -51,10 +51,10 @@ class ShellInput extends StringInput
if ($definition->getArgumentCount() > 0) {
$args = $definition->getArguments();
$lastArg = array_pop($args);
$lastArg = \array_pop($args);
foreach ($args as $arg) {
if ($arg instanceof CodeArgument) {
$msg = sprintf('Unexpected CodeArgument before the final position: %s', $arg->getName());
$msg = \sprintf('Unexpected CodeArgument before the final position: %s', $arg->getName());
throw new \InvalidArgumentException($msg);
}
}
@@ -84,33 +84,33 @@ class ShellInput extends StringInput
private function tokenize($input)
{
$tokens = [];
$length = strlen($input);
$length = \strlen($input);
$cursor = 0;
while ($cursor < $length) {
if (preg_match('/\s+/A', $input, $match, null, $cursor)) {
} elseif (preg_match('/([^="\'\s]+?)(=?)(' . StringInput::REGEX_QUOTED_STRING . '+)/A', $input, $match, null, $cursor)) {
if (\preg_match('/\s+/A', $input, $match, null, $cursor)) {
} elseif (\preg_match('/([^="\'\s]+?)(=?)(' . StringInput::REGEX_QUOTED_STRING . '+)/A', $input, $match, null, $cursor)) {
$tokens[] = [
$match[1] . $match[2] . stripcslashes(str_replace(['"\'', '\'"', '\'\'', '""'], '', substr($match[3], 1, strlen($match[3]) - 2))),
stripcslashes(substr($input, $cursor)),
$match[1] . $match[2] . \stripcslashes(\str_replace(['"\'', '\'"', '\'\'', '""'], '', \substr($match[3], 1, \strlen($match[3]) - 2))),
\stripcslashes(\substr($input, $cursor)),
];
} elseif (preg_match('/' . StringInput::REGEX_QUOTED_STRING . '/A', $input, $match, null, $cursor)) {
} elseif (\preg_match('/' . StringInput::REGEX_QUOTED_STRING . '/A', $input, $match, null, $cursor)) {
$tokens[] = [
stripcslashes(substr($match[0], 1, strlen($match[0]) - 2)),
stripcslashes(substr($input, $cursor)),
\stripcslashes(\substr($match[0], 1, \strlen($match[0]) - 2)),
\stripcslashes(\substr($input, $cursor)),
];
} elseif (preg_match('/' . StringInput::REGEX_STRING . '/A', $input, $match, null, $cursor)) {
} elseif (\preg_match('/' . StringInput::REGEX_STRING . '/A', $input, $match, null, $cursor)) {
$tokens[] = [
stripcslashes($match[1]),
stripcslashes(substr($input, $cursor)),
\stripcslashes($match[1]),
\stripcslashes(\substr($input, $cursor)),
];
} else {
// should never happen
// @codeCoverageIgnoreStart
throw new \InvalidArgumentException(sprintf('Unable to parse input near "... %s ..."', substr($input, $cursor, 10)));
throw new \InvalidArgumentException(\sprintf('Unable to parse input near "... %s ..."', \substr($input, $cursor, 10)));
// @codeCoverageIgnoreEnd
}
$cursor += strlen($match[0]);
$cursor += \strlen($match[0]);
}
return $tokens;
@@ -123,7 +123,7 @@ class ShellInput extends StringInput
{
$parseOptions = true;
$this->parsed = $this->tokenPairs;
while (null !== $tokenPair = array_shift($this->parsed)) {
while (null !== $tokenPair = \array_shift($this->parsed)) {
// token is what you'd expect. rest is the remainder of the input
// string, including token, and will be used if this is a code arg.
list($token, $rest) = $tokenPair;
@@ -132,7 +132,7 @@ class ShellInput extends StringInput
$this->parseShellArgument($token, $rest);
} elseif ($parseOptions && '--' === $token) {
$parseOptions = false;
} elseif ($parseOptions && 0 === strpos($token, '--')) {
} elseif ($parseOptions && 0 === \strpos($token, '--')) {
$this->parseLongOption($token);
} elseif ($parseOptions && '-' === $token[0] && '-' !== $token) {
$this->parseShortOption($token);
@@ -152,7 +152,7 @@ class ShellInput extends StringInput
*/
private function parseShellArgument($token, $rest)
{
$c = count($this->arguments);
$c = \count($this->arguments);
// if input is expecting another argument, add it
if ($this->definition->hasArgument($c)) {
@@ -184,11 +184,11 @@ class ShellInput extends StringInput
// unexpected argument
$all = $this->definition->getArguments();
if (count($all)) {
throw new \RuntimeException(sprintf('Too many arguments, expected arguments "%s".', implode('" "', array_keys($all))));
if (\count($all)) {
throw new \RuntimeException(\sprintf('Too many arguments, expected arguments "%s".', \implode('" "', \array_keys($all))));
}
throw new \RuntimeException(sprintf('No arguments expected, got "%s".', $token));
throw new \RuntimeException(\sprintf('No arguments expected, got "%s".', $token));
// @codeCoverageIgnoreEnd
}
@@ -202,12 +202,12 @@ class ShellInput extends StringInput
*/
private function parseShortOption($token)
{
$name = substr($token, 1);
$name = \substr($token, 1);
if (strlen($name) > 1) {
if (\strlen($name) > 1) {
if ($this->definition->hasShortcut($name[0]) && $this->definition->getOptionForShortcut($name[0])->acceptValue()) {
// an option with a value (with no space)
$this->addShortOption($name[0], substr($name, 1));
$this->addShortOption($name[0], \substr($name, 1));
} else {
$this->parseShortOptionSet($name);
}
@@ -225,15 +225,15 @@ class ShellInput extends StringInput
*/
private function parseShortOptionSet($name)
{
$len = strlen($name);
$len = \strlen($name);
for ($i = 0; $i < $len; $i++) {
if (!$this->definition->hasShortcut($name[$i])) {
throw new \RuntimeException(sprintf('The "-%s" option does not exist.', $name[$i]));
throw new \RuntimeException(\sprintf('The "-%s" option does not exist.', $name[$i]));
}
$option = $this->definition->getOptionForShortcut($name[$i]);
if ($option->acceptValue()) {
$this->addLongOption($option->getName(), $i === $len - 1 ? null : substr($name, $i + 1));
$this->addLongOption($option->getName(), $i === $len - 1 ? null : \substr($name, $i + 1));
break;
} else {
@@ -249,18 +249,18 @@ class ShellInput extends StringInput
*/
private function parseLongOption($token)
{
$name = substr($token, 2);
$name = \substr($token, 2);
if (false !== $pos = strpos($name, '=')) {
if (0 === strlen($value = substr($name, $pos + 1))) {
if (false !== $pos = \strpos($name, '=')) {
if (0 === \strlen($value = \substr($name, $pos + 1))) {
// if no value after "=" then substr() returns "" since php7 only, false before
// see http://php.net/manual/fr/migration70.incompatible.php#119151
if (PHP_VERSION_ID < 70000 && false === $value) {
$value = '';
}
array_unshift($this->parsed, [$value, null]);
\array_unshift($this->parsed, [$value, null]);
}
$this->addLongOption(substr($name, 0, $pos), $value);
$this->addLongOption(\substr($name, 0, $pos), $value);
} else {
$this->addLongOption($name, null);
}
@@ -277,7 +277,7 @@ class ShellInput extends StringInput
private function addShortOption($shortcut, $value)
{
if (!$this->definition->hasShortcut($shortcut)) {
throw new \RuntimeException(sprintf('The "-%s" option does not exist.', $shortcut));
throw new \RuntimeException(\sprintf('The "-%s" option does not exist.', $shortcut));
}
$this->addLongOption($this->definition->getOptionForShortcut($shortcut)->getName(), $value);
@@ -294,30 +294,30 @@ class ShellInput extends StringInput
private function addLongOption($name, $value)
{
if (!$this->definition->hasOption($name)) {
throw new \RuntimeException(sprintf('The "--%s" option does not exist.', $name));
throw new \RuntimeException(\sprintf('The "--%s" option does not exist.', $name));
}
$option = $this->definition->getOption($name);
if (null !== $value && !$option->acceptValue()) {
throw new \RuntimeException(sprintf('The "--%s" option does not accept a value.', $name));
throw new \RuntimeException(\sprintf('The "--%s" option does not accept a value.', $name));
}
if (in_array($value, ['', null], true) && $option->acceptValue() && count($this->parsed)) {
if (\in_array($value, ['', null], true) && $option->acceptValue() && \count($this->parsed)) {
// if option accepts an optional or mandatory argument
// let's see if there is one provided
$next = array_shift($this->parsed);
$next = \array_shift($this->parsed);
$nextToken = $next[0];
if ((isset($nextToken[0]) && '-' !== $nextToken[0]) || in_array($nextToken, ['', null], true)) {
if ((isset($nextToken[0]) && '-' !== $nextToken[0]) || \in_array($nextToken, ['', null], true)) {
$value = $nextToken;
} else {
array_unshift($this->parsed, $next);
\array_unshift($this->parsed, $next);
}
}
if (null === $value) {
if ($option->isValueRequired()) {
throw new \RuntimeException(sprintf('The "--%s" option requires a value.', $name));
throw new \RuntimeException(\sprintf('The "--%s" option requires a value.', $name));
}
if (!$option->isArray() && !$option->isValueOptional()) {

View File

@@ -51,14 +51,14 @@ class ProcOutputPager extends StreamOutput implements OutputPager
public function doWrite($message, $newline)
{
$pipe = $this->getPipe();
if (false === @fwrite($pipe, $message . ($newline ? PHP_EOL : ''))) {
if (false === @\fwrite($pipe, $message . ($newline ? PHP_EOL : ''))) {
// @codeCoverageIgnoreStart
// should never happen
throw new \RuntimeException('Unable to write output');
// @codeCoverageIgnoreEnd
}
fflush($pipe);
\fflush($pipe);
}
/**
@@ -67,11 +67,11 @@ class ProcOutputPager extends StreamOutput implements OutputPager
public function close()
{
if (isset($this->pipe)) {
fclose($this->pipe);
\fclose($this->pipe);
}
if (isset($this->proc)) {
$exit = proc_close($this->proc);
$exit = \proc_close($this->proc);
if ($exit !== 0) {
throw new \RuntimeException('Error closing output stream');
}
@@ -88,10 +88,10 @@ class ProcOutputPager extends StreamOutput implements OutputPager
private function getPipe()
{
if (!isset($this->pipe) || !isset($this->proc)) {
$desc = [['pipe', 'r'], $this->stream, fopen('php://stderr', 'w')];
$this->proc = proc_open($this->cmd, $desc, $pipes);
$desc = [['pipe', 'r'], $this->stream, \fopen('php://stderr', 'w')];
$this->proc = \proc_open($this->cmd, $desc, $pipes);
if (!is_resource($this->proc)) {
if (!\is_resource($this->proc)) {
throw new \RuntimeException('Error opening output stream');
}

View File

@@ -41,7 +41,7 @@ class ShellOutput extends ConsoleOutput
if ($pager === null) {
$this->pager = new PassthruPager($this);
} elseif (is_string($pager)) {
} elseif (\is_string($pager)) {
$this->pager = new ProcOutputPager($this, $pager);
} elseif ($pager instanceof OutputPager) {
$this->pager = $pager;
@@ -65,17 +65,17 @@ class ShellOutput extends ConsoleOutput
*/
public function page($messages, $type = 0)
{
if (is_string($messages)) {
if (\is_string($messages)) {
$messages = (array) $messages;
}
if (!is_array($messages) && !is_callable($messages)) {
if (!\is_array($messages) && !\is_callable($messages)) {
throw new \InvalidArgumentException('Paged output requires a string, array or callback');
}
$this->startPaging();
if (is_callable($messages)) {
if (\is_callable($messages)) {
$messages($this);
} else {
$this->write($messages, true, $type);
@@ -122,15 +122,15 @@ class ShellOutput extends ConsoleOutput
$messages = (array) $messages;
if ($type & self::NUMBER_LINES) {
$pad = strlen((string) count($messages));
$pad = \strlen((string) \count($messages));
$template = $this->isDecorated() ? "<aside>%{$pad}s</aside>: %s" : "%{$pad}s: %s";
if ($type & self::OUTPUT_RAW) {
$messages = array_map(['Symfony\Component\Console\Formatter\OutputFormatter', 'escape'], $messages);
$messages = \array_map(['Symfony\Component\Console\Formatter\OutputFormatter', 'escape'], $messages);
}
foreach ($messages as $i => $line) {
$messages[$i] = sprintf($template, $i, $line);
$messages[$i] = \sprintf($template, $i, $line);
}
// clean this up for super.

View File

@@ -44,7 +44,7 @@ class ParserFactory
*/
public function hasKindsSupport()
{
return class_exists('PhpParser\ParserFactory');
return \class_exists('PhpParser\ParserFactory');
}
/**
@@ -55,7 +55,7 @@ class ParserFactory
public function getDefaultKind()
{
if ($this->hasKindsSupport()) {
return version_compare(PHP_VERSION, '7.0', '>=') ? static::ONLY_PHP7 : static::ONLY_PHP5;
return \version_compare(PHP_VERSION, '7.0', '>=') ? static::ONLY_PHP7 : static::ONLY_PHP5;
}
}
@@ -73,11 +73,11 @@ class ParserFactory
$kind = $kind ?: $this->getDefaultKind();
if (!in_array($kind, static::getPossibleKinds())) {
if (!\in_array($kind, static::getPossibleKinds())) {
throw new \InvalidArgumentException('Unknown parser kind');
}
$parser = $originalFactory->create(constant('PhpParser\ParserFactory::' . $kind));
$parser = $originalFactory->create(\constant('PhpParser\ParserFactory::' . $kind));
} else {
if ($kind !== null) {
throw new \InvalidArgumentException('Install PHP Parser v2.x to specify parser kind');

View File

@@ -36,7 +36,7 @@ class GNUReadline implements Readline
*/
public static function isSupported()
{
return function_exists('readline_list_history');
return \function_exists('readline_list_history');
}
/**
@@ -58,7 +58,7 @@ class GNUReadline implements Readline
*/
public function addHistory($line)
{
if ($res = readline_add_history($line)) {
if ($res = \readline_add_history($line)) {
$this->writeHistory();
}
@@ -70,7 +70,7 @@ class GNUReadline implements Readline
*/
public function clearHistory()
{
if ($res = readline_clear_history()) {
if ($res = \readline_clear_history()) {
$this->writeHistory();
}
@@ -96,12 +96,12 @@ class GNUReadline implements Readline
//
// https://github.com/php/php-src/blob/423a057023ef3c00d2ffc16a6b43ba01d0f71796/NEWS#L19-L21
//
if (version_compare(PHP_VERSION, '5.6.7', '>=') || !ini_get('open_basedir')) {
readline_read_history();
if (\version_compare(PHP_VERSION, '5.6.7', '>=') || !\ini_get('open_basedir')) {
\readline_read_history();
}
readline_clear_history();
\readline_clear_history();
return readline_read_history($this->historyFile);
return \readline_read_history($this->historyFile);
}
/**
@@ -109,7 +109,7 @@ class GNUReadline implements Readline
*/
public function readline($prompt = null)
{
return readline($prompt);
return \readline($prompt);
}
/**
@@ -117,7 +117,7 @@ class GNUReadline implements Readline
*/
public function redisplay()
{
readline_redisplay();
\readline_redisplay();
}
/**
@@ -128,7 +128,7 @@ class GNUReadline implements Readline
// We have to write history first, since it is used
// by Libedit to list history
if ($this->historyFile !== false) {
$res = readline_write_history($this->historyFile);
$res = \readline_write_history($this->historyFile);
} else {
$res = true;
}
@@ -144,25 +144,25 @@ class GNUReadline implements Readline
if ($this->eraseDups) {
// flip-flip technique: removes duplicates, latest entries win.
$hist = array_flip(array_flip($hist));
$hist = \array_flip(\array_flip($hist));
// sort on keys to get the order back
ksort($hist);
\ksort($hist);
}
if ($this->historySize > 0) {
$histsize = count($hist);
$histsize = \count($hist);
if ($histsize > $this->historySize) {
$hist = array_slice($hist, $histsize - $this->historySize);
$hist = \array_slice($hist, $histsize - $this->historySize);
}
}
readline_clear_history();
\readline_clear_history();
foreach ($hist as $line) {
readline_add_history($line);
\readline_add_history($line);
}
if ($this->historyFile !== false) {
return readline_write_history($this->historyFile);
return \readline_write_history($this->historyFile);
}
return true;

View File

@@ -27,7 +27,7 @@ class HoaConsole implements Readline
*/
public static function isSupported()
{
return class_exists('\Hoa\Console\Console', true);
return \class_exists('\Hoa\Console\Console', true);
}
public function __construct()

View File

@@ -29,7 +29,7 @@ class Libedit extends GNUReadline
*/
public static function isSupported()
{
return function_exists('readline') && !function_exists('readline_list_history');
return \function_exists('readline') && !\function_exists('readline_list_history');
}
/**
@@ -37,23 +37,23 @@ class Libedit extends GNUReadline
*/
public function listHistory()
{
$history = file_get_contents($this->historyFile);
$history = \file_get_contents($this->historyFile);
if (!$history) {
return [];
}
// libedit doesn't seem to support non-unix line separators.
$history = explode("\n", $history);
$history = \explode("\n", $history);
// shift the history signature, ensure it's valid
if (array_shift($history) !== '_HiStOrY_V2_') {
if (\array_shift($history) !== '_HiStOrY_V2_') {
return [];
}
// decode the line
$history = array_map([$this, 'parseHistoryLine'], $history);
$history = \array_map([$this, 'parseHistoryLine'], $history);
// filter empty lines & comments
return array_values(array_filter($history));
return \array_values(\array_filter($history));
}
/**
@@ -74,8 +74,8 @@ class Libedit extends GNUReadline
}
// if "\0" is found in an entry, then
// everything from it until the end of line is a comment.
if (($pos = strpos($line, "\0")) !== false) {
$line = substr($line, 0, $pos);
if (($pos = \strpos($line, "\0")) !== false) {
$line = \substr($line, 0, $pos);
}
return ($line !== '') ? Str::unvis($line) : null;

View File

@@ -50,7 +50,7 @@ class Transient implements Readline
public function addHistory($line)
{
if ($this->eraseDups) {
if (($key = array_search($line, $this->history)) !== false) {
if (($key = \array_search($line, $this->history)) !== false) {
unset($this->history[$key]);
}
}
@@ -58,13 +58,13 @@ class Transient implements Readline
$this->history[] = $line;
if ($this->historySize > 0) {
$histsize = count($this->history);
$histsize = \count($this->history);
if ($histsize > $this->historySize) {
$this->history = array_slice($this->history, $histsize - $this->historySize);
$this->history = \array_slice($this->history, $histsize - $this->historySize);
}
}
$this->history = array_values($this->history);
$this->history = \array_values($this->history);
return true;
}
@@ -106,7 +106,7 @@ class Transient implements Readline
{
echo $prompt;
return rtrim(fgets($this->getStdin(), 1024));
return \rtrim(\fgets($this->getStdin(), 1024));
}
/**
@@ -135,10 +135,10 @@ class Transient implements Readline
private function getStdin()
{
if (!isset($this->stdin)) {
$this->stdin = fopen('php://stdin', 'r');
$this->stdin = \fopen('php://stdin', 'r');
}
if (feof($this->stdin)) {
if (\feof($this->stdin)) {
throw new BreakException('Ctrl+D');
}

View File

@@ -38,7 +38,7 @@ class ReflectionClassConstant implements \Reflector
$this->name = $name;
$constants = $class->getConstants();
if (!array_key_exists($name, $constants)) {
if (!\array_key_exists($name, $constants)) {
throw new \InvalidArgumentException('Unknown constant: ' . $name);
}
@@ -59,7 +59,7 @@ class ReflectionClassConstant implements \Reflector
$refl = new self($class, $name);
$value = $refl->getValue();
$str = sprintf('Constant [ public %s %s ] { %s }', gettype($value), $refl->getName(), $value);
$str = \sprintf('Constant [ public %s %s ] { %s }', \gettype($value), $refl->getName(), $value);
if ($return) {
return $str;
@@ -219,7 +219,7 @@ class ReflectionClassConstant implements \Reflector
*/
public static function create($class, $name)
{
if (class_exists('\\ReflectionClassConstant')) {
if (\class_exists('\\ReflectionClassConstant')) {
return new \ReflectionClassConstant($class, $name);
}

View File

@@ -23,7 +23,7 @@ class ReflectionConstant extends ReflectionClassConstant
*/
public function __construct($class, $name)
{
@trigger_error('ReflectionConstant is now ReflectionClassConstant', E_USER_DEPRECATED);
@\trigger_error('ReflectionConstant is now ReflectionClassConstant', E_USER_DEPRECATED);
parent::__construct($class, $name);
}

View File

@@ -46,12 +46,12 @@ class ReflectionConstant_ implements \Reflector
{
$this->name = $name;
if (!defined($name) && !self::isMagicConstant($name)) {
if (!\defined($name) && !self::isMagicConstant($name)) {
throw new \InvalidArgumentException('Unknown constant: ' . $name);
}
if (!self::isMagicConstant($name)) {
$this->value = @constant($name);
$this->value = @\constant($name);
}
}
@@ -68,7 +68,7 @@ class ReflectionConstant_ implements \Reflector
$refl = new self($name);
$value = $refl->getValue();
$str = sprintf('Constant [ %s %s ] { %s }', gettype($value), $refl->getName(), $value);
$str = \sprintf('Constant [ %s %s ] { %s }', \gettype($value), $refl->getName(), $value);
if ($return) {
return $str;
@@ -79,7 +79,7 @@ class ReflectionConstant_ implements \Reflector
public static function isMagicConstant($name)
{
return in_array($name, self::$magicConstants);
return \in_array($name, self::$magicConstants);
}
/**
@@ -115,7 +115,7 @@ class ReflectionConstant_ implements \Reflector
return '';
}
return preg_replace('/\\\\[^\\\\]+$/', '', $this->name);
return \preg_replace('/\\\\[^\\\\]+$/', '', $this->name);
}
/**
@@ -135,7 +135,7 @@ class ReflectionConstant_ implements \Reflector
*/
public function inNamespace()
{
return strpos($this->name, '\\') !== false;
return \strpos($this->name, '\\') !== false;
}
/**

View File

@@ -122,7 +122,7 @@ class ReflectionLanguageConstruct extends \ReflectionFunctionAbstract
{
$params = [];
foreach (self::$languageConstructs[$this->keyword] as $parameter => $opts) {
array_push($params, new ReflectionLanguageConstructParameter($this->keyword, $parameter, $opts));
\array_push($params, new ReflectionLanguageConstructParameter($this->keyword, $parameter, $opts));
}
return $params;
@@ -159,6 +159,6 @@ class ReflectionLanguageConstruct extends \ReflectionFunctionAbstract
*/
public static function isLanguageConstruct($keyword)
{
return array_key_exists($keyword, self::$languageConstructs);
return \array_key_exists($keyword, self::$languageConstructs);
}
}

View File

@@ -44,7 +44,7 @@ class ReflectionLanguageConstructParameter extends \ReflectionParameter
*/
public function isArray()
{
return array_key_exists('isArray', $this->opts) && $this->opts['isArray'];
return \array_key_exists('isArray', $this->opts) && $this->opts['isArray'];
}
/**
@@ -76,7 +76,7 @@ class ReflectionLanguageConstructParameter extends \ReflectionParameter
*/
public function isOptional()
{
return array_key_exists('isOptional', $this->opts) && $this->opts['isOptional'];
return \array_key_exists('isOptional', $this->opts) && $this->opts['isOptional'];
}
/**
@@ -86,7 +86,7 @@ class ReflectionLanguageConstructParameter extends \ReflectionParameter
*/
public function isDefaultValueAvailable()
{
return array_key_exists('defaultValue', $this->opts);
return \array_key_exists('defaultValue', $this->opts);
}
/**
@@ -98,6 +98,6 @@ class ReflectionLanguageConstructParameter extends \ReflectionParameter
*/
public function isPassedByReference()
{
return array_key_exists('isPassedByReference', $this->opts) && $this->opts['isPassedByReference'];
return \array_key_exists('isPassedByReference', $this->opts) && $this->opts['isPassedByReference'];
}
}

View File

@@ -47,7 +47,7 @@ use Symfony\Component\Console\Output\OutputInterface;
*/
class Shell extends Application
{
const VERSION = 'v0.9.6';
const VERSION = 'v0.9.8';
const PROMPT = '>>> ';
const BUFF_PROMPT = '... ';
@@ -109,7 +109,7 @@ class Shell extends Application
public static function isIncluded(array $trace)
{
return isset($trace[0]['function']) &&
in_array($trace[0]['function'], ['require', 'include', 'require_once', 'include_once']);
\in_array($trace[0]['function'], ['require', 'include', 'require_once', 'include_once']);
}
/**
@@ -234,7 +234,7 @@ class Shell extends Application
*/
protected function getTabCompletionMatchers()
{
@trigger_error('getTabCompletionMatchers is no longer used', E_USER_DEPRECATED);
@\trigger_error('getTabCompletionMatchers is no longer used', E_USER_DEPRECATED);
}
/**
@@ -264,7 +264,7 @@ class Shell extends Application
*/
public function addMatchers(array $matchers)
{
$this->matchers = array_merge($this->matchers, $matchers);
$this->matchers = \array_merge($this->matchers, $matchers);
if (isset($this->autoCompleter)) {
$this->addMatchersToAutoCompleter($matchers);
@@ -392,7 +392,7 @@ class Shell extends Application
}
// handle empty input
if (trim($input) === '' && !$this->codeBufferOpen) {
if (\trim($input) === '' && !$this->codeBufferOpen) {
continue;
}
@@ -424,12 +424,12 @@ class Shell extends Application
}
$code = $this->codeBuffer;
array_push($code, $input);
$tokens = @token_get_all('<?php ' . implode("\n", $code));
$last = array_pop($tokens);
\array_push($code, $input);
$tokens = @\token_get_all('<?php ' . \implode("\n", $code));
$last = \array_pop($tokens);
return $last === '"' || $last === '`' ||
(is_array($last) && in_array($last[0], [T_ENCAPSED_AND_WHITESPACE, T_START_HEREDOC, T_COMMENT]));
(\is_array($last) && \in_array($last[0], [T_ENCAPSED_AND_WHITESPACE, T_START_HEREDOC, T_COMMENT]));
}
/**
@@ -558,6 +558,30 @@ class Shell extends Application
return $vars;
}
/**
* Return the set of variables currently in scope which differ from the
* values passed as $currentVars.
*
* This is used inside the Execution Loop Closure to pick up scope variable
* changes made by commands while the loop is running.
*
* @param array $currentVars
*
* @return array Associative array of scope variables which differ from $currentVars
*/
public function getScopeVariablesDiff(array $currentVars)
{
$newVars = [];
foreach ($this->getScopeVariables(false) as $key => $value) {
if (!array_key_exists($key, $currentVars) || $currentVars[$key] !== $value) {
$newVars[$key] = $value;
}
}
return $newVars;
}
/**
* Get the set of unused command-scope variable names.
*
@@ -575,7 +599,7 @@ class Shell extends Application
*/
public function getScopeVariableNames()
{
return array_keys($this->context->getAll());
return \array_keys($this->context->getAll());
}
/**
@@ -647,7 +671,7 @@ class Shell extends Application
*/
public function getIncludes()
{
return array_merge($this->config->getDefaultIncludes(), $this->includes);
return \array_merge($this->config->getDefaultIncludes(), $this->includes);
}
/**
@@ -682,9 +706,9 @@ class Shell extends Application
{
try {
// Code lines ending in \ keep the buffer open
if (substr(rtrim($code), -1) === '\\') {
if (\substr(\rtrim($code), -1) === '\\') {
$this->codeBufferOpen = true;
$code = substr(rtrim($code), 0, -1);
$code = \substr(\rtrim($code), 0, -1);
} else {
$this->codeBufferOpen = false;
}
@@ -766,7 +790,7 @@ class Shell extends Application
throw new \InvalidArgumentException('Command not found: ' . $input);
}
$input = new ShellInput(str_replace('\\', '\\\\', rtrim($input, " \t\n\r\0\x0B;")));
$input = new ShellInput(\str_replace('\\', '\\\\', \rtrim($input, " \t\n\r\0\x0B;")));
if ($input->hasParameterOption(['--help', '-h'])) {
$helpCommand = $this->get('help');
@@ -835,7 +859,7 @@ class Shell extends Application
return;
}
list($codeBuffer, $codeBufferOpen, $code) = array_pop($this->codeStack);
list($codeBuffer, $codeBufferOpen, $code) = \array_pop($this->codeStack);
$this->codeBuffer = $codeBuffer;
$this->codeBufferOpen = $codeBufferOpen;
@@ -861,7 +885,7 @@ class Shell extends Application
}
// Skip empty lines and lines starting with a space
if (trim($line) !== '' && substr($line, 0, 1) !== ' ') {
if (\trim($line) !== '' && \substr($line, 0, 1) !== ' ') {
$this->readline->addHistory($line);
}
}
@@ -871,11 +895,11 @@ class Shell extends Application
*/
private function addCodeBufferToHistory()
{
$codeBuffer = array_filter($this->codeBuffer, function ($line) {
$codeBuffer = \array_filter($this->codeBuffer, function ($line) {
return !$line instanceof SilentInput;
});
$this->addHistory(implode("\n", $codeBuffer));
$this->addHistory(\implode("\n", $codeBuffer));
}
/**
@@ -888,7 +912,7 @@ class Shell extends Application
public function getNamespace()
{
if ($namespace = $this->cleaner->getNamespace()) {
return implode('\\', $namespace);
return \implode('\\', $namespace);
}
}
@@ -907,7 +931,7 @@ class Shell extends Application
// Incremental flush
if ($out !== '' && !$isCleaning) {
$this->output->write($out, false, ShellOutput::OUTPUT_RAW);
$this->outputWantsNewline = (substr($out, -1) !== "\n");
$this->outputWantsNewline = (\substr($out, -1) !== "\n");
$this->stdoutBuffer .= $out;
}
@@ -915,7 +939,7 @@ class Shell extends Application
if ($phase & PHP_OUTPUT_HANDLER_END) {
// Write an extra newline if stdout didn't end with one
if ($this->outputWantsNewline) {
$this->output->writeln(sprintf('<aside>%s</aside>', $this->config->useUnicode() ? '⏎' : '\\n'));
$this->output->writeln(\sprintf('<aside>%s</aside>', $this->config->useUnicode() ? '⏎' : '\\n'));
$this->outputWantsNewline = false;
}
@@ -945,9 +969,9 @@ class Shell extends Application
$this->context->setReturnValue($ret);
$ret = $this->presentValue($ret);
$indent = str_repeat(' ', strlen(static::RETVAL));
$indent = \str_repeat(' ', \strlen(static::RETVAL));
$this->output->writeln(static::RETVAL . str_replace(PHP_EOL, PHP_EOL . $indent, $ret));
$this->output->writeln(static::RETVAL . \str_replace(PHP_EOL, PHP_EOL . $indent, $ret));
}
/**
@@ -981,23 +1005,23 @@ class Shell extends Application
$message = $e->getMessage();
if (!$e instanceof PsyException) {
if ($message === '') {
$message = get_class($e);
$message = \get_class($e);
} else {
$message = sprintf('%s with message \'%s\'', get_class($e), $message);
$message = \sprintf('%s with message \'%s\'', \get_class($e), $message);
}
}
$message = preg_replace(
$message = \preg_replace(
"#(\\w:)?(/\\w+)*/src/Execution(?:Loop)?Closure.php\(\d+\) : eval\(\)'d code#",
"eval()'d code",
str_replace('\\', '/', $message)
\str_replace('\\', '/', $message)
);
$message = str_replace(" in eval()'d code", ' in Psy Shell code', $message);
$message = \str_replace(" in eval()'d code", ' in Psy Shell code', $message);
$severity = ($e instanceof \ErrorException) ? $this->getSeverity($e) : 'error';
return sprintf('<%s>%s</%s>', $severity, OutputFormatter::escape($message), $severity);
return \sprintf('<%s>%s</%s>', $severity, OutputFormatter::escape($message), $severity);
}
/**
@@ -1010,7 +1034,7 @@ class Shell extends Application
protected function getSeverity(\ErrorException $e)
{
$severity = $e->getSeverity();
if ($severity & error_reporting()) {
if ($severity & \error_reporting()) {
switch ($severity) {
case E_WARNING:
case E_NOTICE:
@@ -1086,7 +1110,7 @@ class Shell extends Application
*/
public function handleError($errno, $errstr, $errfile, $errline)
{
if ($errno & error_reporting()) {
if ($errno & \error_reporting()) {
ErrorException::throwException($errno, $errstr, $errfile, $errline);
} elseif ($errno & $this->config->errorLoggingLevel()) {
// log it and continue...
@@ -1132,7 +1156,7 @@ class Shell extends Application
*/
protected function hasCommand($input)
{
if (preg_match('/([^\s]+?)(?:\s|$)/A', ltrim($input), $match)) {
if (\preg_match('/([^\s]+?)(?:\s|$)/A', \ltrim($input), $match)) {
return $this->has($match[1]);
}
@@ -1167,22 +1191,22 @@ class Shell extends Application
protected function readline()
{
if (!empty($this->inputBuffer)) {
$line = array_shift($this->inputBuffer);
$line = \array_shift($this->inputBuffer);
if (!$line instanceof SilentInput) {
$this->output->writeln(sprintf('<aside>%s %s</aside>', static::REPLAY, OutputFormatter::escape($line)));
$this->output->writeln(\sprintf('<aside>%s %s</aside>', static::REPLAY, OutputFormatter::escape($line)));
}
return $line;
}
if ($bracketedPaste = $this->config->useBracketedPaste()) {
printf("\e[?2004h"); // Enable bracketed paste
\printf("\e[?2004h"); // Enable bracketed paste
}
$line = $this->readline->readline($this->getPrompt());
if ($bracketedPaste) {
printf("\e[?2004l"); // ... and disable it again
\printf("\e[?2004l"); // ... and disable it again
}
return $line;
@@ -1195,7 +1219,7 @@ class Shell extends Application
*/
protected function getHeader()
{
return sprintf('<aside>%s by Justin Hileman</aside>', $this->getVersion());
return \sprintf('<aside>%s by Justin Hileman</aside>', $this->getVersion());
}
/**
@@ -1207,7 +1231,7 @@ class Shell extends Application
{
$separator = $this->config->useUnicode() ? '—' : '-';
return sprintf('Psy Shell %s (PHP %s %s %s)', self::VERSION, phpversion(), $separator, php_sapi_name());
return \sprintf('Psy Shell %s (PHP %s %s %s)', self::VERSION, PHP_VERSION, $separator, PHP_SAPI);
}
/**
@@ -1225,7 +1249,7 @@ class Shell extends Application
*/
protected function autocomplete($text)
{
@trigger_error('Tab completion is provided by the AutoCompleter service', E_USER_DEPRECATED);
@\trigger_error('Tab completion is provided by the AutoCompleter service', E_USER_DEPRECATED);
}
/**
@@ -1280,7 +1304,7 @@ class Shell extends Application
try {
$client = $this->config->getChecker();
if (!$client->isLatest()) {
$this->output->writeln(sprintf('New version is available (current: %s, latest: %s)', self::VERSION, $client->getLatest()));
$this->output->writeln(\sprintf('New version is available (current: %s, latest: %s)', self::VERSION, $client->getLatest()));
}
} catch (\InvalidArgumentException $e) {
$this->output->writeln($e->getMessage());

View File

@@ -64,9 +64,9 @@ class Sudo
*/
public static function callMethod($object, $method, $args = null)
{
$args = func_get_args();
$object = array_shift($args);
$method = array_shift($args);
$args = \func_get_args();
$object = \array_shift($args);
$method = \array_shift($args);
$refl = new \ReflectionObject($object);
$reflMethod = $refl->getMethod($method);
@@ -122,9 +122,9 @@ class Sudo
*/
public static function callStatic($class, $method, $args = null)
{
$args = func_get_args();
$class = array_shift($args);
$method = array_shift($args);
$args = \func_get_args();
$class = \array_shift($args);
$method = \array_shift($args);
$refl = new \ReflectionClass($class);
$reflMethod = $refl->getMethod($method);

View File

@@ -52,7 +52,7 @@ class SudoVisitor extends NodeVisitorAbstract
$name = $node->name instanceof Identifier ? $node->name->toString() : $node->name;
$args = [
$node->var,
is_string($name) ? new String_($name) : $name,
\is_string($name) ? new String_($name) : $name,
];
return $this->prepareCall(self::PROPERTY_FETCH, $args);
@@ -61,7 +61,7 @@ class SudoVisitor extends NodeVisitorAbstract
$name = $target->name instanceof Identifier ? $target->name->toString() : $target->name;
$args = [
$target->var,
is_string($name) ? new String_($name) : $name,
\is_string($name) ? new String_($name) : $name,
$node->expr,
];
@@ -69,8 +69,8 @@ class SudoVisitor extends NodeVisitorAbstract
} elseif ($node instanceof MethodCall) {
$name = $node->name instanceof Identifier ? $node->name->toString() : $node->name;
$args = $node->args;
array_unshift($args, new Arg(is_string($name) ? new String_($name) : $name));
array_unshift($args, new Arg($node->var));
\array_unshift($args, new Arg(\is_string($name) ? new String_($name) : $name));
\array_unshift($args, new Arg($node->var));
// not using prepareCall because the $node->args we started with are already Arg instances
return new StaticCall(new FullyQualifiedName(self::SUDO_CLASS), self::METHOD_CALL, $args);
@@ -78,8 +78,8 @@ class SudoVisitor extends NodeVisitorAbstract
$class = $node->class instanceof Name ? $node->class->toString() : $node->class;
$name = $node->name instanceof Identifier ? $node->name->toString() : $node->name;
$args = [
is_string($class) ? new String_($class) : $class,
is_string($name) ? new String_($name) : $name,
\is_string($class) ? new String_($class) : $class,
\is_string($name) ? new String_($name) : $name,
];
return $this->prepareCall(self::STATIC_PROPERTY_FETCH, $args);
@@ -88,8 +88,8 @@ class SudoVisitor extends NodeVisitorAbstract
$class = $target->class instanceof Name ? $target->class->toString() : $target->class;
$name = $target->name instanceof Identifier ? $target->name->toString() : $target->name;
$args = [
is_string($class) ? new String_($class) : $class,
is_string($name) ? new String_($name) : $name,
\is_string($class) ? new String_($class) : $class,
\is_string($name) ? new String_($name) : $name,
$node->expr,
];
@@ -98,8 +98,8 @@ class SudoVisitor extends NodeVisitorAbstract
$args = $node->args;
$class = $node->class instanceof Name ? $node->class->toString() : $node->class;
$name = $node->name instanceof Identifier ? $node->name->toString() : $node->name;
array_unshift($args, new Arg(is_string($name) ? new String_($name) : $name));
array_unshift($args, new Arg(is_string($class) ? new String_($class) : $class));
\array_unshift($args, new Arg(\is_string($name) ? new String_($name) : $name));
\array_unshift($args, new Arg(\is_string($class) ? new String_($class) : $class));
// not using prepareCall because the $node->args we started with are already Arg instances
return new StaticCall(new FullyQualifiedName(self::SUDO_CLASS), self::STATIC_CALL, $args);
@@ -107,8 +107,8 @@ class SudoVisitor extends NodeVisitorAbstract
$class = $node->class instanceof Name ? $node->class->toString() : $node->class;
$name = $node->name instanceof Identifier ? $node->name->toString() : $node->name;
$args = [
is_string($class) ? new String_($class) : $class,
is_string($name) ? new String_($name) : $name,
\is_string($class) ? new String_($class) : $class,
\is_string($name) ? new String_($name) : $name,
];
return $this->prepareCall(self::CLASS_CONST_FETCH, $args);
@@ -117,7 +117,7 @@ class SudoVisitor extends NodeVisitorAbstract
private function prepareCall($method, $args)
{
return new StaticCall(new FullyQualifiedName(self::SUDO_CLASS), $method, array_map(function ($arg) {
return new StaticCall(new FullyQualifiedName(self::SUDO_CLASS), $method, \array_map(function ($arg) {
return new Arg($arg);
}, $args));
}

View File

@@ -38,7 +38,7 @@ class AutoCompleter
*/
public function activate()
{
readline_completion_function([&$this, 'callback']);
\readline_completion_function([&$this, 'callback']);
}
/**
@@ -56,27 +56,27 @@ class AutoCompleter
// try to work around it.
$line = $info['line_buffer'];
if (isset($info['end'])) {
$line = substr($line, 0, $info['end']);
$line = \substr($line, 0, $info['end']);
}
if ($line === '' && $input !== '') {
$line = $input;
}
$tokens = token_get_all('<?php ' . $line);
$tokens = \token_get_all('<?php ' . $line);
// remove whitespaces
$tokens = array_filter($tokens, function ($token) {
$tokens = \array_filter($tokens, function ($token) {
return !AbstractMatcher::tokenIs($token, AbstractMatcher::T_WHITESPACE);
});
$matches = [];
foreach ($this->matchers as $matcher) {
if ($matcher->hasMatched($tokens)) {
$matches = array_merge($matcher->getMatches($tokens), $matches);
$matches = \array_merge($matcher->getMatches($tokens), $matches);
}
}
$matches = array_unique($matches);
$matches = \array_unique($matches);
return !empty($matches) ? $matches : [''];
}
@@ -93,7 +93,7 @@ class AutoCompleter
*/
public function callback($input, $index)
{
return $this->processCallback($input, $index, readline_info());
return $this->processCallback($input, $index, \readline_info());
}
/**
@@ -103,8 +103,8 @@ class AutoCompleter
{
// PHP didn't implement the whole readline API when they first switched
// to libedit. And they still haven't.
if (function_exists('readline_callback_handler_remove')) {
readline_callback_handler_remove();
if (\function_exists('readline_callback_handler_remove')) {
\readline_callback_handler_remove();
}
}
}

View File

@@ -36,7 +36,7 @@ abstract class AbstractDefaultParametersMatcher extends AbstractContextAwareMatc
return [];
}
return [implode(', ', $parametersProcessed) . ')'];
return [\implode(', ', $parametersProcessed) . ')'];
}
/**
@@ -50,8 +50,8 @@ abstract class AbstractDefaultParametersMatcher extends AbstractContextAwareMatc
*/
private function valueToShortString($value)
{
if (!is_array($value)) {
return json_encode($value);
if (!\is_array($value)) {
return \json_encode($value);
}
$chunks = [];
@@ -60,7 +60,7 @@ abstract class AbstractDefaultParametersMatcher extends AbstractContextAwareMatc
$allSequential = true;
foreach ($value as $key => $item) {
$allSequential = $allSequential && is_numeric($key) && $key === count($chunksSequential);
$allSequential = $allSequential && \is_numeric($key) && $key === \count($chunksSequential);
$keyString = $this->valueToShortString($key);
$itemString = $this->valueToShortString($item);
@@ -71,6 +71,6 @@ abstract class AbstractDefaultParametersMatcher extends AbstractContextAwareMatc
$chunksToImplode = $allSequential ? $chunksSequential : $chunks;
return '[' . implode(', ', $chunksToImplode) . ']';
return '[' . \implode(', ', $chunksToImplode) . ']';
}
}

View File

@@ -64,7 +64,7 @@ abstract class AbstractMatcher
protected function getInput(array $tokens)
{
$var = '';
$firstToken = array_pop($tokens);
$firstToken = \array_pop($tokens);
if (self::tokenIs($firstToken, self::T_STRING)) {
$var = $firstToken[1];
}
@@ -84,7 +84,7 @@ abstract class AbstractMatcher
$class = '';
while (self::hasToken(
[self::T_NS_SEPARATOR, self::T_STRING],
$token = array_pop($tokens)
$token = \array_pop($tokens)
)) {
if (self::needCompleteClass($token)) {
continue;
@@ -116,7 +116,7 @@ abstract class AbstractMatcher
*/
public static function startsWith($prefix, $word)
{
return preg_match(sprintf('#^%s#', $prefix), $word);
return \preg_match(\sprintf('#^%s#', $prefix), $word);
}
/**
@@ -129,13 +129,13 @@ abstract class AbstractMatcher
*/
public static function hasSyntax($token, $syntax = self::VAR_SYNTAX)
{
if (!is_array($token)) {
if (!\is_array($token)) {
return false;
}
$regexp = sprintf('#%s#', $syntax);
$regexp = \sprintf('#%s#', $syntax);
return (bool) preg_match($regexp, $token[1]);
return (bool) \preg_match($regexp, $token[1]);
}
/**
@@ -148,11 +148,11 @@ abstract class AbstractMatcher
*/
public static function tokenIs($token, $which)
{
if (!is_array($token)) {
if (!\is_array($token)) {
return false;
}
return token_name($token[0]) === $which;
return \token_name($token[0]) === $which;
}
/**
@@ -164,16 +164,16 @@ abstract class AbstractMatcher
*/
public static function isOperator($token)
{
if (!is_string($token)) {
if (!\is_string($token)) {
return false;
}
return strpos(self::MISC_OPERATORS, $token) !== false;
return \strpos(self::MISC_OPERATORS, $token) !== false;
}
public static function needCompleteClass($token)
{
return in_array($token[1], ['doc', 'ls', 'show']);
return \in_array($token[1], ['doc', 'ls', 'show']);
}
/**
@@ -186,10 +186,10 @@ abstract class AbstractMatcher
*/
public static function hasToken(array $coll, $token)
{
if (!is_array($token)) {
if (!\is_array($token)) {
return false;
}
return in_array(token_name($token[0]), $coll);
return \in_array(\token_name($token[0]), $coll);
}
}

View File

@@ -28,10 +28,10 @@ class ClassAttributesMatcher extends AbstractMatcher
{
$input = $this->getInput($tokens);
$firstToken = array_pop($tokens);
$firstToken = \array_pop($tokens);
if (self::tokenIs($firstToken, self::T_STRING)) {
// second token is the nekudotayim operator
array_pop($tokens);
\array_pop($tokens);
}
$class = $this->getNamespaceAndClass($tokens);
@@ -42,24 +42,24 @@ class ClassAttributesMatcher extends AbstractMatcher
return [];
}
$vars = array_merge(
array_map(
$vars = \array_merge(
\array_map(
function ($var) {
return '$' . $var;
},
array_keys($reflection->getStaticProperties())
\array_keys($reflection->getStaticProperties())
),
array_keys($reflection->getConstants())
\array_keys($reflection->getConstants())
);
return array_map(
return \array_map(
function ($name) use ($class) {
$chunks = explode('\\', $class);
$className = array_pop($chunks);
$chunks = \explode('\\', $class);
$className = \array_pop($chunks);
return $className . '::' . $name;
},
array_filter(
\array_filter(
$vars,
function ($var) use ($input) {
return AbstractMatcher::startsWith($input, $var);
@@ -73,8 +73,8 @@ class ClassAttributesMatcher extends AbstractMatcher
*/
public function hasMatched(array $tokens)
{
$token = array_pop($tokens);
$prevToken = array_pop($tokens);
$token = \array_pop($tokens);
$prevToken = \array_pop($tokens);
switch (true) {
case self::tokenIs($prevToken, self::T_DOUBLE_COLON) && self::tokenIs($token, self::T_STRING):

View File

@@ -15,9 +15,9 @@ class ClassMethodDefaultParametersMatcher extends AbstractDefaultParametersMatch
{
public function getMatches(array $tokens, array $info = [])
{
$openBracket = array_pop($tokens);
$functionName = array_pop($tokens);
$methodOperator = array_pop($tokens);
$openBracket = \array_pop($tokens);
$functionName = \array_pop($tokens);
$methodOperator = \array_pop($tokens);
$class = $this->getNamespaceAndClass($tokens);
@@ -41,19 +41,19 @@ class ClassMethodDefaultParametersMatcher extends AbstractDefaultParametersMatch
public function hasMatched(array $tokens)
{
$openBracket = array_pop($tokens);
$openBracket = \array_pop($tokens);
if ($openBracket !== '(') {
return false;
}
$functionName = array_pop($tokens);
$functionName = \array_pop($tokens);
if (!self::tokenIs($functionName, self::T_STRING)) {
return false;
}
$operator = array_pop($tokens);
$operator = \array_pop($tokens);
if (!self::tokenIs($operator, self::T_DOUBLE_COLON)) {
return false;

View File

@@ -28,10 +28,10 @@ class ClassMethodsMatcher extends AbstractMatcher
{
$input = $this->getInput($tokens);
$firstToken = array_pop($tokens);
$firstToken = \array_pop($tokens);
if (self::tokenIs($firstToken, self::T_STRING)) {
// second token is the nekudotayim operator
array_pop($tokens);
\array_pop($tokens);
}
$class = $this->getNamespaceAndClass($tokens);
@@ -48,18 +48,18 @@ class ClassMethodsMatcher extends AbstractMatcher
$methods = $reflection->getMethods(\ReflectionMethod::IS_STATIC);
}
$methods = array_map(function (\ReflectionMethod $method) {
$methods = \array_map(function (\ReflectionMethod $method) {
return $method->getName();
}, $methods);
return array_map(
return \array_map(
function ($name) use ($class) {
$chunks = explode('\\', $class);
$className = array_pop($chunks);
$chunks = \explode('\\', $class);
$className = \array_pop($chunks);
return $className . '::' . $name;
},
array_filter($methods, function ($method) use ($input) {
\array_filter($methods, function ($method) use ($input) {
return AbstractMatcher::startsWith($input, $method);
})
);
@@ -70,8 +70,8 @@ class ClassMethodsMatcher extends AbstractMatcher
*/
public function hasMatched(array $tokens)
{
$token = array_pop($tokens);
$prevToken = array_pop($tokens);
$token = \array_pop($tokens);
$prevToken = \array_pop($tokens);
switch (true) {
case self::tokenIs($prevToken, self::T_DOUBLE_COLON) && self::tokenIs($token, self::T_STRING):

View File

@@ -26,21 +26,21 @@ class ClassNamesMatcher extends AbstractMatcher
public function getMatches(array $tokens, array $info = [])
{
$class = $this->getNamespaceAndClass($tokens);
if (strlen($class) > 0 && $class[0] === '\\') {
$class = substr($class, 1, strlen($class));
if (\strlen($class) > 0 && $class[0] === '\\') {
$class = \substr($class, 1, \strlen($class));
}
$quotedClass = preg_quote($class);
$quotedClass = \preg_quote($class);
return array_map(
return \array_map(
function ($className) use ($class) {
// get the number of namespace separators
$nsPos = substr_count($class, '\\');
$pieces = explode('\\', $className);
$nsPos = \substr_count($class, '\\');
$pieces = \explode('\\', $className);
//$methods = Mirror::get($class);
return implode('\\', array_slice($pieces, $nsPos, count($pieces)));
return \implode('\\', \array_slice($pieces, $nsPos, \count($pieces)));
},
array_filter(
get_declared_classes(),
\array_filter(
\get_declared_classes(),
function ($className) use ($quotedClass) {
return AbstractMatcher::startsWith($quotedClass, $className);
}
@@ -53,8 +53,8 @@ class ClassNamesMatcher extends AbstractMatcher
*/
public function hasMatched(array $tokens)
{
$token = array_pop($tokens);
$prevToken = array_pop($tokens);
$token = \array_pop($tokens);
$prevToken = \array_pop($tokens);
$blacklistedTokens = [
self::T_INCLUDE, self::T_INCLUDE_ONCE, self::T_REQUIRE, self::T_REQUIRE_ONCE,
@@ -63,7 +63,7 @@ class ClassNamesMatcher extends AbstractMatcher
switch (true) {
case self::hasToken([$blacklistedTokens], $token):
case self::hasToken([$blacklistedTokens], $prevToken):
case is_string($token) && $token === '$':
case \is_string($token) && $token === '$':
return false;
case self::hasToken([self::T_NEW, self::T_OPEN_TAG, self::T_NS_SEPARATOR, self::T_STRING], $prevToken):
case self::hasToken([self::T_NEW, self::T_OPEN_TAG, self::T_NS_SEPARATOR], $token):

View File

@@ -45,8 +45,8 @@ class CommandsMatcher extends AbstractMatcher
{
$names = [];
foreach ($commands as $command) {
$names = array_merge([$command->getName()], $names);
$names = array_merge($command->getAliases(), $names);
$names = \array_merge([$command->getName()], $names);
$names = \array_merge($command->getAliases(), $names);
}
$this->commands = $names;
}
@@ -60,7 +60,7 @@ class CommandsMatcher extends AbstractMatcher
*/
protected function isCommand($name)
{
return in_array($name, $this->commands);
return \in_array($name, $this->commands);
}
/**
@@ -88,7 +88,7 @@ class CommandsMatcher extends AbstractMatcher
{
$input = $this->getInput($tokens);
return array_filter($this->commands, function ($command) use ($input) {
return \array_filter($this->commands, function ($command) use ($input) {
return AbstractMatcher::startsWith($input, $command);
});
}
@@ -98,8 +98,8 @@ class CommandsMatcher extends AbstractMatcher
*/
public function hasMatched(array $tokens)
{
/* $openTag */ array_shift($tokens);
$command = array_shift($tokens);
/* $openTag */ \array_shift($tokens);
$command = \array_shift($tokens);
switch (true) {
case self::tokenIs($command, self::T_STRING) &&

View File

@@ -27,7 +27,7 @@ class ConstantsMatcher extends AbstractMatcher
{
$const = $this->getInput($tokens);
return array_filter(array_keys(get_defined_constants()), function ($constant) use ($const) {
return \array_filter(\array_keys(\get_defined_constants()), function ($constant) use ($const) {
return AbstractMatcher::startsWith($const, $constant);
});
}
@@ -37,8 +37,8 @@ class ConstantsMatcher extends AbstractMatcher
*/
public function hasMatched(array $tokens)
{
$token = array_pop($tokens);
$prevToken = array_pop($tokens);
$token = \array_pop($tokens);
$prevToken = \array_pop($tokens);
switch (true) {
case self::tokenIs($prevToken, self::T_NEW):

View File

@@ -15,9 +15,9 @@ class FunctionDefaultParametersMatcher extends AbstractDefaultParametersMatcher
{
public function getMatches(array $tokens, array $info = [])
{
array_pop($tokens); // open bracket
\array_pop($tokens); // open bracket
$functionName = array_pop($tokens);
$functionName = \array_pop($tokens);
try {
$reflection = new \ReflectionFunction($functionName[1]);
@@ -32,19 +32,19 @@ class FunctionDefaultParametersMatcher extends AbstractDefaultParametersMatcher
public function hasMatched(array $tokens)
{
$openBracket = array_pop($tokens);
$openBracket = \array_pop($tokens);
if ($openBracket !== '(') {
return false;
}
$functionName = array_pop($tokens);
$functionName = \array_pop($tokens);
if (!self::tokenIs($functionName, self::T_STRING)) {
return false;
}
if (!function_exists($functionName[1])) {
if (!\function_exists($functionName[1])) {
return false;
}

View File

@@ -27,10 +27,10 @@ class FunctionsMatcher extends AbstractMatcher
{
$func = $this->getInput($tokens);
$functions = get_defined_functions();
$allFunctions = array_merge($functions['user'], $functions['internal']);
$functions = \get_defined_functions();
$allFunctions = \array_merge($functions['user'], $functions['internal']);
return array_filter($allFunctions, function ($function) use ($func) {
return \array_filter($allFunctions, function ($function) use ($func) {
return AbstractMatcher::startsWith($func, $function);
});
}
@@ -40,8 +40,8 @@ class FunctionsMatcher extends AbstractMatcher
*/
public function hasMatched(array $tokens)
{
$token = array_pop($tokens);
$prevToken = array_pop($tokens);
$token = \array_pop($tokens);
$prevToken = \array_pop($tokens);
switch (true) {
case self::tokenIs($prevToken, self::T_NEW):

View File

@@ -48,7 +48,7 @@ class KeywordsMatcher extends AbstractMatcher
*/
public function isKeyword($keyword)
{
return in_array($keyword, $this->keywords);
return \in_array($keyword, $this->keywords);
}
/**
@@ -58,7 +58,7 @@ class KeywordsMatcher extends AbstractMatcher
{
$input = $this->getInput($tokens);
return array_filter($this->keywords, function ($keyword) use ($input) {
return \array_filter($this->keywords, function ($keyword) use ($input) {
return AbstractMatcher::startsWith($input, $keyword);
});
}
@@ -68,8 +68,8 @@ class KeywordsMatcher extends AbstractMatcher
*/
public function hasMatched(array $tokens)
{
$token = array_pop($tokens);
$prevToken = array_pop($tokens);
$token = \array_pop($tokens);
$prevToken = \array_pop($tokens);
switch (true) {
case self::hasToken([self::T_OPEN_TAG, self::T_VARIABLE], $token):

View File

@@ -27,13 +27,13 @@ class MongoClientMatcher extends AbstractContextAwareMatcher
{
$input = $this->getInput($tokens);
$firstToken = array_pop($tokens);
$firstToken = \array_pop($tokens);
if (self::tokenIs($firstToken, self::T_STRING)) {
// second token is the object operator
array_pop($tokens);
\array_pop($tokens);
}
$objectToken = array_pop($tokens);
$objectName = str_replace('$', '', $objectToken[1]);
$objectToken = \array_pop($tokens);
$objectName = \str_replace('$', '', $objectToken[1]);
$object = $this->getVariable($objectName);
if (!$object instanceof \MongoClient) {
@@ -42,8 +42,8 @@ class MongoClientMatcher extends AbstractContextAwareMatcher
$list = $object->listDBs();
return array_filter(
array_map(function ($info) {
return \array_filter(
\array_map(function ($info) {
return $info['name'];
}, $list['databases']),
function ($var) use ($input) {
@@ -57,8 +57,8 @@ class MongoClientMatcher extends AbstractContextAwareMatcher
*/
public function hasMatched(array $tokens)
{
$token = array_pop($tokens);
$prevToken = array_pop($tokens);
$token = \array_pop($tokens);
$prevToken = \array_pop($tokens);
switch (true) {
case self::tokenIs($token, self::T_OBJECT_OPERATOR):

View File

@@ -27,20 +27,20 @@ class MongoDatabaseMatcher extends AbstractContextAwareMatcher
{
$input = $this->getInput($tokens);
$firstToken = array_pop($tokens);
$firstToken = \array_pop($tokens);
if (self::tokenIs($firstToken, self::T_STRING)) {
// second token is the object operator
array_pop($tokens);
\array_pop($tokens);
}
$objectToken = array_pop($tokens);
$objectName = str_replace('$', '', $objectToken[1]);
$objectToken = \array_pop($tokens);
$objectName = \str_replace('$', '', $objectToken[1]);
$object = $this->getVariable($objectName);
if (!$object instanceof \MongoDB) {
return [];
}
return array_filter(
return \array_filter(
$object->getCollectionNames(),
function ($var) use ($input) {
return AbstractMatcher::startsWith($input, $var);
@@ -53,8 +53,8 @@ class MongoDatabaseMatcher extends AbstractContextAwareMatcher
*/
public function hasMatched(array $tokens)
{
$token = array_pop($tokens);
$prevToken = array_pop($tokens);
$token = \array_pop($tokens);
$prevToken = \array_pop($tokens);
switch (true) {
case self::tokenIs($token, self::T_OBJECT_OPERATOR):

View File

@@ -30,16 +30,16 @@ class ObjectAttributesMatcher extends AbstractContextAwareMatcher
{
$input = $this->getInput($tokens);
$firstToken = array_pop($tokens);
$firstToken = \array_pop($tokens);
if (self::tokenIs($firstToken, self::T_STRING)) {
// second token is the object operator
array_pop($tokens);
\array_pop($tokens);
}
$objectToken = array_pop($tokens);
if (!is_array($objectToken)) {
$objectToken = \array_pop($tokens);
if (!\is_array($objectToken)) {
return [];
}
$objectName = str_replace('$', '', $objectToken[1]);
$objectName = \str_replace('$', '', $objectToken[1]);
try {
$object = $this->getVariable($objectName);
@@ -47,12 +47,12 @@ class ObjectAttributesMatcher extends AbstractContextAwareMatcher
return [];
}
if (!is_object($object)) {
if (!\is_object($object)) {
return [];
}
return array_filter(
array_keys(get_class_vars(get_class($object))),
return \array_filter(
\array_keys(\get_class_vars(\get_class($object))),
function ($var) use ($input) {
return AbstractMatcher::startsWith($input, $var);
}
@@ -64,8 +64,8 @@ class ObjectAttributesMatcher extends AbstractContextAwareMatcher
*/
public function hasMatched(array $tokens)
{
$token = array_pop($tokens);
$prevToken = array_pop($tokens);
$token = \array_pop($tokens);
$prevToken = \array_pop($tokens);
switch (true) {
case self::tokenIs($token, self::T_OBJECT_OPERATOR):

Some files were not shown because too many files have changed in this diff Show More