Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Updating Exceptions, Files code with PHP 8.1 features #626

Merged
merged 6 commits into from
Mar 28, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,8 @@
added return type `mixed` to the method `getContext` in `Spiral\Filters\FilterInterface` interface.
Added return type `mixed` to the method `getValue` in `Spiral\Filters\InputInterface`.
- [spiral/http] Config `Spiral\Config\JsonPayloadConfig` moved to the `Spiral\Bootloader\Http\JsonPayloadConfig`.
- [spiral/files] Added return type `bool` to the method `delete`, added return type `bool` to the method `deleteDirectory`,
added return type `bool` to the method `touch`, added return type `bool` to the method `setPermissions` in `Spiral\Files\FilesInterface`.
- **Medium Impact Changes**
- A minimal version of `PHP` increased to `^8.1`
- A minimal version of `symfony/finder` increased to `^5.3`
Expand Down
14 changes: 2 additions & 12 deletions src/Exceptions/src/AbstractHandler.php
Original file line number Diff line number Diff line change
@@ -1,12 +1,5 @@
<?php

/**
* Spiral Framework.
*
* @license MIT
* @author Anton Titov (Wolfy-J)
*/

declare(strict_types=1);

namespace Spiral\Exceptions;
Expand All @@ -16,12 +9,9 @@
*/
abstract class AbstractHandler implements HandlerInterface
{
/**
* @inheritdoc
*/
public function getMessage(\Throwable $e): string
{
return sprintf('%s: %s in %s at line %s', get_class($e), $e->getMessage(), $e->getFile(), $e->getLine());
return \sprintf('%s: %s in %s at line %s', $e::class, $e->getMessage(), $e->getFile(), $e->getLine());
}

/**
Expand All @@ -41,7 +31,7 @@ protected function getStacktrace(\Throwable $e): array
] + $stacktrace[0];

if ($stacktrace[0] != $header) {
array_unshift($stacktrace, $header);
\array_unshift($stacktrace, $header);
}

return $stacktrace;
Expand Down
56 changes: 19 additions & 37 deletions src/Exceptions/src/ConsoleHandler.php
Original file line number Diff line number Diff line change
@@ -1,12 +1,5 @@
<?php

/**
* Spiral Framework.
*
* @license MIT
* @author Anton Titov (Wolfy-J)
*/

declare(strict_types=1);

namespace Spiral\Exceptions;
Expand Down Expand Up @@ -41,13 +34,12 @@ class ConsoleHandler extends AbstractHandler
'reset' => Color::RESET,
];

/** @var StyleInterface */
private $colorsSupport;
private bool $colorsSupport;

/**
* @param bool|resource $stream
*/
public function __construct($stream = STDOUT)
public function __construct(mixed $stream = STDOUT)
{
$this->colorsSupport = System::isColorsSupported($stream);
}
Expand All @@ -60,18 +52,12 @@ public function setColorsSupport(bool $enabled = true): void
$this->colorsSupport = $enabled;
}

