Skip to content

Commit

Permalink
minor #1450 housekeeping - add rector rules - one step closer to stat…
Browse files Browse the repository at this point in the history
…ic analysis
  • Loading branch information
jrushlow authored Feb 21, 2024
1 parent c953816 commit 122bd8a
Show file tree
Hide file tree
Showing 20 changed files with 64 additions and 125 deletions.
2 changes: 1 addition & 1 deletion src/Command/MakerCommand.php
Original file line number Diff line number Diff line change
Expand Up @@ -86,7 +86,7 @@ protected function interact(InputInterface $input, OutputInterface $output): voi
continue;
}

$value = $this->io->ask($argument->getDescription(), $argument->getDefault(), [Validator::class, 'notBlank']);
$value = $this->io->ask($argument->getDescription(), $argument->getDefault(), Validator::notBlank(...));
$input->setArgument($argument->getName(), $value);
}

Expand Down
2 changes: 1 addition & 1 deletion src/Docker/DockerDatabaseServices.php
Original file line number Diff line number Diff line change
Expand Up @@ -99,7 +99,7 @@ public static function getMissingExtensionName(string $name): ?string
/**
* @throws RuntimeCommandException
*/
private static function throwInvalidDatabase(string $name): void
private static function throwInvalidDatabase(string $name): never
{
throw new RuntimeCommandException(sprintf('%s is not a valid / supported docker database type.', $name));
}
Expand Down
27 changes: 7 additions & 20 deletions src/Doctrine/EntityRegenerator.php
Original file line number Diff line number Diff line change
Expand Up @@ -116,26 +116,13 @@ public function regenerateEntities(string $classOrNamespace): void
continue;
}

switch ($mapping['type']) {
case ClassMetadata::MANY_TO_ONE:
$manipulator->addManyToOneRelation(RelationManyToOne::createFromObject($mapping));

break;
case ClassMetadata::ONE_TO_MANY:
$manipulator->addOneToManyRelation(RelationOneToMany::createFromObject($mapping));

break;
case ClassMetadata::MANY_TO_MANY:
$manipulator->addManyToManyRelation(RelationManyToMany::createFromObject($mapping));

break;
case ClassMetadata::ONE_TO_ONE:
$manipulator->addOneToOneRelation(RelationOneToOne::createFromObject($mapping));

break;
default:
throw new \Exception('Unknown association type.');
}
match ($mapping['type']) {
ClassMetadata::MANY_TO_ONE => $manipulator->addManyToOneRelation(RelationManyToOne::createFromObject($mapping)),
ClassMetadata::ONE_TO_MANY => $manipulator->addOneToManyRelation(RelationOneToMany::createFromObject($mapping)),
ClassMetadata::MANY_TO_MANY => $manipulator->addManyToManyRelation(RelationManyToMany::createFromObject($mapping)),
ClassMetadata::ONE_TO_ONE => $manipulator->addOneToOneRelation(RelationOneToOne::createFromObject($mapping)),
default => throw new \Exception('Unknown association type.'),
};
}
}

