Skip to content

Commit

Permalink
Enhanced code style (#113)
Browse files Browse the repository at this point in the history
* Forbid yoda style condition

* Enforce maximum line length

* Enforce trailing slash on native functions invocation
  • Loading branch information
yann-eugone authored Jan 8, 2024
1 parent 8b20bdc commit f6f6826
Show file tree
Hide file tree
Showing 59 changed files with 247 additions and 192 deletions.
15 changes: 15 additions & 0 deletions ecs.php
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,13 @@
declare(strict_types=1);

use PHP_CodeSniffer\Standards\Generic\Sniffs\PHP\ForbiddenFunctionsSniff;
use PhpCsFixer\Fixer\ControlStructure\YodaStyleFixer;
use PhpCsFixer\Fixer\FunctionNotation\FunctionDeclarationFixer;
use PhpCsFixer\Fixer\FunctionNotation\NativeFunctionInvocationFixer;
use Symplify\CodingStandard\Fixer\ArrayNotation\ArrayListItemNewlineFixer;
use Symplify\CodingStandard\Fixer\ArrayNotation\ArrayOpenerAndCloserNewlineFixer;
use Symplify\CodingStandard\Fixer\ArrayNotation\StandaloneLineInMultilineArrayFixer;
use Symplify\CodingStandard\Fixer\LineLength\LineLengthFixer;
use Symplify\EasyCodingStandard\Config\ECSConfig;
use Symplify\EasyCodingStandard\ValueObject\Set\SetList;

Expand Down Expand Up @@ -35,10 +38,22 @@
StandaloneLineInMultilineArrayFixer::class,
]);

$ecsConfig->ruleWithConfiguration(YodaStyleFixer::class, [
'equal' => false,
'identical' => false,
'less_and_greater' => false,
]);
$ecsConfig->ruleWithConfiguration(LineLengthFixer::class, [
LineLengthFixer::INLINE_SHORT_LINES => false,
]);
$ecsConfig->ruleWithConfiguration(ForbiddenFunctionsSniff::class, [
'forbiddenFunctions' => ['dump' => null, 'dd' => null, 'var_dump' => null, 'die' => null],
]);
$ecsConfig->ruleWithConfiguration(FunctionDeclarationFixer::class, [
'closure_fn_spacing' => 'none',
]);
$ecsConfig->ruleWithConfiguration(NativeFunctionInvocationFixer::class, [
'scope' => 'namespaced',
'include' => ['@all'],
]);
};
20 changes: 10 additions & 10 deletions src/batch-doctrine-dbal/src/DoctrineDBALJobExecutionStorage.php
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@ final class DoctrineDBALJobExecutionStorage implements
*/
public function __construct(ConnectionRegistry $doctrine, array $options)
{
$options = array_filter($options) + self::DEFAULT_OPTIONS;
$options = \array_filter($options) + self::DEFAULT_OPTIONS;
$options['connection'] ??= $doctrine->getDefaultConnectionName();

$this->table = $options['table'];
Expand All @@ -64,26 +64,26 @@ public function setup(): void
fn(string $tableName) => $tableName === $this->table,
);

$schemaManager = method_exists($this->connection, 'createSchemaManager')
$schemaManager = \method_exists($this->connection, 'createSchemaManager')
? $this->connection->createSchemaManager()
: $this->connection->getSchemaManager();
$comparator = method_exists($schemaManager, 'createComparator')
$comparator = \method_exists($schemaManager, 'createComparator')
? $schemaManager->createComparator()
: new Comparator();
$fromSchema = method_exists($schemaManager, 'introspectSchema')
$fromSchema = \method_exists($schemaManager, 'introspectSchema')
? $schemaManager->introspectSchema()
: $schemaManager->createSchema();
$toSchema = $this->getSchema();
$schemaDiff = method_exists($comparator, 'compareSchemas')
$schemaDiff = \method_exists($comparator, 'compareSchemas')
? $comparator->compareSchemas($fromSchema, $toSchema)
: $comparator->compare($fromSchema, $toSchema);
$platform = $this->connection->getDatabasePlatform();
$schemaDiffQueries = method_exists($platform, 'getAlterSchemaSQL')
$schemaDiffQueries = \method_exists($platform, 'getAlterSchemaSQL')
? $platform->getAlterSchemaSQL($schemaDiff)
: $schemaDiff->toSaveSql($platform);

