Skip to content

Commit

Permalink
Adding strict rules for cs fixer
Browse files Browse the repository at this point in the history
  • Loading branch information
chachanagov committed May 10, 2024
1 parent 0435e02 commit 5e59d0f
Show file tree
Hide file tree
Showing 119 changed files with 1,035 additions and 841 deletions.
15 changes: 14 additions & 1 deletion .php-cs-fixer.php
Original file line number Diff line number Diff line change
Expand Up @@ -8,10 +8,22 @@
return (new Config())
->setRules([
'@PER-CS2.0' => true,
'@PhpCsFixer' => true,
'@PHP81Migration' => true,
'new_with_parentheses' => [
'anonymous_class' => false,
],
'global_namespace_import' => [
'import_constants' => false,
'import_functions' => false,
'import_classes' => false,
],
'phpdoc_align' => ['align' => 'left'],
'phpdoc_line_span' => ['const' => 'multi', 'property' => 'multi', 'method' => 'multi'],
'phpdoc_to_comment' => false,
'single_line_comment_style' => ['comment_types' => ['hash']],
'multiline_comment_opening_closing' => false,
'yoda_style' => ['equal' => false, 'identical' => false, 'less_and_greater' => false],
])
->setRiskyAllowed(true)
->setFinder(
Expand All @@ -21,4 +33,5 @@
->in([__DIR__ . '/src'])
->exclude(['Test/Proto/']),
)
->setCacheFile('.cache/.php-cs-fixer.cache');
->setCacheFile('.cache/.php-cs-fixer.cache')
;
2 changes: 1 addition & 1 deletion composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -78,7 +78,7 @@
"roxblnfk/unpoly": "If you want to remove unnecessary PHP polyfills depend on PHP version."
},
"scripts": {
"cs-check": "vendor/bin/php-cs-fixer fix --config=.php-cs-fixer.php --dry-run",
"cs-check": "vendor/bin/php-cs-fixer fix --config=.php-cs-fixer.php --dry-run --diff -vvv",
"cs-fix": "vendor/bin/php-cs-fixer fix --config=.php-cs-fixer.php -vvv --using-cache=no"
}
}
90 changes: 46 additions & 44 deletions src/Application.php
Original file line number Diff line number Diff line change
Expand Up @@ -15,20 +15,25 @@
use Buggregator\Trap\Socket\SocketStream;
use Buggregator\Trap\Support\Timer;
use Buggregator\Trap\Traffic\Inspector;
use Fiber;

