From db51412b397cc7312ed9fcadb04162c69a3fd5da Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jan=20Bar=C3=A1=C5=A1ek?= Date: Tue, 11 May 2021 11:15:44 +0200 Subject: [PATCH] Beautify codestyle to PSR-12 --- src/Cache/SQLite3Cache.php | 5 +- src/DatabaseExtension.php | 173 +++++++++++------- src/Dbal/ConnectionFactory.php | 16 +- .../Events/ContainerAwareEventManager.php | 8 +- src/Dbal/Events/DebugEventManager.php | 9 +- src/Dbal/Logger/AbstractLogger.php | 34 +++- src/Dbal/Tracy/BlueScreen/DbalBlueScreen.php | 44 +++-- src/Dbal/Tracy/QueryPanel/QueryPanel.php | 12 +- .../Tracy/QueryPanel/templates/panel.phtml | 2 - src/Dbal/Utils/QueryUtils.php | 3 +- src/Entity/SlowQuery.php | 1 - src/EntityManager.php | 15 +- ...tabaseToDoctrineEntityExtractorCommand.php | 5 +- src/Orm/ManagerRegistry.php | 3 +- .../ContainerEntityListenerResolver.php | 1 - src/UUID/UuidBinaryType.php | 4 - src/UUID/UuidType.php | 8 +- src/Utils.php | 24 ++- 18 files changed, 215 insertions(+), 152 deletions(-) diff --git a/src/Cache/SQLite3Cache.php b/src/Cache/SQLite3Cache.php index de3fabe..edcb107 100644 --- a/src/Cache/SQLite3Cache.php +++ b/src/Cache/SQLite3Cache.php @@ -12,7 +12,10 @@ public function __construct(string $cachePath, int $ttl = 25) $cache = new \SQLite3($cachePath); $cache->enableExceptions(true); if ($cache->busyTimeout(60_000) === false) { - throw new \RuntimeException('SQLite3 cache: Can not set busy timeout: ' . $cache->lastErrorMsg(), $cache->lastErrorCode()); + throw new \RuntimeException( + 'SQLite3 cache: Can not set busy timeout: ' . $cache->lastErrorMsg(), + $cache->lastErrorCode(), + ); } do { try { diff --git a/src/DatabaseExtension.php b/src/DatabaseExtension.php index b5989e1..bd7044a 100644 --- a/src/DatabaseExtension.php +++ b/src/DatabaseExtension.php @@ -37,13 +37,13 @@ final class DatabaseExtension extends CompilerExtension { public const TAG_DOCTRINE_SUBSCRIBER = 'doctrine.subscriber'; - /** @var string[] (type => typeClass) */ + /** @var array (type => typeClass) */ private static array $customTypes = [ 'uuid' => UuidType::class, 'uuid-binary' => UuidBinaryType::class, ]; - /** @var string[] (name => typeClass) */ + /** @var array (name => typeClass) */ private static array $customNumericFunctions = [ 'RAND' => RandFunction::class, 'ROUND' => RoundFunction::class, @@ -78,47 +78,57 @@ public static function addCustomNumericFunction(string $name, string $type): voi public function getConfigSchema(): Schema { - return Expect::structure([ - 'connection' => Expect::structure([ - 'host' => Expect::string()->required(), - 'dbname' => Expect::string()->required(), - 'user' => Expect::string()->required(), - 'password' => Expect::string()->nullable(), - 'url' => Expect::string()->nullable(), - 'pdo' => Expect::string()->nullable(), - 'memory' => Expect::string()->nullable(), - 'driver' => Expect::string('pdo_mysql'), - 'driverClass' => Expect::string()->nullable(), - 'driverOptions' => Expect::array(), - 'unix_socket' => Expect::string()->nullable(), - 'port' => Expect::int()->nullable(), - 'servicename' => Expect::string()->nullable(), - 'charset' => Expect::string('UTF8'), - 'portability' => Expect::int(PortabilityConnection::PORTABILITY_ALL), - 'fetchCase' => Expect::int(\PDO::CASE_LOWER), - 'persistent' => Expect::bool(true), - 'types' => Expect::array(), - 'typesMapping' => Expect::array(), - 'wrapperClass' => Expect::string()->nullable(), - ])->castTo('array')->required(), - 'configuration' => Expect::structure([ - 'sqlLogger' => Expect::string()->nullable(), - 'resultCacheImpl' => Expect::string()->nullable(), - 'filterSchemaAssetsExpression' => Expect::string()->nullable(), - 'autoCommit' => Expect::bool()->default(true), - ])->castTo('array'), - 'cache' => Expect::string(), - 'types' => Expect::arrayOf(Expect::string())->default([]), - 'customNumericFunctions' => Expect::arrayOf(Expect::string()), - 'propertyIgnoreAnnotations' => Expect::arrayOf(Expect::string())->default([]), - ])->castTo('array')->otherItems(Expect::mixed()); + return Expect::structure( + [ + 'connection' => Expect::structure( + [ + 'host' => Expect::string()->required(), + 'dbname' => Expect::string()->required(), + 'user' => Expect::string()->required(), + 'password' => Expect::string()->nullable(), + 'url' => Expect::string()->nullable(), + 'pdo' => Expect::string()->nullable(), + 'memory' => Expect::string()->nullable(), + 'driver' => Expect::string('pdo_mysql'), + 'driverClass' => Expect::string()->nullable(), + 'driverOptions' => Expect::array(), + 'unix_socket' => Expect::string()->nullable(), + 'port' => Expect::int()->nullable(), + 'servicename' => Expect::string()->nullable(), + 'charset' => Expect::string('UTF8'), + 'portability' => Expect::int(PortabilityConnection::PORTABILITY_ALL), + 'fetchCase' => Expect::int(\PDO::CASE_LOWER), + 'persistent' => Expect::bool(true), + 'types' => Expect::array(), + 'typesMapping' => Expect::array(), + 'wrapperClass' => Expect::string()->nullable(), + ] + )->castTo('array')->required(), + 'configuration' => Expect::structure( + [ + 'sqlLogger' => Expect::string()->nullable(), + 'resultCacheImpl' => Expect::string()->nullable(), + 'filterSchemaAssetsExpression' => Expect::string()->nullable(), + 'autoCommit' => Expect::bool()->default(true), + ] + )->castTo('array'), + 'cache' => Expect::string(), + 'types' => Expect::arrayOf(Expect::string())->default([]), + 'customNumericFunctions' => Expect::arrayOf(Expect::string()), + 'propertyIgnoreAnnotations' => Expect::arrayOf(Expect::string())->default([]), + ] + )->castTo('array')->otherItems(Expect::mixed()); } public function loadConfiguration(): void { $builder = $this->getContainerBuilder(); - OrmAnnotationsExtension::addAnnotationPathToManager($builder, 'Baraja\Doctrine\Entity', __DIR__ . '/Entity'); + OrmAnnotationsExtension::addAnnotationPathToManager( + $builder, + 'Baraja\Doctrine\Entity', + __DIR__ . '/Entity', + ); $this->loadDoctrineConfiguration(); $this->loadConnectionConfiguration(); @@ -143,16 +153,25 @@ public function beforeCompile(): void $eventManager = $builder->getDefinition($this->prefix('eventManager')); foreach (array_keys($builder->findByTag(self::TAG_DOCTRINE_SUBSCRIBER)) as $serviceName) { $class = $builder->getDefinition($serviceName)->getType(); - if ($class === null || !is_subclass_of($class, EventSubscriber::class)) { - throw new \RuntimeException('Subscriber "' . $serviceName . '" does not implement "' . EventSubscriber::class . '".'); + throw new \RuntimeException( + 'Subscriber "' . $serviceName . '" does not implement "' . EventSubscriber::class . '".' + ); } try { - $eventManager->addSetup('?->addEventListener(?, ?)', [ - '@self', - call_user_func([(new \ReflectionClass($class))->newInstanceWithoutConstructor(), 'getSubscribedEvents']), - $serviceName, // Intentionally without @ for laziness. - ]); + $eventManager->addSetup( + '?->addEventListener(?, ?)', + [ + '@self', + call_user_func( + [ + (new \ReflectionClass($class))->newInstanceWithoutConstructor(), + 'getSubscribedEvents', + ] + ), + $serviceName, // Intentionally without @ for laziness. + ] + ); } catch (\ReflectionException $e) { throw new \RuntimeException($e->getMessage(), $e->getCode(), $e); } @@ -161,18 +180,29 @@ public function beforeCompile(): void $types = []; foreach (array_merge(self::$customTypes, $config['types'] ?? []) as $type => $typeClass) { if (\class_exists($typeClass) === false) { - throw new ConfiguratorException('Doctrine type "' . $type . '" does not exist, because class "' . $typeClass . '" is not defined.'); + throw new ConfiguratorException( + 'Doctrine type "' . $type . '" does not exist, because class "' . $typeClass . '" is not defined.', + ); } $types[$type] = $typeClass; } $functionsCode = ''; - foreach (array_merge(self::$customNumericFunctions, $config['customNumericFunctions'] ?? []) as $functionName => $functionType) { + foreach ( + array_merge( + self::$customNumericFunctions, + $config['customNumericFunctions'] ?? [], + ) as $functionName => $functionType + ) { if (\class_exists($functionType) === false) { - throw new ConfiguratorException('Doctrine function definition "' . $functionName . '" does not exist, because class "' . $functionType . '" is not defined.'); + throw new ConfiguratorException( + 'Doctrine function definition "' . $functionName . '" does not exist, ' + . 'because class "' . $functionType . '" is not defined.', + ); } $functionsCode .= ($functionsCode ? "\n\t" : '') - . '$entityManager->getConfiguration()->addCustomNumericFunction(\'' . strtoupper($functionName) . '\', ' . $functionType . '::class);'; + . '$entityManager->getConfiguration()->addCustomNumericFunction(\'' . strtoupper($functionName) . '\', ' + . $functionType . '::class);'; } if (interface_exists(ProjectEntityRepository::class)) { @@ -203,11 +233,14 @@ public function beforeCompile(): void [ '@self', $types, - array_merge([ - 'sample', - 'endpointName', - 'editable', - ], $config['propertyIgnoreAnnotations'] ?? []), + array_merge( + [ + 'sample', + 'endpointName', + 'editable', + ], + $config['propertyIgnoreAnnotations'] ?? [], + ), ], ); } @@ -298,7 +331,10 @@ private function loadDoctrineConfiguration(): void $configuration->addSetup('setResultCacheImpl', [$config['configuration']['resultCacheImpl']]); } if ($config['configuration']['filterSchemaAssetsExpression'] !== null) { // FilterSchemaAssetsExpression - $configuration->addSetup('setFilterSchemaAssetsExpression', [$config['configuration']['filterSchemaAssetsExpression']]); + $configuration->addSetup( + 'setFilterSchemaAssetsExpression', + [$config['configuration']['filterSchemaAssetsExpression']] + ); } // AutoCommit @@ -320,8 +356,10 @@ private function loadConnectionConfiguration(): void ) { throw new \RuntimeException( 'Connection port (suffix included in host string) and given port are different.' . "\n" - . 'Given host "' . $config['connection']['host'] . '" contains port "' . $hostParser[2] . '", but given port is "' . $config['connection']['port'] . '".' . "\n" - . 'To solve this issue: Change "host" string to "' . $hostParser[1] . '" (without ":' . $hostParser[2] . '") or change port to "' . $config['connection']['port'] . '".', + . 'Given host "' . $config['connection']['host'] . '" contains port "' . $hostParser[2] . '", ' + . 'but given port is "' . $config['connection']['port'] . '".' . "\n" + . 'To solve this issue: Change "host" string to "' . $hostParser[1] . '" ' + . '(without ":' . $hostParser[2] . '") or change port to "' . $config['connection']['port'] . '".', ); } $config['connection']['host'] = $hostParser[1]; @@ -332,8 +370,9 @@ private function loadConnectionConfiguration(): void && preg_match('/^.+?\.ondigitalocean\.com$/', $config['connection']['host']) ) { // DigitalOcean managed database support throw new \RuntimeException( - 'In case of DigitalOcean (host is "' . $config['connection']['host'] . '") you must define port (as integer) in your NEON configuration, but NULL given.' . "\n" - . 'Hint: Check if your current IP "' . Utils::userIp() . '" is allowed for connection.', + 'In case of DigitalOcean (host is "' . $config['connection']['host'] . '") ' + . 'you must define port (as integer) in your NEON configuration, but NULL given.' + . "\n" . 'Hint: Check if your current IP "' . Utils::userIp() . '" is allowed for connection.', ); } @@ -348,15 +387,21 @@ private function loadConnectionConfiguration(): void } $builder->addDefinition($this->prefix('connectionFactory')) - ->setFactory(ConnectionFactory::class, [$config['connection']['types'], $config['connection']['typesMapping']]); + ->setFactory( + ConnectionFactory::class, + [$config['connection']['types'], $config['connection']['typesMapping']] + ); $builder->addDefinition($this->prefix('connection')) ->setFactory(Connection::class) - ->setFactory('@' . $this->prefix('connectionFactory') . '::createConnection', [ - $config['connection'], - '@' . $this->prefix('configuration'), - $builder->getDefinitionByType(EventManager::class), - ]); + ->setFactory( + '@' . $this->prefix('connectionFactory') . '::createConnection', + [ + $config['connection'], + '@' . $this->prefix('configuration'), + $builder->getDefinitionByType(EventManager::class), + ] + ); } diff --git a/src/Dbal/ConnectionFactory.php b/src/Dbal/ConnectionFactory.php index 27ba9fe..6f00a14 100644 --- a/src/Dbal/ConnectionFactory.php +++ b/src/Dbal/ConnectionFactory.php @@ -16,13 +16,6 @@ class ConnectionFactory { - - /** @var mixed[] */ - private array $typesConfig; - - /** @var mixed[] */ - private array $typesMapping; - /** @var mixed[] */ private array $commentedTypes = []; @@ -33,10 +26,10 @@ class ConnectionFactory * @param mixed[] $typesConfig * @param mixed[] $typesMapping */ - public function __construct(array $typesConfig = [], array $typesMapping = []) - { - $this->typesConfig = $typesConfig; - $this->typesMapping = $typesMapping; + public function __construct( + private array $typesConfig = [], + private array $typesMapping = [], + ) { } @@ -115,7 +108,6 @@ private function initializeTypes(): void } else { Type::addType($type, $typeConfig['class']); } - if ($typeConfig['commented']) { $this->commentedTypes[] = $type; } diff --git a/src/Dbal/Events/ContainerAwareEventManager.php b/src/Dbal/Events/ContainerAwareEventManager.php index 8333f35..0716975 100644 --- a/src/Dbal/Events/ContainerAwareEventManager.php +++ b/src/Dbal/Events/ContainerAwareEventManager.php @@ -13,8 +13,6 @@ final class ContainerAwareEventManager extends DoctrineEventManager { - protected Container $container; - /** @var bool[] */ protected array $initialized = []; @@ -22,9 +20,9 @@ final class ContainerAwareEventManager extends DoctrineEventManager protected array $listeners = []; - public function __construct(Container $container) - { - $this->container = $container; + public function __construct( + protected Container $container, + ) { } diff --git a/src/Dbal/Events/DebugEventManager.php b/src/Dbal/Events/DebugEventManager.php index 2d8b0e5..befda67 100644 --- a/src/Dbal/Events/DebugEventManager.php +++ b/src/Dbal/Events/DebugEventManager.php @@ -11,12 +11,9 @@ final class DebugEventManager extends DoctrineEventManager { - private EventManager $inner; - - - public function __construct(EventManager $inner) - { - $this->inner = $inner; + public function __construct( + private EventManager $inner, + ) { } diff --git a/src/Dbal/Logger/AbstractLogger.php b/src/Dbal/Logger/AbstractLogger.php index 408a881..483b04d 100644 --- a/src/Dbal/Logger/AbstractLogger.php +++ b/src/Dbal/Logger/AbstractLogger.php @@ -16,14 +16,11 @@ abstract class AbstractLogger implements SQLLogger { - /** @var mixed[] */ protected array $queries = []; protected float $totalTime = 0; - private ?EntityManager $entityManager; - /** @var float[][] */ private array $queriesTimer = []; @@ -33,9 +30,9 @@ abstract class AbstractLogger implements SQLLogger private int $maxQueryTime = 150; - public function __construct(EntityManager $entityManager) - { - $this->entityManager = $entityManager; + public function __construct( + private ?EntityManager $entityManager, + ) { } @@ -83,9 +80,12 @@ public function stopQuery(): ?stdClass && ($durationMs = $duration * 1_000) > $this->maxQueryTime ) { $locked = true; - if (Utils::queryExistsByHash($hash = Utils::createSqlHash($this->queries[$key]->sql), $this->entityManager) === false) { + $hash = Utils::createSqlHash($this->queries[$key]->sql); + if (Utils::queryExistsByHash($hash, $this->entityManager) === false) { try { - $this->entityManager->persist($slowQuery = new SlowQuery($this->queries[$key]->sql, $hash, $durationMs))->flush($slowQuery); + $slowQuery = new SlowQuery($this->queries[$key]->sql, $hash, $durationMs); + $this->entityManager->persist($slowQuery); + $this->entityManager->flush($slowQuery); } catch (EntityManagerException $e) { Debugger::log($e, ILogger::DEBUG); } @@ -139,7 +139,15 @@ private function findLocation(): ?array continue; } if ( - preg_match('/\/vendor\/([^\/]+\/[^\/]+)\//', str_replace(DIRECTORY_SEPARATOR, '/', $item['file'] ?? ''), $parser) + preg_match( + '/\/vendor\/([^\/]+\/[^\/]+)\//', + str_replace( + DIRECTORY_SEPARATOR, + '/', + $item['file'] ?? '' + ), + $parser + ) && ( $parser[1] === 'baraja-core/doctrine' || strncmp($parser[1], 'doctrine/', 9) === 0 @@ -159,7 +167,13 @@ private function findLocation(): ?array return [ 'file' => $location['file'] ?? '', 'line' => $location['line'] ?? '', - 'snippet' => trim((string) preg_match('#\w*dump(er::\w+)?\(.*\)#i', (string) $locationLine, $m) ? $m[0] ?? '' : (string) $locationLine), + 'snippet' => trim( + (string) preg_match( + '#\w*dump(er::\w+)?\(.*\)#i', + (string) $locationLine, + $m + ) ? $m[0] ?? '' : (string) $locationLine + ), ]; } diff --git a/src/Dbal/Tracy/BlueScreen/DbalBlueScreen.php b/src/Dbal/Tracy/BlueScreen/DbalBlueScreen.php index 661b85e..55c3f1a 100644 --- a/src/Dbal/Tracy/BlueScreen/DbalBlueScreen.php +++ b/src/Dbal/Tracy/BlueScreen/DbalBlueScreen.php @@ -28,38 +28,44 @@ public function __invoke(?Throwable $e): ?array if ($e === null) { return null; } + $prev = $e->getPrevious(); if ($e instanceof DriverException) { - if ( - ($prev = $e->getPrevious()) - && ($item = Helpers::findTrace($e->getTrace(), DBALException::class . '::driverExceptionDuringQuery')) - ) { + $itemDriver = Helpers::findTrace($e->getTrace(), DBALException::class . '::driverExceptionDuringQuery'); + if ($prev && $itemDriver) { return [ 'tab' => 'SQL', - 'panel' => QueryUtils::highlight($item['args'][2]), + 'panel' => QueryUtils::highlight($itemDriver['args'][2]), ]; } } elseif ($e instanceof QueryException) { - if ( - ($prev = $e->getPrevious()) - && preg_match('~^(SELECT|INSERT|UPDATE|DELETE)\s+~i', $prev->getMessage()) - ) { + if ($prev && preg_match('~^(SELECT|INSERT|UPDATE|DELETE)\s+~i', $prev->getMessage())) { return [ 'tab' => 'DQL', 'panel' => QueryUtils::highlight($prev->getMessage()), ]; } } elseif ($e instanceof PDOException) { - if (isset($e->queryString)) { - $sql = $e->queryString; - } elseif ($item = Helpers::findTrace($e->getTrace(), Connection::class . '::executeQuery')) { - $sql = $item['args'][0]; - } elseif ($item = Helpers::findTrace($e->getTrace(), PDO::class . '::query')) { - $sql = $item['args'][0]; - } elseif ($item = Helpers::findTrace($e->getTrace(), PDO::class . '::prepare')) { - $sql = $item['args'][0]; - } + $sql = (function (\Throwable $e): ?string { + if (isset($e->queryString)) { + return $e->queryString; + } + $itemExecute = Helpers::findTrace($e->getTrace(), Connection::class . '::executeQuery'); + if ($itemExecute) { + return $itemExecute['args'][0]; + } + $itemQuery = Helpers::findTrace($e->getTrace(), PDO::class . '::query'); + if ($itemQuery) { + return $itemQuery['args'][0]; + } + $itemPrepare = Helpers::findTrace($e->getTrace(), PDO::class . '::prepare'); + if ($itemPrepare) { + return $itemPrepare['args'][0]; + } + + return null; + })($e); - return isset($sql) ? [ + return $sql !== null ? [ 'tab' => 'SQL', 'panel' => QueryUtils::highlight($sql), ] : null; diff --git a/src/Dbal/Tracy/QueryPanel/QueryPanel.php b/src/Dbal/Tracy/QueryPanel/QueryPanel.php index 420d973..893c5b9 100644 --- a/src/Dbal/Tracy/QueryPanel/QueryPanel.php +++ b/src/Dbal/Tracy/QueryPanel/QueryPanel.php @@ -37,13 +37,12 @@ final class QueryPanel extends AbstractLogger implements IBarPanel 5 => 'background:#fbccb7 !important;color:black', ]; - private Connection $connection; - - public function __construct(Connection $connection, EntityManager $entityManager) - { + public function __construct( + private Connection $connection, + EntityManager $entityManager, + ) { parent::__construct($entityManager); - $this->connection = $connection; } @@ -92,7 +91,8 @@ public function startQuery($sql, ?array $params = null, ?array $types = null): v if ($params !== null && $params !== []) { try { [$sql, $params, $types] = SQLParserUtils::expandListParameters($sql, $params ?? [], $types ?? []); - } catch (SQLParserUtilsException $e) { + } catch (SQLParserUtilsException) { + // Silence is golden. } $sql = str_replace(['%', '?'], ['%%', '%s'], (string) $sql); diff --git a/src/Dbal/Tracy/QueryPanel/templates/panel.phtml b/src/Dbal/Tracy/QueryPanel/templates/panel.phtml index ec5d1ff..b2336df 100644 --- a/src/Dbal/Tracy/QueryPanel/templates/panel.phtml +++ b/src/Dbal/Tracy/QueryPanel/templates/panel.phtml @@ -21,12 +21,10 @@ foreach ($queries ?? [] as $query) { $isTransaction = true; $background = 'rgb(204,255,204)'; } - if ($query->sql === '"COMMIT"' || $query->sql === '"ROLLBACK"') { $isTransaction = false; $background = 'rgb(253,169,157)'; } - if ($isTransaction === true && $background === null) { $background = 'rgb(255,244,204)'; } diff --git a/src/Dbal/Utils/QueryUtils.php b/src/Dbal/Utils/QueryUtils.php index 4c38a9c..3410e85 100644 --- a/src/Dbal/Utils/QueryUtils.php +++ b/src/Dbal/Utils/QueryUtils.php @@ -40,7 +40,8 @@ static function (array $matches) { return '' . $matches[2] . ''; } if (!empty($matches[3])) { // most important keywords - return (self::getCounter() > 1 ? '
' : '') . '' . $matches[3] . ''; + return (self::getCounter() > 1 ? '
' : '') + . '' . $matches[3] . ''; } if (!empty($matches[4])) { // other keywords return '' . $matches[4] . ''; diff --git a/src/Entity/SlowQuery.php b/src/Entity/SlowQuery.php index eb88867..e491066 100644 --- a/src/Entity/SlowQuery.php +++ b/src/Entity/SlowQuery.php @@ -24,7 +24,6 @@ class SlowQuery { use UuidIdentifier; - use SmartObject; /** @ORM\Column(type="text") */ private string $query; diff --git a/src/EntityManager.php b/src/EntityManager.php index 6f03faa..a2c4dbe 100644 --- a/src/EntityManager.php +++ b/src/EntityManager.php @@ -25,12 +25,9 @@ */ final class EntityManager extends \Doctrine\ORM\EntityManager { - private Configuration $configuration; - - public function __construct( Connection $connection, - Configuration $configuration, + private Configuration $configuration, EventManager $eventManager, ?QueryPanel $panel = null ) { @@ -43,7 +40,7 @@ public function __construct( } parent::__construct( $connection, - $this->configuration = $configuration, + $configuration, $eventManager, ); } @@ -151,7 +148,9 @@ public function flush($entity = null): self public function find($className, $id, $lockMode = null, $lockVersion = null) { if (\class_exists($className) === false) { - throw new \InvalidArgumentException('Entity name "' . $className . '" must be valid class name. Is your class autoloadable?'); + throw new \InvalidArgumentException( + 'Entity name "' . $className . '" must be valid class name. Is your class autoloadable?', + ); } try { return parent::find($className, $id, $lockMode, $lockVersion); @@ -258,7 +257,9 @@ public function transactional($func) public function getReference($entityName, $id) { if (\class_exists($entityName) === false) { - throw new \InvalidArgumentException('Entity name "' . $entityName . '" must be valid class name. Is your class autoloadable?'); + throw new \InvalidArgumentException( + 'Entity name "' . $entityName . '" must be valid class name. Is your class autoloadable?', + ); } try { return parent::getReference($entityName, $id); diff --git a/src/Orm/DatabaseToDoctrineEntityExtractorCommand.php b/src/Orm/DatabaseToDoctrineEntityExtractorCommand.php index 523b892..d7a9e13 100644 --- a/src/Orm/DatabaseToDoctrineEntityExtractorCommand.php +++ b/src/Orm/DatabaseToDoctrineEntityExtractorCommand.php @@ -103,7 +103,10 @@ public function execute(InputInterface $input, OutputInterface $output): int /** @var Statement $showTablesStatement */ $showTablesStatement = $connection->executeQuery('SHOW TABLES'); - $tables = array_map(static fn(array $item): ?string => array_values($item)[0] ?? null, $showTablesStatement->fetchAllAssociative()); + $tables = array_map( + static fn(array $item): ?string => array_values($item)[0] ?? null, + $showTablesStatement->fetchAllAssociative(), + ); $output->writeln('"' . implode('", "', $tables) . '".'); $output->writeln('Count tables: ' . \count($tables)); diff --git a/src/Orm/ManagerRegistry.php b/src/Orm/ManagerRegistry.php index 282f020..c9981f8 100644 --- a/src/Orm/ManagerRegistry.php +++ b/src/Orm/ManagerRegistry.php @@ -43,7 +43,8 @@ public function getAliasNamespace($alias): string $entityManager = $this->getManager($name); return $entityManager->getConfiguration()->getEntityNamespace($alias); - } catch (ORMException $e) { + } catch (ORMException) { + // Silence is golden. } } diff --git a/src/Orm/Mapping/ContainerEntityListenerResolver.php b/src/Orm/Mapping/ContainerEntityListenerResolver.php index efc92f9..9e9f42d 100644 --- a/src/Orm/Mapping/ContainerEntityListenerResolver.php +++ b/src/Orm/Mapping/ContainerEntityListenerResolver.php @@ -11,7 +11,6 @@ final class ContainerEntityListenerResolver implements EntityListenerResolver { - /** @var array */ private array $instances = []; diff --git a/src/UUID/UuidBinaryType.php b/src/UUID/UuidBinaryType.php index 44b03c2..791c907 100644 --- a/src/UUID/UuidBinaryType.php +++ b/src/UUID/UuidBinaryType.php @@ -37,11 +37,9 @@ public function convertToPHPValue($value, AbstractPlatform $platform): ?UuidInte if (empty($value)) { return null; } - if ($value instanceof UuidInterface) { return $value; } - try { return Uuid::fromBytes($value); } catch (\InvalidArgumentException $e) { @@ -59,11 +57,9 @@ public function convertToDatabaseValue($value, AbstractPlatform $platform): ?str if ($value === null) { return null; } - if ($value instanceof UuidInterface) { return $value->getBytes(); } - try { if (is_string($value) || method_exists($value, '__toString')) { return Uuid::fromString((string) $value)->getBytes(); diff --git a/src/UUID/UuidType.php b/src/UUID/UuidType.php index 9e9f095..3b615ad 100644 --- a/src/UUID/UuidType.php +++ b/src/UUID/UuidType.php @@ -37,10 +37,9 @@ public function convertToPHPValue($value, AbstractPlatform $platform): ?string if ($value instanceof UuidInterface) { return $value->toString(); } - try { return (string) Uuid::fromString($value)->toString(); - } catch (\InvalidArgumentException $e) { + } catch (\InvalidArgumentException) { throw ConversionException::conversionFailed($value, static::NAME); } } @@ -62,7 +61,10 @@ public function convertToDatabaseValue($value, AbstractPlatform $platform): ?str } elseif (\is_object($value) && method_exists($value, '__toString')) { $return = (string) $value; } else { - throw new \InvalidArgumentException('Value must be string or instance of "' . UuidInterface::class . '", but type "' . \gettype($value) . '" given.'); + throw new \InvalidArgumentException( + 'Value must be string or instance of "' . UuidInterface::class . '", ' + . 'but type "' . \gettype($value) . '" given.', + ); } if (Uuid::isValid($return)) { return $return; diff --git a/src/Utils.php b/src/Utils.php index 0735081..080ac0b 100644 --- a/src/Utils.php +++ b/src/Utils.php @@ -94,19 +94,27 @@ public static function userIp(): string static $ip = null; if ($ip === null) { - if (isset($_SERVER['REMOTE_ADDR'])) { - if (\in_array($_SERVER['REMOTE_ADDR'], ['::1', '0.0.0.0', 'localhost'], true)) { - $ip = '127.0.0.1'; - } else { - $ip = filter_var($_SERVER['REMOTE_ADDR'], FILTER_VALIDATE_IP, FILTER_FLAG_IPV4); - - if ($ip === false) { - $ip = '127.0.0.1'; + if (isset($_SERVER['HTTP_CF_CONNECTING_IP'])) { // Cloudflare support + $ip = $_SERVER['HTTP_CF_CONNECTING_IP']; + } elseif (isset($_SERVER['REMOTE_ADDR']) === true) { + $ip = $_SERVER['REMOTE_ADDR']; + if ($ip === '127.0.0.1') { + if (isset($_SERVER['HTTP_X_REAL_IP'])) { + $ip = $_SERVER['HTTP_X_REAL_IP']; + } elseif (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) { + $ip = $_SERVER['HTTP_X_FORWARDED_FOR']; } } } else { $ip = '127.0.0.1'; } + if (in_array($ip, ['::1', '0.0.0.0', 'localhost'], true)) { + $ip = '127.0.0.1'; + } + $filter = filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4); + if ($filter === false) { + $ip = '127.0.0.1'; + } } return $ip;