Skip to content

Commit

Permalink
Fix styling
Browse files Browse the repository at this point in the history
  • Loading branch information
Naoray authored and github-actions[bot] committed Jan 13, 2025
1 parent 2c4591c commit b2295ee
Show file tree
Hide file tree
Showing 17 changed files with 64 additions and 57 deletions.
2 changes: 1 addition & 1 deletion src/Deduplication/DeduplicationHandler.php
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,7 @@ public function flush(): void
return $record;
})
->filter()
->pipe(fn(Collection $records) => $this->handler->handleBatch($records->toArray()));
->pipe(fn (Collection $records) => $this->handler->handleBatch($records->toArray()));

$this->clear();
}
Expand Down
5 changes: 2 additions & 3 deletions src/Deduplication/DefaultSignatureGenerator.php
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@
namespace Naoray\LaravelGithubMonolog\Deduplication;

use Monolog\LogRecord;
use Naoray\LaravelGithubMonolog\Deduplication\SignatureGeneratorInterface;
use Throwable;

class DefaultSignatureGenerator implements SignatureGeneratorInterface
Expand All @@ -27,7 +26,7 @@ public function generate(LogRecord $record): string
*/
private function generateFromMessage(LogRecord $record): string
{
return md5($record->message . json_encode($record->context));
return md5($record->message.json_encode($record->context));
}

/**
Expand All @@ -42,7 +41,7 @@ private function generateFromException(Throwable $exception): string
$exception::class,
$exception->getFile(),
$exception->getLine(),
$firstFrame ? ($firstFrame['file'] ?? '') . ':' . ($firstFrame['line'] ?? '') : '',
$firstFrame ? ($firstFrame['file'] ?? '').':'.($firstFrame['line'] ?? '') : '',
]));
}
}
2 changes: 1 addition & 1 deletion src/Deduplication/Stores/AbstractStore.php
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ public function __construct(

protected function buildEntry(string $signature, int $timestamp): string
{
return $timestamp . ':' . $signature;
return $timestamp.':'.$signature;
}

public function isDuplicate(LogRecord $record, string $signature): bool
Expand Down
3 changes: 2 additions & 1 deletion src/Deduplication/Stores/DatabaseStore.php
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
class DatabaseStore extends AbstractStore
{
private string $table;

private string $connection;

public function __construct(
Expand All @@ -31,7 +32,7 @@ public function get(): array
->table($this->table)
->where('created_at', '>=', $this->getTimestampValidity())
->get()
->map(fn($row) => $this->buildEntry($row->signature, $row->created_at))
->map(fn ($row) => $this->buildEntry($row->signature, $row->created_at))
->all();
}

Expand Down
7 changes: 4 additions & 3 deletions src/Deduplication/Stores/FileStore.php
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ public function get(): array

return Str::of(File::get($this->path))
->explode(PHP_EOL)
->filter(fn($entry) => $entry && str_contains($entry, ':') && is_numeric(explode(':', $entry, 2)[0]))
->filter(fn ($entry) => $entry && str_contains($entry, ':') && is_numeric(explode(':', $entry, 2)[0]))
->toArray();
}

Expand All @@ -36,7 +36,7 @@ public function add(LogRecord $record, string $signature): void

File::put(
$this->path,
($content ? $content . PHP_EOL : '') . $entry
($content ? $content.PHP_EOL : '').$entry
);
}

Expand All @@ -45,7 +45,8 @@ public function cleanup(): void
$valid = collect($this->get())
->filter(function ($entry) {
[$timestamp] = explode(':', $entry, 2);
return is_numeric($timestamp) && !$this->isExpired((int) $timestamp);

return is_numeric($timestamp) && ! $this->isExpired((int) $timestamp);
})
->join(PHP_EOL);

Expand Down
5 changes: 3 additions & 2 deletions src/Deduplication/Stores/RedisStore.php
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
class RedisStore extends AbstractStore
{
private string $connection;

private string $prefix;

public function __construct(
Expand All @@ -28,7 +29,7 @@ private function redis()
// Key Management
public function getKey(): string
{
return $this->prefix . 'dedup';
return $this->prefix.'dedup';
}

// Storage Operations
Expand All @@ -49,7 +50,7 @@ public function get(): array
);

return array_map(
fn($entry, $score) => $this->buildEntry($entry, (int) $score),
fn ($entry, $score) => $this->buildEntry($entry, (int) $score),
array_keys($entries),
array_values($entries)
);
Expand Down
10 changes: 5 additions & 5 deletions src/GithubIssueHandlerFactory.php
Original file line number Diff line number Diff line change
Expand Up @@ -6,14 +6,14 @@
use InvalidArgumentException;
use Monolog\Level;
use Monolog\Logger;
use Naoray\LaravelGithubMonolog\Deduplication\DeduplicationHandler;
use Naoray\LaravelGithubMonolog\Deduplication\DefaultSignatureGenerator;
use Naoray\LaravelGithubMonolog\Deduplication\SignatureGeneratorInterface;
use Naoray\LaravelGithubMonolog\Deduplication\Stores\DatabaseStore;
use Naoray\LaravelGithubMonolog\Deduplication\Stores\FileStore;
use Naoray\LaravelGithubMonolog\Deduplication\Stores\RedisStore;
use Naoray\LaravelGithubMonolog\Issues\Formatter;
use Naoray\LaravelGithubMonolog\Deduplication\DeduplicationHandler;
use Naoray\LaravelGithubMonolog\Deduplication\SignatureGeneratorInterface;
use Naoray\LaravelGithubMonolog\Deduplication\Stores\StoreInterface;
use Naoray\LaravelGithubMonolog\Issues\Formatter;
use Naoray\LaravelGithubMonolog\Issues\Handler;

class GithubIssueHandlerFactory
Expand Down Expand Up @@ -49,7 +49,7 @@ protected function createBaseHandler(array $config): Handler
bubble: Arr::get($config, 'bubble', true)
);

$handler->setFormatter(new Formatter());
$handler->setFormatter(new Formatter);

return $handler;
}
Expand All @@ -65,7 +65,7 @@ protected function wrapWithDeduplication(Handler $handler, array $config): Dedup
}

/** @var SignatureGeneratorInterface $signatureGenerator */
$signatureGenerator = new $signatureGeneratorClass();
$signatureGenerator = new $signatureGeneratorClass;

