Skip to content

Commit

Permalink
Merge pull request #36 from evgenij-vy/confi-dir-v2
Browse files Browse the repository at this point in the history
Add configuration reader and configuration dir argument
  • Loading branch information
Aeliot-Tm authored Oct 4, 2024
2 parents 41b2518 + 549b935 commit 96ab7c1
Show file tree
Hide file tree
Showing 8 changed files with 179 additions and 49 deletions.
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -109,6 +109,7 @@ in different environments.
| a | absolute | Store absolute paths in baseline file. It does not expect any value. | |
| b | baseline | Pathname of baseline file. | .php-cs-fixer-baseline.json |
| c | config | Pathname of config file. | .php-cs-fixer.dist.php |
| d | config-dir| Config files path | '' |
| f | finder | Pathname of file with definition of Finder. | .php-cs-fixer-finder.php |
| w | workdir | Working directory. | |

Expand Down
51 changes: 2 additions & 49 deletions bin/pcsf-baseline
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ declare(strict_types=1);
use Aeliot\PhpCsFixerBaseline\Model\BuilderConfig;
use Aeliot\PhpCsFixerBaseline\Service\Builder;
use Aeliot\PhpCsFixerBaseline\Service\Saver;
use Aeliot\PhpCsFixerBaseline\Service\ConsoleOptionsReader;

