commit ce5df090b00e406b6f96254be3dd1d65ea2f99f8 Author: Jan Pavlíček Date: Sun Jan 14 07:40:05 2024 +0100 Initial commit diff --git a/README b/README new file mode 100644 index 0000000..e69de29 diff --git a/composer.json b/composer.json new file mode 100644 index 0000000..60c38bb --- /dev/null +++ b/composer.json @@ -0,0 +1,12 @@ +{ + "name": "pavlicek.dev/webapp-doctrine-utils", + "description": "Collection of tools and utils useful when developing web application with Doctrine ORM and PostgreSQL", + "autoload": { + "psr-0": {"": "lib/"} + }, + "require": { + "php": ">= 8.2.0", + "doctrine/orm": "*", + "symfony/cache": "~6.3" + } +} diff --git a/lib/Common/EntityManagerFactory.php b/lib/Common/EntityManagerFactory.php new file mode 100755 index 0000000..f876c9d --- /dev/null +++ b/lib/Common/EntityManagerFactory.php @@ -0,0 +1,58 @@ + + * @since 1.0.0 + */ +class EntityManagerFactory +{ + public static function create(array $params, bool $dev_mode = false) : EntityManager + { + self::checkRequiredParams($params, ['paths', 'database', 'proxy_dir']); + + $paths = $params['paths']; + $connection = $params['database']; + + $cache_adapter = $dev_mode ? new ArrayAdapter : new FilesystemAdapter('', 0, $params['cache_dir']); + + $config = ORMSetup::createAttributeMetadataConfiguration($paths, $dev_mode, $params['proxy_dir'], $cache_adapter); + $config->setAutoGenerateProxyClasses($dev_mode ? AbstractProxyFactory::AUTOGENERATE_ALWAYS : AbstractProxyFactory::AUTOGENERATE_NEVER); + + $connection = DriverManager::getConnection($params['database'], $config); + $em = new EntityManager($connection, $config); + return $em; + } + + + + /** + * Validation method for checking parameters + * + * @throws RuntimeException + */ + private static function checkRequiredParams(array $params, array $required) : void + { + $errors = []; + foreach ($required as $name) { + if (!isset($params[$name])) { + $errors[] = "Required parameter '$name' not found in array."; + } + } + + if ($errors) { + throw new RuntimeException(implode(' ', $errors)); + } + } +} diff --git a/lib/Common/EntityRepositoryFactory.php b/lib/Common/EntityRepositoryFactory.php new file mode 100755 index 0000000..c4a5076 --- /dev/null +++ b/lib/Common/EntityRepositoryFactory.php @@ -0,0 +1,37 @@ + + * @since 1.0.0 + */ +class EntityRepositoryFactory +{ + /** + * @var Doctrine\ORM\EntityManager + */ + protected $em; + + + public function __construct(EntityManager $em) + { + $this->em = $em; + } + + + + /** + * Creates the repository using entity manager + */ + public function create(string $class) : EntityRepository + { + return $this->em->getRepository($class); + } +}