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

Add Rector to CI #133

Merged
merged 3 commits into from
Jul 22, 2024
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
67 changes: 67 additions & 0 deletions .github/workflows/refactoring.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
---

on: # yamllint disable-line rule:truthy
pull_request:
paths:
- 'src/**'
- 'tests/**'
- 'composer.*'
push:
paths:
- 'src/**'
- 'tests/**'
- 'composer.*'

name: ⚙️ Refactoring

jobs:
rector:
timeout-minutes: 4
runs-on: ${{ matrix.os }}
concurrency:
cancel-in-progress: true
group: rector-${{ github.workflow }}-${{ github.event.pull_request.number || github.ref }}
strategy:
fail-fast: true
matrix:
os:
- ubuntu-latest
php-version:
- '8.2'
dependencies:
- locked
steps:
- name: 📦 Check out the codebase
uses: actions/checkout@v4.1.7

- name: 🛠️ Setup PHP
uses: shivammathur/setup-php@2.30.4
with:
php-version: ${{ matrix.php-version }}
extensions: none, ctype, curl, dom, json, mbstring, phar, simplexml, tokenizer, xml, xmlwriter, sockets, opcache, pcntl, posix
ini-values: error_reporting=E_ALL
coverage: none

- name: 🛠️ Setup problem matchers
run: echo "::add-matcher::${{ runner.tool_cache }}/php.json"

- name: 🤖 Validate composer.json and composer.lock
run: composer validate --ansi --strict

- name: 🔍 Get composer cache directory
uses: wayofdev/gh-actions/actions/composer/get-cache-directory@v3.1.0

- name: ♻️ Restore cached dependencies installed with composer
uses: actions/cache@v4
with:
path: ${{ env.COMPOSER_CACHE_DIR }}
key: php-${{ matrix.php-version }}-composer-${{ matrix.dependencies }}-${{ hashFiles('composer.lock') }}
restore-keys: php-${{ matrix.php-version }}-composer-${{ matrix.dependencies }}-

- name: 📥 Install "${{ matrix.dependencies }}" dependencies
uses: wayofdev/gh-actions/actions/composer/install@v3.1.0
with:
dependencies: ${{ matrix.dependencies }}

- name: 🔍 Run static analysis using rector/rector
run: composer refactor:ci
4 changes: 2 additions & 2 deletions .github/workflows/static-analysis.yml
lotyp marked this conversation as resolved.
Show resolved Hide resolved
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,7 @@ jobs:
uses: wayofdev/gh-actions/actions/composer/get-cache-directory@v3.1.0

- name: ♻️ Restore cached dependencies installed with composer
uses: actions/cache@v4.0.2
uses: actions/cache@v4
with:
path: ${{ env.COMPOSER_CACHE_DIR }}
key: php-${{ matrix.php-version }}-composer-${{ matrix.dependencies }}-${{ hashFiles('composer.lock') }}
Expand Down Expand Up @@ -109,7 +109,7 @@ jobs:
uses: wayofdev/gh-actions/actions/composer/get-cache-directory@v3.1.0

- name: ♻️ Restore cached dependencies installed with composer
uses: actions/cache@v4.0.2
uses: actions/cache@v4
with:
path: ${{ env.COMPOSER_CACHE_DIR }}
key: php-${{ matrix.php-version }}-composer-${{ matrix.dependencies }}-${{ hashFiles('composer.lock') }}
Expand Down
2 changes: 1 addition & 1 deletion .php-cs-fixer.dist.php
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@
->exclude([
__DIR__ . '/src/Test/Proto',
])
->addFiles([__FILE__])
->addFiles([__FILE__, __DIR__ . '/rector.php'])
->getConfig();

