Skip to content

Commit

Permalink
Auto-generated types for standard int/string/uuid objects
Browse files Browse the repository at this point in the history
Not sure if this should become part of the main package. The API still
needs work, and there is currently no interface for the string/int/uuid
objects to enforce the correct methods.
  • Loading branch information
benr77 committed May 25, 2024
1 parent 05ea3ab commit 435c5c5
Show file tree
Hide file tree
Showing 13 changed files with 430 additions and 0 deletions.
15 changes: 15 additions & 0 deletions config/services.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
<?php
declare(strict_types=1);

namespace Symfony\Component\DependencyInjection\Loader\Configurator;

return function (ContainerConfigurator $configurator): void
{
$services = $configurator->services()
->defaults()
->autowire()
->autoconfigure()
;

$services->load('Headsnet\\DoctrineToolsBundle\\', '../src/*');
};
16 changes: 16 additions & 0 deletions src/Attribute/DoctrineType.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
<?php
declare(strict_types=1);

namespace Headsnet\DoctrineToolsBundle\Attribute;

use Attribute;

#[Attribute(Attribute::TARGET_CLASS)]
final class DoctrineType
{
public function __construct(
public readonly string $name,
public readonly string $type
) {
}
}
20 changes: 20 additions & 0 deletions src/HeadsnetDoctrineToolsBundle.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@