/**
* @internal
*/
final class Application implements Processable, Cancellable, Destroyable
{
/** @var Processable[] */
/**
* @var Processable[]
*/
private array $processors = [];

/** @var Server[] */
/**
* @var Server[]
*/
private array $servers = [];

/** @var Fiber[] Any tasks in fibers */
/**
* @var \Fiber[] Any tasks in fibers
*/
private array $fibers = [];

private readonly Buffer $buffer;
Expand Down Expand Up @@ -135,7 +140,7 @@ public function destroy(): void
public function cancel(): void
{
$this->cancelled = true;
$this->fibers[] = new Fiber(
$this->fibers[] = new \Fiber(
function () {
foreach ($this->servers as $server) {
$server->cancel();
Expand All @@ -144,51 +149,16 @@ function () {
);
}

/**
* @param Sender[] $senders
*/
private function sendBuffer(array $senders = []): void
{
$data = $this->buffer->getAndClean();

foreach ($senders as $sender) {
$this->fibers[] = new Fiber(
static fn() => $sender->send($data)
);
}
}

private function createServer(SocketServer $config, Inspector $inspector): Server
{
$logger = $this->logger;
$clientInflector = static function (Client $client, int $id) use ($inspector, $logger): Client {
$logger->debug('Client %d connected', $id);
$inspector->addStream(SocketStream::create($client, $id));
return $client;
};

return Server::init(
$config->port,
payloadSize: 524_288,
clientInflector: $clientInflector,
logger: $this->logger,
);
}

/**
* @param SocketServer $config
* @param Inspector $inspector
* @return Fiber
*/
public function prepareServerFiber(SocketServer $config, Inspector $inspector, Logger $logger): Fiber
public function prepareServerFiber(SocketServer $config, Inspector $inspector, Logger $logger): \Fiber
{
return $this->fibers[] = new Fiber(function () use ($config, $inspector, $logger) {
return $this->fibers[] = new \Fiber(function () use ($config, $inspector, $logger) {
do {
try {
$this->processors[] = $this->servers[$config->port] = $this->createServer($config, $inspector);

return;
} catch (\Throwable) {
$logger->error("Can't create TCP socket on port $config->port.");
$logger->error("Can't create TCP socket on port {$config->port}.");
(new Timer(1.0))->wait();
}
} while (!$this->cancelled);
Expand Down Expand Up @@ -219,4 +189,36 @@ public function configureFrontend(int $port): void
$config = $this->container->get(FrontendConfig::class);
$this->prepareServerFiber(new SocketServer(port: $config->port), $inspector, $this->logger);
}

/**
* @param Sender[] $senders
*/
private function sendBuffer(array $senders = []): void
{
$data = $this->buffer->getAndClean();

foreach ($senders as $sender) {
$this->fibers[] = new \Fiber(
static fn () => $sender->send($data)
);
}
}

private function createServer(SocketServer $config, Inspector $inspector): Server
{
$logger = $this->logger;
$clientInflector = static function (Client $client, int $id) use ($inspector, $logger): Client {
$logger->debug('Client %d connected', $id);
$inspector->addStream(SocketStream::create($client, $id));

return $client;
};

return Server::init(
$config->port,
payloadSize: 524_288,
clientInflector: $clientInflector,
logger: $this->logger,
);
}
}
2 changes: 1 addition & 1 deletion src/Bootstrap.php
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ public function finish(): Container
}

/**
* @param non-empty-string|null $xml File or XML content
* @param null|non-empty-string $xml File or XML content
*/
public function withConfig(
?string $xml = null,
Expand Down
39 changes: 22 additions & 17 deletions src/Client/TrapHandle.php
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,17 @@ final class TrapHandle
private int $depth = 0;
private StaticState $staticState;

private function __construct(
private array $values,
) {
$this->staticState = StaticState::new();
}

public function __destruct()
{
$this->haveToSend() and $this->sendDump();
}

public static function fromArray(array $array): self
{
return new self($array);
Expand All @@ -42,6 +53,7 @@ public function if(bool|callable $condition): self
}

$this->haveToSend = $condition;

return $this;
}

Expand All @@ -62,11 +74,12 @@ public function stackTrace(): self
/**
* Set max depth for the dump.
*
* @param int<0, max> $depth If 0 - no limit.
* @param int<0, max> $depth if 0 - no limit
*/
public function depth(int $depth): self
{
$this->depth = $depth;

return $this;
}

Expand All @@ -75,8 +88,8 @@ public function depth(int $depth): self
* The counter isn't incremented if the dump is not sent (any other condition is not met).
* It might be useful for debugging in loops, recursive or just multiple function calls.
*
* @param positive-int $times Zero means no limit.
* @param bool $fullStack If true, the counter is incremented for each stack trace, not for the line.
* @param positive-int $times zero means no limit
* @param bool $fullStack if true, the counter is incremented for each stack trace, not for the line
*/
public function times(int $times, bool $fullStack = false): self
{
Expand All @@ -86,6 +99,7 @@ public function times(int $times, bool $fullStack = false): self
? $this->staticState->stackTrace
: $this->staticState->stackTrace[0]
));

return $this;
}

Expand Down Expand Up @@ -148,23 +162,18 @@ public function return(int|string $key = 0): mixed
* ```php
* trap()->context(['foo bar', => 42, 'baz' => 69]);
* ```
*
* @param mixed ...$values
*/
public function context(mixed ...$values): self
{
if (\array_keys($values) === [0] && \is_array($values[0])) {
$this->staticState->dataContext = \array_merge($this->staticState->dataContext, $values[0]);

return $this;
}

$this->staticState->dataContext = \array_merge($this->staticState->dataContext, $values);
return $this;
}

public function __destruct()
{
$this->haveToSend() and $this->sendDump();
return $this;
}

private function sendDump(): void
Expand All @@ -184,12 +193,13 @@ private function sendDump(): void
// Dump single value
if (\array_keys($this->values) === [0]) {
VarDumper::dump($this->values[0], depth: $this->depth);

return;
}

// Dump sequence of values
/**
* @var string|int $key
* @var int|string $key
* @var mixed $value
*/
foreach ($this->values as $key => $value) {
Expand All @@ -201,12 +211,6 @@ private function sendDump(): void
}
}

private function __construct(
private array $values,
) {
$this->staticState = StaticState::new();
}

private function haveToSend(): bool
{
if (!$this->haveToSend || $this->values === []) {
Expand All @@ -215,6 +219,7 @@ private function haveToSend(): bool

if ($this->times > 0) {
\assert($this->timesCounterKey !== '');

return Counter::checkAndIncrement($this->timesCounterKey, $this->times);
}

Expand Down
26 changes: 14 additions & 12 deletions src/Client/TrapHandle/ContextProvider/Source.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@

namespace Buggregator\Trap\Client\TrapHandle\ContextProvider;

use Buggregator\Trap\Client\TrapHandle\StackTrace;
use Buggregator\Trap\Client\TrapHandle\StaticState;
use Symfony\Component\HttpKernel\Debug\FileLinkFormatter;
use Symfony\Component\VarDumper\Cloner\VarCloner;
Expand All @@ -17,8 +16,8 @@
* @author Nicolas Grekas <[email protected]>
* @author Maxime Steinhausser <[email protected]>
*
* @link https://github.com/symfony/var-dumper/blob/7.0/Dumper/ContextProvider/SourceContextProvider.php
* @link https://github.com/symfony/var-dumper/blob/6.3/Dumper/ContextProvider/SourceContextProvider.php
* @see https://github.com/symfony/var-dumper/blob/7.0/Dumper/ContextProvider/SourceContextProvider.php
* @see https://github.com/symfony/var-dumper/blob/6.3/Dumper/ContextProvider/SourceContextProvider.php
*
* @psalm-suppress all
*
Expand All @@ -34,7 +33,7 @@ final class Source implements ContextProviderInterface
/**
* @psalm-suppress UndefinedClass
*/
public function __construct(string $charset = null, string $projectDir = null, FileLinkFormatter $fileLinkFormatter = null, int $limit = 9)
public function __construct(?string $charset = null, ?string $projectDir = null, ?FileLinkFormatter $fileLinkFormatter = null, int $limit = 9)
{
$this->charset = $charset;
$this->projectDir = $projectDir;
Expand All @@ -49,13 +48,13 @@ public function getContext(): ?array

$file = $trace[0]['file'];
$line = $trace[0]['line'];
$name = '-' === $file || 'Standard input code' === $file ? 'Standard input code' : false;
$name = $file === '-' || $file === 'Standard input code' ? 'Standard input code' : false;
$fileExcerpt = false;

for ($i = 0; $i < $this->limit; ++$i) {
if (isset($trace[$i]['class'], $trace[$i]['function'])
&& 'dump' === $trace[$i]['function']
&& VarDumper::class === $trace[$i]['class']
&& $trace[$i]['function'] === 'dump'
&& $trace[$i]['class'] === VarDumper::class
) {
$file = $trace[$i]['file'] ?? $file;
$line = $trace[$i]['line'] ?? $line;
Expand All @@ -66,7 +65,8 @@ public function getContext(): ?array
$line = $trace[$i]['line'];

break;
} elseif (isset($trace[$i]['object']) && $trace[$i]['object'] instanceof Template) {
}
if (isset($trace[$i]['object']) && $trace[$i]['object'] instanceof Template) {
$template = $trace[$i]['object'];
$name = $template->getTemplateName();
$src = method_exists($template, 'getSourceContext') ? $template->getSourceContext()->getCode() : (method_exists($template, 'getSource') ? $template->getSource() : false);
Expand All @@ -80,28 +80,30 @@ public function getContext(): ?array
$fileExcerpt = [];

for ($i = max($line - 3, 1), $max = min($line + 3, \count($src)); $i <= $max; ++$i) {
$fileExcerpt[] = '<li' . ($i === $line ? ' class="selected"' : '') . '><code>' . $this->htmlEncode($src[$i - 1]) . '</code></li>';
$fileExcerpt[] = '<li'.($i === $line ? ' class="selected"' : '').'><code>'.$this->htmlEncode($src[$i - 1]).'</code></li>';
}

$fileExcerpt = '<ol start="' . max($line - 3, 1) . '">' . implode("\n", $fileExcerpt) . '</ol>';
$fileExcerpt = '<ol start="'.max($line - 3, 1).'">'.implode("\n", $fileExcerpt).'</ol>';
}
}

break;
}
}

break;
}
}

if (false === $name) {
if ($name === false) {
$name = str_replace('\\', '/', $file);
$name = substr($name, strrpos($name, '/') + 1);
}

$context = ['name' => $name, 'file' => $file, 'line' => $line];
$context['file_excerpt'] = $fileExcerpt;

if (null !== $this->projectDir) {
if ($this->projectDir !== null) {
$context['project_dir'] = $this->projectDir;
if (str_starts_with($file, $this->projectDir)) {
$context['file_relative'] = ltrim(substr($file, \strlen($this->projectDir)), \DIRECTORY_SEPARATOR);
Expand Down
Loading

0 comments on commit 5e59d0f

Please sign in to comment.