$config->setCacheFile(__DIR__ . '/.build/php-cs-fixer/php-cs-fixer.cache');
Expand Down
1 change: 1 addition & 0 deletions composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -67,6 +67,7 @@
"phpstan/phpstan-phpunit": "^1.3",
"phpstan/phpstan-strict-rules": "^1.5",
"phpunit/phpunit": "^10.5",
"rector/rector": "^1.1",
"roxblnfk/unpoly": "^1.8.1",
"vimeo/psalm": "^5.11",
"wayofdev/cs-fixer-config": "^1.4"
Expand Down
63 changes: 61 additions & 2 deletions composer.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

54 changes: 54 additions & 0 deletions rector.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
<?php

declare(strict_types=1);

use Rector\CodeQuality\Rector\ClassMethod\InlineArrayReturnAssignRector;
use Rector\CodeQuality\Rector\Expression\InlineIfToExplicitIfRector;
use Rector\CodeQuality\Rector\Identical\FlipTypeControlToUseExclusiveTypeRector;
use Rector\CodeQuality\Rector\LogicalAnd\LogicalToBooleanRector;
use Rector\CodingStyle\Rector\Encapsed\EncapsedStringsToSprintfRector;
use Rector\CodingStyle\Rector\PostInc\PostIncDecToPreIncDecRector;
use Rector\Config\RectorConfig;
use Rector\Php81\Rector\FuncCall\NullToStrictStringFuncCallArgRector;
use Rector\Strict\Rector\Empty_\DisallowedEmptyRuleFixerRector;
use Rector\TypeDeclaration\Rector\BooleanAnd\BinaryOpNullableToInstanceofRector;
use Rector\ValueObject\PhpVersion;

return RectorConfig::configure()
->withPaths([
// let's add more directories step by step
// __DIR__ . '/src',
// __DIR__ . '/tests',
// __DIR__ . '/bin',
__DIR__ . '/src/Client',
])
->withSkipPath('src/Client/TrapHandle/ContextProvider/Source.php')
->withPHPStanConfigs([
__DIR__ . '/phpstan-baseline.neon',
])
->withImportNames(importNames: false, importDocBlockNames: true, importShortClasses: false, removeUnusedImports: true)
->withPhpVersion(PhpVersion::PHP_81)
->withPhpSets(php81: true)
->withPreparedSets(
deadCode: false,
codeQuality: true,
codingStyle: true,
typeDeclarations: true,
privatization: true,
naming: false,
instanceOf: true,
earlyReturn: true,
strictBooleans: true,
carbon: false,
rectorPreset: true,
)->withSkip([
InlineArrayReturnAssignRector::class,
PostIncDecToPreIncDecRector::class,
InlineIfToExplicitIfRector::class,
LogicalToBooleanRector::class,
BinaryOpNullableToInstanceofRector::class,
FlipTypeControlToUseExclusiveTypeRector::class,
DisallowedEmptyRuleFixerRector::class,
NullToStrictStringFuncCallArgRector::class,
EncapsedStringsToSprintfRector::class,
]);
9 changes: 6 additions & 3 deletions src/Client/Caster/ProtobufCaster.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,9 @@

namespace Buggregator\Trap\Client\Caster;