foreach ($schemaDiffQueries as $sql) {
if (method_exists($this->connection, 'executeStatement')) {
if (\method_exists($this->connection, 'executeStatement')) {
$this->connection->executeStatement($sql);
} else {
$this->connection->exec($sql);
Expand Down Expand Up @@ -155,21 +155,21 @@ public function query(Query $query): iterable
->from($this->table);

$names = $query->jobs();
if (count($names) > 0) {
if (\count($names) > 0) {
$qb->andWhere($qb->expr()->in('job_name', ':jobNames'));
$queryParameters['jobNames'] = $names;
$queryTypes['jobNames'] = Connection::PARAM_STR_ARRAY;
}

$ids = $query->ids();
if (count($ids) > 0) {
if (\count($ids) > 0) {
$qb->andWhere($qb->expr()->in('id', ':ids'));
$queryParameters['ids'] = $ids;
$queryTypes['ids'] = Connection::PARAM_STR_ARRAY;
}

$statuses = $query->statuses();
if (count($statuses) > 0) {
if (\count($statuses) > 0) {
$qb->andWhere($qb->expr()->in('status', ':statuses'));
$queryParameters['statuses'] = $statuses;
$queryTypes['statuses'] = Connection::PARAM_INT_ARRAY;
Expand Down
26 changes: 13 additions & 13 deletions src/batch-doctrine-dbal/src/JobExecutionRowNormalizer.php
Original file line number Diff line number Diff line change
Expand Up @@ -37,13 +37,13 @@ public function toRow(JobExecution $jobExecution): array
'id' => $jobExecution->getId(),
'job_name' => $jobExecution->getJobName(),
'status' => $jobExecution->getStatus()->getValue(),
'parameters' => iterator_to_array($jobExecution->getParameters()),
'parameters' => \iterator_to_array($jobExecution->getParameters()),
'start_time' => $jobExecution->getStartTime(),
'end_time' => $jobExecution->getEndTime(),
'summary' => $jobExecution->getSummary()->all(),
'failures' => array_map([$this, 'failureToArray'], $jobExecution->getFailures()),
'warnings' => array_map([$this, 'warningToArray'], $jobExecution->getWarnings()),
'child_executions' => array_map([$this, 'toChildRow'], $jobExecution->getChildExecutions()),
'failures' => \array_map([$this, 'failureToArray'], $jobExecution->getFailures()),
'warnings' => \array_map([$this, 'warningToArray'], $jobExecution->getWarnings()),
'child_executions' => \array_map([$this, 'toChildRow'], $jobExecution->getChildExecutions()),
'logs' => $jobExecution->getParentExecution() === null ? (string)$jobExecution->getLogs() : null,
];
}
Expand All @@ -55,15 +55,15 @@ public function toRow(JobExecution $jobExecution): array
*/
public function fromRow(array $data, JobExecution $parent = null): JobExecution
{
$data['status'] = intval($data['status']);
$data['status'] = \intval($data['status']);
$data['parameters'] = $this->jsonFromString($data['parameters']);
$data['summary'] = $this->jsonFromString($data['summary']);
$data['failures'] = $this->jsonFromString($data['failures']);
$data['warnings'] = $this->jsonFromString($data['warnings']);
$data['child_executions'] = $this->jsonFromString($data['child_executions']);

$name = $data['job_name'];
$status = new BatchStatus(intval($data['status']));
$status = new BatchStatus(\intval($data['status']));
$parameters = new JobParameters($data['parameters']);
$summary = new Summary($data['summary']);

Expand Down Expand Up @@ -106,13 +106,13 @@ private function toChildRow(JobExecution $jobExecution): array
return [
'job_name' => $jobExecution->getJobName(),
'status' => $jobExecution->getStatus()->getValue(),
'parameters' => iterator_to_array($jobExecution->getParameters()),
'parameters' => \iterator_to_array($jobExecution->getParameters()),
'start_time' => $this->toDateString($jobExecution->getStartTime()),
'end_time' => $this->toDateString($jobExecution->getEndTime()),
'summary' => $jobExecution->getSummary()->all(),
'failures' => array_map([$this, 'failureToArray'], $jobExecution->getFailures()),
'warnings' => array_map([$this, 'warningToArray'], $jobExecution->getWarnings()),
'child_executions' => array_map([$this, 'toChildRow'], $jobExecution->getChildExecutions()),
'failures' => \array_map([$this, 'failureToArray'], $jobExecution->getFailures()),
'warnings' => \array_map([$this, 'warningToArray'], $jobExecution->getWarnings()),
'child_executions' => \array_map([$this, 'toChildRow'], $jobExecution->getChildExecutions()),
];
}

Expand All @@ -123,11 +123,11 @@ private function toChildRow(JobExecution $jobExecution): array
*/
private function jsonFromString(array|string $value): array
{
if (is_string($value)) {
$value = json_decode($value, true, 512, JSON_THROW_ON_ERROR);
if (\is_string($value)) {
$value = \json_decode($value, true, 512, JSON_THROW_ON_ERROR);
}

if (!is_array($value)) {
if (!\is_array($value)) {
throw UnexpectedValueException::type('array', $value);
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,7 @@ public function testCreateStandardTable(): void
'child_executions',
'logs',
],
array_keys($columns)
\array_keys($columns)
);
}

Expand All @@ -81,7 +81,7 @@ public function testCreateCustomTable(): void
'child_executions',
'logs',
],
array_keys($columns)
\array_keys($columns)
);
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ public function getConnection($name = null)
return $this->connection;
}

throw new InvalidArgumentException(sprintf('Doctrine Connection named "%s" does not exist.', $name));
throw new InvalidArgumentException(\sprintf('Doctrine Connection named "%s" does not exist.', $name));
}

public function getConnections()
Expand Down
8 changes: 4 additions & 4 deletions src/batch-doctrine-persistence/src/ObjectRegistry.php
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@ function ($repository) use ($criteria) {

return $repository->findOneBy($criteria);
},
serialize($criteria)
\serialize($criteria)
);
}

