Skip to content

Commit

Permalink
Initial commit
Browse files Browse the repository at this point in the history
  • Loading branch information
egbuk committed Jan 7, 2025
0 parents commit ab78a57
Show file tree
Hide file tree
Showing 22 changed files with 1,163 additions and 0 deletions.
22 changes: 22 additions & 0 deletions .github/workflows/test.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
name: Test
run-name: ${{ github.actor }} is testing heymoon/doctrine-psql-enum
on:
workflow_dispatch: {}
push:
paths:
- config
- src
- tests
- composer.json
- Makefile
- phpunit.xml
jobs:
test:
runs-on: Linux
steps:
- uses: actions/checkout@v1
- run: make test
- name: Upload test results
uses: mikepenz/action-junit-report@v3
with:
report_paths: test-reports/tests.xml
5 changes: 5 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
/.idea
/.phpunit.cache
/vendor
/test-reports
/composer.lock
21 changes: 21 additions & 0 deletions LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
MIT License

Copyright (c) 2023 HeyMoon

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
2 changes: 2 additions & 0 deletions Makefile
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
test:
bash -c "docker run --rm -i -v $$(pwd):/app composer:latest test"
61 changes: 61 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
# Doctrine enums for PostgreSQL
[![Test](https://github.com/heymoon-cc/doctrine-psql-enum/actions/workflows/test.yaml/badge.svg)](https://github.com/heymoon-cc/doctrine-psql-enum/actions/workflows/test.yaml)
## Prerequisites: *Symfony 6 + Doctrine 2*

### Installation
`composer require heymoon/doctrine-psql-enum`

### Usage
Create library configuration:

`config/packages/doctrine_postgres_enum.yaml`
```yaml
doctrine_postgres_enum:
type_name: enum
migrations:
enabled: true
comment_tag: DC2Enum
```
For defining new enum type, [use native PHP enums](https://www.php.net/manual/language.types.enumerations.php):
```php
enum AuthStatus: string
{
case New = 'new';
case Active = 'active';
case Inactive = 'inactive';
case Deleted = 'deleted';
}

enum Service: string
{
case Google = 'google';
}
```
For creation of enum-field in model, use `enum` as `type` value, `enumType` in `Column` attribute must be defined:
```php
#[ORM\Entity(repositoryClass: AuthRepository::class)]
class Auth
{
#[ORM\Id]
#[ORM\GeneratedValue(strategy: "CUSTOM")]
#[ORM\CustomIdGenerator(class: "doctrine.uuid_generator")]
#[ORM\Column(type: 'uuid')]
private Uuid $id;

#[ORM\Column(type: 'enum', enumType: AuthStatus::class)]
private AuthStatus $status;

#[ORM\Column(type: 'enum', enumType: Service::class)]
private Service $service;
}
```
Create migrations via `make:migration`. If enum was created or modified, the `CREATE TYPE`/`ALTER TYPE` calls would be added to migration. Example:
```php
$this->addSql('DROP TYPE IF EXISTS app_entity_type_authstatus');
$this->addSql('CREATE TYPE app_entity_type_authstatus AS ENUM (\'new\',\'active\',\'inactive\',\'deleted\')');
$this->addSql('DROP TYPE IF EXISTS app_entity_type_service');
$this->addSql('CREATE TYPE app_entity_type_service AS ENUM (\'google\')');
$this->addSql('CREATE TABLE auth (id UUID NOT NULL, status app_entity_type_authstatus NOT NULL, service app_entity_type_service NOT NULL, PRIMARY KEY(id))');
$this->addSql('COMMENT ON COLUMN auth.status IS \'(DC2Enum:App\\Entity\\Type\\AuthStatus)\'');
$this->addSql('COMMENT ON COLUMN auth.service IS \'(DC2Enum:App\\Entity\\Type\\Service)\'');
```
45 changes: 45 additions & 0 deletions composer.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
{
"name": "heymoon/doctrine-psql-enum",
"version": "1.0.0",
"description": "Store PHP8.1 native enums as PostgeSQL custom enum types",
"type": "symfony-bundle",
"license": "MIT",
"keywords": ["doctrine-orm", "postgresql", "enum"],
"require": {
"php": ">=8.1",
"doctrine/doctrine-bundle": "2.*",
"doctrine/orm": "2.*",
"symfony/framework-bundle": "6.*"
},
"require-dev": {
"symfony/yaml": "6.*",
"doctrine/doctrine-migrations-bundle": "3.*",
"phpunit/phpunit": "^9.5",
"symfony/orm-pack": "2.*"
},
"autoload": {
"psr-4": {
"HeyMoon\\DoctrinePostgresEnum\\": "src/"
}
},
"autoload-dev": {
"psr-4": {
"HeyMoon\\DoctrinePostgresEnum\\Tests\\": "tests/"
}
},
"authors": [
{
"name": "Egor",
"email": "me@heymoon.cc"
}
],
"scripts": {
"test": [
"@composer install",
"phpunit --log-junit=test-reports/tests.xml"
]
},
"config": {
"secure-http": false
}
}
11 changes: 11 additions & 0 deletions config/subscriber.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
services:
_defaults:
autowire: true
autoconfigure: true

HeyMoon\DoctrinePostgresEnum\Doctrine\Provider\MetaDataProviderInterface:
class: HeyMoon\DoctrinePostgresEnum\Doctrine\Provider\MetaDataProvider

HeyMoon\DoctrinePostgresEnum\Doctrine\Listener\DoctrineEnumColumnListener:
tags:
name: 'doctrine.event_subscriber'
27 changes: 27 additions & 0 deletions phpunit.xml
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
<?xml version="1.0" encoding="UTF-8"?>
<phpunit xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="https://schema.phpunit.de/9.5/phpunit.xsd"
bootstrap="vendor/autoload.php"
cacheResultFile=".phpunit.cache/test-results"
executionOrder="depends,defects"
forceCoversAnnotation="true"
beStrictAboutCoversAnnotation="true"
beStrictAboutOutputDuringTests="true"
beStrictAboutTodoAnnotatedTests="true"
convertDeprecationsToExceptions="true"
failOnRisky="true"
failOnWarning="true"
verbose="true">
<testsuites>
<testsuite name="default">
<directory>tests</directory>
</testsuite>
</testsuites>

<coverage cacheDirectory=".phpunit.cache/code-coverage"
processUncoveredFiles="true">
<include>
<directory suffix=".php">src</directory>
</include>
</coverage>
</phpunit>
25 changes: 25 additions & 0 deletions src/DependencyInjection/Configuration.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
<?php

namespace HeyMoon\DoctrinePostgresEnum\DependencyInjection;

use HeyMoon\DoctrinePostgresEnum\Doctrine\Type\EnumType;
use Symfony\Component\Config\Definition\Builder\TreeBuilder;
use Symfony\Component\Config\Definition\ConfigurationInterface;

class Configuration implements ConfigurationInterface
{
public function getConfigTreeBuilder(): TreeBuilder
{
$treeBuilder = new TreeBuilder('doctrine_postgres_enum');
$treeBuilder->getRootNode()
->children()
->scalarNode('type_name')->defaultValue(EnumType::DEFAULT_NAME)->end()
->arrayNode('migrations')
->children()
->scalarNode('enabled')->defaultTrue()->end()
->scalarNode('comment_tag')->defaultValue('DC2Enum')->end()
->end()
->end();
return $treeBuilder;
}
}
64 changes: 64 additions & 0 deletions src/DependencyInjection/DoctrinePostgresEnumExtension.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
<?php

namespace HeyMoon\DoctrinePostgresEnum\DependencyInjection;

use Doctrine\Bundle\MigrationsBundle\DoctrineMigrationsBundle;
use Exception;
use LogicException;
use HeyMoon\DoctrinePostgresEnum\Doctrine\Type\EnumType;
use Symfony\Component\Config\FileLocator;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Extension\Extension;
use Symfony\Component\DependencyInjection\Extension\PrependExtensionInterface;
use Symfony\Component\DependencyInjection\Loader\YamlFileLoader;

class DoctrinePostgresEnumExtension extends Extension implements PrependExtensionInterface
{
/**
* @throws Exception
*/
public function load(array $configs, ContainerBuilder $container)
{
$configuration = $this->getConfiguration($configs, $container);
$cfg = $this->processConfiguration($configuration, $configs);
EnumType::setDefaultName($cfg['type_name'] ?? EnumType::DEFAULT_NAME);
$loader = new YamlFileLoader($container, new FileLocator(__DIR__.'/../../config'));
if ($this->isConfigEnabled($container, $cfg['migrations'])) {
if ($this->checkMigrationsAvailability()) {
EnumType::setCommentTag($cfg['migrations']['comment_tag']);
$loader->load('subscriber.yaml');
} else {
throw new LogicException('Cannot use migrations without doctrine/doctrine-migrations-bundle.');
}
}
}

public function getConfiguration(array $config, ContainerBuilder $container): Configuration
{
return new Configuration();
}

private function checkMigrationsAvailability(): bool
{
return ContainerBuilder::willBeAvailable(
'doctrine/doctrine-migrations-bundle',
DoctrineMigrationsBundle::class,
['heymoon/doctrine-psql-enum']
);
}

/**
* @throws Exception
*/
public function prepend(ContainerBuilder $container): void
{
$this->load($container->getExtensionConfig('doctrine_postgres_enum'), $container);
$container->prependExtensionConfig('doctrine', [
'dbal' => [
'types' => [
EnumType::getDefaultName() => EnumType::class
]
]
]);
}
}
18 changes: 18 additions & 0 deletions src/Doctrine/Exception/UnsupportedPlatformException.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
<?php

namespace HeyMoon\DoctrinePostgresEnum\Doctrine\Exception;

use Doctrine\DBAL\Platforms\AbstractPlatform;
use Doctrine\ORM\Exception\ORMException;
use ReflectionClass;

final class UnsupportedPlatformException extends ORMException
{
public static function create(AbstractPlatform $platform): self
{
$reflection = new ReflectionClass($platform);
return new self(
"Platform {$reflection->getShortName()} is unsupported by heymoon/doctrine-psql-enum. Switch platform to PostgreSQL or disable this extension."
);
}
}
Loading

0 comments on commit ab78a57

Please sign in to comment.