Skip to content

Commit

Permalink
rector php 8 support
Browse files Browse the repository at this point in the history
  • Loading branch information
jrushlow committed May 24, 2022
1 parent 18d1bc8 commit 29c74cc
Show file tree
Hide file tree
Showing 18 changed files with 83 additions and 93 deletions.
2 changes: 1 addition & 1 deletion src/DependencyBuilder.php
Original file line number Diff line number Diff line change
Expand Up @@ -139,6 +139,6 @@ private function calculateMissingDependencies(array $dependencies): array
return [];
}

return array_unique(array_merge($missingPackages, $missingOptionalPackages));
return array_unique([...$missingPackages, ...$missingOptionalPackages]);
}
}
16 changes: 5 additions & 11 deletions src/Docker/DockerDatabaseServices.php
Original file line number Diff line number Diff line change
Expand Up @@ -83,17 +83,11 @@ public static function getSuggestedServiceVersion(string $name): string

public static function getMissingExtensionName(string $name): ?string
{
switch ($name) {
case 'mariadb':
case 'mysql':
$driver = 'mysql';
break;
case 'postgres':
$driver = 'pgsql';
break;
default:
self::throwInvalidDatabase($name);
}
$driver = match ($name) {
'mariadb', 'mysql' => 'mysql',
'postgres' => 'pgsql',
default => self::throwInvalidDatabase($name),
};

if (!\in_array($driver, \PDO::getAvailableDrivers(), true)) {
return $driver;
Expand Down
4 changes: 2 additions & 2 deletions src/Doctrine/DoctrineHelper.php
Original file line number Diff line number Diff line change
Expand Up @@ -68,7 +68,7 @@ public function doesClassUseDriver(string $className, string $driverClass): bool
try {
/** @var EntityManagerInterface $em */
$em = $this->getRegistry()->getManagerForClass($className);
} catch (\ReflectionException $exception) {
} catch (\ReflectionException) {
// this exception will be thrown by the registry if the class isn't created yet.
// an example case is the "make:entity" command, which needs to know which driver is used for the class to determine
// if the class should be generated with attributes or annotations. If this exception is thrown, we will check based on the
Expand Down Expand Up @@ -167,7 +167,7 @@ public function getMetadata(string $classOrNamespace = null, bool $disconnected
if ($disconnected) {
try {
$loaded = $cmf->getAllMetadata();
} catch (ORMMappingException|PersistenceMappingException $e) {
} catch (ORMMappingException|PersistenceMappingException) {
$loaded = $this->isInstanceOf($cmf, AbstractClassMetadataFactory::class) ? $cmf->getLoadedMetadata() : [];
}

Expand Down
4 changes: 1 addition & 3 deletions src/Doctrine/EntityDetails.php
Original file line number Diff line number Diff line change
Expand Up @@ -52,9 +52,7 @@ public function getFormFields(): array

if (!empty($this->metadata->embeddedClasses)) {
foreach (array_keys($this->metadata->embeddedClasses) as $embeddedClassKey) {
$fields = array_filter($fields, function ($v) use ($embeddedClassKey) {
return 0 !== strpos($v, $embeddedClassKey.'.');
});
$fields = array_filter($fields, static fn ($v) => !str_starts_with($v, $embeddedClassKey.'.'));
}
}

Expand Down
22 changes: 10 additions & 12 deletions src/Doctrine/EntityRegenerator.php
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@ public function regenerateEntities(string $classOrNamespace): void
{
try {
$metadata = $this->doctrineHelper->getMetadata($classOrNamespace);
} catch (MappingException|LegacyCommonMappingException|PersistenceMappingException $mappingException) {
} catch (MappingException|LegacyCommonMappingException|PersistenceMappingException) {
$metadata = $this->doctrineHelper->getMetadata($classOrNamespace, true);
}

Expand Down Expand Up @@ -72,7 +72,7 @@ public function regenerateEntities(string $classOrNamespace): void
$embeddedClasses = [];

foreach ($classMetadata->embeddedClasses as $fieldName => $mapping) {
if (false !== strpos($fieldName, '.')) {
if (str_contains($fieldName, '.')) {
continue;
}

Expand All @@ -91,7 +91,7 @@ public function regenerateEntities(string $classOrNamespace): void

foreach ($classMetadata->fieldMappings as $fieldName => $mapping) {
// skip embedded fields
if (false !== strpos($fieldName, '.')) {
if (str_contains($fieldName, '.')) {
[$fieldName, $embeddedFiledName] = explode('.', $fieldName);

$operations[$embeddedClasses[$fieldName]]->addEntityField($embeddedFiledName, $mapping);
Expand Down Expand Up @@ -239,11 +239,11 @@ private function getMappedFieldsInEntity(ClassMetadata $classMetadata): array
/** @var \ReflectionClass $classReflection */
$classReflection = $classMetadata->reflClass;

$targetFields = array_merge(
array_keys($classMetadata->fieldMappings),
array_keys($classMetadata->associationMappings),
array_keys($classMetadata->embeddedClasses)
);
$targetFields = [
...array_keys($classMetadata->fieldMappings),
...array_keys($classMetadata->associationMappings),
...array_keys($classMetadata->embeddedClasses),
];

if ($classReflection) {
// exclude traits
Expand All @@ -258,10 +258,8 @@ private function getMappedFieldsInEntity(ClassMetadata $classMetadata): array
$targetFields = array_diff($targetFields, $traitProperties);

// exclude inherited properties
$targetFields = array_filter($targetFields, static function ($field) use ($classReflection) {
return $classReflection->hasProperty($field) &&
$classReflection->getProperty($field)->getDeclaringClass()->getName() == $classReflection->getName();
});
$targetFields = array_filter($targetFields, static fn ($field) => $classReflection->hasProperty($field) &&
$classReflection->getProperty($field)->getDeclaringClass()->getName() === $classReflection->getName());
}

return $targetFields;
Expand Down
8 changes: 7 additions & 1 deletion src/Maker/AbstractMaker.php
Original file line number Diff line number Diff line change
Expand Up @@ -22,10 +22,16 @@
*/
abstract class AbstractMaker implements MakerInterface
{
/**
* @return void
*/
public function interact(InputInterface $input, ConsoleStyle $io, Command $command)
{
}

/**
* @return void
*/
protected function writeSuccessMessage(ConsoleStyle $io)
{
$io->newLine();
Expand All @@ -44,7 +50,7 @@ protected function addDependencies(array $dependencies, string $message = null):
}

return $dependencyBuilder->getMissingPackagesMessage(
$this->getCommandName(),
static::getCommandName(),
$message
);
}
Expand Down
2 changes: 1 addition & 1 deletion src/Maker/MakeAuthenticator.php
Original file line number Diff line number Diff line change
Expand Up @@ -218,7 +218,7 @@ public function generate(InputInterface $input, ConsoleStyle $io, Generator $gen
);
$generator->dumpFile($path, $newYaml);
$securityYamlUpdated = true;
} catch (YamlManipulationFailedException $e) {
} catch (YamlManipulationFailedException) {
}

if (self::AUTH_TYPE_FORM_LOGIN === $input->getArgument('authenticator-type')) {
Expand Down
2 changes: 1 addition & 1 deletion src/Maker/MakeCommand.php
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,7 @@ public function configureCommand(Command $command, InputConfiguration $inputConf
public function generate(InputInterface $input, ConsoleStyle $io, Generator $generator): void
{
$commandName = trim($input->getArgument('name'));
$commandNameHasAppPrefix = 0 === strpos($commandName, 'app:');
$commandNameHasAppPrefix = str_starts_with($commandName, 'app:');

$commandClassNameDetails = $generator->createClassNameDetails(
$commandNameHasAppPrefix ? substr($commandName, 4) : $commandName,
Expand Down
17 changes: 7 additions & 10 deletions src/Maker/MakeDockerDatabase.php
Original file line number Diff line number Diff line change
Expand Up @@ -30,32 +30,27 @@
*/
final class MakeDockerDatabase extends AbstractMaker
{
private $fileManager;
private $composeFilePath;

/**
* @var ComposeFileManipulator
*/
private $composeFileManipulator;
private ?ComposeFileManipulator $composeFileManipulator = null;

/**
* @var string type of database selected by the user
*/
private $databaseChoice;
private ?string $databaseChoice = null;

/**
* @var string Service identifier to be set in docker-compose.yaml
*/
private $serviceName = 'database';
private string $serviceName = 'database';

/**
* @var string Version set in docker-compose.yaml for the service. e.g. latest
*/
private $serviceVersion = 'latest';
private string $serviceVersion = 'latest';

public function __construct(FileManager $fileManager)
public function __construct(private FileManager $fileManager)
{
$this->fileManager = $fileManager;
}

public static function getCommandName(): string
Expand All @@ -77,6 +72,7 @@ public function configureCommand(Command $command, InputConfiguration $inputConf

public function interact(InputInterface $input, ConsoleStyle $io, Command $command): void
{
$serviceNameMsg = [];
$io->section('- Docker Compose Setup-');

$this->composeFileManipulator = new ComposeFileManipulator($this->getComposeFileContents($io));
Expand Down Expand Up @@ -116,6 +112,7 @@ public function interact(InputInterface $input, ConsoleStyle $io, Command $comma

public function generate(InputInterface $input, ConsoleStyle $io, Generator $generator): void
{
$closing = [];
$io->newLine();

$service = DockerDatabaseServices::getDatabaseSkeleton($this->databaseChoice, $this->serviceVersion);
Expand Down
60 changes: 26 additions & 34 deletions src/Maker/MakeEntity.php
Original file line number Diff line number Diff line change
Expand Up @@ -369,9 +369,9 @@ private function askForNextField(ConsoleStyle $io, array $fields, string $entity
$defaultType = 'datetime_immutable';
} elseif ('_id' === $suffix) {
$defaultType = 'integer';
} elseif (0 === strpos($snakeCasedField, 'is_')) {
} elseif (str_starts_with($snakeCasedField, 'is_')) {
$defaultType = 'boolean';
} elseif (0 === strpos($snakeCasedField, 'has_')) {
} elseif (str_starts_with($snakeCasedField, 'has_')) {
$defaultType = 'boolean';
} elseif ('uuid' === $snakeCasedField) {
$defaultType = 'uuid';
Expand Down Expand Up @@ -479,9 +479,9 @@ private function printAvailableTypes(ConsoleStyle $io): void
if (\is_string($subTypes) && $subTypes) {
$line .= sprintf(' (%s)', $subTypes);
} elseif (\is_array($subTypes) && !empty($subTypes)) {
$line .= sprintf(' (or %s)', implode(', ', array_map(function ($subType) {
return sprintf('<comment>%s</comment>', $subType);
}, $subTypes)));
$line .= sprintf(' (or %s)', implode(', ', array_map(
static fn ($subType) => sprintf('<comment>%s</comment>', $subType), $subTypes))
);

foreach ($subTypes as $subType) {
unset($allTypes[$subType]);
Expand All @@ -508,9 +508,7 @@ private function printAvailableTypes(ConsoleStyle $io): void

$io->writeln('<info>Other Types</info>');
// empty the values
$allTypes = array_map(function () {
return [];
}, $allTypes);
$allTypes = array_map(static fn () => [], $allTypes);
$printSection($allTypes);
}

Expand Down Expand Up @@ -551,31 +549,27 @@ private function askRelationDetails(ConsoleStyle $io, string $generatedEntityCla
$type = $this->askRelationType($io, $generatedEntityClass, $targetEntityClass);
}

$askFieldName = function (string $targetClass, string $defaultValue) use ($io) {
return $io->ask(
sprintf('New field name inside %s', Str::getShortClassName($targetClass)),
$defaultValue,
function ($name) use ($targetClass) {
// it's still *possible* to create duplicate properties - by
// trying to generate the same property 2 times during the
// same make:entity run. property_exists() only knows about
// properties that *originally* existed on this class.
if (property_exists($targetClass, $name)) {
throw new \InvalidArgumentException(sprintf('The "%s" class already has a "%s" property.', $targetClass, $name));
}

return Validator::validateDoctrineFieldName($name, $this->doctrineHelper->getRegistry());
$askFieldName = fn (string $targetClass, string $defaultValue) => $io->ask(
sprintf('New field name inside %s', Str::getShortClassName($targetClass)),
$defaultValue,
function ($name) use ($targetClass) {
// it's still *possible* to create duplicate properties - by
// trying to generate the same property 2 times during the
// same make:entity run. property_exists() only knows about
// properties that *originally* existed on this class.
if (property_exists($targetClass, $name)) {
throw new \InvalidArgumentException(sprintf('The "%s" class already has a "%s" property.', $targetClass, $name));
}
);
};

$askIsNullable = static function (string $propertyName, string $targetClass) use ($io) {
return $io->confirm(sprintf(
'Is the <comment>%s</comment>.<comment>%s</comment> property allowed to be null (nullable)?',
Str::getShortClassName($targetClass),
$propertyName
));
};
return Validator::validateDoctrineFieldName($name, $this->doctrineHelper->getRegistry());
}
);

$askIsNullable = static fn (string $propertyName, string $targetClass) => $io->confirm(sprintf(
'Is the <comment>%s</comment>.<comment>%s</comment> property allowed to be null (nullable)?',
Str::getShortClassName($targetClass),
$propertyName
));

$askOrphanRemoval = static function (string $owningClass, string $inverseClass) use ($io) {
$io->text([
Expand Down Expand Up @@ -837,9 +831,7 @@ private function getPropertyNames(string $class): array

$reflClass = new \ReflectionClass($class);

return array_map(static function (\ReflectionProperty $prop) {
return $prop->getName();
}, $reflClass->getProperties());
return array_map(static fn (\ReflectionProperty $prop) => $prop->getName(), $reflClass->getProperties());
}

/** @legacy Drop when Annotations are no longer supported */
Expand Down
2 changes: 1 addition & 1 deletion src/Maker/MakeForm.php
Original file line number Diff line number Diff line change
Expand Up @@ -67,7 +67,7 @@ public function interact(InputInterface $input, ConsoleStyle $io, Command $comma
$entities = $this->entityHelper->getEntitiesForAutocomplete();

$question = new Question($argument->getDescription());
$question->setValidator(function ($answer) use ($entities) {return Validator::existsOrNull($answer, $entities); });
$question->setValidator(fn ($answer) => Validator::existsOrNull($answer, $entities));
$question->setAutocompleterValues($entities);
$question->setMaxAttempts(3);

Expand Down
6 changes: 4 additions & 2 deletions src/Maker/MakeMessage.php
Original file line number Diff line number Diff line change
Expand Up @@ -58,13 +58,15 @@ public function interact(InputInterface $input, ConsoleStyle $io, Command $comma
{
$command->addArgument('chosen-transport', InputArgument::OPTIONAL);

$messengerData = [];

try {
$manipulator = new YamlSourceManipulator($this->fileManager->getFileContents('config/packages/messenger.yaml'));
$messengerData = $manipulator->getData();
} catch (\Exception $e) {
} catch (\Exception) {
}

if (!isset($messengerData, $messengerData['framework']['messenger']['transports'])) {
if (!isset($messengerData['framework']['messenger']['transports'])) {
return;
}

Expand Down
4 changes: 2 additions & 2 deletions src/Maker/MakeMigration.php
Original file line number Diff line number Diff line change
Expand Up @@ -104,12 +104,12 @@ public function generate(InputInterface $input, ConsoleStyle $io, Generator $gen

$migrationOutput = $commandOutput->fetch();

if (false !== strpos($migrationOutput, 'No changes detected')) {
if (str_contains($migrationOutput, 'No changes detected')) {
$this->noChangesMessage($io);

return;
}
} catch (\Doctrine\Migrations\Generator\Exception\NoChangesDetected $exception) {
} catch (\Doctrine\Migrations\Generator\Exception\NoChangesDetected) {
$this->noChangesMessage($io);

return;
Expand Down
10 changes: 6 additions & 4 deletions src/Maker/MakeRegistrationForm.php
Original file line number Diff line number Diff line change
Expand Up @@ -70,8 +70,8 @@ final class MakeRegistrationForm extends AbstractMaker
private $userClass;
private $usernameField;
private $passwordField;
private $willVerifyEmail = false;
private $verifyEmailAnonymously = false;
private bool $willVerifyEmail = false;
private bool $verifyEmailAnonymously = false;
private $idGetter;
private $emailGetter;
private $fromEmailAddress;
Expand All @@ -80,7 +80,7 @@ final class MakeRegistrationForm extends AbstractMaker
private $firewallName;
private $redirectRouteName;
private $addUniqueEntityConstraint;
private $useNewAuthenticatorSystem = false;
private bool $useNewAuthenticatorSystem = false;

public function __construct(
private FileManager $fileManager,
Expand Down Expand Up @@ -109,6 +109,7 @@ public function configureCommand(Command $command, InputConfiguration $inputConf

public function interact(InputInterface $input, ConsoleStyle $io, Command $command): void
{
$emailText = [];
$interactiveSecurityHelper = new InteractiveSecurityHelper();

if (!$this->fileManager->fileExists($path = 'config/packages/security.yaml')) {
Expand Down Expand Up @@ -228,7 +229,7 @@ public function generate(InputInterface $input, ConsoleStyle $io, Generator $gen
$userDoctrineDetails = $this->doctrineHelper->createDoctrineDetails($userClassNameDetails->getFullName());

$userRepoVars = [
'repository_full_class_name' => 'Doctrine\ORM\EntityManagerInterface',
'repository_full_class_name' => EntityManagerInterface::class,
'repository_class_name' => 'EntityManagerInterface',
'repository_var' => '$manager',
];
Expand Down Expand Up @@ -425,6 +426,7 @@ public function generate(InputInterface $input, ConsoleStyle $io, Generator $gen

private function successMessage(ConsoleStyle $io, bool $emailVerification, string $userClass): void
{
$closing = [];
$closing[] = 'Next:';

if (!$emailVerification) {
Expand Down
Loading

0 comments on commit 29c74cc

Please sign in to comment.