Expand All @@ -62,11 +62,11 @@ public function findOneUsing(string $class, \Closure $closure, string $key = nul
{
$manager = $this->doctrine->getManagerForClass($class);
if ($manager === null) {
throw new InvalidArgumentException(sprintf('Class "%s" is not a managed Doctrine entity.', $class));
throw new InvalidArgumentException(\sprintf('Class "%s" is not a managed Doctrine entity.', $class));
}

$key ??= spl_object_hash($closure);
$key = md5($key);
$key ??= \spl_object_hash($closure);
$key = \md5($key);

$identity = $this->identities[$class][$key] ?? null;
if ($identity !== null) {
Expand Down
6 changes: 3 additions & 3 deletions src/batch-doctrine-persistence/src/ObjectWriter.php
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ public function __construct(
public function write(iterable $items): void
{
foreach ($items as $item) {
if (!is_object($item)) {
if (!\is_object($item)) {
throw $this->createInvalidItemException($item);
}

Expand Down Expand Up @@ -62,15 +62,15 @@ private function getManagerForClass(object $item): ObjectManager
$this->managerForClass[$class] = $manager;
}

$this->encounteredManagers[spl_object_id($manager)] = $manager;
$this->encounteredManagers[\spl_object_id($manager)] = $manager;

return $manager;
}

private function createInvalidItemException(mixed $item): InvalidArgumentException
{
return new InvalidArgumentException(
sprintf('Items to write must be object managed by Doctrine. Got "%s".', get_debug_type($item))
\sprintf('Items to write must be object managed by Doctrine. Got "%s".', \get_debug_type($item))
);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,8 @@ public function __construct(

public function getRepository(EntityManagerInterface $entityManager, $entityName): ObjectRepository
{
return $this->repositories[$entityName] ??= new $this->class($this->decorated->getRepository($entityManager, $entityName));
return $this->repositories[$entityName] ??= new $this->class(
$this->decorated->getRepository($entityManager, $entityName)
);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@ public function findOneBy(array $criteria)
return null;
}

$this->ensureNotCalledAlready(__FUNCTION__, func_get_args());
$this->ensureNotCalledAlready(__FUNCTION__, \func_get_args());

return $result;
}
Expand All @@ -49,7 +49,7 @@ public function getClassName()

private function ensureNotCalledAlready(string $method, array $args): void
{
$key = md5($method . $serializedArgs = serialize($args));
$key = \md5($method . $serializedArgs = \serialize($args));
if (isset($this->calls[$key])) {
throw new \LogicException(
'Method ' . $method . ' with args ' . $serializedArgs . ' has already been called'
Expand Down
9 changes: 7 additions & 2 deletions src/batch-doctrine-persistence/tests/ObjectRegistryTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -59,7 +59,10 @@ public function testFindOneBy(): void
self::assertSame($this->lucy, $registry->findOneBy(User::class, ['name' => 'Lucy']));
self::assertNull($registry->findOneBy(User::class, ['name' => 'John']));

self::assertSame($this->galaxyExplorer, $registry->findOneBy(Product::class, ['name' => 'Galaxy Explorer']));
self::assertSame(
$this->galaxyExplorer,
$registry->findOneBy(Product::class, ['name' => 'Galaxy Explorer'])
);
self::assertSame($this->boutiqueHotel, $registry->findOneBy(Product::class, ['name' => 'Boutique Hotel']));
self::assertNull($registry->findOneBy(Product::class, ['name' => 'Haunted House']));
}
Expand Down Expand Up @@ -115,7 +118,9 @@ public function testReset(): void
// But here in the test, it is not possible to call the repository more than once
// Hence, if we call reset after using the registry at least once, the repository will fail
$this->expectException(\LogicException::class);
$this->expectExceptionMessage('Method findOneBy with args a:1:{i:0;a:1:{s:4:"name";s:5:"Emmet";}} has already been called');
$this->expectExceptionMessage(
'Method findOneBy with args a:1:{i:0;a:1:{s:4:"name";s:5:"Emmet";}} has already been called'
);

$registry = new ObjectRegistry($this->doctrine);

Expand Down
8 changes: 4 additions & 4 deletions src/batch-openspout/src/Reader/FlatFileReader.php
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,7 @@ public function read(): iterable
{
/** @var string $path */
$path = $this->filePath->get($this->jobExecution);
$extension = strtolower(pathinfo($path, PATHINFO_EXTENSION));
$extension = \strtolower(\pathinfo($path, PATHINFO_EXTENSION));
$reader = match ($extension) {
'csv' => new CSVReader($this->options),
'xlsx' => new XLSXReader($this->options),
Expand All @@ -70,11 +70,11 @@ public function read(): iterable
} catch (InvalidRowSizeException $exception) {
$this->jobExecution->addWarning(
new Warning(
sprintf(
\sprintf(
'Expecting row %s to have exactly %d columns(s), but got %d.',
$rowIndex,
count($exception->getHeaders()),
count($exception->getRow()),
\count($exception->getHeaders()),
\count($exception->getRow()),
),
[],
['headers' => $exception->getHeaders(), 'row' => $exception->getRow()]
Expand Down
2 changes: 1 addition & 1 deletion src/batch-openspout/src/Reader/HeaderStrategy.php
Original file line number Diff line number Diff line change
Expand Up @@ -89,7 +89,7 @@ public function getItem(array $row): array

try {
/** @var array<string, string> $combined */
$combined = @array_combine($this->headers, $row);
$combined = @\array_combine($this->headers, $row);
} catch (\ValueError) {
throw new InvalidRowSizeException($this->headers, $row);
}
Expand Down
2 changes: 1 addition & 1 deletion src/batch-openspout/src/Writer/FlatFileWriter.php
Original file line number Diff line number Diff line change
Expand Up @@ -59,7 +59,7 @@ public function initialize(): void
throw new RuntimeException(\sprintf('Cannot create dir "%s".', $dir));
}

$extension = strtolower(pathinfo($path, PATHINFO_EXTENSION));
$extension = \strtolower(\pathinfo($path, PATHINFO_EXTENSION));
$this->writer = match ($extension) {
'csv' => new CSVWriter($this->options),
'xlsx' => new XLSXWriter($this->options),
Expand Down
6 changes: 3 additions & 3 deletions src/batch-openspout/tests/Reader/FlatFileReaderTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@ public function testRead(
/** @var \Iterator $got */
$got = $reader->read();
self::assertInstanceOf(\Iterator::class, $got);
self::assertSame($expected, iterator_to_array($got));
self::assertSame($expected, \iterator_to_array($got));
}

public function sets(): Generator
Expand Down Expand Up @@ -206,7 +206,7 @@ public function testReadWrongLineSize(): void
['firstName' => 'John', 'lastName' => 'Doe'],
['firstName' => 'Jack', 'lastName' => 'Doe'],
],
iterator_to_array($result)
\iterator_to_array($result)
);

self::assertSame(
Expand All @@ -230,7 +230,7 @@ public function testWrongOptions(string $file, object $options): void
$reader = new FlatFileReader(new StaticValueParameterAccessor($file), $options);
$reader->setJobExecution($jobExecution);

iterator_to_array($reader->read());
\iterator_to_array($reader->read());
}

public function wrongOptions(): \Generator
Expand Down
Loading

0 comments on commit f6f6826

Please sign in to comment.