$autoloaderPath = (static function (): string {
if (Phar::running()) {
Expand Down Expand Up @@ -43,55 +44,7 @@ $autoloaderPath = (static function (): string {

require_once $autoloaderPath;

$absolutePathMaker = static function (string $path): string {
if (preg_match('#^(?:[[:alpha:]]:[/\\\\]|/)#', $path)) {
return $path;
}

return getcwd() . '/' . $path;
};

$options = (static function () use ($absolutePathMaker): array {
$values = [];
$options = getopt('ab:c:f:w:', ['absolute', 'baseline:', 'config:', 'finder:', 'workdir:']);
$defaultPaths = [
'.php-cs-fixer-baseline.json' => ['b', 'baseline'],
'.php-cs-fixer.dist.php' => ['c', 'config'],
'.php-cs-fixer-finder.php' => ['f', 'finder'],
];

foreach ($defaultPaths as $default => [$short, $long]) {
if (isset($options['b'], $options['baseline'])) {
throw new InvalidArgumentException(sprintf('%s is duplicated', $long));
}
$values[$long] = $absolutePathMaker($options[$short] ?? $options[$long] ?? $default);
}

$values += [
'relative' => !(isset($options['a']) || isset($options['absolute'])),
'workdir' => $options['w'] ?? $options['workdir'] ?? null,
];

if ($values['workdir']) {
if (!$values['relative']) {
throw new InvalidArgumentException('Both options "absolute" and "workdir" are passed');
}
if (!is_dir($values['workdir'])) {
throw new InvalidArgumentException('Value of the option "workdir" is not directory');
}
}

return $values;
})();

$config = $options;
$config['baselinePath'] = $options['baseline'];
unset($config['baseline']);
// NOTE: enclose the including of files into functions to avoid conflict of variables
$config['config'] = (static fn () => require $options['config'])();
$config['finder'] = (static fn () => require $options['finder'])();

$baseline = (new Builder())->create(new BuilderConfig($config));
$baseline = (new Builder())->create(new BuilderConfig((new ConsoleOptionsReader())->getAsArray()));
(new Saver())->save($baseline);

echo sprintf("Ok, %s files added to baseline\n", $baseline->getLockedFilesCount());
Empty file modified docker-entrypoint.sh
100644 → 100755
Empty file.
104 changes: 104 additions & 0 deletions src/Service/ConsoleOptionsReader.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,104 @@
<?php

declare(strict_types=1);

/*
* This file is part of the box project.
*
* (c) Anatoliy Melnikov <[email protected]>
*
* This source file is subject to the MIT license that is bundled
* with this source code in the file LICENSE.
*/

namespace Aeliot\PhpCsFixerBaseline\Service;

use PhpCsFixer\Config;
use PhpCsFixer\ConfigInterface;
use PhpCsFixer\Finder;

final class ConsoleOptionsReader
{
private string $rootDirectory;

/** @var array<string, string> */
private array $option;

public function __construct()
{
$this->option = getopt(
'ab:c:d:f:w:',
['absolute', 'baseline:', 'config:', 'config-dir:', 'finder:', 'workdir:']
);
$this->rootDirectory = $this->getOptionValue('d','config-dir', '');
}

/**
* @return array{
* baselinePath: string,
* config: Config|ConfigInterface,
* finder: Finder,
* relative?: bool,
* workdir?: string|null
* }
*/
public function getAsArray(): array
{
return [
'baselinePath' => $this->getBaselinePath(),
'config' => $this->getConfig(),
'finder' => $this->getFinder(),
'relative' => $this->getRelative(),
'workdir' => $this->getWorkdir(),
];
}

private function getBaselinePath(): string
{
return $this->getAbsolutePath($this->getOptionValue('b', 'baseline', '.php-cs-fixer-baseline.json'));
}

private function getConfig(): Config
{
$configPath = $this->getAbsolutePath($this->getOptionValue('c', 'config', '.php-cs-fixer.dist.php'));

return require $configPath;
}

private function getFinder(): Finder
{
$finderPath = $this->getAbsolutePath($this->getOptionValue('f', 'finder', '.php-cs-fixer-finder.php'));

return require $finderPath;
}

private function getWorkdir(): ?string
{
return $this->getOptionValue('w', 'workdir', null);
}

private function getRelative(): ?bool

Check failure on line 80 in src/Service/ConsoleOptionsReader.php

View workflow job for this annotation

GitHub Actions / Static analyze with PHPStan

Method Aeliot\PhpCsFixerBaseline\Service\ConsoleOptionsReader::getRelative() never returns null so it can be removed from the return type.

Check failure on line 80 in src/Service/ConsoleOptionsReader.php

View workflow job for this annotation

GitHub Actions / Static analyze with PHPStan

Method Aeliot\PhpCsFixerBaseline\Service\ConsoleOptionsReader::getRelative() never returns null so it can be removed from the return type.
{
return !$this->getOptionValue('a', 'relative', false);
}

private function getAbsolutePath(string $path): string
{
$path = $this->rootDirectory . $path;

if (preg_match('#^(?:[[:alpha:]]:[/\\\\]|/)#', $path)) {
return $path;
}

return getcwd() . '/' . $path;
}

private function getOptionValue(string $short, string $long, bool|null|string $default): bool|null|string
{
if (\array_key_exists($short, $this->option) && \array_key_exists($long, $this->option)) {
throw new \InvalidArgumentException(sprintf('%s is duplicated', $long));
}

return $this->option[$short] ?? $this->option[$long] ?? $default;
}
}
25 changes: 25 additions & 0 deletions tests/Unit/Functional/CommandLineTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
<?php

declare(strict_types=1);

namespace Aeliot\PhpCsFixerBaseline\Test\Unit\Functional;

use PHPUnit\Framework\Attributes\CoversNothing;
use PHPUnit\Framework\TestCase;

#[CoversNothing]
final class CommandLineTest extends TestCase
{
public function testCommandLine(): void
{
$baselinePath = __DIR__ . '/../../config/.php-cs-fixer-baseline.json';

if (file_exists($baselinePath)) {
unlink($baselinePath);
}

shell_exec('php bin/pcsf-baseline -d tests/config/');

self::assertFileExists($baselinePath);
}
}
9 changes: 9 additions & 0 deletions tests/config/.php-cs-fixer-baseline.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
{
"config_hash": 309824811,
"relative": true,
"hashes": {
"tests\/fixtures\/file-for-calculation-of-hash.php": {
"hash": 4266623405
}
}
}
11 changes: 11 additions & 0 deletions tests/config/.php-cs-fixer-finder.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
<?php

declare(strict_types=1);

return $finder = (new PhpCsFixer\Finder())
->files()
->name('file-for-calculation-of-hash.php')
->in(__DIR__ . '/../fixtures/');



27 changes: 27 additions & 0 deletions tests/config/.php-cs-fixer.dist.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
<?php

use Aeliot\PhpCsFixerBaseline\Service\FilterFactory;

$rules = [
'header_comment' => [
'header' => <<<'EOF'
This file is part of the box project.
(c) Anatoliy Melnikov <[email protected]>
This source file is subject to the MIT license that is bundled
with this source code in the file LICENSE.
EOF,
],
'phpdoc_align' => ['align' => 'left'],
];

$config = (new PhpCsFixer\Config())
->setRiskyAllowed(true)
->setRules($rules);

/** @var PhpCsFixer\Finder $finder */
$finder = require __DIR__ . '/.php-cs-fixer-finder.php';
$finder->filter((new FilterFactory())->createFilter(__DIR__ . '/.php-cs-fixer-baseline.json', $config));

return $config->setFinder($finder);

0 comments on commit 96ab7c1

Please sign in to comment.