/**
* @inheritdoc
*/
public function renderException(\Throwable $e, int $verbosity = self::VERBOSITY_BASIC): string
{
$result = '';

if ($e instanceof \Error) {
$result .= $this->renderHeader('[' . get_class($e) . "]\n" . $e->getMessage(), 'bg:magenta,white');
} else {
$result .= $this->renderHeader('[' . get_class($e) . "]\n" . $e->getMessage(), 'bg:red,white');
}
$result = $this->renderHeader(
\sprintf("[%s]\n%s", $e::class, $e->getMessage()),
$e instanceof \Error ? 'bg:magenta,white' : 'bg:red,white'
);

$result .= $this->format(
"<yellow>in</reset> <green>%s</reset><yellow>:</reset><white>%s</reset>\n",
Expand Down Expand Up @@ -100,21 +86,21 @@ private function renderHeader(string $title, string $style, int $padding = 0): s
{
$result = '';

$lines = explode("\n", str_replace("\r", '', $title));
$lines = \explode("\n", \str_replace("\r", '', $title));

$length = 0;
array_walk($lines, function ($v) use (&$length): void {
$length = max($length, mb_strlen($v));
\array_walk($lines, static function ($v) use (&$length): void {
$length = max($length, \mb_strlen($v));
});

$length += $padding;

foreach ($lines as $line) {
$result .= $this->format(
"<{$style}>%s%s%s</reset>\n",
str_repeat(' ', $padding + 1),
\str_repeat(' ', $padding + 1),
$line,
str_repeat(' ', $length - mb_strlen($line) + 1)
\str_repeat(' ', $length - \mb_strlen($line) + 1)
);
}

Expand All @@ -123,8 +109,6 @@ private function renderHeader(string $title, string $style, int $padding = 0): s

/**
* Render exception call stack.
*
* @param Highlighter|null $h
*/
private function renderTrace(\Throwable $e, Highlighter $h = null): string
{
Expand All @@ -136,7 +120,7 @@ private function renderTrace(\Throwable $e, Highlighter $h = null): string
$result = $this->format("\n<red>Exception Trace:</reset>\n");

foreach ($stacktrace as $trace) {
if (isset($trace['type']) && isset($trace['class'])) {
if (isset($trace['type'], $trace['class'])) {
$line = $this->format(
' <white>%s%s%s()</reset>',
$trace['class'],
Expand Down Expand Up @@ -166,9 +150,9 @@ private function renderTrace(\Throwable $e, Highlighter $h = null): string

$result .= $line . "\n";

if (!empty($h) && !empty($trace['file'])) {
if ($h !== null && !empty($trace['file'])) {
$result .= $h->highlightLines(
file_get_contents($trace['file']),
\file_get_contents($trace['file']),
$trace['line'],
static::SHOW_LINES
) . "\n";
Expand All @@ -180,17 +164,15 @@ private function renderTrace(\Throwable $e, Highlighter $h = null): string

/**
* Format string and apply color formatting (if enabled).
*
* @param mixed ...$args
*/
private function format(string $format, ...$args): string
private function format(string $format, mixed ...$args): string
{
if (!$this->colorsSupport) {
$format = preg_replace('/<[^>]+>/', '', $format);
$format = \preg_replace('/<[^>]+>/', '', $format);
} else {
$format = preg_replace_callback('/(<([^>]+)>)/', function ($partial) {
$format = \preg_replace_callback('/(<([^>]+)>)/', function ($partial) {
$style = '';
foreach (explode(',', trim($partial[2], '/')) as $color) {
foreach (\explode(',', \trim($partial[2], '/')) as $color) {
if (isset(self::COLORS[$color])) {
$style .= self::COLORS[$color];
}
Expand All @@ -200,6 +182,6 @@ private function format(string $format, ...$args): string
}, $format);
}

return sprintf($format, ...$args);
return \sprintf($format, ...$args);
}
}
7 changes: 0 additions & 7 deletions src/Exceptions/src/HandlerInterface.php
Original file line number Diff line number Diff line change
@@ -1,12 +1,5 @@
<?php

/**
* Spiral Framework.
*
* @license MIT
* @author Anton Titov (Wolfy-J)
*/

declare(strict_types=1);

namespace Spiral\Exceptions;
Expand Down
26 changes: 8 additions & 18 deletions src/Exceptions/src/Highlighter.php
Original file line number Diff line number Diff line change
@@ -1,12 +1,5 @@
<?php

/**
* Spiral Framework.
*
* @license MIT
* @author Anton Titov (Wolfy-J)
*/

declare(strict_types=1);

namespace Spiral\Exceptions;
Expand All @@ -16,20 +9,17 @@
*/
class Highlighter
{
/** @var StyleInterface */
private $r;

public function __construct(StyleInterface $renderer)
{
$this->r = $renderer;
public function __construct(
private StyleInterface $renderer
) {
}

/**
* Highlight PHP source and return N lines around target line.
*/
public function highlightLines(string $source, int $line, int $around = 5): string
{
$lines = explode("\n", str_replace("\r\n", "\n", $this->highlight($source)));
$lines = \explode("\n", \str_replace("\r\n", "\n", $this->highlight($source)));

$result = '';
foreach ($lines as $number => $code) {
Expand All @@ -39,7 +29,7 @@ public function highlightLines(string $source, int $line, int $around = 5): stri
continue;
}

$result .= $this->r->line($human, mb_convert_encoding($code, 'utf-8'), $human === $line);
$result .= $this->renderer->line($human, \mb_convert_encoding($code, 'utf-8'), $human === $line);
}

return $result;
Expand All @@ -53,7 +43,7 @@ public function highlight(string $source): string
$result = '';
$previous = [];
foreach ($this->getTokens($source) as $token) {
$result .= $this->r->token($token, $previous);
$result .= $this->renderer->token($token, $previous);
$previous = $token;
}

Expand All @@ -68,12 +58,12 @@ private function getTokens(string $source): array
$tokens = [];
$line = 0;

foreach (token_get_all($source) as $token) {
foreach (\token_get_all($source) as $token) {
if (isset($token[2])) {
$line = $token[2];
}

if (!is_array($token)) {
if (!\is_array($token)) {
$token = [$token, $token, $line];
}

Expand Down
42 changes: 11 additions & 31 deletions src/Exceptions/src/HtmlHandler.php
Original file line number Diff line number Diff line change
@@ -1,12 +1,5 @@
<?php

/**
* Spiral Framework.
*
* @license MIT
* @author Anton Titov (Wolfy-J)
*/

declare(strict_types=1);

namespace Spiral\Exceptions;
Expand All @@ -27,24 +20,14 @@ class HtmlHandler extends AbstractHandler
public const DEFAULT = 'default';
public const INVERTED = 'inverted';

/** @var HtmlRenderer */
protected $renderer;

/** @var Highlighter */
protected $highlighter;

/** @var string */
protected $style = self::DEFAULT;
protected HtmlRenderer $renderer;
protected Highlighter $highlighter;
protected Dumper $dumper;
protected ?StateInterface $state = null;

/** @var Dumper */
protected $dumper;

/** @var StateInterface|null */
protected $state;

public function __construct(string $style = self::DEFAULT)
{
$this->style = $style;
public function __construct(
protected string $style = self::DEFAULT
) {
$this->dumper = new Dumper();

if ($style == self::INVERTED) {
Expand All @@ -66,9 +49,6 @@ public function withState(StateInterface $state): HandlerInterface
return $handler;
}

/**
* @inheritdoc
*/
public function renderException(\Throwable $e, int $verbosity = self::VERBOSITY_BASIC): string
{
$options = [
Expand Down Expand Up @@ -126,19 +106,19 @@ public function renderException(\Throwable $e, int $verbosity = self::VERBOSITY_
*/
private function render(string $view, array $options = []): string
{
extract($options, EXTR_OVERWRITE);
\extract($options, EXTR_OVERWRITE);

ob_start();
\ob_start();
require $this->getFilename($view);

return ob_get_clean();
return \ob_get_clean();
}

/**
* Get view filename.
*/
private function getFilename(string $view): string
{
return sprintf('%s/views/%s.php', dirname(__DIR__), $view);
return \sprintf('%s/views/%s.php', \dirname(__DIR__), $view);
}
}
Loading