Expand Down
7 changes: 2 additions & 5 deletions src/Generator.php
Original file line number Diff line number Diff line change
Expand Up @@ -25,23 +25,20 @@ class Generator
{
private GeneratorTwigHelper $twigHelper;
private array $pendingOperations = [];
private ?TemplateComponentGenerator $templateComponentGenerator;
private array $generatedFiles = [];

public function __construct(
private FileManager $fileManager,
private string $namespacePrefix,
?PhpCompatUtil $phpCompatUtil = null,
?TemplateComponentGenerator $templateComponentGenerator = null,
private ?TemplateComponentGenerator $templateComponentGenerator = null,
) {
$this->twigHelper = new GeneratorTwigHelper($fileManager);
$this->namespacePrefix = trim($namespacePrefix, '\\');

if (null !== $phpCompatUtil) {
trigger_deprecation('symfony/maker-bundle', 'v1.44.0', 'Initializing Generator while providing an instance of PhpCompatUtil is deprecated.');
}

$this->templateComponentGenerator = $templateComponentGenerator;
}

/**
Expand Down Expand Up @@ -152,7 +149,7 @@ public function createClassNameDetails(string $name, string $namespacePrefix, st
try {
Validator::classDoesNotExist($className);
$className = rtrim($fullNamespacePrefix, '\\').'\\'.$className;
} catch (RuntimeCommandException $e) {
} catch (RuntimeCommandException) {
}
}

Expand Down
45 changes: 12 additions & 33 deletions src/GeneratorTwigHelper.php
Original file line number Diff line number Diff line change
Expand Up @@ -23,41 +23,20 @@ public function __construct(

public function getEntityFieldPrintCode($entity, $field): string
{
$twigField = preg_replace_callback('/(?!^)_([a-z0-9])/', static function ($s) {
return strtoupper($s[1]);
}, $field['fieldName']);
$twigField = preg_replace_callback('/(?!^)_([a-z0-9])/', static fn ($s) => strtoupper($s[1]), $field['fieldName']);
$printCode = $entity.'.'.str_replace('_', '', $twigField);

switch ($field['type']) {
case 'datetimetz_immutable':
case 'datetimetz':
$printCode .= ' ? '.$printCode.'|date(\'Y-m-d H:i:s T\') : \'\'';
break;
case 'datetime_immutable':
case 'datetime':
$printCode .= ' ? '.$printCode.'|date(\'Y-m-d H:i:s\') : \'\'';
break;
case 'dateinterval':
$printCode .= ' ? '.$printCode.'.format(\'%y year(s), %m month(s), %d day(s)\') : \'\'';
break;
case 'date_immutable':
case 'date':
$printCode .= ' ? '.$printCode.'|date(\'Y-m-d\') : \'\'';
break;
case 'time_immutable':
case 'time':
$printCode .= ' ? '.$printCode.'|date(\'H:i:s\') : \'\'';
break;
case 'json':
$printCode .= ' ? '.$printCode.'|json_encode : \'\'';
break;
case 'array':
$printCode .= ' ? '.$printCode.'|join(\', \') : \'\'';
break;
case 'boolean':
$printCode .= ' ? \'Yes\' : \'No\'';
break;
}
match ($field['type']) {
'datetimetz_immutable', 'datetimetz' => $printCode .= ' ? '.$printCode.'|date(\'Y-m-d H:i:s T\') : \'\'',
'datetime_immutable', 'datetime' => $printCode .= ' ? '.$printCode.'|date(\'Y-m-d H:i:s\') : \'\'',
'dateinterval' => $printCode .= ' ? '.$printCode.'.format(\'%y year(s), %m month(s), %d day(s)\') : \'\'',
'date_immutable', 'date' => $printCode .= ' ? '.$printCode.'|date(\'Y-m-d\') : \'\'',
'time_immutable', 'time' => $printCode .= ' ? '.$printCode.'|date(\'H:i:s\') : \'\'',
'json' => $printCode .= ' ? '.$printCode.'|json_encode : \'\'',
'array' => $printCode .= ' ? '.$printCode.'|join(\', \') : \'\'',
'boolean' => $printCode .= ' ? \'Yes\' : \'No\'',
default => $printCode,
};

return $printCode;
}
Expand Down
2 changes: 1 addition & 1 deletion src/Maker/MakeAuthenticator.php
Original file line number Diff line number Diff line change
Expand Up @@ -157,7 +157,7 @@ function ($answer) {
$io->ask(
'Choose a name for the controller class (e.g. <fg=yellow>SecurityController</>)',
'SecurityController',
[Validator::class, 'validateClassName']
Validator::validateClassName(...)
)
);

Expand Down
2 changes: 1 addition & 1 deletion src/Maker/MakeDockerDatabase.php
Original file line number Diff line number Diff line change
Expand Up @@ -102,7 +102,7 @@ public function interact(InputInterface $input, ConsoleStyle $io, Command $comma

$io->text($serviceNameMsg);

$this->serviceName = $io->ask(sprintf('What name should we call the new %s service? (e.g. <fg=yellow>database</>)', $this->serviceName), null, [Validator::class, 'notBlank']);
$this->serviceName = $io->ask(sprintf('What name should we call the new %s service? (e.g. <fg=yellow>database</>)', $this->serviceName), null, Validator::notBlank(...));
}

$this->checkForPDOSupport($this->databaseChoice, $io);
Expand Down
10 changes: 5 additions & 5 deletions src/Maker/MakeEntity.php
Original file line number Diff line number Diff line change
Expand Up @@ -111,7 +111,7 @@ public function interact(InputInterface $input, ConsoleStyle $io, Command $comma
'This command will generate any missing methods (e.g. getters & setters) for a class or all classes in a namespace.',
'To overwrite any existing methods, re-run this command with the --overwrite flag',
], null, 'fg=yellow');
$classOrNamespace = $io->ask('Enter a class or namespace to regenerate', $this->getEntityNamespace(), [Validator::class, 'notBlank']);
$classOrNamespace = $io->ask('Enter a class or namespace to regenerate', $this->getEntityNamespace(), Validator::notBlank(...));

$input->setArgument('name', $classOrNamespace);

Expand Down Expand Up @@ -407,13 +407,13 @@ private function askForNextField(ConsoleStyle $io, array $fields, string $entity

if ('string' === $type) {
// default to 255, avoid the question
$classProperty->length = $io->ask('Field length', 255, [Validator::class, 'validateLength']);
$classProperty->length = $io->ask('Field length', 255, Validator::validateLength(...));
} elseif ('decimal' === $type) {
// 10 is the default value given in \Doctrine\DBAL\Schema\Column::$_precision
$classProperty->precision = $io->ask('Precision (total number of digits stored: 100.00 would be 5)', 10, [Validator::class, 'validatePrecision']);
$classProperty->precision = $io->ask('Precision (total number of digits stored: 100.00 would be 5)', 10, Validator::validatePrecision(...));

// 0 is the default value given in \Doctrine\DBAL\Schema\Column::$_scale
$classProperty->scale = $io->ask('Scale (number of decimals to store: 100.00 would be 2)', 0, [Validator::class, 'validateScale']);
$classProperty->scale = $io->ask('Scale (number of decimals to store: 100.00 would be 2)', 0, Validator::validateScale(...));
}

if ($io->confirm('Can this field be null in the database (nullable)', false)) {
Expand Down Expand Up @@ -525,7 +525,7 @@ private function printAvailableTypes(ConsoleStyle $io): void
private function createEntityClassQuestion(string $questionText): Question
{
$question = new Question($questionText);
$question->setValidator([Validator::class, 'notBlank']);
$question->setValidator(Validator::notBlank(...));
$question->setAutocompleterValues($this->doctrineHelper->getEntitiesForAutocomplete());

return $question;
Expand Down
2 changes: 1 addition & 1 deletion src/Maker/MakeListener.php
Original file line number Diff line number Diff line change
Expand Up @@ -98,7 +98,7 @@ public function interact(InputInterface $input, ConsoleStyle $io, Command $comma
$io->listing($this->eventRegistry->listActiveEvents($events));
$question = new Question(sprintf(' <fg=green>%s</>', $command->getDefinition()->getArgument('event')->getDescription()));
$question->setAutocompleterValues($events);
$question->setValidator([Validator::class, 'notBlank']);
$question->setValidator(Validator::notBlank(...));
$event = $io->askQuestion($question);
$input->setArgument('event', $event);
}
Expand Down
4 changes: 2 additions & 2 deletions src/Maker/MakeRegistrationForm.php
Original file line number Diff line number Diff line change
Expand Up @@ -158,13 +158,13 @@ public function interact(InputInterface $input, ConsoleStyle $io, Command $comma
$this->fromEmailAddress = $io->ask(
'What email address will be used to send registration confirmations? (e.g. <fg=yellow>mailer@your-domain.com</>)',
null,
[Validator::class, 'validateEmailAddress']
Validator::validateEmailAddress(...)
);

$this->fromEmailName = $io->ask(
'What "name" should be associated with that email address? (e.g. <fg=yellow>Acme Mail Bot</>)',
null,
[Validator::class, 'notBlank']
Validator::notBlank(...)
);
}

Expand Down
6 changes: 3 additions & 3 deletions src/Maker/MakeResetPassword.php
Original file line number Diff line number Diff line change
Expand Up @@ -160,7 +160,7 @@ public function interact(InputInterface $input, ConsoleStyle $io, Command $comma
$this->controllerResetSuccessRedirect = $io->ask(
'What route should users be redirected to after their password has been successfully reset?',
'app_home',
[Validator::class, 'notBlank']
Validator::notBlank(...)
);

$io->section('- Email -');
Expand All @@ -170,13 +170,13 @@ public function interact(InputInterface $input, ConsoleStyle $io, Command $comma
$this->fromEmailAddress = $io->ask(
'What email address will be used to send reset confirmations? e.g. mailer@your-domain.com',
null,
[Validator::class, 'validateEmailAddress']
Validator::validateEmailAddress(...)
);

$this->fromEmailName = $io->ask(
'What "name" should be associated with that email address? e.g. "Acme Mail Bot"',
null,
[Validator::class, 'notBlank']
Validator::notBlank(...)
);
}

Expand Down
2 changes: 1 addition & 1 deletion src/Maker/MakeStimulusController.php
Original file line number Diff line number Diff line change
Expand Up @@ -175,7 +175,7 @@ private function askForNextValue(ConsoleStyle $io, array $values, bool $isFirstV
// convert to snake case for simplicity
$snakeCasedField = Str::asSnakeCase($valueName);

if ('_id' === substr($snakeCasedField, -3)) {
if (str_ends_with($snakeCasedField, '_id')) {
$defaultType = 'Number';
} elseif (str_starts_with($snakeCasedField, 'is_')) {
$defaultType = 'Boolean';
Expand Down
2 changes: 1 addition & 1 deletion src/Maker/MakeSubscriber.php
Original file line number Diff line number Diff line change
Expand Up @@ -70,7 +70,7 @@ public function interact(InputInterface $input, ConsoleStyle $io, Command $comma
$io->listing($this->eventRegistry->listActiveEvents($events));
$question = new Question(sprintf(' <fg=green>%s</>', $command->getDefinition()->getArgument('event')->getDescription()));
$question->setAutocompleterValues($events);
$question->setValidator([Validator::class, 'notBlank']);
$question->setValidator(Validator::notBlank(...));
$event = $io->askQuestion($question);
$input->setArgument('event', $event);
}
Expand Down
2 changes: 1 addition & 1 deletion src/Maker/MakeTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -126,7 +126,7 @@ public function interact(InputInterface $input, ConsoleStyle $io, Command $comma
]);

$nameArgument = $command->getDefinition()->getArgument('name');
$value = $io->ask($nameArgument->getDescription(), $nameArgument->getDefault(), [Validator::class, 'notBlank']);
$value = $io->ask($nameArgument->getDescription(), $nameArgument->getDefault(), Validator::notBlank(...));
$input->setArgument($nameArgument->getName(), $value);
}
}
Expand Down
2 changes: 1 addition & 1 deletion src/Maker/MakeUser.php
Original file line number Diff line number Diff line change
Expand Up @@ -104,7 +104,7 @@ class_exists(DoctrineBundle::class)
}
$input->setOption('is-entity', $userIsEntity);

$identityFieldName = $io->ask('Enter a property name that will be the unique "display" name for the user (e.g. <comment>email, username, uuid</comment>)', 'email', [Validator::class, 'validatePropertyName']);
$identityFieldName = $io->ask('Enter a property name that will be the unique "display" name for the user (e.g. <comment>email, username, uuid</comment>)', 'email', Validator::validatePropertyName(...));
$input->setOption('identity-property-name', $identityFieldName);

$io->text('Will this app need to hash/check user passwords? Choose <comment>No</comment> if passwords are not needed or will be checked/hashed by some other system (e.g. a single sign-on server).');
Expand Down
2 changes: 1 addition & 1 deletion src/Maker/Security/MakeFormLogin.php
Original file line number Diff line number Diff line change
Expand Up @@ -111,7 +111,7 @@ public function interact(InputInterface $input, ConsoleStyle $io, Command $comma
$this->controllerName = $io->ask(
'Choose a name for the controller class (e.g. <fg=yellow>SecurityController</>)',
'SecurityController',
[Validator::class, 'validateClassName']
Validator::validateClassName(...)
);

$securityHelper = new InteractiveSecurityHelper();
Expand Down
14 changes: 4 additions & 10 deletions src/Security/InteractiveSecurityHelper.php
Original file line number Diff line number Diff line change
Expand Up @@ -25,9 +25,7 @@ public function guessFirewallName(SymfonyStyle $io, array $securityData, ?string
{
$realFirewalls = array_filter(
$securityData['security']['firewalls'] ?? [],
static function ($item) {
return !isset($item['security']) || true === $item['security'];
}
static fn ($item) => !isset($item['security']) || true === $item['security']
);

if (0 === \count($realFirewalls)) {
Expand Down Expand Up @@ -56,7 +54,7 @@ public function guessUserClass(SymfonyStyle $io, array $providers, ?string $ques
return $io->ask(
$questionText ?? 'Enter the User class that you want to authenticate (e.g. <fg=yellow>App\\Entity\\User</>)',
$this->guessUserClassDefault(),
[Validator::class, 'classIsUserInterface']
Validator::classIsUserInterface(...)
);
}

Expand Down Expand Up @@ -145,9 +143,7 @@ public function guessPasswordField(SymfonyStyle $io, string $userClass): string
public function getAuthenticatorClasses(array $firewallData): array
{
if (isset($firewallData['guard'])) {
return array_filter($firewallData['guard']['authenticators'] ?? [], static function ($authenticator) {
return class_exists($authenticator);
});
return array_filter($firewallData['guard']['authenticators'] ?? [], static fn ($authenticator) => class_exists($authenticator));
}

if (isset($firewallData['custom_authenticator'])) {
Expand All @@ -156,9 +152,7 @@ public function getAuthenticatorClasses(array $firewallData): array
$authenticators = [$authenticators];
}

return array_filter($authenticators, static function ($authenticator) {
return class_exists($authenticator);
});
return array_filter($authenticators, static fn ($authenticator) => class_exists($authenticator));
}

return [];
Expand Down
2 changes: 1 addition & 1 deletion src/Security/SecurityConfigUpdater.php
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@
*/
final class SecurityConfigUpdater
{
private ?YamlSourceManipulator $manipulator;
private ?YamlSourceManipulator $manipulator = null;

public function __construct(
private ?Logger $ysmLogger = null,
Expand Down
Loading

0 comments on commit 122bd8a

Please sign in to comment.