diff --git a/composer.json b/composer.json
index 3e169be91..7df60cf48 100644
--- a/composer.json
+++ b/composer.json
@@ -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",
diff --git a/src/CodeCleaner.php b/src/CodeCleaner.php
index 0f0d378f7..e44c2c18e 100644
--- a/src/CodeCleaner.php
+++ b/src/CodeCleaner.php
@@ -138,7 +138,7 @@ private function addImplicitDebugContext(array $passes)
}
try {
- $code = @file_get_contents($file);
+ $code = @\file_get_contents($file);
if (!$code) {
return;
}
@@ -169,15 +169,15 @@ private function addImplicitDebugContext(array $passes)
*/
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 @@ private static function isDebugCall(array $stackFrame)
*/
public function clean(array $codeLines, $requireSemicolons = false)
{
- $stmts = $this->parse('parse('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 @@ private function parseErrorIsEOF(\PhpParser\Error $e)
{
$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 @@ private function parseErrorIsUnterminatedComment(\PhpParser\Error $e, $code)
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) === ',');
}
}
diff --git a/src/CodeCleaner/AbstractClassPass.php b/src/CodeCleaner/AbstractClassPass.php
index 66eaf42c1..81d12b6a5 100644
--- a/src/CodeCleaner/AbstractClassPass.php
+++ b/src/CodeCleaner/AbstractClassPass.php
@@ -36,11 +36,11 @@ public function enterNode(Node $node)
$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 @@ public function enterNode(Node $node)
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());
}
diff --git a/src/CodeCleaner/CalledClassPass.php b/src/CodeCleaner/CalledClassPass.php
index 280be3b7c..e78f08d07 100644
--- a/src/CodeCleaner/CalledClassPass.php
+++ b/src/CodeCleaner/CalledClassPass.php
@@ -58,9 +58,9 @@ public function enterNode(Node $node)
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 @@ public function leaveNode(Node $node)
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';
}
}
diff --git a/src/CodeCleaner/FinalClassPass.php b/src/CodeCleaner/FinalClassPass.php
index bf1063fd5..23f143be5 100644
--- a/src/CodeCleaner/FinalClassPass.php
+++ b/src/CodeCleaner/FinalClassPass.php
@@ -41,13 +41,13 @@ public function enterNode(Node $node)
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 @@ public function enterNode(Node $node)
*/
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);
diff --git a/src/CodeCleaner/FunctionReturnInWriteContextPass.php b/src/CodeCleaner/FunctionReturnInWriteContextPass.php
index c3aad342f..87e5e7abf 100644
--- a/src/CodeCleaner/FunctionReturnInWriteContextPass.php
+++ b/src/CodeCleaner/FunctionReturnInWriteContextPass.php
@@ -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', '>=');
}
/**
diff --git a/src/CodeCleaner/ImplicitReturnPass.php b/src/CodeCleaner/ImplicitReturnPass.php
index 971a98045..06b069780 100644
--- a/src/CodeCleaner/ImplicitReturnPass.php
+++ b/src/CodeCleaner/ImplicitReturnPass.php
@@ -49,7 +49,7 @@ private function addImplicitReturn(array $nodes)
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 @@ private function addImplicitReturn(array $nodes)
} 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(),
]);
diff --git a/src/CodeCleaner/LegacyEmptyPass.php b/src/CodeCleaner/LegacyEmptyPass.php
index a298c8494..9793d8c4c 100644
--- a/src/CodeCleaner/LegacyEmptyPass.php
+++ b/src/CodeCleaner/LegacyEmptyPass.php
@@ -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 @@ public function enterNode(Node $node)
}
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 @@ private function getUnexpectedThing(Node $node)
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;
diff --git a/src/CodeCleaner/ListPass.php b/src/CodeCleaner/ListPass.php
index 04d32e9f8..aefc7ad27 100644
--- a/src/CodeCleaner/ListPass.php
+++ b/src/CodeCleaner/ListPass.php
@@ -28,7 +28,7 @@ class ListPass extends CodeCleanerPass
public function __construct()
{
- $this->atLeastPhp71 = version_compare(PHP_VERSION, '7.1', '>=');
+ $this->atLeastPhp71 = \version_compare(PHP_VERSION, '7.1', '>=');
}
/**
diff --git a/src/CodeCleaner/LoopContextPass.php b/src/CodeCleaner/LoopContextPass.php
index 9744fcb6c..933278e73 100644
--- a/src/CodeCleaner/LoopContextPass.php
+++ b/src/CodeCleaner/LoopContextPass.php
@@ -62,23 +62,23 @@ public function enterNode(Node $node)
$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;
diff --git a/src/CodeCleaner/NamespaceAwarePass.php b/src/CodeCleaner/NamespaceAwarePass.php
index 9b4044504..6679206dc 100644
--- a/src/CodeCleaner/NamespaceAwarePass.php
+++ b/src/CodeCleaner/NamespaceAwarePass.php
@@ -59,13 +59,13 @@ public function enterNode(Node $node)
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));
}
}
diff --git a/src/CodeCleaner/NamespacePass.php b/src/CodeCleaner/NamespacePass.php
index af8253765..d26f07cce 100644
--- a/src/CodeCleaner/NamespacePass.php
+++ b/src/CodeCleaner/NamespacePass.php
@@ -53,7 +53,7 @@ public function beforeTraverse(array $nodes)
return $nodes;
}
- $last = end($nodes);
+ $last = \end($nodes);
if ($last instanceof Namespace_) {
$kind = $last->getAttribute('kind');
diff --git a/src/CodeCleaner/PassableByReferencePass.php b/src/CodeCleaner/PassableByReferencePass.php
index 4380eef2d..5b5dc0868 100644
--- a/src/CodeCleaner/PassableByReferencePass.php
+++ b/src/CodeCleaner/PassableByReferencePass.php
@@ -56,7 +56,7 @@ public function enterNode(Node $node)
}
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());
diff --git a/src/CodeCleaner/RequirePass.php b/src/CodeCleaner/RequirePass.php
index 0e8056116..3e27184a1 100644
--- a/src/CodeCleaner/RequirePass.php
+++ b/src/CodeCleaner/RequirePass.php
@@ -79,7 +79,7 @@ public static function resolve($file, $lineNumber = null)
// @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…
@@ -87,8 +87,8 @@ public static function resolve($file, $lineNumber = null)
}
}
- 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 +97,6 @@ public static function resolve($file, $lineNumber = null)
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);
}
}
diff --git a/src/CodeCleaner/StrictTypesPass.php b/src/CodeCleaner/StrictTypesPass.php
index a63fe75e7..058a5a829 100644
--- a/src/CodeCleaner/StrictTypesPass.php
+++ b/src/CodeCleaner/StrictTypesPass.php
@@ -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 @@ public function beforeTraverse(array $nodes)
}
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);
}
}
diff --git a/src/CodeCleaner/UseStatementPass.php b/src/CodeCleaner/UseStatementPass.php
index d6ca878c4..64ac5be6d 100644
--- a/src/CodeCleaner/UseStatementPass.php
+++ b/src/CodeCleaner/UseStatementPass.php
@@ -49,7 +49,7 @@ public function enterNode(Node $node)
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 @@ public function leaveNode(Node $node)
// 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 @@ public function leaveNode(Node $node)
// 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 @@ public function leaveNode(Node $node)
*/
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)));
}
}
}
diff --git a/src/CodeCleaner/ValidClassNamePass.php b/src/CodeCleaner/ValidClassNamePass.php
index 682399bfa..022289dab 100644
--- a/src/CodeCleaner/ValidClassNamePass.php
+++ b/src/CodeCleaner/ValidClassNamePass.php
@@ -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 @@ protected function validateNewExpression(New_ $stmt)
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 @@ protected function ensureCanDefine(Stmt $stmt, $scopeType = self::CLASS_TYPE)
}
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 @@ protected function ensureCanDefine(Stmt $stmt, $scopeType = self::CLASS_TYPE)
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,7 @@ protected function ensureClassExists($name, $stmt)
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);
}
}
@@ -262,7 +262,7 @@ protected function ensureMethodExists($class, $name, $stmt)
$this->ensureClassExists($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 +276,8 @@ protected function ensureMethodExists($class, $name, $stmt)
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 +295,7 @@ protected function ensureInterfacesExist($interfaces, $stmt)
/** @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 +335,11 @@ protected function classExists($name)
// 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 +351,7 @@ protected function classExists($name)
*/
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 +363,7 @@ protected function interfaceExists($name)
*/
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 +375,7 @@ protected function traitExists($name)
*/
protected function findInScope($name)
{
- $name = strtolower($name);
+ $name = \strtolower($name);
if (isset($this->currentScope[$name])) {
return $this->currentScope[$name];
}
diff --git a/src/CodeCleaner/ValidConstantPass.php b/src/CodeCleaner/ValidConstantPass.php
index 7134bb281..2d5e3e6d9 100644
--- a/src/CodeCleaner/ValidConstantPass.php
+++ b/src/CodeCleaner/ValidConstantPass.php
@@ -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 @@ protected function validateClassConstFetchExpression(ClassConstFetch $stmt)
// 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());
}
}
diff --git a/src/CodeCleaner/ValidConstructorPass.php b/src/CodeCleaner/ValidConstructorPass.php
index b049dbc0a..a079e26c9 100644
--- a/src/CodeCleaner/ValidConstructorPass.php
+++ b/src/CodeCleaner/ValidConstructorPass.php
@@ -57,14 +57,14 @@ public function enterNode(Node $node)
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 @@ private function validateConstructor(Node $constructor, Node $classNode)
// 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());
diff --git a/src/CodeCleaner/ValidFunctionNamePass.php b/src/CodeCleaner/ValidFunctionNamePass.php
index a6bf01e72..dd1e05763 100644
--- a/src/CodeCleaner/ValidFunctionNamePass.php
+++ b/src/CodeCleaner/ValidFunctionNamePass.php
@@ -49,14 +49,14 @@ public function enterNode(Node $node)
// @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 @@ public function leaveNode(Node $node)
// 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());
}
}
diff --git a/src/Command/BufferCommand.php b/src/Command/BufferCommand.php
index 6319ccf8c..83ba34a8a 100644
--- a/src/Command/BufferCommand.php
+++ b/src/Command/BufferCommand.php
@@ -68,10 +68,10 @@ protected function execute(InputInterface $input, OutputInterface $output)
*/
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);
}
}
diff --git a/src/Command/ClearCommand.php b/src/Command/ClearCommand.php
index 1a5b845d6..6b12048a9 100644
--- a/src/Command/ClearCommand.php
+++ b/src/Command/ClearCommand.php
@@ -44,6 +44,6 @@ protected function configure()
*/
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));
}
}
diff --git a/src/Command/Command.php b/src/Command/Command.php
index 83e1dcead..be013a1b9 100644
--- a/src/Command/Command.php
+++ b/src/Command/Command.php
@@ -65,10 +65,10 @@ public function asText()
if ($help = $this->getProcessedHelp()) {
$messages[] = 'Help:';
- $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 @@ private function getArguments()
{
$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 @@ private function getOptions()
{
$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 @@ protected function getHiddenOptions()
*/
private function aliasesAsText()
{
- return 'Aliases: ' . implode(', ', $this->getAliases()) . '' . PHP_EOL;
+ return 'Aliases: ' . \implode(', ', $this->getAliases()) . '' . PHP_EOL;
}
/**
@@ -139,21 +139,21 @@ private function argumentsAsText()
if (!empty($arguments)) {
$messages[] = 'Arguments:';
foreach ($arguments as $argument) {
- if (null !== $argument->getDefault() && (!is_array($argument->getDefault()) || count($argument->getDefault()))) {
- $default = sprintf(' (default: %s)', $this->formatDefaultValue($argument->getDefault()));
+ if (null !== $argument->getDefault() && (!\is_array($argument->getDefault()) || \count($argument->getDefault()))) {
+ $default = \sprintf(' (default: %s)', $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(" %-${max}s %s%s", $argument->getName(), $description, $default);
+ $messages[] = \sprintf(" %-${max}s %s%s", $argument->getName(), $description, $default);
}
$messages[] = '';
}
- return implode(PHP_EOL, $messages);
+ return \implode(PHP_EOL, $messages);
}
/**
@@ -171,20 +171,20 @@ private function optionsAsText()
$messages[] = 'Options:';
foreach ($options as $option) {
- if ($option->acceptValue() && null !== $option->getDefault() && (!is_array($option->getDefault()) || count($option->getDefault()))) {
- $default = sprintf(' (default: %s)', $this->formatDefaultValue($option->getDefault()));
+ if ($option->acceptValue() && null !== $option->getDefault() && (!\is_array($option->getDefault()) || \count($option->getDefault()))) {
+ $default = \sprintf(' (default: %s)', $this->formatDefaultValue($option->getDefault()));
} else {
$default = '';
}
$multiple = $option->isArray() ? ' (multiple values allowed)' : '';
- $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(
" %s %-${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 @@ private function optionsAsText()
$messages[] = '';
}
- return implode(PHP_EOL, $messages);
+ return \implode(PHP_EOL, $messages);
}
/**
@@ -207,16 +207,16 @@ private function getMaxWidth()
$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 @@ private function getMaxWidth()
*/
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 @@ private function formatDefaultValue($default)
*/
protected function getTable(OutputInterface $output)
{
- if (!class_exists('Symfony\Component\Console\Helper\Table')) {
+ if (!\class_exists('Symfony\Component\Console\Helper\Table')) {
return $this->getTableHelper();
}
diff --git a/src/Command/DocCommand.php b/src/Command/DocCommand.php
index fe2028690..913634a0a 100644
--- a/src/Command/DocCommand.php
+++ b/src/Command/DocCommand.php
@@ -14,7 +14,6 @@
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 @@ protected function execute(InputInterface $input, OutputInterface $output)
private function getManualDoc($reflector)
{
- switch (get_class($reflector)) {
+ switch (\get_class($reflector)) {
case 'ReflectionClass':
case 'ReflectionObject':
case 'ReflectionFunction':
@@ -125,7 +124,7 @@ private function getManualDocById($id)
{
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);
}
}
diff --git a/src/Command/DumpCommand.php b/src/Command/DumpCommand.php
index 77bd0e2d9..9a8aad826 100644
--- a/src/Command/DumpCommand.php
+++ b/src/Command/DumpCommand.php
@@ -73,7 +73,7 @@ protected function execute(InputInterface $input, OutputInterface $output)
$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 @@ protected function execute(InputInterface $input, OutputInterface $output)
*/
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);
}
diff --git a/src/Command/EditCommand.php b/src/Command/EditCommand.php
index 7d9556928..057141494 100644
--- a/src/Command/EditCommand.php
+++ b/src/Command/EditCommand.php
@@ -95,7 +95,7 @@ protected function execute(InputInterface $input, OutputInterface $output)
$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 @@ private function extractFilePath($fileArgument)
{
// 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 @@ private function extractFilePath($fileArgument)
*/
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) {
diff --git a/src/Command/HelpCommand.php b/src/Command/HelpCommand.php
index a50f25624..82ec3a835 100644
--- a/src/Command/HelpCommand.php
+++ b/src/Command/HelpCommand.php
@@ -74,13 +74,13 @@ protected function execute(InputInterface $input, OutputInterface $output)
}
if ($command->getAliases()) {
- $aliases = sprintf('Aliases: %s', implode(', ', $command->getAliases()));
+ $aliases = \sprintf('Aliases: %s', \implode(', ', $command->getAliases()));
} else {
$aliases = '';
}
$table->addRow([
- sprintf('%s', $name),
+ \sprintf('%s', $name),
$command->getDescription(),
$aliases,
]);
diff --git a/src/Command/HistoryCommand.php b/src/Command/HistoryCommand.php
index eef8ef9d0..23f6899e3 100644
--- a/src/Command/HistoryCommand.php
+++ b/src/Command/HistoryCommand.php
@@ -110,11 +110,11 @@ protected function execute(InputInterface $input, OutputInterface $output)
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('%s', self::escape($matches[0]));
+ $chunks = \explode($matches[0], $history[$i]);
+ $chunks = \array_map([__CLASS__, 'escape'], $chunks);
+ $glue = \sprintf('%s', self::escape($matches[0]));
- $highlighted[$i] = implode($glue, $chunks);
+ $highlighted[$i] = \implode($glue, $chunks);
}
} else {
unset($history[$i]);
@@ -123,16 +123,16 @@ protected function execute(InputInterface $input, OutputInterface $output)
}
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('History saved.');
} 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 @@ protected function execute(InputInterface $input, OutputInterface $output)
*/
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 @@ private function getHistorySlice($show, $head, $tail)
$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 @@ private function validateOnlyOne(InputInterface $input, array $options)
}
if ($count > 1) {
- throw new \InvalidArgumentException('Please specify only one of --' . implode(', --', $options));
+ throw new \InvalidArgumentException('Please specify only one of --' . \implode(', --', $options));
}
}
diff --git a/src/Command/ListCommand.php b/src/Command/ListCommand.php
index 2e65895e8..67f4e041e 100644
--- a/src/Command/ListCommand.php
+++ b/src/Command/ListCommand.php
@@ -178,8 +178,8 @@ protected function write(OutputInterface $output, array $result = null)
}
foreach ($result as $label => $items) {
- $names = array_map([$this, 'formatItemName'], $items);
- $output->writeln(sprintf('%s: %s', $label, implode(', ', $names)));
+ $names = \array_map([$this, 'formatItemName'], $items);
+ $output->writeln(\sprintf('%s: %s', $label, \implode(', ', $names)));
}
}
@@ -201,7 +201,7 @@ protected function writeLong(OutputInterface $output, array $result = null)
foreach ($result as $label => $items) {
$output->writeln('');
- $output->writeln(sprintf('%s:', $label));
+ $output->writeln(\sprintf('%s:', $label));
$table->setRows([]);
foreach ($items as $item) {
@@ -225,7 +225,7 @@ protected function writeLong(OutputInterface $output, array $result = null)
*/
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']);
}
/**
diff --git a/src/Command/ListCommand/ClassConstantEnumerator.php b/src/Command/ListCommand/ClassConstantEnumerator.php
index 0b0992709..a1d82ead6 100644
--- a/src/Command/ListCommand/ClassConstantEnumerator.php
+++ b/src/Command/ListCommand/ClassConstantEnumerator.php
@@ -68,7 +68,7 @@ protected function getConstants(\Reflector $reflector, $noInherit = false)
$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 @@ protected function getConstants(\Reflector $reflector, $noInherit = false)
$constants[$name] = $constReflector;
}
- ksort($constants, SORT_NATURAL | SORT_FLAG_CASE);
+ \ksort($constants, SORT_NATURAL | SORT_FLAG_CASE);
return $constants;
}
@@ -118,7 +118,7 @@ protected function getKindLabel(\ReflectionClass $reflector)
{
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';
diff --git a/src/Command/ListCommand/ClassEnumerator.php b/src/Command/ListCommand/ClassEnumerator.php
index 858f5a2e1..8ab6d7a95 100644
--- a/src/Command/ListCommand/ClassEnumerator.php
+++ b/src/Command/ListCommand/ClassEnumerator.php
@@ -43,18 +43,18 @@ protected function listItems(InputInterface $input, \Reflector $reflector = null
// 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 @@ protected function filterClasses($key, $classes, $internal, $user)
$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 @@ protected function filterClasses($key, $classes, $internal, $user)
}
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 @@ protected function filterClasses($key, $classes, $internal, $user)
*/
protected function prepareClasses(array $classes)
{
- natcasesort($classes);
+ \natcasesort($classes);
// My kingdom for a generator.
$ret = [];
diff --git a/src/Command/ListCommand/ConstantEnumerator.php b/src/Command/ListCommand/ConstantEnumerator.php
index e17d42a07..ad4ce0d12 100644
--- a/src/Command/ListCommand/ConstantEnumerator.php
+++ b/src/Command/ListCommand/ConstantEnumerator.php
@@ -54,7 +54,7 @@ protected function listItems(InputInterface $input, \Reflector $reflector = null
}
if ($category) {
- $label = ucfirst($category) . ' Constants';
+ $label = \ucfirst($category) . ' Constants';
$ret[$label] = $this->getConstants($category);
}
@@ -62,7 +62,7 @@ protected function listItems(InputInterface $input, \Reflector $reflector = null
$ret['Constants'] = $this->getConstants();
}
- return array_map([$this, 'prepareConstants'], array_filter($ret));
+ return \array_map([$this, 'prepareConstants'], \array_filter($ret));
}
/**
@@ -78,15 +78,15 @@ protected function listItems(InputInterface $input, \Reflector $reflector = null
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 @@ protected function prepareConstants(array $constants)
// 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)) {
diff --git a/src/Command/ListCommand/FunctionEnumerator.php b/src/Command/ListCommand/FunctionEnumerator.php
index 733055a60..6c3fa5ea9 100644
--- a/src/Command/ListCommand/FunctionEnumerator.php
+++ b/src/Command/ListCommand/FunctionEnumerator.php
@@ -74,12 +74,12 @@ protected function listItems(InputInterface $input, \Reflector $reflector = null
*/
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 @@ protected function getFunctions($type = null)
*/
protected function prepareFunctions(array $functions)
{
- natcasesort($functions);
+ \natcasesort($functions);
// My kingdom for a generator.
$ret = [];
diff --git a/src/Command/ListCommand/GlobalVariableEnumerator.php b/src/Command/ListCommand/GlobalVariableEnumerator.php
index 8e58af8b0..f51791cb6 100644
--- a/src/Command/ListCommand/GlobalVariableEnumerator.php
+++ b/src/Command/ListCommand/GlobalVariableEnumerator.php
@@ -53,8 +53,8 @@ protected function getGlobals()
{
global $GLOBALS;
- $names = array_keys($GLOBALS);
- natcasesort($names);
+ $names = \array_keys($GLOBALS);
+ \natcasesort($names);
$ret = [];
foreach ($names as $name) {
diff --git a/src/Command/ListCommand/InterfaceEnumerator.php b/src/Command/ListCommand/InterfaceEnumerator.php
index dae0dace8..4531fce83 100644
--- a/src/Command/ListCommand/InterfaceEnumerator.php
+++ b/src/Command/ListCommand/InterfaceEnumerator.php
@@ -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 @@ protected function listItems(InputInterface $input, \Reflector $reflector = null
return;
}
- $interfaces = $this->prepareInterfaces(get_declared_interfaces());
+ $interfaces = $this->prepareInterfaces(\get_declared_interfaces());
if (empty($interfaces)) {
return;
@@ -69,7 +69,7 @@ protected function listItems(InputInterface $input, \Reflector $reflector = null
*/
protected function prepareInterfaces(array $interfaces)
{
- natcasesort($interfaces);
+ \natcasesort($interfaces);
// My kingdom for a generator.
$ret = [];
diff --git a/src/Command/ListCommand/MethodEnumerator.php b/src/Command/ListCommand/MethodEnumerator.php
index ebe43afad..49d7e104e 100644
--- a/src/Command/ListCommand/MethodEnumerator.php
+++ b/src/Command/ListCommand/MethodEnumerator.php
@@ -77,7 +77,7 @@ protected function getMethods($showAll, \Reflector $reflector, $noInherit = fals
}
}
- ksort($methods, SORT_NATURAL | SORT_FLAG_CASE);
+ \ksort($methods, SORT_NATURAL | SORT_FLAG_CASE);
return $methods;
}
@@ -118,7 +118,7 @@ protected function getKindLabel(\ReflectionClass $reflector)
{
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';
diff --git a/src/Command/ListCommand/PropertyEnumerator.php b/src/Command/ListCommand/PropertyEnumerator.php
index 15ce45db7..d56caded6 100644
--- a/src/Command/ListCommand/PropertyEnumerator.php
+++ b/src/Command/ListCommand/PropertyEnumerator.php
@@ -77,7 +77,7 @@ protected function getProperties($showAll, \Reflector $reflector, $noInherit = f
}
}
- ksort($properties, SORT_NATURAL | SORT_FLAG_CASE);
+ \ksort($properties, SORT_NATURAL | SORT_FLAG_CASE);
return $properties;
}
@@ -119,7 +119,7 @@ protected function getKindLabel(\ReflectionClass $reflector)
{
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 @@ protected function presentValue(\ReflectionProperty $property, $target)
{
// 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() ? '' : ' ';
return $this->presentRef($props[$property->name]) . $suffix;
diff --git a/src/Command/ListCommand/TraitEnumerator.php b/src/Command/ListCommand/TraitEnumerator.php
index c4c74da7e..3ee601558 100644
--- a/src/Command/ListCommand/TraitEnumerator.php
+++ b/src/Command/ListCommand/TraitEnumerator.php
@@ -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 @@ protected function listItems(InputInterface $input, \Reflector $reflector = null
return;
}
- $traits = $this->prepareTraits(get_declared_traits());
+ $traits = $this->prepareTraits(\get_declared_traits());
if (empty($traits)) {
return;
@@ -69,7 +69,7 @@ protected function listItems(InputInterface $input, \Reflector $reflector = null
*/
protected function prepareTraits(array $traits)
{
- natcasesort($traits);
+ \natcasesort($traits);
// My kingdom for a generator.
$ret = [];
diff --git a/src/Command/ListCommand/VariableEnumerator.php b/src/Command/ListCommand/VariableEnumerator.php
index 257ceac53..0586c203e 100644
--- a/src/Command/ListCommand/VariableEnumerator.php
+++ b/src/Command/ListCommand/VariableEnumerator.php
@@ -79,9 +79,9 @@ protected function listItems(InputInterface $input, \Reflector $reflector = null
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 @@ protected function getVariables($showAll)
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 @@ protected function prepareVariables(array $variables)
$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),
];
}
diff --git a/src/Command/ParseCommand.php b/src/Command/ParseCommand.php
index 5fe36d126..3f3286e8a 100644
--- a/src/Command/ParseCommand.php
+++ b/src/Command/ParseCommand.php
@@ -97,7 +97,7 @@ protected function configure()
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 @@ protected function configure()
protected function execute(InputInterface $input, OutputInterface $output)
{
$code = $input->getArgument('code');
- if (strpos('', $code) === false) {
+ if (\strpos('', $code) === false) {
$code = '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 @@ private function parse(Parser $parser, $code)
*/
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);
}
diff --git a/src/Command/ReflectingCommand.php b/src/Command/ReflectingCommand.php
index 8bc56f6fd..328632805 100644
--- a/src/Command/ReflectingCommand.php
+++ b/src/Command/ReflectingCommand.php
@@ -56,19 +56,19 @@ public function setContext(Context $context)
*/
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 @@ protected function resolveName($name, $includeFunctions = false)
$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 @@ private function resolveObject($code)
{
$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 @@ private function resolveObject($code)
*/
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 @@ protected function setCommandScopeVariables(\Reflector $reflector)
{
$vars = [];
- switch (get_class($reflector)) {
+ switch (\get_class($reflector)) {
case 'ReflectionClass':
case 'ReflectionObject':
$vars['__class'] = $reflector->name;
@@ -240,7 +240,7 @@ protected function setCommandScopeVariables(\Reflector $reflector)
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 @@ protected function setCommandScopeVariables(\Reflector $reflector)
if ($fileName = $reflector->getExecutingFile()) {
$vars['__file'] = $fileName;
$vars['__line'] = $reflector->getExecutingLine();
- $vars['__dir'] = dirname($fileName);
+ $vars['__dir'] = \dirname($fileName);
}
break;
@@ -279,7 +279,7 @@ protected function setCommandScopeVariables(\Reflector $reflector)
// 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 @@ protected function setCommandScopeVariables(\Reflector $reflector)
if ($fileName = $reflector->getFileName()) {
$vars['__file'] = $fileName;
$vars['__line'] = $reflector->getStartLine();
- $vars['__dir'] = dirname($fileName);
+ $vars['__dir'] = \dirname($fileName);
}
}
diff --git a/src/Command/ShowCommand.php b/src/Command/ShowCommand.php
index cae86e59c..47d186548 100644
--- a/src/Command/ShowCommand.php
+++ b/src/Command/ShowCommand.php
@@ -140,16 +140,16 @@ private function writeExceptionContext(InputInterface $input, OutputInterface $o
$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 @@ private function writeTraceLine(OutputInterface $output, array $trace, $index)
$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 %s:%d at level %d 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 @@ private function writeTraceCodeSnippet(OutputInterface $output, array $trace, $i
$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 @@ private function setCommandScopeVariablesFromContext(array $context)
$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 @@ private function setCommandScopeVariablesFromContext(array $context)
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]];
}
}
diff --git a/src/Command/SudoCommand.php b/src/Command/SudoCommand.php
index 44cc2c0e5..9d5afbf04 100644
--- a/src/Command/SudoCommand.php
+++ b/src/Command/SudoCommand.php
@@ -103,13 +103,13 @@ protected function execute(InputInterface $input, OutputInterface $output)
// 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 = 'parser->parse($code);
} catch (\PhpParser\Error $e) {
- if (strpos($e->getMessage(), 'unexpected EOF') === false) {
+ if (\strpos($e->getMessage(), 'unexpected EOF') === false) {
throw $e;
}
diff --git a/src/Command/ThrowUpCommand.php b/src/Command/ThrowUpCommand.php
index 99af9a8aa..b37f7573c 100644
--- a/src/Command/ThrowUpCommand.php
+++ b/src/Command/ThrowUpCommand.php
@@ -125,12 +125,12 @@ private function prepareArgs($code = null)
return [new Arg(new Variable('_e'))];
}
- if (strpos('', $code) === false) {
+ if (\strpos('', $code) === false) {
$code = 'parse($code);
- if (count($nodes) !== 1) {
+ if (\count($nodes) !== 1) {
throw new \InvalidArgumentException('No idea how to throw this');
}
@@ -161,7 +161,7 @@ private function parse($code)
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;
}
diff --git a/src/Command/TimeitCommand.php b/src/Command/TimeitCommand.php
index 70d70c0e1..c59663131 100644
--- a/src/Command/TimeitCommand.php
+++ b/src/Command/TimeitCommand.php
@@ -16,7 +16,6 @@
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 @@ protected function execute(InputInterface $input, OutputInterface $output)
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 @@ protected function execute(InputInterface $input, OutputInterface $output)
*/
public static function markStart()
{
- self::$start = microtime(true);
+ self::$start = \microtime(true);
}
/**
@@ -137,7 +136,7 @@ public static function markStart()
*/
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 @@ private function parse($code)
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;
}
diff --git a/src/Command/TimeitCommand/TimeitVisitor.php b/src/Command/TimeitCommand/TimeitVisitor.php
index 6ee66994d..841ba135d 100644
--- a/src/Command/TimeitCommand/TimeitVisitor.php
+++ b/src/Command/TimeitCommand/TimeitVisitor.php
@@ -75,15 +75,15 @@ public function leaveNode(Node $node)
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 @@ private function getEndCall(Expr $arg = null)
*/
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;
}
}
diff --git a/src/Command/TraceCommand.php b/src/Command/TraceCommand.php
index becc58316..c28b0e728 100644
--- a/src/Command/TraceCommand.php
+++ b/src/Command/TraceCommand.php
@@ -90,8 +90,8 @@ protected function execute(InputInterface $input, OutputInterface $output)
*/
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 @@ protected function getBacktrace(\Exception $e, $count = null, $includePsy = true
$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 @@ protected function getBacktrace(\Exception $e, $count = null, $includePsy = true
]);
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 @@ protected function getBacktrace(\Exception $e, $count = null, $includePsy = true
$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(
' %s%s%s() at %s:%s',
OutputFormatter::escape($class),
OutputFormatter::escape($type),
@@ -161,7 +161,7 @@ private function replaceCwd($cwd, $file)
if ($cwd === false) {
return $file;
} else {
- return preg_replace('/^' . preg_quote($cwd, '/') . '/', '', $file);
+ return \preg_replace('/^' . \preg_quote($cwd, '/') . '/', '', $file);
}
}
}
diff --git a/src/Command/WhereamiCommand.php b/src/Command/WhereamiCommand.php
index c2b27843b..98593d13a 100644
--- a/src/Command/WhereamiCommand.php
+++ b/src/Command/WhereamiCommand.php
@@ -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 @@ protected function configure()
*/
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 @@ private static function isDebugCall(array $stackFrame)
$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 @@ private static function isDebugCall(array $stackFrame)
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 @@ protected function fileInfo()
$line = $stackFrame['line'];
}
- return compact('file', 'line');
+ return \compact('file', 'line');
}
/**
@@ -117,11 +117,11 @@ protected function execute(InputInterface $input, OutputInterface $output)
$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 %s:%s:', $this->replaceCwd($info['file']), $info['line']));
+ $output->writeln(\sprintf('From %s:%s:', $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 @@ protected function execute(InputInterface $input, OutputInterface $output)
*/
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);
}
}
diff --git a/src/Command/WtfCommand.php b/src/Command/WtfCommand.php
index 68ba0f3f1..c6d53000e 100644
--- a/src/Command/WtfCommand.php
+++ b/src/Command/WtfCommand.php
@@ -86,26 +86,26 @@ protected function execute(InputInterface $input, OutputInterface $output)
{
$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 @@ protected function execute(InputInterface $input, OutputInterface $output)
$output->writeln('');
if ($moreLines > 0) {
- $output->writeln(sprintf(
+ $output->writeln(\sprintf(
'',
$moreLines
));
diff --git a/src/ConfigPaths.php b/src/ConfigPaths.php
index 0c9c78a42..c4de2d576 100644
--- a/src/ConfigPaths.php
+++ b/src/ConfigPaths.php
@@ -68,7 +68,7 @@ public static function getCurrentConfigDir()
{
$configDirs = self::getHomeConfigDirs();
foreach ($configDirs as $configDir) {
- if (@is_dir($configDir)) {
+ if (@\is_dir($configDir)) {
return $configDir;
}
}
@@ -136,7 +136,7 @@ public static function getRuntimeDir()
{
$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 @@ public static function getRuntimeDir()
} 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 @@ private static function getRealFiles(array $dirNames, array $fileNames)
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 @@ private static function getRealFiles(array $dirNames, array $fileNames)
*/
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;
}
diff --git a/src/Configuration.php b/src/Configuration.php
index b37f2e57f..67c76e7b3 100644
--- a/src/Configuration.php
+++ b/src/Configuration.php
@@ -114,7 +114,7 @@ public function __construct(array $config = [])
// 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 @@ public function __construct(array $config = [])
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 @@ public function getConfigFile()
$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 @@ public function getConfigFile()
*/
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 @@ public function loadConfig(array $options)
{
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 @@ public function loadConfig(array $options)
// 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 @@ public function loadConfig(array $options)
// 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 @@ public function loadConfigFile($file)
$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 @@ public function getRuntimeDir()
$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 @@ public function getHistoryFile()
$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 @@ public function getEraseDuplicates()
*/
public function getTempFile($type, $pid)
{
- return tempnam($this->getRuntimeDir(), $type . '_' . $pid . '_');
+ return \tempnam($this->getRuntimeDir(), $type . '_' . $pid . '_');
}
/**
@@ -477,7 +477,7 @@ public function getTempFile($type, $pid)
*/
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 @@ public function getOutputDecorated()
*/
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 @@ public function setPager($pager)
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 @@ public function getTabCompletionMatchers()
*/
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 @@ public function addTabCompletionMatchers(array $matchers)
*/
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 @@ public function getManualDbFile()
$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 @@ public function getManualDb()
{
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 @@ public function setColorMode($colorMode)
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 @@ public function setUpdateCheck($interval)
Checker::NEVER,
];
- if (!in_array($interval, $validIntervals)) {
+ if (!\in_array($interval, $validIntervals)) {
throw new \InvalidArgumentException('invalid update check interval: ' . $interval);
}
diff --git a/src/Context.php b/src/Context.php
index c0e58e89b..104dc8ffa 100644
--- a/src/Context.php
+++ b/src/Context.php
@@ -75,13 +75,13 @@ public function get($name)
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 @@ public function get($name)
*/
public function getAll()
{
- return array_merge($this->scopeVariables, $this->getSpecialVariables());
+ return \array_merge($this->scopeVariables, $this->getSpecialVariables());
}
/**
@@ -123,7 +123,7 @@ public function getSpecialVariables()
$vars['this'] = $this->boundObject;
}
- return array_merge($vars, $this->commandScopeVariables);
+ return \array_merge($vars, $this->commandScopeVariables);
}
/**
@@ -228,7 +228,7 @@ public function getLastStdout()
*/
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 @@ public function getBoundObject()
*/
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 @@ public function setCommandScopeVariables(array $commandScopeVariables)
$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 @@ public function getCommandScopeVariables()
*/
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 @@ public function getUnusedCommandScopeVariableNames()
*/
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);
}
}
diff --git a/src/Exception/BreakException.php b/src/Exception/BreakException.php
index 1436d56a1..2200e78dc 100644
--- a/src/Exception/BreakException.php
+++ b/src/Exception/BreakException.php
@@ -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);
}
/**
diff --git a/src/Exception/ErrorException.php b/src/Exception/ErrorException.php
index 2cd7e95f7..822fa9275 100644
--- a/src/Exception/ErrorException.php
+++ b/src/Exception/ErrorException.php
@@ -32,7 +32,7 @@ public function __construct($message = '', $code = 0, $severity = 1, $filename =
{
$this->rawMessage = $message;
- if (!empty($filename) && preg_match('{Psy[/\\\\]ExecutionLoop}', $filename)) {
+ if (!empty($filename) && \preg_match('{Psy[/\\\\]ExecutionLoop}', $filename)) {
$filename = '';
}
@@ -67,7 +67,7 @@ public function __construct($message = '', $code = 0, $severity = 1, $filename =
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);
}
diff --git a/src/Exception/FatalErrorException.php b/src/Exception/FatalErrorException.php
index 08b56c0b4..48a4e2b81 100644
--- a/src/Exception/FatalErrorException.php
+++ b/src/Exception/FatalErrorException.php
@@ -36,7 +36,7 @@ public function __construct($message = '', $code = 0, $severity = 1, $filename =
}
$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);
}
diff --git a/src/Exception/ParseErrorException.php b/src/Exception/ParseErrorException.php
index 93d0d3c9f..cb6380e6b 100644
--- a/src/Exception/ParseErrorException.php
+++ b/src/Exception/ParseErrorException.php
@@ -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);
}
diff --git a/src/Exception/ThrowUpException.php b/src/Exception/ThrowUpException.php
index 8c3eb06c4..b0ca490a7 100644
--- a/src/Exception/ThrowUpException.php
+++ b/src/Exception/ThrowUpException.php
@@ -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);
}
diff --git a/src/Exception/TypeErrorException.php b/src/Exception/TypeErrorException.php
index 9dbdb9365..b6894983f 100644
--- a/src/Exception/TypeErrorException.php
+++ b/src/Exception/TypeErrorException.php
@@ -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);
}
/**
diff --git a/src/ExecutionClosure.php b/src/ExecutionClosure.php
index 29a3bcc6d..5c7cd25ac 100644
--- a/src/ExecutionClosure.php
+++ b/src/ExecutionClosure.php
@@ -28,42 +28,42 @@ public function __construct(Shell $__psysh__)
$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 @@ protected function setClosure(Shell $shell, \Closure $closure)
{
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 @@ protected static function shouldBindClosure()
{
// 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;
diff --git a/src/ExecutionLoop.php b/src/ExecutionLoop.php
index eacd1d3c4..2e4307cb7 100644
--- a/src/ExecutionLoop.php
+++ b/src/ExecutionLoop.php
@@ -42,7 +42,7 @@ protected function loadIncludes(Shell $shell)
{
// 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 @@ protected function loadIncludes(Shell $shell)
$__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);
diff --git a/src/ExecutionLoop/ProcessForker.php b/src/ExecutionLoop/ProcessForker.php
index 2e6450325..470479594 100644
--- a/src/ExecutionLoop/ProcessForker.php
+++ b/src/ExecutionLoop/ProcessForker.php
@@ -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 @@ public static function isSupported()
*/
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 @@ public function beforeRun(Shell $shell)
$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 @@ public function afterLoop(Shell $shell)
{
// 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 @@ public function afterRun(Shell $shell)
{
// 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 @@ public function afterRun(Shell $shell)
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 @@ private function serializeReturn(array $return)
}
// 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 @@ private function serializeReturn(array $return)
}
}
- return @serialize($serializable);
+ return @\serialize($serializable);
}
}
diff --git a/src/ExecutionLoop/RunkitReloader.php b/src/ExecutionLoop/RunkitReloader.php
index 5706b79ad..d80480b0a 100644
--- a/src/ExecutionLoop/RunkitReloader.php
+++ b/src/ExecutionLoop/RunkitReloader.php
@@ -30,7 +30,7 @@ class RunkitReloader extends AbstractListener
*/
public static function isSupported()
{
- return extension_loaded('runkit');
+ return \extension_loaded('runkit');
}
/**
@@ -62,11 +62,11 @@ public function onInput(Shell $shell, $input)
*/
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 @@ private function reload(Shell $shell)
}
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 @@ private function lintFile($file)
{
// 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;
}
diff --git a/src/ExecutionLoopClosure.php b/src/ExecutionLoopClosure.php
index e34848ed5..94d3ce2e7 100644
--- a/src/ExecutionLoopClosure.php
+++ b/src/ExecutionLoopClosure.php
@@ -31,7 +31,7 @@ public function __construct(Shell $__psysh__)
{
$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 @@ public function __construct(Shell $__psysh__)
$__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) {
diff --git a/src/Formatter/CodeFormatter.php b/src/Formatter/CodeFormatter.php
index 5ef195dff..2ac37cc9d 100644
--- a/src/Formatter/CodeFormatter.php
+++ b/src/Formatter/CodeFormatter.php
@@ -38,11 +38,11 @@ public static function format(\Reflector $reflector, $colorMode = null)
$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;
diff --git a/src/Formatter/DocblockFormatter.php b/src/Formatter/DocblockFormatter.php
index 33f450e1a..39ea60e54 100644
--- a/src/Formatter/DocblockFormatter.php
+++ b/src/Formatter/DocblockFormatter.php
@@ -45,20 +45,20 @@ public static function format(\Reflector $reflector)
if (!empty($docblock->tags)) {
foreach ($docblock::$vectors as $name => $vector) {
if (isset($docblock->tags[$name])) {
- $chunks[] = sprintf('%s:', self::inflect($name));
+ $chunks[] = \sprintf('%s:', 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 @@ private static function formatVector(array $vector, array $lines)
$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 @@ private static function formatVector(array $vector, array $lines)
$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 @@ private static function formatTags(array $skip, array $tags)
$chunks = [];
foreach ($tags as $name => $values) {
- if (in_array($name, $skip)) {
+ if (\in_array($name, $skip)) {
continue;
}
foreach ($values as $value) {
- $chunks[] = sprintf('%s%s %s', self::inflect($name), empty($value) ? '' : ':', OutputFormatter::escape($value));
+ $chunks[] = \sprintf('%s%s %s', self::inflect($name), empty($value) ? '' : ':', OutputFormatter::escape($value));
}
$chunks[] = '';
}
- return implode("\n", $chunks);
+ return \implode("\n", $chunks);
}
/**
@@ -133,10 +133,10 @@ private static function formatTags(array $skip, array $tags)
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 @@ private static function getVectorParamTemplate($type, $max)
*/
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 @@ private static function indent($text, $indent = ' ')
*/
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)));
}
}
diff --git a/src/Formatter/SignatureFormatter.php b/src/Formatter/SignatureFormatter.php
index 2a83ad1cb..ec8725d9f 100644
--- a/src/Formatter/SignatureFormatter.php
+++ b/src/Formatter/SignatureFormatter.php
@@ -56,7 +56,7 @@ public static function format(\Reflector $reflector)
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 @@ private static function formatModifiers(\Reflector $reflector)
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('%s', $modifier);
+ return \implode(' ', \array_map(function ($modifier) {
+ return \sprintf('%s', $modifier);
}, \Reflection::getModifierNames($reflector->getModifiers())));
}
@@ -115,24 +115,24 @@ private static function formatClass(\ReflectionClass $reflector)
$chunks[] = $reflector->isInterface() ? 'interface' : 'class';
}
- $chunks[] = sprintf('%s', self::formatName($reflector));
+ $chunks[] = \sprintf('%s', self::formatName($reflector));
if ($parent = $reflector->getParentClass()) {
$chunks[] = 'extends';
- $chunks[] = sprintf('%s', $parent->getName());
+ $chunks[] = \sprintf('%s', $parent->getName());
}
$interfaces = $reflector->getInterfaceNames();
if (!empty($interfaces)) {
- sort($interfaces);
+ \sort($interfaces);
$chunks[] = 'implements';
- $chunks[] = implode(', ', array_map(function ($name) {
- return sprintf('%s', $name);
+ $chunks[] = \implode(', ', \array_map(function ($name) {
+ return \sprintf('%s', $name);
}, $interfaces));
}
- return implode(' ', $chunks);
+ return \implode(' ', $chunks);
}
/**
@@ -147,7 +147,7 @@ private static function formatClassConstant($reflector)
$value = $reflector->getValue();
$style = self::getTypeStyle($value);
- return sprintf(
+ return \sprintf(
'const %s = <%s>%s%s>',
self::formatName($reflector),
$style,
@@ -168,7 +168,7 @@ private static function formatConstant($reflector)
$value = $reflector->getValue();
$style = self::getTypeStyle($value);
- return sprintf(
+ return \sprintf(
'define(%s, <%s>%s%s>)',
OutputFormatter::escape(Json::encode($reflector->getName())),
$style,
@@ -186,11 +186,11 @@ private static function formatConstant($reflector)
*/
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 @@ private static function getTypeStyle($value)
*/
private static function formatProperty(\ReflectionProperty $reflector)
{
- return sprintf(
+ return \sprintf(
'%s $%s',
self::formatModifiers($reflector),
$reflector->getName()
@@ -222,11 +222,11 @@ private static function formatProperty(\ReflectionProperty $reflector)
*/
private static function formatFunction(\ReflectionFunctionAbstract $reflector)
{
- return sprintf(
+ return \sprintf(
'function %s%s(%s)',
$reflector->returnsReference() ? '&' : '',
self::formatName($reflector),
- implode(', ', self::formatFunctionParams($reflector))
+ \implode(', ', self::formatFunctionParams($reflector))
);
}
@@ -239,7 +239,7 @@ private static function formatFunction(\ReflectionFunctionAbstract $reflector)
*/
private static function formatMethod(\ReflectionMethod $reflector)
{
- return sprintf(
+ return \sprintf(
'%s %s',
self::formatModifiers($reflector),
self::formatFunction($reflector)
@@ -262,7 +262,7 @@ private static function formatFunctionParams(\ReflectionFunctionAbstract $reflec
if ($param->isArray()) {
$hint = 'array ';
} elseif ($class = $param->getClass()) {
- $hint = sprintf('%s ', $class->getName());
+ $hint = \sprintf('%s ', $class->getName());
}
} catch (\Exception $e) {
// sometimes we just don't know...
@@ -272,11 +272,11 @@ private static function formatFunctionParams(\ReflectionFunctionAbstract $reflec
// 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('%s ', $guess);
+ $hint = \sprintf('%s ', $guess);
// @codeCoverageIgnoreEnd
}
@@ -287,14 +287,14 @@ private static function formatFunctionParams(\ReflectionFunctionAbstract $reflec
} 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$%s%s',
$param->isPassedByReference() ? '&' : '',
$hint,
diff --git a/src/Input/FilterOptions.php b/src/Input/FilterOptions.php
index a2ed49d05..d77a04fb7 100644
--- a/src/Input/FilterOptions.php
+++ b/src/Input/FilterOptions.php
@@ -56,7 +56,7 @@ public function bind(InputInterface $input)
}
if (!$this->stringIsRegex($pattern)) {
- $pattern = '/' . preg_quote($pattern, '/') . '/';
+ $pattern = '/' . \preg_quote($pattern, '/') . '/';
}
if ($insensitive = $input->getOption('insensitive')) {
@@ -91,7 +91,7 @@ public function hasFilter()
*/
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 @@ private function validateInput(InputInterface $input)
*/
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 @@ private function stringIsRegex($string)
*/
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();
}
}
diff --git a/src/Input/ShellInput.php b/src/Input/ShellInput.php
index 7141d2d4c..8675f4d12 100644
--- a/src/Input/ShellInput.php
+++ b/src/Input/ShellInput.php
@@ -51,10 +51,10 @@ public function bind(InputDefinition $definition)
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 @@ public function bind(InputDefinition $definition)
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 @@ protected function parse()
{
$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 @@ protected function parse()
$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 @@ protected function parse()
*/
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 @@ private function parseShellArgument($token, $rest)
// 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 @@ private function parseShellArgument($token, $rest)
*/
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 @@ private function parseShortOption($token)
*/
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 @@ private function parseShortOptionSet($name)
*/
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 @@ private function parseLongOption($token)
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 @@ private function addShortOption($shortcut, $value)
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()) {
diff --git a/src/Output/ProcOutputPager.php b/src/Output/ProcOutputPager.php
index d8c030285..a047b1c3f 100644
--- a/src/Output/ProcOutputPager.php
+++ b/src/Output/ProcOutputPager.php
@@ -51,14 +51,14 @@ public function __construct(StreamOutput $output, $cmd = 'less -R -S -F -X')
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 @@ public function doWrite($message, $newline)
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 @@ public function close()
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');
}
diff --git a/src/Output/ShellOutput.php b/src/Output/ShellOutput.php
index e980d3875..5881a5c20 100644
--- a/src/Output/ShellOutput.php
+++ b/src/Output/ShellOutput.php
@@ -41,7 +41,7 @@ public function __construct($verbosity = self::VERBOSITY_NORMAL, $decorated = nu
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 @@ public function __construct($verbosity = self::VERBOSITY_NORMAL, $decorated = nu
*/
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 @@ public function write($messages, $newline = false, $type = 0)
$messages = (array) $messages;
if ($type & self::NUMBER_LINES) {
- $pad = strlen((string) count($messages));
+ $pad = \strlen((string) \count($messages));
$template = $this->isDecorated() ? ": %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.
diff --git a/src/ParserFactory.php b/src/ParserFactory.php
index 21427483f..263da2022 100644
--- a/src/ParserFactory.php
+++ b/src/ParserFactory.php
@@ -44,7 +44,7 @@ public static function getPossibleKinds()
*/
public function hasKindsSupport()
{
- return class_exists('PhpParser\ParserFactory');
+ return \class_exists('PhpParser\ParserFactory');
}
/**
@@ -55,7 +55,7 @@ public function hasKindsSupport()
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 @@ public function createParser($kind = null)
$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');
diff --git a/src/Readline/GNUReadline.php b/src/Readline/GNUReadline.php
index e10412208..1cec3c63a 100644
--- a/src/Readline/GNUReadline.php
+++ b/src/Readline/GNUReadline.php
@@ -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 @@ public function __construct($historyFile = null, $historySize = 0, $eraseDups =
*/
public function addHistory($line)
{
- if ($res = readline_add_history($line)) {
+ if ($res = \readline_add_history($line)) {
$this->writeHistory();
}
@@ -70,7 +70,7 @@ public function addHistory($line)
*/
public function clearHistory()
{
- if ($res = readline_clear_history()) {
+ if ($res = \readline_clear_history()) {
$this->writeHistory();
}
@@ -96,12 +96,12 @@ public function readHistory()
//
// 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 @@ public function readHistory()
*/
public function readline($prompt = null)
{
- return readline($prompt);
+ return \readline($prompt);
}
/**
@@ -117,7 +117,7 @@ public function readline($prompt = null)
*/
public function redisplay()
{
- readline_redisplay();
+ \readline_redisplay();
}
/**
@@ -128,7 +128,7 @@ public function writeHistory()
// 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 @@ public function writeHistory()
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;
diff --git a/src/Readline/HoaConsole.php b/src/Readline/HoaConsole.php
index 9330d259e..a49b59285 100644
--- a/src/Readline/HoaConsole.php
+++ b/src/Readline/HoaConsole.php
@@ -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()
diff --git a/src/Readline/Libedit.php b/src/Readline/Libedit.php
index 008affeac..d1dc002fd 100644
--- a/src/Readline/Libedit.php
+++ b/src/Readline/Libedit.php
@@ -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 @@ public static function isSupported()
*/
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 @@ protected function parseHistoryLine($line)
}
// 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;
diff --git a/src/Readline/Transient.php b/src/Readline/Transient.php
index 585189470..e238fdf49 100644
--- a/src/Readline/Transient.php
+++ b/src/Readline/Transient.php
@@ -50,7 +50,7 @@ public function __construct($historyFile = null, $historySize = 0, $eraseDups =
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 @@ public function addHistory($line)
$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 @@ public function readline($prompt = null)
{
echo $prompt;
- return rtrim(fgets($this->getStdin(), 1024));
+ return \rtrim(\fgets($this->getStdin(), 1024));
}
/**
@@ -135,10 +135,10 @@ public function writeHistory()
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');
}
diff --git a/src/Reflection/ReflectionClassConstant.php b/src/Reflection/ReflectionClassConstant.php
index ab686bbef..019ad21da 100644
--- a/src/Reflection/ReflectionClassConstant.php
+++ b/src/Reflection/ReflectionClassConstant.php
@@ -38,7 +38,7 @@ public function __construct($class, $name)
$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 @@ public static function export($class, $name, $return = false)
$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 @@ public function getEndLine()
*/
public static function create($class, $name)
{
- if (class_exists('\\ReflectionClassConstant')) {
+ if (\class_exists('\\ReflectionClassConstant')) {
return new \ReflectionClassConstant($class, $name);
}
diff --git a/src/Reflection/ReflectionConstant.php b/src/Reflection/ReflectionConstant.php
index 7fa9b8a6a..a813fc573 100644
--- a/src/Reflection/ReflectionConstant.php
+++ b/src/Reflection/ReflectionConstant.php
@@ -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);
}
diff --git a/src/Reflection/ReflectionConstant_.php b/src/Reflection/ReflectionConstant_.php
index 91f96b6f6..b355e3509 100644
--- a/src/Reflection/ReflectionConstant_.php
+++ b/src/Reflection/ReflectionConstant_.php
@@ -46,12 +46,12 @@ public function __construct($name)
{
$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 @@ public static function export($name, $return = false)
$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 @@ public static function export($name, $return = false)
public static function isMagicConstant($name)
{
- return in_array($name, self::$magicConstants);
+ return \in_array($name, self::$magicConstants);
}
/**
@@ -115,7 +115,7 @@ public function getNamespaceName()
return '';
}
- return preg_replace('/\\\\[^\\\\]+$/', '', $this->name);
+ return \preg_replace('/\\\\[^\\\\]+$/', '', $this->name);
}
/**
@@ -135,7 +135,7 @@ public function getValue()
*/
public function inNamespace()
{
- return strpos($this->name, '\\') !== false;
+ return \strpos($this->name, '\\') !== false;
}
/**
diff --git a/src/Reflection/ReflectionLanguageConstruct.php b/src/Reflection/ReflectionLanguageConstruct.php
index bda081946..9b8eefc17 100644
--- a/src/Reflection/ReflectionLanguageConstruct.php
+++ b/src/Reflection/ReflectionLanguageConstruct.php
@@ -122,7 +122,7 @@ public function getParameters()
{
$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 @@ public function __toString()
*/
public static function isLanguageConstruct($keyword)
{
- return array_key_exists($keyword, self::$languageConstructs);
+ return \array_key_exists($keyword, self::$languageConstructs);
}
}
diff --git a/src/Reflection/ReflectionLanguageConstructParameter.php b/src/Reflection/ReflectionLanguageConstructParameter.php
index af1f4cb48..9161aa78b 100644
--- a/src/Reflection/ReflectionLanguageConstructParameter.php
+++ b/src/Reflection/ReflectionLanguageConstructParameter.php
@@ -44,7 +44,7 @@ public function getClass()
*/
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 @@ public function getName()
*/
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 @@ public function isOptional()
*/
public function isDefaultValueAvailable()
{
- return array_key_exists('defaultValue', $this->opts);
+ return \array_key_exists('defaultValue', $this->opts);
}
/**
@@ -98,6 +98,6 @@ public function isDefaultValueAvailable()
*/
public function isPassedByReference()
{
- return array_key_exists('isPassedByReference', $this->opts) && $this->opts['isPassedByReference'];
+ return \array_key_exists('isPassedByReference', $this->opts) && $this->opts['isPassedByReference'];
}
}
diff --git a/src/Shell.php b/src/Shell.php
index 3fe0b761c..6f7c79bd6 100644
--- a/src/Shell.php
+++ b/src/Shell.php
@@ -47,7 +47,7 @@
*/
class Shell extends Application
{
- const VERSION = 'v0.9.6';
+ const VERSION = 'v0.9.7';
const PROMPT = '>>> ';
const BUFF_PROMPT = '... ';
@@ -109,7 +109,7 @@ public function __construct(Configuration $config = null)
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 @@ protected function getDefaultMatchers()
*/
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 @@ protected function getDefaultLoopListeners()
*/
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 @@ public function getInput()
}
// handle empty input
- if (trim($input) === '' && !$this->codeBufferOpen) {
+ if (\trim($input) === '' && !$this->codeBufferOpen) {
continue;
}
@@ -424,12 +424,12 @@ private function inputInOpenStringOrComment($input)
}
$code = $this->codeBuffer;
- array_push($code, $input);
- $tokens = @token_get_all('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 @@ public function getUnusedCommandScopeVariableNames()
*/
public function getScopeVariableNames()
{
- return array_keys($this->context->getAll());
+ return \array_keys($this->context->getAll());
}
/**
@@ -647,7 +671,7 @@ public function setIncludes(array $includes = [])
*/
public function getIncludes()
{
- return array_merge($this->config->getDefaultIncludes(), $this->includes);
+ return \array_merge($this->config->getDefaultIncludes(), $this->includes);
}
/**
@@ -682,9 +706,9 @@ public function addCode($code, $silent = false)
{
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 @@ protected function runCommand($input)
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 @@ private function popCodeStack()
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 @@ private function addHistory($line)
}
// 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 @@ private function addHistory($line)
*/
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 @@ private function addCodeBufferToHistory()
public function getNamespace()
{
if ($namespace = $this->cleaner->getNamespace()) {
- return implode('\\', $namespace);
+ return \implode('\\', $namespace);
}
}
@@ -907,7 +931,7 @@ public function writeStdout($out, $phase = PHP_OUTPUT_HANDLER_END)
// 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 @@ public function writeStdout($out, $phase = PHP_OUTPUT_HANDLER_END)
if ($phase & PHP_OUTPUT_HANDLER_END) {
// Write an extra newline if stdout didn't end with one
if ($this->outputWantsNewline) {
- $this->output->writeln(sprintf('', $this->config->useUnicode() ? '⏎' : '\\n'));
+ $this->output->writeln(\sprintf('', $this->config->useUnicode() ? '⏎' : '\\n'));
$this->outputWantsNewline = false;
}
@@ -945,9 +969,9 @@ public function writeReturnValue($ret)
$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 @@ public function formatException(\Exception $e)
$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 @@ public function formatException(\Exception $e)
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 @@ public function execute($code, $throwExceptions = false)
*/
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 @@ protected function getCommand($input)
*/
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 @@ protected function getPrompt()
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('', static::REPLAY, OutputFormatter::escape($line)));
+ $this->output->writeln(\sprintf('', 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 @@ protected function readline()
*/
protected function getHeader()
{
- return sprintf('', $this->getVersion());
+ return \sprintf('', $this->getVersion());
}
/**
@@ -1207,7 +1231,7 @@ public function getVersion()
{
$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 @@ public function getManualDb()
*/
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 @@ protected function writeVersionInfo()
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());
diff --git a/src/Sudo.php b/src/Sudo.php
index 3c0852395..be354bef9 100644
--- a/src/Sudo.php
+++ b/src/Sudo.php
@@ -64,9 +64,9 @@ public static function assignProperty($object, $property, $value)
*/
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 @@ public static function assignStaticProperty($class, $property, $value)
*/
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);
diff --git a/src/Sudo/SudoVisitor.php b/src/Sudo/SudoVisitor.php
index 31fe6bfb0..2b78a423e 100644
--- a/src/Sudo/SudoVisitor.php
+++ b/src/Sudo/SudoVisitor.php
@@ -52,7 +52,7 @@ public function enterNode(Node $node)
$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 @@ public function enterNode(Node $node)
$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 @@ public function enterNode(Node $node)
} 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 @@ public function enterNode(Node $node)
$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 @@ public function enterNode(Node $node)
$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 @@ public function enterNode(Node $node)
$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 @@ public function enterNode(Node $node)
$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 @@ public function enterNode(Node $node)
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));
}
diff --git a/src/TabCompletion/AutoCompleter.php b/src/TabCompletion/AutoCompleter.php
index 8b3164450..0751aa78b 100644
--- a/src/TabCompletion/AutoCompleter.php
+++ b/src/TabCompletion/AutoCompleter.php
@@ -38,7 +38,7 @@ public function addMatcher(AbstractMatcher $matcher)
*/
public function activate()
{
- readline_completion_function([&$this, 'callback']);
+ \readline_completion_function([&$this, 'callback']);
}
/**
@@ -56,27 +56,27 @@ public function processCallback($input, $index, $info = [])
// 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('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 @@ public function processCallback($input, $index, $info = [])
*/
public function callback($input, $index)
{
- return $this->processCallback($input, $index, readline_info());
+ return $this->processCallback($input, $index, \readline_info());
}
/**
@@ -103,8 +103,8 @@ public function __destruct()
{
// 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();
}
}
}
diff --git a/src/TabCompletion/Matcher/AbstractDefaultParametersMatcher.php b/src/TabCompletion/Matcher/AbstractDefaultParametersMatcher.php
index 1dc0765af..c44af36ad 100644
--- a/src/TabCompletion/Matcher/AbstractDefaultParametersMatcher.php
+++ b/src/TabCompletion/Matcher/AbstractDefaultParametersMatcher.php
@@ -36,7 +36,7 @@ public function getDefaultParameterCompletion(array $reflectionParameters)
return [];
}
- return [implode(', ', $parametersProcessed) . ')'];
+ return [\implode(', ', $parametersProcessed) . ')'];
}
/**
@@ -50,8 +50,8 @@ public function getDefaultParameterCompletion(array $reflectionParameters)
*/
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 @@ private function valueToShortString($value)
$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 @@ private function valueToShortString($value)
$chunksToImplode = $allSequential ? $chunksSequential : $chunks;
- return '[' . implode(', ', $chunksToImplode) . ']';
+ return '[' . \implode(', ', $chunksToImplode) . ']';
}
}
diff --git a/src/TabCompletion/Matcher/AbstractMatcher.php b/src/TabCompletion/Matcher/AbstractMatcher.php
index efa9e57e4..63b715473 100644
--- a/src/TabCompletion/Matcher/AbstractMatcher.php
+++ b/src/TabCompletion/Matcher/AbstractMatcher.php
@@ -64,7 +64,7 @@ public function hasMatched(array $tokens)
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 @@ protected function getNamespaceAndClass($tokens)
$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 public function getMatches(array $tokens, array $info = []);
*/
public static function startsWith($prefix, $word)
{
- return preg_match(sprintf('#^%s#', $prefix), $word);
+ return \preg_match(\sprintf('#^%s#', $prefix), $word);
}
/**
@@ -129,13 +129,13 @@ public static function startsWith($prefix, $word)
*/
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 @@ public static function hasSyntax($token, $syntax = self::VAR_SYNTAX)
*/
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 @@ public static function tokenIs($token, $which)
*/
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 @@ public static function needCompleteClass($token)
*/
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);
}
}
diff --git a/src/TabCompletion/Matcher/ClassAttributesMatcher.php b/src/TabCompletion/Matcher/ClassAttributesMatcher.php
index b26df7781..8e976b0a2 100644
--- a/src/TabCompletion/Matcher/ClassAttributesMatcher.php
+++ b/src/TabCompletion/Matcher/ClassAttributesMatcher.php
@@ -28,10 +28,10 @@ public function getMatches(array $tokens, array $info = [])
{
$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 @@ public function getMatches(array $tokens, array $info = [])
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 @@ function ($var) use ($input) {
*/
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):
diff --git a/src/TabCompletion/Matcher/ClassMethodDefaultParametersMatcher.php b/src/TabCompletion/Matcher/ClassMethodDefaultParametersMatcher.php
index 4e6025bb4..3a269a353 100644
--- a/src/TabCompletion/Matcher/ClassMethodDefaultParametersMatcher.php
+++ b/src/TabCompletion/Matcher/ClassMethodDefaultParametersMatcher.php
@@ -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 @@ public function getMatches(array $tokens, array $info = [])
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;
diff --git a/src/TabCompletion/Matcher/ClassMethodsMatcher.php b/src/TabCompletion/Matcher/ClassMethodsMatcher.php
index 2aba6dc1a..d278c18bf 100644
--- a/src/TabCompletion/Matcher/ClassMethodsMatcher.php
+++ b/src/TabCompletion/Matcher/ClassMethodsMatcher.php
@@ -28,10 +28,10 @@ public function getMatches(array $tokens, array $info = [])
{
$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 @@ public function getMatches(array $tokens, array $info = [])
$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 @@ function ($name) use ($class) {
*/
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):
diff --git a/src/TabCompletion/Matcher/ClassNamesMatcher.php b/src/TabCompletion/Matcher/ClassNamesMatcher.php
index 8c35094f5..844b3d2ae 100644
--- a/src/TabCompletion/Matcher/ClassNamesMatcher.php
+++ b/src/TabCompletion/Matcher/ClassNamesMatcher.php
@@ -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 @@ function ($className) use ($quotedClass) {
*/
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 @@ public function hasMatched(array $tokens)
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):
diff --git a/src/TabCompletion/Matcher/CommandsMatcher.php b/src/TabCompletion/Matcher/CommandsMatcher.php
index eddcef984..e3d8423a6 100644
--- a/src/TabCompletion/Matcher/CommandsMatcher.php
+++ b/src/TabCompletion/Matcher/CommandsMatcher.php
@@ -45,8 +45,8 @@ public function setCommands(array $commands)
{
$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 @@ public function setCommands(array $commands)
*/
protected function isCommand($name)
{
- return in_array($name, $this->commands);
+ return \in_array($name, $this->commands);
}
/**
@@ -88,7 +88,7 @@ public function getMatches(array $tokens, array $info = [])
{
$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 @@ public function getMatches(array $tokens, array $info = [])
*/
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) &&
diff --git a/src/TabCompletion/Matcher/ConstantsMatcher.php b/src/TabCompletion/Matcher/ConstantsMatcher.php
index ddd8bcb0c..71be18f58 100644
--- a/src/TabCompletion/Matcher/ConstantsMatcher.php
+++ b/src/TabCompletion/Matcher/ConstantsMatcher.php
@@ -27,7 +27,7 @@ public function getMatches(array $tokens, array $info = [])
{
$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 @@ public function getMatches(array $tokens, array $info = [])
*/
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):
diff --git a/src/TabCompletion/Matcher/FunctionDefaultParametersMatcher.php b/src/TabCompletion/Matcher/FunctionDefaultParametersMatcher.php
index 14c568e1f..66d9ea1dc 100644
--- a/src/TabCompletion/Matcher/FunctionDefaultParametersMatcher.php
+++ b/src/TabCompletion/Matcher/FunctionDefaultParametersMatcher.php
@@ -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 @@ public function getMatches(array $tokens, array $info = [])
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;
}
diff --git a/src/TabCompletion/Matcher/FunctionsMatcher.php b/src/TabCompletion/Matcher/FunctionsMatcher.php
index 8bf168562..3aa12a1f0 100644
--- a/src/TabCompletion/Matcher/FunctionsMatcher.php
+++ b/src/TabCompletion/Matcher/FunctionsMatcher.php
@@ -27,10 +27,10 @@ public function getMatches(array $tokens, array $info = [])
{
$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 @@ public function getMatches(array $tokens, array $info = [])
*/
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):
diff --git a/src/TabCompletion/Matcher/KeywordsMatcher.php b/src/TabCompletion/Matcher/KeywordsMatcher.php
index b576f82bb..9d0deeeea 100644
--- a/src/TabCompletion/Matcher/KeywordsMatcher.php
+++ b/src/TabCompletion/Matcher/KeywordsMatcher.php
@@ -48,7 +48,7 @@ public function getKeywords()
*/
public function isKeyword($keyword)
{
- return in_array($keyword, $this->keywords);
+ return \in_array($keyword, $this->keywords);
}
/**
@@ -58,7 +58,7 @@ public function getMatches(array $tokens, array $info = [])
{
$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 @@ public function getMatches(array $tokens, array $info = [])
*/
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):
diff --git a/src/TabCompletion/Matcher/MongoClientMatcher.php b/src/TabCompletion/Matcher/MongoClientMatcher.php
index eb15f15c2..fb51bf7d2 100644
--- a/src/TabCompletion/Matcher/MongoClientMatcher.php
+++ b/src/TabCompletion/Matcher/MongoClientMatcher.php
@@ -27,13 +27,13 @@ public function getMatches(array $tokens, array $info = [])
{
$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 @@ public function getMatches(array $tokens, array $info = [])
$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 @@ function ($var) use ($input) {
*/
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):
diff --git a/src/TabCompletion/Matcher/MongoDatabaseMatcher.php b/src/TabCompletion/Matcher/MongoDatabaseMatcher.php
index 26e2337ad..fb1b9bbfb 100644
--- a/src/TabCompletion/Matcher/MongoDatabaseMatcher.php
+++ b/src/TabCompletion/Matcher/MongoDatabaseMatcher.php
@@ -27,20 +27,20 @@ public function getMatches(array $tokens, array $info = [])
{
$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 @@ function ($var) use ($input) {
*/
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):
diff --git a/src/TabCompletion/Matcher/ObjectAttributesMatcher.php b/src/TabCompletion/Matcher/ObjectAttributesMatcher.php
index bed365a82..ff44f5ac1 100644
--- a/src/TabCompletion/Matcher/ObjectAttributesMatcher.php
+++ b/src/TabCompletion/Matcher/ObjectAttributesMatcher.php
@@ -30,16 +30,16 @@ public function getMatches(array $tokens, array $info = [])
{
$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 @@ public function getMatches(array $tokens, array $info = [])
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 @@ function ($var) use ($input) {
*/
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):
diff --git a/src/TabCompletion/Matcher/ObjectMethodDefaultParametersMatcher.php b/src/TabCompletion/Matcher/ObjectMethodDefaultParametersMatcher.php
index cb95ae7ef..16fa0189f 100644
--- a/src/TabCompletion/Matcher/ObjectMethodDefaultParametersMatcher.php
+++ b/src/TabCompletion/Matcher/ObjectMethodDefaultParametersMatcher.php
@@ -15,16 +15,16 @@ class ObjectMethodDefaultParametersMatcher extends AbstractDefaultParametersMatc
{
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);
- $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);
@@ -48,19 +48,19 @@ public function getMatches(array $tokens, array $info = [])
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_OBJECT_OPERATOR)) {
return false;
diff --git a/src/TabCompletion/Matcher/ObjectMethodsMatcher.php b/src/TabCompletion/Matcher/ObjectMethodsMatcher.php
index cc45b1d9e..23c751c7b 100644
--- a/src/TabCompletion/Matcher/ObjectMethodsMatcher.php
+++ b/src/TabCompletion/Matcher/ObjectMethodsMatcher.php
@@ -30,16 +30,16 @@ public function getMatches(array $tokens, array $info = [])
{
$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 @@ public function getMatches(array $tokens, array $info = [])
return [];
}
- if (!is_object($object)) {
+ if (!\is_object($object)) {
return [];
}
- return array_filter(
- get_class_methods($object),
+ return \array_filter(
+ \get_class_methods($object),
function ($var) use ($input) {
return AbstractMatcher::startsWith($input, $var) &&
// also check that we do not suggest invoking a super method(__construct, __wakeup, …)
@@ -66,8 +66,8 @@ function ($var) use ($input) {
*/
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):
diff --git a/src/TabCompletion/Matcher/VariablesMatcher.php b/src/TabCompletion/Matcher/VariablesMatcher.php
index 286852593..a142b7b2e 100644
--- a/src/TabCompletion/Matcher/VariablesMatcher.php
+++ b/src/TabCompletion/Matcher/VariablesMatcher.php
@@ -25,9 +25,9 @@ class VariablesMatcher extends AbstractContextAwareMatcher
*/
public function getMatches(array $tokens, array $info = [])
{
- $var = str_replace('$', '', $this->getInput($tokens));
+ $var = \str_replace('$', '', $this->getInput($tokens));
- return array_filter(array_keys($this->getVariables()), function ($variable) use ($var) {
+ return \array_filter(\array_keys($this->getVariables()), function ($variable) use ($var) {
return AbstractMatcher::startsWith($var, $variable);
});
}
@@ -37,11 +37,11 @@ public function getMatches(array $tokens, array $info = [])
*/
public function hasMatched(array $tokens)
{
- $token = array_pop($tokens);
+ $token = \array_pop($tokens);
switch (true) {
case self::hasToken([self::T_OPEN_TAG, self::T_VARIABLE], $token):
- case is_string($token) && $token === '$':
+ case \is_string($token) && $token === '$':
case self::isOperator($token):
return true;
}
diff --git a/src/Util/Docblock.php b/src/Util/Docblock.php
index c7989471d..750210baa 100644
--- a/src/Util/Docblock.php
+++ b/src/Util/Docblock.php
@@ -101,18 +101,18 @@ protected function setComment($comment)
protected static function prefixLength(array $lines)
{
// find only lines with interesting things
- $lines = array_filter($lines, function ($line) {
- return substr($line, strspn($line, "* \t\n\r\0\x0B"));
+ $lines = \array_filter($lines, function ($line) {
+ return \substr($line, \strspn($line, "* \t\n\r\0\x0B"));
});
// if we sort the lines, we only have to compare two items
- sort($lines);
+ \sort($lines);
- $first = reset($lines);
- $last = end($lines);
+ $first = \reset($lines);
+ $last = \end($lines);
// find the longest common substring
- $count = min(strlen($first), strlen($last));
+ $count = \min(\strlen($first), \strlen($last));
for ($i = 0; $i < $count; $i++) {
if ($first[$i] !== $last[$i]) {
return $i;
@@ -130,15 +130,15 @@ protected static function prefixLength(array $lines)
protected function parseComment($comment)
{
// Strip the opening and closing tags of the docblock
- $comment = substr($comment, 3, -2);
+ $comment = \substr($comment, 3, -2);
// Split into arrays of lines
- $comment = array_filter(preg_split('/\r?\n\r?/', $comment));
+ $comment = \array_filter(\preg_split('/\r?\n\r?/', $comment));
// Trim asterisks and whitespace from the beginning and whitespace from the end of lines
$prefixLength = self::prefixLength($comment);
- $comment = array_map(function ($line) use ($prefixLength) {
- return rtrim(substr($line, $prefixLength));
+ $comment = \array_map(function ($line) use ($prefixLength) {
+ return \rtrim(\substr($line, $prefixLength));
}, $comment);
// Group the lines together by @tags
@@ -157,30 +157,30 @@ protected function parseComment($comment)
// Parse the blocks
foreach ($blocks as $block => $body) {
- $body = trim(implode("\n", $body));
+ $body = \trim(\implode("\n", $body));
if ($block === 0 && !self::isTagged($body)) {
// This is the description block
$this->desc = $body;
} else {
// This block is tagged
- $tag = substr(self::strTag($body), 1);
- $body = ltrim(substr($body, strlen($tag) + 2));
+ $tag = \substr(self::strTag($body), 1);
+ $body = \ltrim(\substr($body, \strlen($tag) + 2));
if (isset(self::$vectors[$tag])) {
// The tagged block is a vector
- $count = count(self::$vectors[$tag]);
+ $count = \count(self::$vectors[$tag]);
if ($body) {
- $parts = preg_split('/\s+/', $body, $count);
+ $parts = \preg_split('/\s+/', $body, $count);
} else {
$parts = [];
}
// Default the trailing values
- $parts = array_pad($parts, $count, null);
+ $parts = \array_pad($parts, $count, null);
// Store as a mapped array
- $this->tags[$tag][] = array_combine(self::$vectors[$tag], $parts);
+ $this->tags[$tag][] = \array_combine(self::$vectors[$tag], $parts);
} else {
// The tagged block is only text
$this->tags[$tag][] = $body;
@@ -198,7 +198,7 @@ protected function parseComment($comment)
*/
public function hasTag($tag)
{
- return is_array($this->tags) && array_key_exists($tag, $this->tags);
+ return \is_array($this->tags) && \array_key_exists($tag, $this->tags);
}
/**
@@ -222,7 +222,7 @@ public function tag($tag)
*/
public static function isTagged($str)
{
- return isset($str[1]) && $str[0] === '@' && ctype_alpha($str[1]);
+ return isset($str[1]) && $str[0] === '@' && !\preg_match('/[^A-Za-z]/', $str[1]);
}
/**
@@ -234,7 +234,7 @@ public static function isTagged($str)
*/
public static function strTag($str)
{
- if (preg_match('/^@[a-z0-9_]+/', $str, $matches)) {
+ if (\preg_match('/^@[a-z0-9_]+/', $str, $matches)) {
return $matches[0];
}
}
diff --git a/src/Util/Json.php b/src/Util/Json.php
index 54ccf3134..471f10e7d 100644
--- a/src/Util/Json.php
+++ b/src/Util/Json.php
@@ -28,6 +28,6 @@ public static function encode($val, $opt = 0)
{
$opt |= JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE;
- return json_encode($val, $opt);
+ return \json_encode($val, $opt);
}
}
diff --git a/src/Util/Mirror.php b/src/Util/Mirror.php
index 862d0bed0..09c0b5b9a 100644
--- a/src/Util/Mirror.php
+++ b/src/Util/Mirror.php
@@ -44,10 +44,10 @@ class Mirror
*/
public static function get($value, $member = null, $filter = 15)
{
- if ($member === null && is_string($value)) {
- if (function_exists($value)) {
+ if ($member === null && \is_string($value)) {
+ if (\function_exists($value)) {
return new \ReflectionFunction($value);
- } elseif (defined($value) || ReflectionConstant_::isMagicConstant($value)) {
+ } elseif (\defined($value) || ReflectionConstant_::isMagicConstant($value)) {
return new ReflectionConstant_($value);
}
}
@@ -65,10 +65,10 @@ public static function get($value, $member = null, $filter = 15)
} elseif ($filter & self::STATIC_PROPERTY && $class->hasProperty($member) && $class->getProperty($member)->isStatic()) {
return $class->getProperty($member);
} else {
- throw new RuntimeException(sprintf(
+ throw new RuntimeException(\sprintf(
'Unknown member %s on class %s',
$member,
- is_object($value) ? get_class($value) : $value
+ \is_object($value) ? \get_class($value) : $value
));
}
}
@@ -84,13 +84,13 @@ public static function get($value, $member = null, $filter = 15)
*/
private static function getClass($value)
{
- if (is_object($value)) {
+ if (\is_object($value)) {
return new \ReflectionObject($value);
}
- if (!is_string($value)) {
+ if (!\is_string($value)) {
throw new \InvalidArgumentException('Mirror expects an object or class');
- } elseif (!class_exists($value) && !interface_exists($value) && !trait_exists($value)) {
+ } elseif (!\class_exists($value) && !\interface_exists($value) && !\trait_exists($value)) {
throw new \InvalidArgumentException('Unknown class or function: ' . $value);
}
diff --git a/src/Util/Str.php b/src/Util/Str.php
index 88c052af2..47d523996 100644
--- a/src/Util/Str.php
+++ b/src/Util/Str.php
@@ -61,9 +61,9 @@ class Str
*/
public static function unvis($input)
{
- $output = preg_replace_callback(self::UNVIS_RX, 'self::unvisReplace', $input);
+ $output = \preg_replace_callback(self::UNVIS_RX, 'self::unvisReplace', $input);
// other escapes & octal are handled by stripcslashes
- return stripcslashes($output);
+ return \stripcslashes($output);
}
/**
@@ -88,27 +88,27 @@ protected static function unvisReplace($match)
$chr = $match[3];
// unvis S_META1
$cp = 0200;
- $cp |= ord($chr);
+ $cp |= \ord($chr);
- return chr($cp);
+ return \chr($cp);
}
// \M^(.)
if (isset($match[4]) && $match[4] !== '') {
$chr = $match[4];
// unvis S_META | S_CTRL
$cp = 0200;
- $cp |= ($chr === '?') ? 0177 : ord($chr) & 037;
+ $cp |= ($chr === '?') ? 0177 : \ord($chr) & 037;
- return chr($cp);
+ return \chr($cp);
}
// \^(.)
if (isset($match[5]) && $match[5] !== '') {
$chr = $match[5];
// unvis S_CTRL
$cp = 0;
- $cp |= ($chr === '?') ? 0177 : ord($chr) & 037;
+ $cp |= ($chr === '?') ? 0177 : \ord($chr) & 037;
- return chr($cp);
+ return \chr($cp);
}
}
}
diff --git a/src/VarDumper/Dumper.php b/src/VarDumper/Dumper.php
index a6e9e8759..cc13b265a 100644
--- a/src/VarDumper/Dumper.php
+++ b/src/VarDumper/Dumper.php
@@ -67,20 +67,20 @@ protected function dumpKey(Cursor $cursor)
protected function style($style, $value, $attr = [])
{
if ('ref' === $style) {
- $value = strtr($value, '@', '#');
+ $value = \strtr($value, '@', '#');
}
$styled = '';
$map = self::$controlCharsMap;
$cchr = $this->styles['cchr'];
- $chunks = preg_split(self::$controlCharsRx, $value, null, PREG_SPLIT_NO_EMPTY | PREG_SPLIT_DELIM_CAPTURE);
+ $chunks = \preg_split(self::$controlCharsRx, $value, null, PREG_SPLIT_NO_EMPTY | PREG_SPLIT_DELIM_CAPTURE);
foreach ($chunks as $chunk) {
- if (preg_match(self::$onlyControlCharsRx, $chunk)) {
+ if (\preg_match(self::$onlyControlCharsRx, $chunk)) {
$chars = '';
$i = 0;
do {
- $chars .= isset($map[$chunk[$i]]) ? $map[$chunk[$i]] : sprintf('\x%02X', ord($chunk[$i]));
+ $chars .= isset($map[$chunk[$i]]) ? $map[$chunk[$i]] : \sprintf('\x%02X', \ord($chunk[$i]));
} while (isset($chunk[++$i]));
$chars = $this->formatter->escape($chars);
diff --git a/src/VarDumper/Presenter.php b/src/VarDumper/Presenter.php
index 400778ab2..4f821e0cd 100644
--- a/src/VarDumper/Presenter.php
+++ b/src/VarDumper/Presenter.php
@@ -49,14 +49,14 @@ class Presenter
public function __construct(OutputFormatter $formatter, $forceArrayIndexes = false)
{
// Work around https://github.com/symfony/symfony/issues/23572
- $oldLocale = setlocale(LC_NUMERIC, 0);
- setlocale(LC_NUMERIC, 'C');
+ $oldLocale = \setlocale(LC_NUMERIC, 0);
+ \setlocale(LC_NUMERIC, 'C');
$this->dumper = new Dumper($formatter, $forceArrayIndexes);
$this->dumper->setStyles($this->styles);
// Now put the locale back
- setlocale(LC_NUMERIC, $oldLocale);
+ \setlocale(LC_NUMERIC, $oldLocale);
$this->cloner = new Cloner();
$this->cloner->addCasters(['*' => function ($obj, array $a, Stub $stub, $isNested, $filter = 0) {
@@ -116,8 +116,8 @@ public function present($value, $depth = null, $options = 0)
}
// Work around https://github.com/symfony/symfony/issues/23572
- $oldLocale = setlocale(LC_NUMERIC, 0);
- setlocale(LC_NUMERIC, 'C');
+ $oldLocale = \setlocale(LC_NUMERIC, 0);
+ \setlocale(LC_NUMERIC, 'C');
$output = '';
$this->dumper->dump($data, function ($line, $depth) use (&$output) {
@@ -125,12 +125,12 @@ public function present($value, $depth = null, $options = 0)
if ('' !== $output) {
$output .= PHP_EOL;
}
- $output .= str_repeat(' ', $depth) . $line;
+ $output .= \str_repeat(' ', $depth) . $line;
}
});
// Now put the locale back
- setlocale(LC_NUMERIC, $oldLocale);
+ \setlocale(LC_NUMERIC, $oldLocale);
return OutputFormatter::escape($output);
}
diff --git a/src/VersionUpdater/GitHubChecker.php b/src/VersionUpdater/GitHubChecker.php
index e62a4d27c..40cfc2e2f 100644
--- a/src/VersionUpdater/GitHubChecker.php
+++ b/src/VersionUpdater/GitHubChecker.php
@@ -24,7 +24,7 @@ class GitHubChecker implements Checker
*/
public function isLatest()
{
- return version_compare(Shell::VERSION, $this->getLatest(), '>=');
+ return \version_compare(Shell::VERSION, $this->getLatest(), '>=');
}
/**
@@ -68,22 +68,22 @@ private function getVersionFromTag()
*/
public function fetchLatestRelease()
{
- $context = stream_context_create([
+ $context = \stream_context_create([
'http' => [
'user_agent' => 'PsySH/' . Shell::VERSION,
'timeout' => 3,
],
]);
- set_error_handler(function () {
+ \set_error_handler(function () {
// Just ignore all errors with this. The checker will throw an exception
// if it doesn't work :)
});
- $result = @file_get_contents(self::URL, false, $context);
+ $result = @\file_get_contents(self::URL, false, $context);
- restore_error_handler();
+ \restore_error_handler();
- return json_decode($result);
+ return \json_decode($result);
}
}
diff --git a/src/VersionUpdater/IntervalChecker.php b/src/VersionUpdater/IntervalChecker.php
index 712f27587..7e0da4327 100644
--- a/src/VersionUpdater/IntervalChecker.php
+++ b/src/VersionUpdater/IntervalChecker.php
@@ -11,8 +11,6 @@
namespace Psy\VersionUpdater;
-use Psy\Shell;
-
class IntervalChecker extends GitHubChecker
{
private $cacheFile;
@@ -27,7 +25,7 @@ public function __construct($cacheFile, $interval)
public function fetchLatestRelease()
{
// Read the cached file
- $cached = json_decode(@file_get_contents($this->cacheFile, false));
+ $cached = \json_decode(@\file_get_contents($this->cacheFile, false));
if ($cached && isset($cached->last_check) && isset($cached->release)) {
$now = new \DateTime();
$lastCheck = new \DateTime($cached->last_check);
@@ -60,10 +58,10 @@ private function getDateInterval()
private function updateCache($release)
{
$data = [
- 'last_check' => date(DATE_ATOM),
+ 'last_check' => \date(DATE_ATOM),
'release' => $release,
];
- file_put_contents($this->cacheFile, json_encode($data));
+ \file_put_contents($this->cacheFile, \json_encode($data));
}
}
diff --git a/src/functions.php b/src/functions.php
index b07c49207..4e875bbab 100644
--- a/src/functions.php
+++ b/src/functions.php
@@ -18,7 +18,7 @@
use Symfony\Component\Console\Input\InputOption;
use XdgBaseDir\Xdg;
-if (!function_exists('Psy\sh')) {
+if (!\function_exists('Psy\sh')) {
/**
* Command to return the eval-able code to startup PsySH.
*
@@ -32,7 +32,7 @@ function sh()
}
}
-if (!function_exists('Psy\debug')) {
+if (!\function_exists('Psy\debug')) {
/**
* Invoke a Psy Shell from the current context.
*
@@ -89,7 +89,7 @@ function debug(array $vars = [], $bindTo = null)
$sh->addInput('whereami -n2', true);
}
- if (is_string($bindTo)) {
+ if (\is_string($bindTo)) {
$sh->setBoundClass($bindTo);
} elseif ($bindTo !== null) {
$sh->setBoundObject($bindTo);
@@ -101,7 +101,7 @@ function debug(array $vars = [], $bindTo = null)
}
}
-if (!function_exists('Psy\info')) {
+if (!\function_exists('Psy\info')) {
/**
* Get a bunch of debugging info about the current PsySH environment and
* configuration.
@@ -123,12 +123,12 @@ function info(Configuration $config = null)
}
$xdg = new Xdg();
- $home = rtrim(str_replace('\\', '/', $xdg->getHomeDir()), '/');
- $homePattern = '#^' . preg_quote($home, '#') . '/#';
+ $home = \rtrim(\str_replace('\\', '/', $xdg->getHomeDir()), '/');
+ $homePattern = '#^' . \preg_quote($home, '#') . '/#';
$prettyPath = function ($path) use ($homePattern) {
- if (is_string($path)) {
- return preg_replace($homePattern, '~/', $path);
+ if (\is_string($path)) {
+ return \preg_replace($homePattern, '~/', $path);
} else {
return $path;
}
@@ -146,7 +146,7 @@ function info(Configuration $config = null)
'config file' => [
'default config file' => $prettyPath($config->getConfigFile()),
'local config file' => $prettyPath($config->getLocalConfigFile()),
- 'PSYSH_CONFIG env' => $prettyPath(getenv('PSYSH_CONFIG')),
+ 'PSYSH_CONFIG env' => $prettyPath(\getenv('PSYSH_CONFIG')),
],
// 'config dir' => $config->getConfigDir(),
// 'data dir' => $config->getDataDir(),
@@ -171,12 +171,12 @@ function info(Configuration $config = null)
];
if ($config->hasReadline()) {
- $info = readline_info();
+ $info = \readline_info();
$readline = [
'readline available' => true,
'readline enabled' => $config->useReadline(),
- 'readline service' => get_class($config->getReadline()),
+ 'readline service' => \get_class($config->getReadline()),
];
if (isset($info['library_version'])) {
@@ -193,12 +193,12 @@ function info(Configuration $config = null)
}
$pcntl = [
- 'pcntl available' => function_exists('pcntl_signal'),
- 'posix available' => function_exists('posix_getpid'),
+ 'pcntl available' => \function_exists('pcntl_signal'),
+ 'posix available' => \function_exists('posix_getpid'),
];
- $disabledFuncs = array_map('trim', explode(',', ini_get('disable_functions')));
- if (in_array('pcntl_signal', $disabledFuncs) || in_array('pcntl_fork', $disabledFuncs)) {
+ $disabledFuncs = \array_map('trim', \explode(',', \ini_get('disable_functions')));
+ if (\in_array('pcntl_signal', $disabledFuncs) || \in_array('pcntl_fork', $disabledFuncs)) {
$pcntl['pcntl disabled'] = true;
}
@@ -226,7 +226,7 @@ function info(Configuration $config = null)
$val = $d->format(\DateTime::RFC2822);
break;
}
- $key = 'db ' . str_replace('_', ' ', $key);
+ $key = 'db ' . \str_replace('_', ' ', $key);
$docs[$key] = $val;
}
} else {
@@ -243,25 +243,25 @@ function info(Configuration $config = null)
$autocomplete = [
'tab completion enabled' => $config->useTabCompletion(),
- 'custom matchers' => array_map('get_class', $config->getTabCompletionMatchers()),
+ 'custom matchers' => \array_map('get_class', $config->getTabCompletionMatchers()),
'bracketed paste' => $config->useBracketedPaste(),
];
// Shenanigans, but totally justified.
if ($shell = Sudo::fetchProperty($config, 'shell')) {
- $core['loop listeners'] = array_map('get_class', Sudo::fetchProperty($shell, 'loopListeners'));
- $core['commands'] = array_map('get_class', $shell->all());
+ $core['loop listeners'] = \array_map('get_class', Sudo::fetchProperty($shell, 'loopListeners'));
+ $core['commands'] = \array_map('get_class', $shell->all());
- $autocomplete['custom matchers'] = array_map('get_class', Sudo::fetchProperty($shell, 'matchers'));
+ $autocomplete['custom matchers'] = \array_map('get_class', Sudo::fetchProperty($shell, 'matchers'));
}
// @todo Show Presenter / custom casters.
- return array_merge($core, compact('updates', 'pcntl', 'readline', 'history', 'docs', 'autocomplete'));
+ return \array_merge($core, \compact('updates', 'pcntl', 'readline', 'history', 'docs', 'autocomplete'));
}
}
-if (!function_exists('Psy\bin')) {
+if (!\function_exists('Psy\bin')) {
/**
* `psysh` command line executable.
*
@@ -313,7 +313,7 @@ function bin()
}
$version = $shell->getVersion();
- $name = basename(reset($_SERVER['argv']));
+ $name = \basename(\reset($_SERVER['argv']));
echo <<traverser->traverse($this->parse('isset(strtolower("A"))'));
$this->fail();
} catch (FatalErrorException $e) {
- if (version_compare(PHP_VERSION, '5.5', '>=')) {
+ if (\version_compare(PHP_VERSION, '5.5', '>=')) {
$this->assertContains(
'Cannot use isset() on the result of a function call (you can use "null !== func()" instead)',
$e->getMessage()
@@ -66,7 +66,7 @@ public function testIsset()
*/
public function testEmpty()
{
- if (version_compare(PHP_VERSION, '5.5', '>=')) {
+ if (\version_compare(PHP_VERSION, '5.5', '>=')) {
$this->markTestSkipped();
}
diff --git a/test/CodeCleaner/LegacyEmptyPassTest.php b/test/CodeCleaner/LegacyEmptyPassTest.php
index 5afb57591..5c4c7b059 100644
--- a/test/CodeCleaner/LegacyEmptyPassTest.php
+++ b/test/CodeCleaner/LegacyEmptyPassTest.php
@@ -31,7 +31,7 @@ public function testProcessInvalidStatement($code)
public function invalidStatements()
{
- if (version_compare(PHP_VERSION, '5.5', '>=')) {
+ if (\version_compare(PHP_VERSION, '5.5', '>=')) {
return [
['empty()'],
];
@@ -58,7 +58,7 @@ public function testProcessValidStatement($code)
public function validStatements()
{
- if (version_compare(PHP_VERSION, '5.5', '<')) {
+ if (\version_compare(PHP_VERSION, '5.5', '<')) {
return [
['empty($foo)'],
];
diff --git a/test/CodeCleaner/ListPassTest.php b/test/CodeCleaner/ListPassTest.php
index 95cf3a744..fd955a6aa 100644
--- a/test/CodeCleaner/ListPassTest.php
+++ b/test/CodeCleaner/ListPassTest.php
@@ -26,7 +26,7 @@ public function setUp()
*/
public function testProcessInvalidStatement($code, $expectedMessage)
{
- if (method_exists($this, 'setExpectedException')) {
+ if (\method_exists($this, 'setExpectedException')) {
$this->setExpectedException('Psy\Exception\ParseErrorException', $expectedMessage);
} else {
$this->expectExceptionMessage($expectedMessage);
@@ -50,8 +50,8 @@ public function invalidStatements()
['list("a") = array(1)', $errorPhpParserSyntax],
];
- if (version_compare(PHP_VERSION, '7.1', '<')) {
- return array_merge($invalidExpr, [
+ if (\version_compare(PHP_VERSION, '7.1', '<')) {
+ return \array_merge($invalidExpr, [
['list("a" => _) = array("a" => 1)', $errorPhpParserSyntax],
['[] = []', $errorShortListAssign],
['[$a] = [1]', $errorShortListAssign],
@@ -59,7 +59,7 @@ public function invalidStatements()
]);
}
- return array_merge($invalidExpr, [
+ return \array_merge($invalidExpr, [
['list("a" => _) = array("a" => 1)', $errorPhpParserSyntax],
['["a"] = [1]', $errorNonVariableAssign],
['[] = []', $errorEmptyList],
@@ -84,8 +84,8 @@ public function validStatements()
['list($x, $y) = array(1, 2)'],
];
- if (version_compare(PHP_VERSION, '7.1', '>=')) {
- return array_merge($validExpr, [
+ if (\version_compare(PHP_VERSION, '7.1', '>=')) {
+ return \array_merge($validExpr, [
['[$a] = array(1)'],
['list($b) = [2]'],
['[$x, $y] = array(1, 2)'],
diff --git a/test/CodeCleaner/NamespacePassTest.php b/test/CodeCleaner/NamespacePassTest.php
index 0c28dc6e4..e8f013961 100644
--- a/test/CodeCleaner/NamespacePassTest.php
+++ b/test/CodeCleaner/NamespacePassTest.php
@@ -43,7 +43,7 @@ public function testProcess()
// A new block namespace clears out the current namespace...
$this->parseAndTraverse('namespace Gamma { array_merge(); }');
- if (defined('PhpParser\\Node\\Stmt\\Namespace_::KIND_SEMICOLON')) {
+ if (\defined('PhpParser\\Node\\Stmt\\Namespace_::KIND_SEMICOLON')) {
$this->assertNull($this->cleaner->getNamespace());
} else {
// But not for PHP-Parser < v3.1.2 :(
diff --git a/test/CodeCleaner/NoReturnValueTest.php b/test/CodeCleaner/NoReturnValueTest.php
index 6a7d009a9..11e9d013f 100644
--- a/test/CodeCleaner/NoReturnValueTest.php
+++ b/test/CodeCleaner/NoReturnValueTest.php
@@ -20,7 +20,7 @@ class NoReturnValueTest extends ParserTestCase
public function testCreate()
{
$stmt = NoReturnValue::create();
- if (class_exists('PhpParser\Node\Stmt\Expression')) {
+ if (\class_exists('PhpParser\Node\Stmt\Expression')) {
$stmt = new Expression($stmt);
}
diff --git a/test/CodeCleaner/RequirePassTest.php b/test/CodeCleaner/RequirePassTest.php
index 0b7b3bc37..6640e639b 100644
--- a/test/CodeCleaner/RequirePassTest.php
+++ b/test/CodeCleaner/RequirePassTest.php
@@ -70,7 +70,7 @@ public function testResolve()
*/
public function testResolveEmptyWarnings($file)
{
- if (!E_WARNING & error_reporting()) {
+ if (!E_WARNING & \error_reporting()) {
$this->markTestSkipped();
}
diff --git a/test/CodeCleaner/StrictTypesPassTest.php b/test/CodeCleaner/StrictTypesPassTest.php
index ee147824a..54186190d 100644
--- a/test/CodeCleaner/StrictTypesPassTest.php
+++ b/test/CodeCleaner/StrictTypesPassTest.php
@@ -17,7 +17,7 @@ class StrictTypesPassTest extends CodeCleanerTestCase
{
public function setUp()
{
- if (version_compare(PHP_VERSION, '7.0', '<')) {
+ if (\version_compare(PHP_VERSION, '7.0', '<')) {
$this->markTestSkipped();
}
diff --git a/test/CodeCleaner/UseStatementPassTest.php b/test/CodeCleaner/UseStatementPassTest.php
index aedfd499d..4d5ac3420 100644
--- a/test/CodeCleaner/UseStatementPassTest.php
+++ b/test/CodeCleaner/UseStatementPassTest.php
@@ -80,7 +80,7 @@ public function testGroupUseProcess($from, $to)
public function groupUseStatements()
{
- if (version_compare(PHP_VERSION, '7.0', '<')) {
+ if (\version_compare(PHP_VERSION, '7.0', '<')) {
$this->markTestSkipped();
}
diff --git a/test/CodeCleaner/ValidClassNamePassTest.php b/test/CodeCleaner/ValidClassNamePassTest.php
index 67b157501..3736f351e 100644
--- a/test/CodeCleaner/ValidClassNamePassTest.php
+++ b/test/CodeCleaner/ValidClassNamePassTest.php
@@ -305,12 +305,12 @@ class A {}
];
// Ugh. There's gotta be a better way to test for this.
- if (class_exists('PhpParser\ParserFactory')) {
+ if (\class_exists('PhpParser\ParserFactory')) {
// PHP 7.0 anonymous classes, only supported by PHP Parser v2.x
$valid[] = ['$obj = new class() {}'];
}
- if (version_compare(PHP_VERSION, '5.5', '>=')) {
+ if (\version_compare(PHP_VERSION, '5.5', '>=')) {
$valid[] = ['interface A {} A::class'];
$valid[] = ['interface A {} A::CLASS'];
$valid[] = ['class A {} A::class'];
diff --git a/test/CodeCleaner/ValidConstructorPassTest.php b/test/CodeCleaner/ValidConstructorPassTest.php
index c0379b26b..4f7e40c44 100644
--- a/test/CodeCleaner/ValidConstructorPassTest.php
+++ b/test/CodeCleaner/ValidConstructorPassTest.php
@@ -47,7 +47,7 @@ public function invalidStatements()
['class A { private static function a() {}}'],
];
- if (version_compare(PHP_VERSION, '7.0', '>=')) {
+ if (\version_compare(PHP_VERSION, '7.0', '>=')) {
$data[] = ['class A { public function A(): ?array {}}'];
$data[] = ['class A { public function a(): ?array {}}'];
}
@@ -82,7 +82,7 @@ public function validStatements()
['namespace B; class A { private static function A() {}}'],
];
- if (version_compare(PHP_VERSION, '7.0', '>=')) {
+ if (\version_compare(PHP_VERSION, '7.0', '>=')) {
$data[] = ['class A { public static function A() {} public function __construct() {}}'];
$data[] = ['class A { private function __construct() {} public static function A(): ?array {}}'];
$data[] = ['namespace B; class A { private static function A(): ?array {}}'];
diff --git a/test/CodeCleanerTest.php b/test/CodeCleanerTest.php
index 40ec6b42e..2195a4ff8 100644
--- a/test/CodeCleanerTest.php
+++ b/test/CodeCleanerTest.php
@@ -79,7 +79,7 @@ public function unclosedStatementsProvider()
*/
public function testMoreUnclosedStatements(array $lines)
{
- if (defined('HHVM_VERSION')) {
+ if (\defined('HHVM_VERSION')) {
$this->markTestSkipped('HHVM not supported.');
}
diff --git a/test/ConfigurationTest.php b/test/ConfigurationTest.php
index a250d834b..b7b6c0c01 100644
--- a/test/ConfigurationTest.php
+++ b/test/ConfigurationTest.php
@@ -30,10 +30,10 @@ public function testDefaults()
{
$config = $this->getConfig();
- $this->assertSame(function_exists('readline'), $config->hasReadline());
- $this->assertSame(function_exists('readline'), $config->useReadline());
- $this->assertSame(function_exists('pcntl_signal'), $config->hasPcntl());
- $this->assertSame(function_exists('pcntl_signal'), $config->usePcntl());
+ $this->assertSame(\function_exists('readline'), $config->hasReadline());
+ $this->assertSame(\function_exists('readline'), $config->useReadline());
+ $this->assertSame(\function_exists('pcntl_signal'), $config->hasPcntl());
+ $this->assertSame(\function_exists('pcntl_signal'), $config->usePcntl());
$this->assertFalse($config->requireSemicolons());
$this->assertSame(Configuration::COLOR_MODE_AUTO, $config->colorMode());
$this->assertNull($config->getStartupMessage());
@@ -57,20 +57,20 @@ public function testGettersAndSetters()
*/
public function testFilesAndDirectories($home, $configFile, $historyFile, $manualDbFile)
{
- $oldHome = getenv('HOME');
- putenv("HOME=$home");
+ $oldHome = \getenv('HOME');
+ \putenv("HOME=$home");
$config = new Configuration();
- $this->assertSame(realpath($configFile), realpath($config->getConfigFile()));
- $this->assertSame(realpath($historyFile), realpath($config->getHistoryFile()));
- $this->assertSame(realpath($manualDbFile), realpath($config->getManualDbFile()));
+ $this->assertSame(\realpath($configFile), \realpath($config->getConfigFile()));
+ $this->assertSame(\realpath($historyFile), \realpath($config->getHistoryFile()));
+ $this->assertSame(\realpath($manualDbFile), \realpath($config->getManualDbFile()));
- putenv("HOME=$oldHome");
+ \putenv("HOME=$oldHome");
}
public function directories()
{
- $base = realpath(__DIR__ . '/fixtures');
+ $base = \realpath(__DIR__ . '/fixtures');
return [
[
@@ -125,21 +125,21 @@ public function testLoadConfigFile()
{
$config = $this->getConfig(__DIR__ . '/fixtures/config.php');
- $runtimeDir = $this->joinPath(realpath(sys_get_temp_dir()), 'psysh_test', 'withconfig', 'temp');
+ $runtimeDir = $this->joinPath(\realpath(\sys_get_temp_dir()), 'psysh_test', 'withconfig', 'temp');
- $this->assertStringStartsWith($runtimeDir, realpath($config->getTempFile('foo', 123)));
- $this->assertStringStartsWith($runtimeDir, realpath(dirname($config->getPipe('pipe', 123))));
- $this->assertStringStartsWith($runtimeDir, realpath($config->getRuntimeDir()));
+ $this->assertStringStartsWith($runtimeDir, \realpath($config->getTempFile('foo', 123)));
+ $this->assertStringStartsWith($runtimeDir, \realpath(\dirname($config->getPipe('pipe', 123))));
+ $this->assertStringStartsWith($runtimeDir, \realpath($config->getRuntimeDir()));
- $this->assertSame(function_exists('readline'), $config->useReadline());
+ $this->assertSame(\function_exists('readline'), $config->useReadline());
$this->assertFalse($config->usePcntl());
$this->assertSame(E_ALL & ~E_NOTICE, $config->errorLoggingLevel());
}
public function testLoadLocalConfigFile()
{
- $oldPwd = getcwd();
- chdir(realpath(__DIR__ . '/fixtures/project/'));
+ $oldPwd = \getcwd();
+ \chdir(\realpath(__DIR__ . '/fixtures/project/'));
$config = new Configuration();
@@ -153,7 +153,7 @@ public function testLoadLocalConfigFile()
$this->assertFalse($config->requireSemicolons());
$this->assertTrue($config->useUnicode());
- chdir($oldPwd);
+ \chdir($oldPwd);
}
/**
@@ -166,7 +166,7 @@ public function testBaseDirConfigIsDeprecated()
private function joinPath()
{
- return implode(DIRECTORY_SEPARATOR, func_get_args());
+ return \implode(DIRECTORY_SEPARATOR, \func_get_args());
}
public function testConfigIncludes()
diff --git a/test/ContextTest.php b/test/ContextTest.php
index 0b8b6dc87..d19370367 100644
--- a/test/ContextTest.php
+++ b/test/ContextTest.php
@@ -244,7 +244,7 @@ public function testCommandScopeVariables()
$__line = 'dixie';
$__dir = 'wrinkly';
- $vars = compact('__function', '__method', '__class', '__namespace', '__file', '__line', '__dir');
+ $vars = \compact('__function', '__method', '__class', '__namespace', '__file', '__line', '__dir');
$context = new Context();
$context->setCommandScopeVariables($vars);
@@ -259,7 +259,7 @@ public function testCommandScopeVariables()
$this->assertEquals($__line, $context->get('__line'));
$this->assertEquals($__dir, $context->get('__dir'));
- $someVars = compact('__function', '__namespace', '__file', '__line', '__dir');
+ $someVars = \compact('__function', '__namespace', '__file', '__line', '__dir');
$context->setCommandScopeVariables($someVars);
}
@@ -282,7 +282,7 @@ public function testGetUnusedCommandScopeVariableNames()
$this->assertEquals(
['__method', '__class'],
- array_values($context->getUnusedCommandScopeVariableNames())
+ \array_values($context->getUnusedCommandScopeVariableNames())
);
}
diff --git a/test/Exception/ErrorExceptionTest.php b/test/Exception/ErrorExceptionTest.php
index e66319b91..ef9fb9ab4 100644
--- a/test/Exception/ErrorExceptionTest.php
+++ b/test/Exception/ErrorExceptionTest.php
@@ -76,14 +76,14 @@ public function getLevels()
*/
public function testThrowExceptionAsErrorHandler($level, $type)
{
- set_error_handler(['Psy\Exception\ErrorException', 'throwException']);
+ \set_error_handler(['Psy\Exception\ErrorException', 'throwException']);
try {
- trigger_error('{whot}', $level);
+ \trigger_error('{whot}', $level);
} catch (ErrorException $e) {
$this->assertContains('PHP ' . $type, $e->getMessage());
$this->assertContains('{whot}', $e->getMessage());
}
- restore_error_handler();
+ \restore_error_handler();
}
public function getUserLevels()
@@ -110,7 +110,7 @@ public function testIgnoreExecutionLoopFilename()
public function testFromError()
{
- if (version_compare(PHP_VERSION, '7.0.0', '<')) {
+ if (\version_compare(PHP_VERSION, '7.0.0', '<')) {
$this->markTestSkipped();
}
diff --git a/test/Exception/ThrowUpExceptionTest.php b/test/Exception/ThrowUpExceptionTest.php
index f44ab8736..09c337324 100644
--- a/test/Exception/ThrowUpExceptionTest.php
+++ b/test/Exception/ThrowUpExceptionTest.php
@@ -40,7 +40,7 @@ public function testFromThrowable()
public function testFromThrowableWithError()
{
- if (version_compare(PHP_VERSION, '7.0.0', '<')) {
+ if (\version_compare(PHP_VERSION, '7.0.0', '<')) {
$this->markTestSkipped();
}
diff --git a/test/Exception/TypeErrorExceptionTest.php b/test/Exception/TypeErrorExceptionTest.php
index 7bf27af95..01f251bb8 100644
--- a/test/Exception/TypeErrorExceptionTest.php
+++ b/test/Exception/TypeErrorExceptionTest.php
@@ -37,7 +37,7 @@ public function testStripsEvalFromMessage()
public function testFromTypeError()
{
- if (version_compare(PHP_VERSION, '7.0.0', '<')) {
+ if (\version_compare(PHP_VERSION, '7.0.0', '<')) {
$this->markTestSkipped();
}
diff --git a/test/Formatter/CodeFormatterTest.php b/test/Formatter/CodeFormatterTest.php
index ee213f1c0..87f56dfd7 100644
--- a/test/Formatter/CodeFormatterTest.php
+++ b/test/Formatter/CodeFormatterTest.php
@@ -22,7 +22,7 @@ class CodeFormatterTest extends \PHPUnit\Framework\TestCase
public function testFormat($reflector, $expected)
{
$formatted = CodeFormatter::format($reflector);
- $formattedWithoutColors = preg_replace('#' . chr(27) . '\[\d\d?m#', '', $formatted);
+ $formattedWithoutColors = \preg_replace('#' . \chr(27) . '\[\d\d?m#', '', $formatted);
$this->assertEquals($expected, self::trimLines($formattedWithoutColors));
$this->assertNotEquals($expected, self::trimLines($formatted));
@@ -88,7 +88,7 @@ public function invalidReflectors()
[new \ReflectionProperty('Psy\Test\Formatter\Fixtures\SomeClass', 'someProp')],
];
- if (version_compare(PHP_VERSION, '7.1.0', '>=')) {
+ if (\version_compare(PHP_VERSION, '7.1.0', '>=')) {
$reflectors[] = [new \ReflectionClassConstant('Psy\Test\Formatter\Fixtures\SomeClass', 'SOME_CONST')];
}
@@ -115,7 +115,7 @@ public function testCodeFormatterThrowsExceptionForMissingFile($filename)
public function filenames()
{
- if (defined('HHVM_VERSION')) {
+ if (\defined('HHVM_VERSION')) {
$this->markTestSkipped('We have issues with PHPUnit mocks on HHVM.');
}
@@ -124,6 +124,6 @@ public function filenames()
private static function trimLines($code)
{
- return rtrim(implode("\n", array_map('rtrim', explode("\n", $code))));
+ return \rtrim(\implode("\n", \array_map('rtrim', \explode("\n", $code))));
}
}
diff --git a/test/Formatter/SignatureFormatterTest.php b/test/Formatter/SignatureFormatterTest.php
index 7d4938d0b..096e6ae78 100644
--- a/test/Formatter/SignatureFormatterTest.php
+++ b/test/Formatter/SignatureFormatterTest.php
@@ -29,7 +29,7 @@ private function someFakeMethod(array $one, $two = 'TWO', \Reflector $three = nu
*/
public function testFormat($reflector, $expected)
{
- $this->assertSame($expected, strip_tags(SignatureFormatter::format($reflector)));
+ $this->assertSame($expected, \strip_tags(SignatureFormatter::format($reflector)));
}
public function signatureReflectors()
@@ -37,7 +37,7 @@ public function signatureReflectors()
return [
[
new \ReflectionFunction('implode'),
- defined('HHVM_VERSION') ? 'function implode($arg1, $arg2 = null)' : 'function implode($glue, $pieces)',
+ \defined('HHVM_VERSION') ? 'function implode($arg1, $arg2 = null)' : 'function implode($glue, $pieces)',
],
[
ReflectionClassConstant::create($this, 'FOO'),
diff --git a/test/ParserTestCase.php b/test/ParserTestCase.php
index 780552068..a0740b663 100644
--- a/test/ParserTestCase.php
+++ b/test/ParserTestCase.php
@@ -92,6 +92,6 @@ private function parseErrorIsEOF(\PhpParser\Error $e)
{
$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);
}
}
diff --git a/test/Readline/GNUReadlineTest.php b/test/Readline/GNUReadlineTest.php
index 7f39197e6..406377fcc 100644
--- a/test/Readline/GNUReadlineTest.php
+++ b/test/Readline/GNUReadlineTest.php
@@ -23,8 +23,8 @@ public function setUp()
$this->markTestSkipped('GNUReadline not enabled');
}
- $this->historyFile = tempnam(sys_get_temp_dir(), 'psysh_test_history');
- file_put_contents($this->historyFile, "_HiStOrY_V2_\n");
+ $this->historyFile = \tempnam(\sys_get_temp_dir(), 'psysh_test_history');
+ \file_put_contents($this->historyFile, "_HiStOrY_V2_\n");
}
public function testHistory()
diff --git a/test/Readline/LibeditTest.php b/test/Readline/LibeditTest.php
index 44a06c61f..2d7be2889 100644
--- a/test/Readline/LibeditTest.php
+++ b/test/Readline/LibeditTest.php
@@ -23,20 +23,20 @@ public function setUp()
$this->markTestSkipped('Libedit not enabled');
}
- $this->historyFile = tempnam(sys_get_temp_dir(), 'psysh_test_history');
- if (false === file_put_contents($this->historyFile, "_HiStOrY_V2_\n")) {
+ $this->historyFile = \tempnam(\sys_get_temp_dir(), 'psysh_test_history');
+ if (false === \file_put_contents($this->historyFile, "_HiStOrY_V2_\n")) {
$this->fail('Unable to write history file: ' . $this->historyFile);
}
// Calling readline_read_history before readline_clear_history
// avoids segfault with PHP 5.5.7 & libedit v3.1
- readline_read_history($this->historyFile);
- readline_clear_history();
+ \readline_read_history($this->historyFile);
+ \readline_clear_history();
}
public function tearDown()
{
- if (is_file($this->historyFile)) {
- unlink($this->historyFile);
+ if (\is_file($this->historyFile)) {
+ \unlink($this->historyFile);
}
}
@@ -94,7 +94,7 @@ public function testHistoryEraseDups()
public function testListHistory()
{
$readline = new Libedit($this->historyFile);
- file_put_contents(
+ \file_put_contents(
$this->historyFile,
"This is an entry\n\0This is a comment\nThis is an entry\0With a comment\n",
FILE_APPEND
@@ -113,7 +113,7 @@ public function testListHistory()
public function testLinebreaksSupport()
{
$readline = new Libedit($this->historyFile);
- file_put_contents(
+ \file_put_contents(
$this->historyFile,
"foo\rbar\nbaz\r\nw00t",
FILE_APPEND
diff --git a/test/Reflection/ReflectionConstantTest.php b/test/Reflection/ReflectionConstantTest.php
index 95328ff89..02c1a8442 100644
--- a/test/Reflection/ReflectionConstantTest.php
+++ b/test/Reflection/ReflectionConstantTest.php
@@ -13,7 +13,7 @@
use Psy\Reflection\ReflectionConstant_;
-define('Psy\\Test\\Reflection\\SOME_CONSTANT', 'yep');
+\define('Psy\\Test\\Reflection\\SOME_CONSTANT', 'yep');
class ReflectionConstantTest extends \PHPUnit\Framework\TestCase
{
diff --git a/test/ShellTest.php b/test/ShellTest.php
index 5b587d634..809af021e 100644
--- a/test/ShellTest.php
+++ b/test/ShellTest.php
@@ -25,7 +25,7 @@ class ShellTest extends \PHPUnit\Framework\TestCase
public function tearDown()
{
foreach ($this->streams as $stream) {
- fclose($stream);
+ \fclose($stream);
}
}
@@ -39,7 +39,7 @@ public function testScopeVariables()
$_e = 'ignore this';
$shell = new Shell($this->getConfig());
- $shell->setScopeVariables(compact('one', 'two', 'three', '__psysh__', '_', '_e', 'this'));
+ $shell->setScopeVariables(\compact('one', 'two', 'three', '__psysh__', '_', '_e', 'this'));
$this->assertNotContains('__psysh__', $shell->getScopeVariableNames());
$this->assertSame(['one', 'two', 'three', '_'], $shell->getScopeVariableNames());
@@ -48,6 +48,9 @@ public function testScopeVariables()
$this->assertSame($three, $shell->getScopeVariable('three'));
$this->assertNull($shell->getScopeVariable('_'));
+ $diff = $shell->getScopeVariablesDiff(['one' => $one, 'two' => 'not two']);
+ $this->assertSame(['two' => $two, 'three' => $three, '_' => null], $diff);
+
$shell->setScopeVariables([]);
$this->assertSame(['_'], $shell->getScopeVariableNames());
@@ -80,7 +83,7 @@ public function testIncludesWithScopeVariables()
$config = $this->getConfig(['usePcntl' => false]);
$shell = new Shell($config);
- $shell->setScopeVariables(compact('one', 'two', 'three', '__psysh__', '_', '_e', 'this'));
+ $shell->setScopeVariables(\compact('one', 'two', 'three', '__psysh__', '_', '_e', 'this'));
$shell->addInput('exit', true);
// This is super slow and we shouldn't do this :(
@@ -160,8 +163,8 @@ public function testRenderingExceptions()
$this->assertFalse($shell->hasCode());
$this->assertEmpty($shell->getCodeBuffer());
- rewind($stream);
- $streamContents = stream_get_contents($stream);
+ \rewind($stream);
+ $streamContents = \stream_get_contents($stream);
$this->assertContains('PHP Parse error', $streamContents);
$this->assertContains('message', $streamContents);
@@ -175,19 +178,19 @@ public function testHandlingErrors()
$stream = $output->getStream();
$shell->setOutput($output);
- $oldLevel = error_reporting();
- error_reporting($oldLevel & ~E_USER_NOTICE);
+ $oldLevel = \error_reporting();
+ \error_reporting($oldLevel & ~E_USER_NOTICE);
try {
$shell->handleError(E_USER_NOTICE, 'wheee', null, 13);
} catch (ErrorException $e) {
- error_reporting($oldLevel);
+ \error_reporting($oldLevel);
$this->fail('Unexpected error exception');
}
- error_reporting($oldLevel);
+ \error_reporting($oldLevel);
- rewind($stream);
- $streamContents = stream_get_contents($stream);
+ \rewind($stream);
+ $streamContents = \stream_get_contents($stream);
$this->assertContains('PHP Notice:', $streamContents);
$this->assertContains('wheee', $streamContents);
@@ -200,13 +203,13 @@ public function testHandlingErrors()
public function testNotHandlingErrors()
{
$shell = new Shell($this->getConfig());
- $oldLevel = error_reporting();
- error_reporting($oldLevel | E_USER_NOTICE);
+ $oldLevel = \error_reporting();
+ \error_reporting($oldLevel | E_USER_NOTICE);
try {
$shell->handleError(E_USER_NOTICE, 'wheee', null, 13);
} catch (ErrorException $e) {
- error_reporting($oldLevel);
+ \error_reporting($oldLevel);
throw $e;
}
}
@@ -217,8 +220,8 @@ public function testVersion()
$this->assertInstanceOf('Symfony\Component\Console\Application', $shell);
$this->assertContains(Shell::VERSION, $shell->getVersion());
- $this->assertContains(phpversion(), $shell->getVersion());
- $this->assertContains(php_sapi_name(), $shell->getVersion());
+ $this->assertContains(PHP_VERSION, $shell->getVersion());
+ $this->assertContains(PHP_SAPI, $shell->getVersion());
}
public function testCodeBuffer()
@@ -236,7 +239,7 @@ public function testCodeBuffer()
$shell->addCode('{}');
$code = $shell->flushCode();
$this->assertFalse($shell->hasCode());
- $code = preg_replace('/\s+/', ' ', $code);
+ $code = \preg_replace('/\s+/', ' ', $code);
$this->assertNotNull($code);
$this->assertSame('class a { } return new \\Psy\\CodeCleaner\\NoReturnValue();', $code);
}
@@ -256,7 +259,7 @@ public function testKeepCodeBufferOpen()
$shell->addCode('+ 1');
$code = $shell->flushCode();
$this->assertFalse($shell->hasCode());
- $code = preg_replace('/\s+/', ' ', $code);
+ $code = \preg_replace('/\s+/', ' ', $code);
$this->assertNotNull($code);
$this->assertSame('return 1 + 1 + 1;', $code);
}
@@ -291,8 +294,8 @@ public function testWriteStdout()
$shell->writeStdout("{{stdout}}\n");
- rewind($stream);
- $streamContents = stream_get_contents($stream);
+ \rewind($stream);
+ $streamContents = \stream_get_contents($stream);
$this->assertSame('{{stdout}}' . PHP_EOL, $streamContents);
}
@@ -306,8 +309,8 @@ public function testWriteStdoutWithoutNewline()
$shell->writeStdout('{{stdout}}');
- rewind($stream);
- $streamContents = stream_get_contents($stream);
+ \rewind($stream);
+ $streamContents = \stream_get_contents($stream);
$this->assertSame('{{stdout}}' . PHP_EOL, $streamContents);
}
@@ -323,8 +326,8 @@ public function testWriteReturnValue($input, $expected)
$shell->setOutput($output);
$shell->writeReturnValue($input);
- rewind($stream);
- $this->assertEquals($expected, stream_get_contents($stream));
+ \rewind($stream);
+ $this->assertEquals($expected, \stream_get_contents($stream));
}
public function getReturnValues()
@@ -346,8 +349,8 @@ public function testWriteException($exception, $expected)
$shell->setOutput($output);
$shell->writeException($exception);
- rewind($stream);
- $this->assertSame($expected, stream_get_contents($stream));
+ \rewind($stream);
+ $this->assertSame($expected, \stream_get_contents($stream));
}
public function getRenderedExceptions()
@@ -367,8 +370,8 @@ public function testShellExecute($input, $expected)
$shell = new Shell($this->getConfig());
$shell->setOutput($output);
$this->assertEquals($expected, $shell->execute($input));
- rewind($stream);
- $this->assertSame('', stream_get_contents($stream));
+ \rewind($stream);
+ $this->assertSame('', \stream_get_contents($stream));
}
public function getExecuteValues()
@@ -414,7 +417,7 @@ public function commandsToHas()
private function getOutput()
{
- $stream = fopen('php://memory', 'w+');
+ $stream = \fopen('php://memory', 'w+');
$this->streams[] = $stream;
$output = new StreamOutput($stream, StreamOutput::VERBOSITY_NORMAL, false);
@@ -425,8 +428,8 @@ private function getOutput()
private function getConfig(array $config = [])
{
// Mebbe there's a better way than this?
- $dir = tempnam(sys_get_temp_dir(), 'psysh_shell_test_');
- unlink($dir);
+ $dir = \tempnam(\sys_get_temp_dir(), 'psysh_shell_test_');
+ \unlink($dir);
$defaults = [
'configDir' => $dir,
@@ -434,6 +437,6 @@ private function getConfig(array $config = [])
'runtimeDir' => $dir,
];
- return new Configuration(array_merge($defaults, $config));
+ return new Configuration(\array_merge($defaults, $config));
}
}
diff --git a/test/SudoTest.php b/test/SudoTest.php
index 8ac077743..6123db04e 100644
--- a/test/SudoTest.php
+++ b/test/SudoTest.php
@@ -17,7 +17,7 @@ class SudoTest extends \PHPUnit\Framework\TestCase
{
public function setUp()
{
- if (version_compare(PHP_VERSION, '7.1.0', '<')) {
+ if (\version_compare(PHP_VERSION, '7.1.0', '<')) {
$this->markTestSkipped('YOLO');
}
}
diff --git a/test/TabCompletion/AutoCompleterTest.php b/test/TabCompletion/AutoCompleterTest.php
index 258780462..d98d452c4 100644
--- a/test/TabCompletion/AutoCompleterTest.php
+++ b/test/TabCompletion/AutoCompleterTest.php
@@ -62,7 +62,7 @@ public function testClassesCompletion($line, $mustContain, $mustNotContain)
$code = $tabCompletion->processCallback('', 0, [
'line_buffer' => $line,
'point' => 0,
- 'end' => strlen($line),
+ 'end' => \strlen($line),
]);
foreach ($mustContain as $mc) {
diff --git a/test/Util/DocblockTest.php b/test/Util/DocblockTest.php
index 6fa775d92..82e12fede 100644
--- a/test/Util/DocblockTest.php
+++ b/test/Util/DocblockTest.php
@@ -41,7 +41,7 @@ public function testDocblockParsing($comment, $body, $tags)
public function comments()
{
- if (defined('HHVM_VERSION')) {
+ if (\defined('HHVM_VERSION')) {
$this->markTestSkipped('We have issues with PHPUnit mocks on HHVM.');
}
diff --git a/test/Util/MirrorTest.php b/test/Util/MirrorTest.php
index 09976bdfd..585fffbb2 100644
--- a/test/Util/MirrorTest.php
+++ b/test/Util/MirrorTest.php
@@ -36,7 +36,7 @@ public function testMirror()
$this->assertInstanceOf('ReflectionObject', $refl);
$refl = Mirror::get($this, 'FOO');
- if (version_compare(PHP_VERSION, '7.1.0', '>=')) {
+ if (\version_compare(PHP_VERSION, '7.1.0', '>=')) {
$this->assertInstanceOf('ReflectionClassConstant', $refl);
} else {
$this->assertInstanceOf('Psy\Reflection\ReflectionClassConstant', $refl);
diff --git a/test/Util/StrTest.php b/test/Util/StrTest.php
index 2a58d9f98..4f99a79b3 100644
--- a/test/Util/StrTest.php
+++ b/test/Util/StrTest.php
@@ -26,6 +26,6 @@ public function testUnvis($input, $expected)
public function unvisProvider()
{
//return require_once(__DIR__.'/../fixtures/unvis_fixtures.php');
- return json_decode(file_get_contents(__DIR__ . '/../fixtures/unvis_fixtures.json'));
+ return \json_decode(\file_get_contents(__DIR__ . '/../fixtures/unvis_fixtures.json'));
}
}
diff --git a/test/VersionUpdater/GitHubCheckerTest.php b/test/VersionUpdater/GitHubCheckerTest.php
index bbbd69cf3..7d12d47d6 100644
--- a/test/VersionUpdater/GitHubCheckerTest.php
+++ b/test/VersionUpdater/GitHubCheckerTest.php
@@ -52,13 +52,13 @@ public function testDataSetResults($assertion, $input)
public function jsonResults()
{
return [
- [false, json_decode('{"tag_name":"v9.0.0"}')],
- [true, json_decode('{"tag_name":"v' . Shell::VERSION . '"}')],
- [true, json_decode('{"tag_name":"v0.0.1"}')],
- [true, json_decode('{"tag_name":"v0.4.1-alpha"}')],
- [true, json_decode('{"tag_name":"v0.4.2-beta3"}')],
- [true, json_decode('{"tag_name":"v0.0.1"}')],
- [true, json_decode('{"tag_name":""}')],
+ [false, \json_decode('{"tag_name":"v9.0.0"}')],
+ [true, \json_decode('{"tag_name":"v' . Shell::VERSION . '"}')],
+ [true, \json_decode('{"tag_name":"v0.0.1"}')],
+ [true, \json_decode('{"tag_name":"v0.4.1-alpha"}')],
+ [true, \json_decode('{"tag_name":"v0.4.2-beta3"}')],
+ [true, \json_decode('{"tag_name":"v0.0.1"}')],
+ [true, \json_decode('{"tag_name":""}')],
];
}
@@ -71,12 +71,12 @@ public function malformedResults()
[null],
[false],
[true],
- [json_decode('{"foo":"bar"}')],
- [json_decode('{}')],
- [json_decode('[]')],
+ [\json_decode('{"foo":"bar"}')],
+ [\json_decode('{}')],
+ [\json_decode('[]')],
[[]],
- [json_decode('{"tag_name":false"}')],
- [json_decode('{"tag_name":true"}')],
+ [\json_decode('{"tag_name":false"}')],
+ [\json_decode('{"tag_name":true"}')],
];
}
}
diff --git a/test/fixtures/config.php b/test/fixtures/config.php
index 4aa1f5fbe..4c74b79d0 100644
--- a/test/fixtures/config.php
+++ b/test/fixtures/config.php
@@ -9,7 +9,7 @@
* file that was distributed with this source code.
*/
-$config->setRuntimeDir(sys_get_temp_dir() . '/psysh_test/withconfig/temp');
+$config->setRuntimeDir(\sys_get_temp_dir() . '/psysh_test/withconfig/temp');
return [
'useReadline' => true,