diff --git a/src/AutoLoader.php b/src/AutoLoader.php index f3d3b10..a19099d 100644 --- a/src/AutoLoader.php +++ b/src/AutoLoader.php @@ -9,8 +9,20 @@ namespace Toolkit\PhpUtil; +use InvalidArgumentException; +use function array_merge; +use function file_exists; +use function spl_autoload_register; +use function spl_autoload_unregister; +use function str_replace; +use function strlen; +use function strpos; +use function substr; +use const DIRECTORY_SEPARATOR; + /** * Class AutoLoader + * * @package Toolkit\PhpUtil * ```php * AutoLoader::addFiles([ @@ -65,6 +77,7 @@ class AutoLoader /** * @param array $files + * * @return self */ public static function getLoader(array $files = []): self @@ -114,7 +127,7 @@ public static function setFiles(array $files): void public static function addFiles(array $files): void { if (self::$files) { - self::$files = \array_merge(self::$files, $files); + self::$files = array_merge(self::$files, $files); } else { self::$files = $files; } @@ -139,7 +152,7 @@ public function addPsr0(string $prefix, string $path): void public function addPsr0Map(array $psr0Map): void { if ($this->psr0Map) { - $this->psr0Map = \array_merge($this->psr0Map, $psr0Map); + $this->psr0Map = array_merge($this->psr0Map, $psr0Map); } else { $this->psr0Map = $psr0Map; } @@ -148,15 +161,16 @@ public function addPsr0Map(array $psr0Map): void /** * @param string $prefix * @param string $path - * @throws \InvalidArgumentException + * + * @throws InvalidArgumentException */ public function addPsr4(string $prefix, string $path): void { // Register directories for a new namespace. - $length = \strlen($prefix); + $length = strlen($prefix); if ('\\' !== $prefix[$length - 1]) { - throw new \InvalidArgumentException('A non-empty PSR-4 prefix must end with a namespace separator.'); + throw new InvalidArgumentException('A non-empty PSR-4 prefix must end with a namespace separator.'); } $this->psr4Map[$prefix] = $path; @@ -168,7 +182,7 @@ public function addPsr4(string $prefix, string $path): void public function addPsr4Map(array $psr4Map): void { if ($this->psr4Map) { - $this->psr4Map = \array_merge($this->psr4Map, $psr4Map); + $this->psr4Map = array_merge($this->psr4Map, $psr4Map); } else { $this->psr4Map = $psr4Map; } @@ -212,7 +226,7 @@ public function setClassMap(array $classMap): void public function addClassMap(array $classMap): void { if ($this->classMap) { - $this->classMap = \array_merge($this->classMap, $classMap); + $this->classMap = array_merge($this->classMap, $classMap); } else { $this->classMap = $classMap; } @@ -220,11 +234,12 @@ public function addClassMap(array $classMap): void /** * Registers this instance as an autoloader. + * * @param bool $prepend Whether to prepend the autoloader or not */ public function register(bool $prepend = false): void { - \spl_autoload_register([$this, 'loadClass'], true, $prepend); + spl_autoload_register([$this, 'loadClass'], true, $prepend); } /** @@ -232,12 +247,14 @@ public function register(bool $prepend = false): void */ public function unRegister(): void { - \spl_autoload_unregister([$this, 'loadClass']); + spl_autoload_unregister([$this, 'loadClass']); } /** * Loads the given class or interface. - * @param string $class The name of the class + * + * @param string $class The name of the class + * * @return bool|null True if loaded, null otherwise */ public function loadClass(string $class): ?bool @@ -252,14 +269,16 @@ public function loadClass(string $class): ?bool /** * Finds the path to the file where the class is defined. + * * @param string $class The name of the class + * * @return string|false The path if found, false otherwise */ public function findFile(string $class) { // work around for PHP 5.3.0 - 5.3.2 https://bugs.php.net/50731 if ('\\' === $class[0]) { - $class = (string)\substr($class, 1); + $class = (string)substr($class, 1); } // class map lookup @@ -280,32 +299,33 @@ public function findFile(string $class) /** * @param string $class * @param string $ext + * * @return bool|string */ private function findFileWithExtension(string $class, string $ext) { // PSR-4 lookup - $logicalPathPsr4 = \str_replace('\\', \DIRECTORY_SEPARATOR, $class) . $ext; + $logicalPathPsr4 = str_replace('\\', DIRECTORY_SEPARATOR, $class) . $ext; // PSR-4 foreach ($this->psr4Map as $prefix => $dir) { - if (0 === \strpos($class, $prefix)) { - $length = \strlen($prefix); + if (0 === strpos($class, $prefix)) { + $length = strlen($prefix); - if (\file_exists($file = $dir . \DIRECTORY_SEPARATOR . \substr($logicalPathPsr4, $length))) { + if (file_exists($file = $dir . DIRECTORY_SEPARATOR . substr($logicalPathPsr4, $length))) { return $file; } } } // PEAR-like class name - $logicalPathPsr0 = \str_replace('_', \DIRECTORY_SEPARATOR, $class) . $ext; + $logicalPathPsr0 = str_replace('_', DIRECTORY_SEPARATOR, $class) . $ext; foreach ($this->psr0Map as $prefix => $dir) { - if (0 === \strpos($class, $prefix)) { - $file = $dir . \DIRECTORY_SEPARATOR . $logicalPathPsr0; + if (0 === strpos($class, $prefix)) { + $file = $dir . DIRECTORY_SEPARATOR . $logicalPathPsr0; - if (\file_exists($file)) { + if (file_exists($file)) { return $file; } } @@ -335,6 +355,7 @@ function _globalIncludeFile($fileIdentifier, $file) /** * Scope isolated include. * Prevents access to $this/self from included files. + * * @param $file */ function _includeClassFile($file) diff --git a/src/Php.php b/src/Php.php index af9e59a..8edec73 100644 --- a/src/Php.php +++ b/src/Php.php @@ -10,6 +10,7 @@ /** * Class Php - alias of the class PhpHelper + * * @package Toolkit\PhpUtil */ class Php extends PhpHelper diff --git a/src/PhpDoc.php b/src/PhpDoc.php index 760d31c..08d5314 100644 --- a/src/PhpDoc.php +++ b/src/PhpDoc.php @@ -8,8 +8,21 @@ namespace Toolkit\PhpUtil; +use function array_merge; +use function in_array; +use function is_array; +use function preg_match; +use function preg_replace; +use function preg_split; +use function str_replace; +use function substr; +use function trim; +use const PREG_OFFSET_CAPTURE; +use const PREG_SPLIT_NO_EMPTY; + /** * Class PhpDoc + * * @package Toolkit\PhpUtil */ class PhpDoc @@ -20,20 +33,23 @@ class PhpDoc /** * Parses the comment block into tags. + * * @param string $comment The comment block text * @param array $options - * - 'allow' // only allowed tags - * - 'ignore' // ignored tags - * - 'default' => 'description', // default tag name, first line text will attach to it. + * - 'allow' // only allowed tags + * - 'ignore' // ignored tags + * - 'default' => 'description', // default tag name, first line text will attach to it. + * @param array $defaults + * * @return array The parsed tags */ - public static function getTags(string $comment, array $options = []): array + public static function getTags(string $comment, array $options = [], array $defaults = []): array { - if (!$comment = \trim($comment, "/ \n")) { + if (!$comment = trim($comment, "/ \n")) { return []; } - $options = \array_merge([ + $options = array_merge([ 'allow' => [], // only allowed tags 'ignore' => ['param', 'return'], // ignore tags 'default' => 'description', // default tag name, first line text will attach to it. @@ -43,51 +59,54 @@ public static function getTags(string $comment, array $options = []): array $ignored = (array)$options['ignore']; $default = (string)$options['default']; - $comment = \str_replace("\r\n", "\n", $comment); - $comment = "@{$default} \n" . - \str_replace("\r", '', - \trim(\preg_replace('/^\s*\**( |\t)?/m', '', $comment)) - ); + $comment = str_replace("\r\n", "\n", $comment); + $comment = "@{$default} \n" . str_replace("\r", '', trim(preg_replace('/^\s*\**( |\t)?/m', '', $comment))); $tags = []; - $parts = \preg_split('/^\s*@/m', $comment, -1, \PREG_SPLIT_NO_EMPTY); + $parts = preg_split('/^\s*@/m', $comment, -1, PREG_SPLIT_NO_EMPTY); foreach ($parts as $part) { - if (\preg_match('/^(\w+)(.*)/ms', \trim($part), $matches)) { + if (preg_match('/^(\w+)(.*)/ms', trim($part), $matches)) { $name = $matches[1]; - if (!$name || \in_array($name, $ignored, true)) { + if (!$name || in_array($name, $ignored, true)) { + continue; + } + + if (!$value = trim($matches[2])) { continue; } // always allow default tag - if ($default !== $name && $allow && !\in_array($name, $allow, true)) { + if ($default !== $name && $allow && !in_array($name, $allow, true)) { continue; } if (!isset($tags[$name])) { - $tags[$name] = \trim($matches[2]); - } elseif (\is_array($tags[$name])) { - $tags[$name][] = \trim($matches[2]); + $tags[$name] = $value; + } elseif (is_array($tags[$name])) { + $tags[$name][] = $value; } else { - $tags[$name] = [$tags[$name], \trim($matches[2])]; + $tags[$name] = [$tags[$name], $value]; } } } - return $tags; + return $defaults ? array_merge($defaults, $tags) : $tags; } /** * Returns the first line of docBlock. + * * @param string $comment + * * @return string */ public static function firstLine(string $comment): string { - $docLines = \preg_split('~\R~u', $comment); + $docLines = preg_split('~\R~u', $comment); if (isset($docLines[1])) { - return \trim($docLines[1], "/\t *"); + return trim($docLines[1], "/\t *"); } return ''; @@ -96,15 +115,17 @@ public static function firstLine(string $comment): string /** * Returns full description from the doc-block. * If have multi line text, will return multi line. + * * @param string $comment + * * @return string */ public static function description(string $comment): string { - $comment = \str_replace("\r", '', \trim(\preg_replace('/^\s*\**( |\t)?/m', '', trim($comment, '/')))); + $comment = str_replace("\r", '', trim(preg_replace('/^\s*\**( |\t)?/m', '', trim($comment, '/')))); - if (\preg_match('/^\s*@\w+/m', $comment, $matches, \PREG_OFFSET_CAPTURE)) { - $comment = \trim(\substr($comment, 0, $matches[0][1])); + if (preg_match('/^\s*@\w+/m', $comment, $matches, PREG_OFFSET_CAPTURE)) { + $comment = trim(substr($comment, 0, $matches[0][1])); } return $comment; diff --git a/src/PhpDotEnv.php b/src/PhpDotEnv.php index ff9309e..bf3a170 100644 --- a/src/PhpDotEnv.php +++ b/src/PhpDotEnv.php @@ -8,8 +8,25 @@ namespace Toolkit\PhpUtil; +use function array_flip; +use function array_keys; +use function constant; +use function defined; +use function explode; +use function getenv; +use function implode; +use function is_file; +use function is_int; +use function is_readable; +use function is_string; +use function parse_ini_file; +use function putenv; +use function strpos; +use function strtoupper; + /** * Class PhpDotEnv - local env read + * * @package Toolkit\PhpUtil * * in local config file `.env` (must is 'ini' format): @@ -35,6 +52,7 @@ final class PhpDotEnv /** * @param string $fileDir * @param string $fileName + * * @return static */ public static function load(string $fileDir, string $fileName = '.env') @@ -44,6 +62,7 @@ public static function load(string $fileDir, string $fileName = '.env') /** * constructor. + * * @param string $fileDir * @param string $fileName */ @@ -59,27 +78,28 @@ public function __construct(string $fileDir, string $fileName = '.env') */ public function add(string $file): void { - if (\is_file($file) && \is_readable($file)) { - $this->settingEnv(\parse_ini_file($file)); + if (is_file($file) && is_readable($file)) { + $this->settingEnv(parse_ini_file($file)); } } /** * setting env data + * * @param array $data */ private function settingEnv(array $data): void { - $loadedVars = \array_flip(\explode(',', \getenv(self::FULL_KEY))); + $loadedVars = array_flip(explode(',', getenv(self::FULL_KEY))); unset($loadedVars['']); foreach ($data as $name => $value) { - if (\is_int($name) || !\is_string($value)) { + if (is_int($name) || !is_string($value)) { continue; } - $name = \strtoupper($name); - $notHttpName = 0 !== \strpos($name, 'HTTP_'); + $name = strtoupper($name); + $notHttpName = 0 !== strpos($name, 'HTTP_'); // don't check existence with getenv() because of thread safety issues if ((isset($_ENV[$name]) || (isset($_SERVER[$name]) && $notHttpName)) && !isset($loadedVars[$name])) { @@ -87,12 +107,12 @@ private function settingEnv(array $data): void } // is a constant var - if ($value && \defined($value)) { - $value = \constant($value); + if ($value && defined($value)) { + $value = constant($value); } // eg: "FOO=BAR" - \putenv("$name=$value"); + putenv("$name=$value"); $_ENV[$name] = $value; if ($notHttpName) { @@ -103,9 +123,9 @@ private function settingEnv(array $data): void } if ($loadedVars) { - $loadedVars = \implode(',', \array_keys($loadedVars)); - \putenv(self::FULL_KEY . "=$loadedVars"); - $_ENV[self::FULL_KEY] = $loadedVars; + $loadedVars = implode(',', array_keys($loadedVars)); + putenv(self::FULL_KEY . "=$loadedVars"); + $_ENV[self::FULL_KEY] = $loadedVars; $_SERVER[self::FULL_KEY] = $loadedVars; } } diff --git a/src/PhpEnv.php b/src/PhpEnv.php index e643caa..a072333 100644 --- a/src/PhpEnv.php +++ b/src/PhpEnv.php @@ -8,8 +8,17 @@ namespace Toolkit\PhpUtil; +use RuntimeException; +use function defined; +use function error_reporting; +use function extension_loaded; +use function function_exists; +use function get_loaded_extensions; +use function in_array; + /** * Class PhpEnv + * * @package Toolkit\PhpUtil */ class PhpEnv @@ -20,15 +29,17 @@ class PhpEnv /** * Get PHP version + * * @return string */ public static function getVersion(): string { - return \defined('HHVM_VERSION') ? HHVM_VERSION : PHP_VERSION; + return defined('HHVM_VERSION') ? HHVM_VERSION : PHP_VERSION; } /** * isEmbed + * * @return boolean */ public static function isEmbed(): bool @@ -46,6 +57,7 @@ public static function isCgi(): bool /** * is Cli + * * @return boolean */ public static function isCli(): bool @@ -56,6 +68,7 @@ public static function isCli(): bool /** * is Build In Server * run server use like: `php -S 127.0.0.1:8085` + * * @return boolean */ public static function isBuiltInServer(): bool @@ -73,11 +86,12 @@ public static function isDevServer(): bool /** * isWeb + * * @return boolean */ public static function isWeb(): bool { - return \in_array(PHP_SAPI, [ + return in_array(PHP_SAPI, [ 'apache', 'cgi', 'fast-cgi', @@ -90,15 +104,17 @@ public static function isWeb(): bool /** * isHHVM + * * @return boolean */ public static function isHHVM(): bool { - return \defined('HHVM_VERSION'); + return defined('HHVM_VERSION'); } /** * isPHP + * * @return boolean */ public static function isPHP(): bool @@ -108,6 +124,7 @@ public static function isPHP(): bool /** * setStrict + * * @return void */ public static function setStrict(): void @@ -117,29 +134,32 @@ public static function setStrict(): void /** * setMuted + * * @return void */ public static function setMuted(): void { - \error_reporting(0); + error_reporting(0); } /** * @param string $name + * * @return bool */ public static function hasExtension(string $name): bool { - return \extension_loaded($name); + return extension_loaded($name); } /** * Returns true when the runtime used is PHP and Xdebug is loaded. + * * @return boolean */ public static function hasXDebug(): bool { - return static::isPHP() && \extension_loaded('xdebug'); + return static::isPHP() && extension_loaded('xdebug'); } /** @@ -147,7 +167,7 @@ public static function hasXDebug(): bool */ public static function hasPcntl(): bool { - return \function_exists('pcntl_fork'); + return function_exists('pcntl_fork'); } /** @@ -155,21 +175,22 @@ public static function hasPcntl(): bool */ public static function hasPosix(): bool { - return \function_exists('posix_kill'); + return function_exists('posix_kill'); } /** * @param $name * @param bool|false $throwException + * * @return bool - * @throws \RuntimeException + * @throws RuntimeException */ public static function extIsLoaded(string $name, $throwException = false): bool { - $result = \extension_loaded($name); + $result = extension_loaded($name); if (!$result && $throwException) { - throw new \RuntimeException("Extension [$name] is not loaded."); + throw new RuntimeException("Extension [$name] is not loaded."); } return $result; @@ -177,7 +198,9 @@ public static function extIsLoaded(string $name, $throwException = false): bool /** * 检查多个扩展加载情况 + * * @param array $extensions + * * @return array|bool */ public static function checkExtList(array $extensions = []) @@ -185,7 +208,7 @@ public static function checkExtList(array $extensions = []) $allTotal = []; foreach ($extensions as $extension) { - if (!\extension_loaded($extension)) { + if (!extension_loaded($extension)) { $allTotal['no'][] = $extension; } else { $allTotal['yes'][] = $extension; @@ -197,11 +220,13 @@ public static function checkExtList(array $extensions = []) /** * 返回加载的扩展 + * * @param bool $zend_extensions + * * @return array */ public static function getLoadedExtension($zend_extensions = false): array { - return \get_loaded_extensions($zend_extensions); + return get_loaded_extensions($zend_extensions); } } diff --git a/src/PhpError.php b/src/PhpError.php index e3fbffa..ba532cc 100644 --- a/src/PhpError.php +++ b/src/PhpError.php @@ -8,25 +8,44 @@ namespace Toolkit\PhpUtil; +use const E_COMPILE_ERROR; +use const E_COMPILE_WARNING; +use const E_CORE_ERROR; +use const E_CORE_WARNING; +use const E_DEPRECATED; +use const E_ERROR; +use const E_NOTICE; +use const E_PARSE; +use const E_RECOVERABLE_ERROR; +use const E_STRICT; +use const E_USER_DEPRECATED; +use const E_USER_ERROR; +use const E_USER_NOTICE; +use const E_USER_WARNING; +use const E_WARNING; + /** * Class PhpError + * * @package Toolkit\PhpUtil */ class PhpError { /** @var array */ - public static $fatalErrors = [\E_ERROR, \E_PARSE, \E_CORE_ERROR, \E_COMPILE_ERROR, \E_USER_ERROR]; + public static $fatalErrors = [E_ERROR, E_PARSE, E_CORE_ERROR, E_COMPILE_ERROR, E_USER_ERROR]; /** * $lastError = error_get_last(); + * * @param array $lastError * @param null|string $catcher + * * @return array */ public static function toArray(array $lastError, $catcher = null): array { $digest = 'Fatal Error (' . self::codeToString($lastError['type']) . '): ' . $lastError['message']; - $data = [ + $data = [ 'code' => $lastError['type'], 'message' => $lastError['message'], 'file' => $lastError['file'], @@ -43,40 +62,41 @@ public static function toArray(array $lastError, $catcher = null): array /** * @param int $code + * * @return string */ public static function codeToString(int $code): string { switch ($code) { - case \E_ERROR: + case E_ERROR: return 'E_ERROR'; - case \E_WARNING: + case E_WARNING: return 'E_WARNING'; - case \E_PARSE: + case E_PARSE: return 'E_PARSE'; - case \E_NOTICE: + case E_NOTICE: return 'E_NOTICE'; - case \E_CORE_ERROR: + case E_CORE_ERROR: return 'E_CORE_ERROR'; - case \E_CORE_WARNING: + case E_CORE_WARNING: return 'E_CORE_WARNING'; - case \E_COMPILE_ERROR: + case E_COMPILE_ERROR: return 'E_COMPILE_ERROR'; - case \E_COMPILE_WARNING: + case E_COMPILE_WARNING: return 'E_COMPILE_WARNING'; - case \E_USER_ERROR: + case E_USER_ERROR: return 'E_USER_ERROR'; - case \E_USER_WARNING: + case E_USER_WARNING: return 'E_USER_WARNING'; - case \E_USER_NOTICE: + case E_USER_NOTICE: return 'E_USER_NOTICE'; - case \E_STRICT: + case E_STRICT: return 'E_STRICT'; - case \E_RECOVERABLE_ERROR: + case E_RECOVERABLE_ERROR: return 'E_RECOVERABLE_ERROR'; - case \E_DEPRECATED: + case E_DEPRECATED: return 'E_DEPRECATED'; - case \E_USER_DEPRECATED: + case E_USER_DEPRECATED: return 'E_USER_DEPRECATED'; } diff --git a/src/PhpException.php b/src/PhpException.php index 30d939e..a63c072 100644 --- a/src/PhpException.php +++ b/src/PhpException.php @@ -8,8 +8,15 @@ namespace Toolkit\PhpUtil; +use Exception; +use Throwable; +use function get_class; +use function json_encode; +use function strip_tags; + /** * Class PhpException + * * @package Toolkit\PhpUtil */ class PhpException @@ -25,10 +32,12 @@ public static function toString($e, $getTrace = true, $catcher = null): string /** * Converts an exception into a simple string. - * @param \Exception|\Throwable $e the exception being converted - * @param bool $clearHtml - * @param bool $getTrace - * @param null|string $catcher + * + * @param Exception|Throwable $e the exception being converted + * @param bool $clearHtml + * @param bool $getTrace + * @param null|string $catcher + * * @return string the string representation of the exception. */ public static function toHtml($e, bool $getTrace = true, string $catcher = null, bool $clearHtml = false): string @@ -36,32 +45,27 @@ public static function toHtml($e, bool $getTrace = true, string $catcher = null, if (!$getTrace) { $message = "Error: {$e->getMessage()}"; } else { - $message = sprintf( - "
File: %s(Line %d)%s \n\n%s", - \get_class($e), - $e->getCode(), - $e->getMessage(), - $e->getFile(), - $e->getLine(), - $catcher ? "\nCatch By: $catcher" : '', - $e->getTraceAsString() - ); + $message = sprintf("
File: %s(Line %d)%s \n\n%s", + get_class($e), $e->getCode(), $e->getMessage(), $e->getFile(), $e->getLine(), + $catcher ? "\nCatch By: $catcher" : '', $e->getTraceAsString()); } - return $clearHtml ? \strip_tags($message) : "