return new DeduplicationHandler(
handler: $handler,
Expand Down
12 changes: 6 additions & 6 deletions src/Issues/Formatter.php
Original file line number Diff line number Diff line change
Expand Up @@ -93,7 +93,7 @@ private function formatTitle(LogRecord $record, ?Throwable $exception = null): s
private function formatContent(LogRecord $record, ?Throwable $exception): string
{
return Str::of('')
->when($record->message, fn($str, $message) => $str->append("**Message:**\n{$message}\n\n"))
->when($record->message, fn ($str, $message) => $str->append("**Message:**\n{$message}\n\n"))
->when(
$exception,
function (Stringable $str, Throwable $exception) {
Expand All @@ -103,8 +103,8 @@ function (Stringable $str, Throwable $exception) {
);
}
)
->when(! empty($record->context), fn($str, $context) => $str->append("**Context:**\n```json\n" . json_encode(Arr::except($record->context, ['exception']), JSON_PRETTY_PRINT) . "\n```\n\n"))
->when(! empty($record->extra), fn($str, $extra) => $str->append("**Extra Data:**\n```json\n" . json_encode($record->extra, JSON_PRETTY_PRINT) . "\n```\n"))
->when(! empty($record->context), fn ($str, $context) => $str->append("**Context:**\n```json\n".json_encode(Arr::except($record->context, ['exception']), JSON_PRETTY_PRINT)."\n```\n\n"))
->when(! empty($record->extra), fn ($str, $extra) => $str->append("**Extra Data:**\n```json\n".json_encode($record->extra, JSON_PRETTY_PRINT)."\n```\n"))
->toString();
}

Expand All @@ -124,7 +124,7 @@ private function formatBody(LogRecord $record, string $signature, ?Throwable $ex
private function cleanStackTrace(string $stackTrace): string
{
return collect(explode("\n", $stackTrace))
->filter(fn($line) => ! empty(trim($line)))
->filter(fn ($line) => ! empty(trim($line)))
->map(function ($line) {
if (trim($line) === '"}') {
return '';
Expand Down Expand Up @@ -200,8 +200,8 @@ private function formatExceptionDetails(Throwable $exception): array

return [
'message' => $exception->getMessage(),
'stack_trace' => $header . "\n[stacktrace]\n" . $this->cleanStackTrace($exception->getTraceAsString()),
'full_stack_trace' => $header . "\n[stacktrace]\n" . $exception->getTraceAsString(),
'stack_trace' => $header."\n[stacktrace]\n".$this->cleanStackTrace($exception->getTraceAsString()),
'full_stack_trace' => $header."\n[stacktrace]\n".$exception->getTraceAsString(),
];
}

Expand Down
10 changes: 5 additions & 5 deletions src/Issues/Handler.php
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@ public function __construct(
protected function write(LogRecord $record): void
{
if (! $record->formatted instanceof Formatted) {
throw new \RuntimeException('Record must be formatted with ' . Formatted::class);
throw new \RuntimeException('Record must be formatted with '.Formatted::class);
}

$formatted = $record->formatted;
Expand All @@ -64,11 +64,11 @@ private function findExistingIssue(LogRecord $record): ?array

$response = Http::withToken($this->token)
->get('https://api.github.com/search/issues', [
'q' => "repo:{$this->repo} is:issue is:open label:" . self::DEFAULT_LABEL . " \"Signature: {$record->extra['github_issue_signature']}\"",
'q' => "repo:{$this->repo} is:issue is:open label:".self::DEFAULT_LABEL." \"Signature: {$record->extra['github_issue_signature']}\"",
]);

if ($response->failed()) {
throw new \RuntimeException('Failed to search GitHub issues: ' . $response->body());
throw new \RuntimeException('Failed to search GitHub issues: '.$response->body());
}

return $response->json('items.0', null);
Expand All @@ -85,7 +85,7 @@ private function commentOnIssue(int $issueNumber, Formatted $formatted): void
]);

if ($response->failed()) {
throw new \RuntimeException('Failed to comment on GitHub issue: ' . $response->body());
throw new \RuntimeException('Failed to comment on GitHub issue: '.$response->body());
}
}

Expand All @@ -102,7 +102,7 @@ private function createIssue(Formatted $formatted): void
]);

if ($response->failed()) {
throw new \RuntimeException('Failed to create GitHub issue: ' . $response->body());
throw new \RuntimeException('Failed to create GitHub issue: '.$response->body());
}
}
}
13 changes: 7 additions & 6 deletions tests/Deduplication/DeduplicationHandlerTest.php
Original file line number Diff line number Diff line change
@@ -1,14 +1,15 @@
<?php