use Headsnet\DoctrineToolsBundle\Mapping\CarbonTypeMappingsCompilerPass;
use Headsnet\DoctrineToolsBundle\Mapping\DoctrineTypeMappingsCompilerPass;
use Headsnet\DoctrineToolsBundle\Types\DoctrineTypesCompilerPass;
use Symfony\Component\Config\Definition\Configurator\DefinitionConfigurator;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Loader\Configurator\ContainerConfigurator;
Expand All @@ -15,6 +16,15 @@ public function configure(DefinitionConfigurator $definition): void
{
$definition->rootNode()
->children()
->scalarNode('root_namespace')->cannotBeEmpty()->end()
->arrayNode('preset_types')
->canBeDisabled()
->children()
->arrayNode('scan_dirs')
->defaultValue(['src/'])->scalarPrototype()->end()
->end()
->end()
->end() // End preset_types
->arrayNode('custom_types')
->children()
->arrayNode('scan_dirs')
Expand All @@ -33,13 +43,19 @@ public function configure(DefinitionConfigurator $definition): void

/**
* @param array{
* root_namespace: string,
* preset_types: array{scan_dirs: array<string>},
* custom_types: array{scan_dirs: array<string>},
* carbon_types: array{enabled: boolean, replace: boolean}
* } $config
*/
public function loadExtension(array $config, ContainerConfigurator $container, ContainerBuilder $builder): void
{
$container->import('../config/services.php');

$container->parameters()
->set('headsnet_doctrine_tools.root_namespace', $config['root_namespace'])
->set('headsnet_doctrine_tools.preset_types.scan_dirs', $config['preset_types']['scan_dirs'])
->set('headsnet_doctrine_tools.custom_types.scan_dirs', $config['custom_types']['scan_dirs'])
->set('headsnet_doctrine_tools.carbon_types.enabled', $config['carbon_types']['enabled'])
->set('headsnet_doctrine_tools.carbon_types.replace', $config['carbon_types']['replace'])
Expand All @@ -50,6 +66,10 @@ public function build(ContainerBuilder $container): void
{
parent::build($container);

$container->addCompilerPass(
new DoctrineTypesCompilerPass()
);

$container->addCompilerPass(
new DoctrineTypeMappingsCompilerPass()
);
Expand Down
30 changes: 30 additions & 0 deletions src/Types/CandidateType.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
<?php
declare(strict_types=1);

namespace Headsnet\DoctrineToolsBundle\Types;

final class CandidateType
{
private string $baseTypeClass;

/**
* @param class-string $objectClass
*/
public function __construct(
public readonly string $typeName,
public readonly string $typeClass,
public readonly string $baseType,
public readonly string $objectClass,
) {
}

public function setBaseTypeClass(string $baseTypeClass): void
{
$this->baseTypeClass = $baseTypeClass;
}

public function getBaseTypeClass(): string
{
return $this->baseTypeClass;
}
}
136 changes: 136 additions & 0 deletions src/Types/DoctrineTypesCompilerPass.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,136 @@
<?php
declare(strict_types=1);

namespace Headsnet\DoctrineToolsBundle\Types;

use Headsnet\DoctrineToolsBundle\Attribute\DoctrineType;
use Headsnet\DoctrineToolsBundle\Types\StandardTypes\MappingPrototype;
use League\ConstructFinder\ConstructFinder;
use ReflectionClass;
use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface;
use Symfony\Component\DependencyInjection\ContainerBuilder;

/**
* Automatically create Doctrine types for any class that implements #[DoctrineType].
*/
final class DoctrineTypesCompilerPass implements CompilerPassInterface
{
private const TYPE_DEFINITION_PARAMETER = 'doctrine.dbal.connection_factory.types';

private string $rootNamespace;

public function process(ContainerBuilder $container): void
{
if (!$container->hasParameter(self::TYPE_DEFINITION_PARAMETER)) {
return;
}

/** @var array<string, array{class: class-string}> $typeDefinitions */
$typeDefinitions = $container->getParameter(self::TYPE_DEFINITION_PARAMETER);
/** @var array<string> $scanDirs */
$scanDirs = $container->getParameter('headsnet_doctrine_tools.preset_types.scan_dirs');
$this->rootNamespace = $container->getParameter('headsnet_doctrine_tools.root_namespace'); // @phpstan-ignore-line

$objectsToRegister = $this->findObjectsToRegister($scanDirs);

$prototypeTypes = array_keys($container->findTaggedServiceIds(MappingPrototype::TAG));

foreach ($objectsToRegister as $candidate) {
// Do not add the type if it's been manually defined already
if (array_key_exists($candidate->typeName, $typeDefinitions)) {
continue;
}

/** @var MappingPrototype $prototypeType */
foreach ($prototypeTypes as $prototypeType) {
if ($prototypeType::supports($candidate->baseType)) {
$candidate->setBaseTypeClass(
$prototypeType::mappedBy()
);
}
}

if (!$candidate->getBaseTypeClass()) {
throw new \RuntimeException('Unsupported base type for Doctrine!');
}

$this->writeClassToFile($candidate);

$typeDefinitions[$candidate->typeName] = [
'class' => sprintf(
'%s\_generated\HeadsnetDoctrineTools\Types\\%s',
$this->rootNamespace,
$candidate->typeClass
),
];
}

$container->setParameter(self::TYPE_DEFINITION_PARAMETER, $typeDefinitions);
}

/**
* @param array<string> $scanDirs
*
* @return iterable<CandidateType>
*/
private function findObjectsToRegister(array $scanDirs): iterable
{
$classNames = ConstructFinder::locatedIn(...$scanDirs)->findClassNames();

foreach ($classNames as $className) {
$reflection = new ReflectionClass($className);

// Skip any abstract parent types
if ($reflection->isAbstract()) {
continue;
}

// Only register types that have the #[DoctrineType] attribute
if ($reflection->getAttributes(DoctrineType::class)) {
$attribute = $reflection->getAttributes(DoctrineType::class)[0];
$attributeArgs = $attribute->getArguments();

yield new CandidateType(
typeName: $attributeArgs['name'],
typeClass: $reflection->getShortName() . 'Type',
baseType: $attributeArgs['type'],
objectClass: $className
);
}
}
}

private function generateClass(CandidateType $candidate): string
{
return <<<PHP
<?php
namespace $this->rootNamespace\_generated\HeadsnetDoctrineTools\Types;
class $candidate->typeClass extends \\{$candidate->getBaseTypeClass()} {
public function getName(): string
{
return '$candidate->typeName';
}
public function getClass(): string
{
return '$candidate->objectClass';
}
}
PHP;
}

private function writeClassToFile(CandidateType $candidate): void
{
$classCode = $this->generateClass($candidate);

$filePath = sprintf('src/_generated/HeadsnetDoctrineTools/Types/%s.php', $candidate->typeClass);

if (!is_dir(dirname($filePath))) {
mkdir(dirname($filePath), 0777, true);
}

file_put_contents($filePath, $classCode);
}
}
45 changes: 45 additions & 0 deletions src/Types/StandardTypes/AbstractIntegerMappingType.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
<?php
declare(strict_types=1);

namespace Headsnet\DoctrineToolsBundle\Types\StandardTypes;

use Doctrine\DBAL\Platforms\AbstractPlatform;
use Doctrine\DBAL\Types\Type;

abstract class AbstractIntegerMappingType extends Type
{
public function getSQLDeclaration(array $column, AbstractPlatform $platform): string
{
return $platform->getIntegerTypeDeclarationSQL($column);
}

/**
* @param int|null $value
*/
public function convertToPHPValue($value, AbstractPlatform $platform): ?object
{
if ($value === null) {
return null;
}

$class = $this->getClass();

return $class::create($value);
}

/**
* @param object|null $value
*/
public function convertToDatabaseValue($value, AbstractPlatform $platform): ?int
{
if ($value === null) {
return null;
}

return $value->asInteger(); // @phpstan-ignore-line
}

abstract public function getName(): string;

abstract public function getClass(): string;
}
45 changes: 45 additions & 0 deletions src/Types/StandardTypes/AbstractStringMappingType.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
<?php
declare(strict_types=1);

namespace Headsnet\DoctrineToolsBundle\Types\StandardTypes;

use Doctrine\DBAL\Platforms\AbstractPlatform;
use Doctrine\DBAL\Types\Type;

abstract class AbstractStringMappingType extends Type
{
public function getSQLDeclaration(array $column, AbstractPlatform $platform): string
{
return $platform->getStringTypeDeclarationSQL($column);
}

/**
* @param string|null $value
*/
public function convertToPHPValue($value, AbstractPlatform $platform): ?object
{
if ($value === null) {
return null;
}

$class = $this->getClass();

return $class::create($value);
}

/**
* @param object|null $value
*/
public function convertToDatabaseValue($value, AbstractPlatform $platform): ?string
{
if ($value === null) {
return null;
}

return $value->asString(); // @phpstan-ignore-line
}

abstract public function getName(): string;

abstract public function getClass(): string;
}
49 changes: 49 additions & 0 deletions src/Types/StandardTypes/AbstractUuidMappingType.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
<?php
declare(strict_types=1);

namespace Headsnet\DoctrineToolsBundle\Types\StandardTypes;

use Doctrine\DBAL\Platforms\AbstractPlatform;
use Doctrine\DBAL\Types\Type;

abstract class AbstractUuidMappingType extends Type
{
public function getSQLDeclaration(array $column, AbstractPlatform $platform): string
{
return $platform->getGuidTypeDeclarationSQL($column);
}

/**
* @param string|null $value
*/
public function convertToPHPValue($value, AbstractPlatform $platform): ?object
{
if ($value === null) {
return null;
}

$class = $this->getClass();

return $class::fromString($value);
}

/**
* @param object|string|null $value
*/
public function convertToDatabaseValue($value, AbstractPlatform $platform): ?string
{
if ($value === null) {
return null;
}

if (is_string($value)) {
return $value;
}

return $value->asString(); // @phpstan-ignore-line
}

abstract public function getName(): string;

abstract public function getClass(): string;
}
Loading

0 comments on commit 435c5c5

Please sign in to comment.