use Google\Protobuf\Internal\FieldDescriptor;
use Google\Protobuf\Internal\EnumDescriptor;
use Google\Protobuf\Internal\EnumValueDescriptorProto;
use Google\Protobuf\Descriptor as PublicDescriptor;
use Google\Protobuf\Internal\Descriptor as InternalDescriptor;
use Google\Protobuf\Internal\DescriptorPool;
Expand Down Expand Up @@ -118,7 +121,7 @@ private static function extractViaInternal(Message $message, InternalDescriptor
$values = [];

for ($i = 0; $i < $pub->getFieldCount(); $i++) {
/** @var \Google\Protobuf\Internal\FieldDescriptor $fd */
/** @var FieldDescriptor $fd */
$fd = $descriptor->getFieldByIndex($i);
$value = $message->{$fd->getGetter()}();

Expand Down Expand Up @@ -150,9 +153,9 @@ private static function extractViaInternal(Message $message, InternalDescriptor

// Wrap ENUM
if ($fd->getType() === GPBType::ENUM) {
/** @var \Google\Protobuf\Internal\EnumDescriptor $ed */
/** @var EnumDescriptor $ed */
$ed = $fd->getEnumType();
/** @var \Google\Protobuf\Internal\EnumValueDescriptorProto $v */
/** @var EnumValueDescriptorProto $v */
$v = $ed->getValueByNumber($value);

$values[$fd->getName()] = new EnumValue(
Expand Down
2 changes: 1 addition & 1 deletion src/Client/Caster/Trace.php
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@
* @see tr()
* @internal
*/
final class Trace
final class Trace implements \Stringable
{
/**
* @param int<0, max> $number The tick number.
Expand Down
2 changes: 1 addition & 1 deletion src/Client/Caster/TraceFile.php
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
/**
* @internal
*/
final class TraceFile
final class TraceFile implements \Stringable
{
/**
* @param array{
Expand Down
6 changes: 2 additions & 4 deletions src/Client/TrapHandle.php
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ final class TrapHandle

private int $depth = 0;

private StaticState $staticState;
private readonly StaticState $staticState;

private function __construct(
private array $values,
Expand Down Expand Up @@ -139,7 +139,7 @@ public function once(): self
*/
public function return(int|string $key = 0): mixed
{
if (\count($this->values) === 0) {
if ($this->values === []) {
throw new \InvalidArgumentException('No values to return.');
}

Expand Down Expand Up @@ -176,8 +176,6 @@ 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
{
Expand Down
26 changes: 7 additions & 19 deletions src/Client/TrapHandle/ContextProvider/Source.php
Original file line number Diff line number Diff line change
Expand Up @@ -27,24 +27,10 @@
*/
final class Source implements ContextProviderInterface
{
private int $limit;

private ?string $charset;

private ?string $projectDir;

private ?FileLinkFormatter $fileLinkFormatter;

/**
* @psalm-suppress UndefinedClass
*/
public function __construct(string $charset = null, string $projectDir = null, FileLinkFormatter $fileLinkFormatter = null, int $limit = 9)
{
$this->charset = $charset;
$this->projectDir = $projectDir;
$this->fileLinkFormatter = $fileLinkFormatter;
$this->limit = $limit;
}
public function __construct(private readonly ?string $charset = null, private ?string $projectDir = null, private readonly ?FileLinkFormatter $fileLinkFormatter = null, private readonly int $limit = 9) {}

public function getContext(): ?array
{
Expand Down Expand Up @@ -80,7 +66,7 @@ public function getContext(): ?array
$file = \method_exists($template, 'getSourceContext') ? $template->getSourceContext()->getPath() : null;

if ($src) {
$src = \explode("\n", $src);
$src = \explode("\n", (string) $src);
$fileExcerpt = [];

for ($i = \max($line - 3, 1), $max = \min($line + 3, \count($src)); $i <= $max; ++$i) {
Expand All @@ -90,9 +76,11 @@ public function getContext(): ?array
$fileExcerpt = '<ol start="' . \max($line - 3, 1) . '">' . \implode("\n", $fileExcerpt) . '</ol>';
}
}

break;
}
}

break;
}
}
Expand All @@ -107,8 +95,8 @@ public function getContext(): ?array

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);
if (\str_starts_with((string) $file, $this->projectDir)) {
$context['file_relative'] = \ltrim(\substr((string) $file, \strlen($this->projectDir)), \DIRECTORY_SEPARATOR);
}
}

Expand All @@ -123,7 +111,7 @@ private function htmlEncode(string $s): string
{
$html = '';

$dumper = new HtmlDumper(static function ($line) use (&$html): void { $html .= $line; }, $this->charset);
$dumper = new HtmlDumper(static function (string $line) use (&$html): void { $html .= $line; }, $this->charset);
$dumper->setDumpHeader('');
$dumper->setDumpBoundaries('', '');

Expand Down
Loading