use Monolog\Handler\TestHandler;
use function Pest\Laravel\travel;
use Naoray\LaravelGithubMonolog\Deduplication\DeduplicationHandler;
use Naoray\LaravelGithubMonolog\Deduplication\Stores\FileStore;
use Naoray\LaravelGithubMonolog\Deduplication\DefaultSignatureGenerator;
use Naoray\LaravelGithubMonolog\Deduplication\Stores\FileStore;

use function Pest\Laravel\travel;

beforeEach(function () {
$this->testHandler = new TestHandler;
$this->tempFile = sys_get_temp_dir() . '/dedup-test-' . uniqid() . '.log';
$this->tempFile = sys_get_temp_dir().'/dedup-test-'.uniqid().'.log';
});

afterEach(function () {
Expand All @@ -20,7 +21,7 @@
$handler = new DeduplicationHandler(
handler: $this->testHandler,
store: $store,
signatureGenerator: new DefaultSignatureGenerator(),
signatureGenerator: new DefaultSignatureGenerator,
);

$record = createLogRecord();
Expand All @@ -41,7 +42,7 @@
$handler = new DeduplicationHandler(
handler: $this->testHandler,
store: $store,
signatureGenerator: new DefaultSignatureGenerator()
signatureGenerator: new DefaultSignatureGenerator
);

$record = createLogRecord();
Expand All @@ -57,7 +58,7 @@
$handler = new DeduplicationHandler(
handler: $this->testHandler,
store: $store,
signatureGenerator: new DefaultSignatureGenerator()
signatureGenerator: new DefaultSignatureGenerator
);

$record1 = createLogRecord('First message');
Expand Down
2 changes: 1 addition & 1 deletion tests/Deduplication/Stores/DatabaseStoreTest.php
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
<?php

use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;
use Naoray\LaravelGithubMonolog\Deduplication\Stores\DatabaseStore;

use function Pest\Laravel\travel;

beforeEach(function () {
Expand Down
1 change: 1 addition & 0 deletions tests/Deduplication/Stores/FileStoreTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

use Illuminate\Support\Facades\File;
use Naoray\LaravelGithubMonolog\Deduplication\Stores\FileStore;

use function Pest\Laravel\travel;

beforeEach(function () {
Expand Down
3 changes: 1 addition & 2 deletions tests/Deduplication/Stores/RedisStoreTest.php
Original file line number Diff line number Diff line change
@@ -1,9 +1,8 @@
<?php

use Illuminate\Support\Facades\Redis;
use Monolog\Level;
use Monolog\LogRecord;
use Naoray\LaravelGithubMonolog\Deduplication\Stores\RedisStore;

use function Pest\Laravel\travel;

beforeEach(function () {
Expand Down
23 changes: 13 additions & 10 deletions tests/GithubIssueHandlerFactoryTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,30 +2,33 @@

use Monolog\Level;
use Monolog\Logger;
use Naoray\LaravelGithubMonolog\Deduplication\DeduplicationHandler;
use Naoray\LaravelGithubMonolog\Deduplication\DefaultSignatureGenerator;
use Naoray\LaravelGithubMonolog\Deduplication\Stores\DatabaseStore;
use Naoray\LaravelGithubMonolog\Deduplication\Stores\FileStore;
use Naoray\LaravelGithubMonolog\Deduplication\Stores\RedisStore;
use Naoray\LaravelGithubMonolog\Issues\Formatter;
use Naoray\LaravelGithubMonolog\GithubIssueHandlerFactory;
use Naoray\LaravelGithubMonolog\Deduplication\DeduplicationHandler;
use Naoray\LaravelGithubMonolog\Issues\Formatter;
use Naoray\LaravelGithubMonolog\Issues\Handler;

function getWrappedHandler(DeduplicationHandler $handler): Handler
{
$reflection = new ReflectionProperty($handler, 'handler');

return $reflection->getValue($handler);
}

function getDeduplicationStore(DeduplicationHandler $handler): mixed
{
$reflection = new ReflectionProperty($handler, 'store');

return $reflection->getValue($handler);
}

function getSignatureGenerator(DeduplicationHandler $handler): mixed
{
$reflection = new ReflectionProperty($handler, 'signatureGenerator');

return $reflection->getValue($handler);
}

Expand All @@ -37,7 +40,7 @@ function getSignatureGenerator(DeduplicationHandler $handler): mixed
'labels' => ['test-label'],
];

$this->signatureGenerator = new DefaultSignatureGenerator();
$this->signatureGenerator = new DefaultSignatureGenerator;
$this->factory = new GithubIssueHandlerFactory($this->signatureGenerator);
});

Expand Down Expand Up @@ -66,9 +69,9 @@ function getSignatureGenerator(DeduplicationHandler $handler): mixed
});

test('it throws exception when required config is missing', function () {
expect(fn() => ($this->factory)([]))->toThrow(\InvalidArgumentException::class);
expect(fn() => ($this->factory)(['repo' => 'test/repo']))->toThrow(\InvalidArgumentException::class);
expect(fn() => ($this->factory)(['token' => 'test-token']))->toThrow(\InvalidArgumentException::class);
expect(fn () => ($this->factory)([]))->toThrow(\InvalidArgumentException::class);
expect(fn () => ($this->factory)(['repo' => 'test/repo']))->toThrow(\InvalidArgumentException::class);
expect(fn () => ($this->factory)(['token' => 'test-token']))->toThrow(\InvalidArgumentException::class);
});

test('it configures buffer settings correctly', function () {
Expand All @@ -89,7 +92,7 @@ function getSignatureGenerator(DeduplicationHandler $handler): mixed
});

test('it can use file store driver', function () {
$path = sys_get_temp_dir() . '/dedup-test-' . uniqid() . '.log';
$path = sys_get_temp_dir().'/dedup-test-'.uniqid().'.log';

$logger = ($this->factory)([
...$this->config,
Expand Down Expand Up @@ -142,7 +145,7 @@ function getSignatureGenerator(DeduplicationHandler $handler): mixed
});

test('it uses same signature generator across components', function () {
$factory = new GithubIssueHandlerFactory(new DefaultSignatureGenerator());
$factory = new GithubIssueHandlerFactory(new DefaultSignatureGenerator);
$logger = $factory([
'repo' => 'test/repo',
'token' => 'test-token',
Expand All @@ -161,14 +164,14 @@ function getSignatureGenerator(DeduplicationHandler $handler): mixed
});

test('it throws exception for invalid deduplication time', function () {
expect(fn() => ($this->factory)([
expect(fn () => ($this->factory)([
...$this->config,
'deduplication' => [
'time' => -1,
],
]))->toThrow(\InvalidArgumentException::class, 'Deduplication time must be a positive integer');

expect(fn() => ($this->factory)([
expect(fn () => ($this->factory)([
...$this->config,
'deduplication' => [
'time' => 'invalid',
Expand Down
Loading

0 comments on commit b2295ee

Please sign in to comment.