Advertisement
Guest User

DoctrineORMServiceProvider

a guest
Apr 13th, 2016
102
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 18.29 KB | None | 0 0
  1. <?php
  2.  
  3. /*
  4.  * This file is a part of dflydev/doctrine-orm-service-provider.
  5.  *
  6.  * (c) Dragonfly Development Inc.
  7.  *
  8.  * For the full copyright and license information, please view the LICENSE
  9.  * file that was distributed with this source code.
  10.  */
  11.  
  12. namespace App\Service;
  13.  
  14. use Doctrine\Common\Cache\ApcCache;
  15. use Doctrine\Common\Cache\ArrayCache;
  16. use Doctrine\Common\Cache\CacheProvider;
  17. use Doctrine\Common\Cache\FilesystemCache;
  18. use Doctrine\Common\Cache\MemcacheCache;
  19. use Doctrine\Common\Cache\MemcachedCache;
  20. use Doctrine\Common\Cache\CouchbaseCache;
  21. use Doctrine\Common\Cache\XcacheCache;
  22. use Doctrine\Common\Cache\RedisCache;
  23. use Doctrine\Common\Persistence\Mapping\Driver\MappingDriver;
  24. use Doctrine\Common\Persistence\Mapping\Driver\MappingDriverChain;
  25. use Doctrine\DBAL\Types\Type;
  26. use Doctrine\ORM\Configuration;
  27. use Doctrine\ORM\EntityManager;
  28. use Doctrine\ORM\Mapping\DefaultEntityListenerResolver;
  29. use Doctrine\ORM\Mapping\DefaultNamingStrategy;
  30. use Doctrine\ORM\Mapping\DefaultQuoteStrategy;
  31. use Doctrine\ORM\Mapping\Driver\Driver;
  32. use Doctrine\ORM\Mapping\Driver\SimplifiedXmlDriver;
  33. use Doctrine\ORM\Mapping\Driver\SimplifiedYamlDriver;
  34. use Doctrine\ORM\Mapping\Driver\XmlDriver;
  35. use Doctrine\ORM\Mapping\Driver\YamlDriver;
  36. use Doctrine\ORM\Mapping\Driver\StaticPHPDriver;
  37. use Doctrine\ORM\Repository\DefaultRepositoryFactory;
  38. use Pimple\Container;
  39. use Pimple\ServiceProviderInterface;
  40.  
  41. /**
  42.  * Doctrine ORM Pimple Service Provider.
  43.  *
  44.  * @author Beau Simensen <beau@dflydev.com>
  45.  */
  46. class DoctrineOrmServiceProvider implements ServiceProviderInterface
  47. {
  48.     public function register(Container $container)
  49.     {
  50.         foreach ($this->getOrmDefaults() as $key => $value) {
  51.             if (!isset($container[$key])) {
  52.                 $container[$key] = $value;
  53.             }
  54.         }
  55.  
  56.         $container['orm.em.default_options'] = array(
  57.             'connection' => 'default',
  58.             'mappings' => array(),
  59.             'types' => array()
  60.         );
  61.  
  62.         $container['orm.ems.options.initializer'] = $container->protect(function () use ($container) {
  63.             static $initialized = false;
  64.  
  65.             if ($initialized) {
  66.                 return;
  67.             }
  68.  
  69.             $initialized = true;
  70.  
  71.             if (!isset($container['orm.ems.options'])) {
  72.                 $container['orm.ems.options'] = array('default' => isset($container['orm.em.options']) ? $container['orm.em.options'] : array());
  73.             }
  74.  
  75.             $tmp = $container['orm.ems.options'];
  76.             foreach ($tmp as $name => &$options) {
  77.                 $options = array_replace($container['orm.em.default_options'], $options);
  78.  
  79.                 if (!isset($container['orm.ems.default'])) {
  80.                     $container['orm.ems.default'] = $name;
  81.                 }
  82.             }
  83.             $container['orm.ems.options'] = $tmp;
  84.         });
  85.  
  86.         $container['orm.em_name_from_param_key'] = $container->protect(function ($paramKey) use ($container) {
  87.             $container['orm.ems.options.initializer']();
  88.  
  89.             if (isset($container[$paramKey])) {
  90.                 return $container[$paramKey];
  91.             }
  92.  
  93.             return $container['orm.ems.default'];
  94.         });
  95.  
  96.         $container['orm.ems'] = function ($container) {
  97.             $container['orm.ems.options.initializer']();
  98.  
  99.             $ems = new Container();
  100.             foreach ($container['orm.ems.options'] as $name => $options) {
  101.                 if ($container['orm.ems.default'] === $name) {
  102.                     // we use shortcuts here in case the default has been overridden
  103.                     $config = $container['orm.em.config'];
  104.                 } else {
  105.                     $config = $container['orm.ems.config'][$name];
  106.                 }
  107.  
  108.                 $ems[$name] = function ($ems) use ($container, $options, $config) {
  109.                     return EntityManager::create(
  110.                         $container['dbs'][$options['connection']],
  111.                         $config,
  112.                         $container['dbs.event_manager'][$options['connection']]
  113.                     );
  114.                 };
  115.             }
  116.  
  117.             return $ems;
  118.         };
  119.  
  120.         $container['orm.ems.config'] = function ($container) {
  121.             $container['orm.ems.options.initializer']();
  122.  
  123.             $configs = new Container();
  124.             foreach ($container['orm.ems.options'] as $name => $options) {
  125.                 $config = new Configuration;
  126.  
  127.                 $container['orm.cache.configurer']($name, $config, $options);
  128.  
  129.                 $config->setProxyDir($container['orm.proxies_dir']);
  130.                 $config->setProxyNamespace($container['orm.proxies_namespace']);
  131.                 $config->setAutoGenerateProxyClasses($container['orm.auto_generate_proxies']);
  132.  
  133.                 $config->setCustomStringFunctions($container['orm.custom.functions.string']);
  134.                 $config->setCustomNumericFunctions($container['orm.custom.functions.numeric']);
  135.                 $config->setCustomDatetimeFunctions($container['orm.custom.functions.datetime']);
  136.                 $config->setCustomHydrationModes($container['orm.custom.hydration_modes']);
  137.  
  138.                 $config->setClassMetadataFactoryName($container['orm.class_metadata_factory_name']);
  139.                 $config->setDefaultRepositoryClassName($container['orm.default_repository_class']);
  140.  
  141.                 $config->setEntityListenerResolver($container['orm.entity_listener_resolver']);
  142.                 $config->setRepositoryFactory($container['orm.repository_factory']);
  143.  
  144.                 $config->setNamingStrategy($container['orm.strategy.naming']);
  145.                 $config->setQuoteStrategy($container['orm.strategy.quote']);
  146.  
  147.                 $chain = $container['orm.mapping_driver_chain.locator']($name);
  148.  
  149.                 foreach ((array) $options['mappings'] as $entity) {
  150.                     if (!is_array($entity)) {
  151.                         throw new \InvalidArgumentException(
  152.                             "The 'orm.em.options' option 'mappings' should be an array of arrays."
  153.                         );
  154.                     }
  155.  
  156.                     if (isset($entity['alias'])) {
  157.                         $config->addEntityNamespace($entity['alias'], $entity['namespace']);
  158.                     }
  159.  
  160.                     switch ($entity['type']) {
  161.                         case 'annotation':
  162.                             $useSimpleAnnotationReader =
  163.                                 isset($entity['use_simple_annotation_reader'])
  164.                                 ? $entity['use_simple_annotation_reader']
  165.                                 : true;
  166.                             $driver = $config->newDefaultAnnotationDriver((array) $entity['path'], $useSimpleAnnotationReader);
  167.                             $chain->addDriver($driver, $entity['namespace']);
  168.                             break;
  169.                         case 'yml':
  170.                             $driver = new YamlDriver($entity['path']);
  171.                             $chain->addDriver($driver, $entity['namespace']);
  172.                             break;
  173.                         case 'simple_yml':
  174.                             $driver = new SimplifiedYamlDriver(array($entity['path'] => $entity['namespace']));
  175.                             $chain->addDriver($driver, $entity['namespace']);
  176.                             break;
  177.                         case 'xml':
  178.                             $driver = new XmlDriver($entity['path']);
  179.                             $chain->addDriver($driver, $entity['namespace']);
  180.                             break;
  181.                         case 'simple_xml':
  182.                             $driver = new SimplifiedXmlDriver(array($entity['path'] => $entity['namespace']));
  183.                             $chain->addDriver($driver, $entity['namespace']);
  184.                             break;
  185.                         case 'php':
  186.                             $driver = new StaticPHPDriver($entity['path']);
  187.                             $chain->addDriver($driver, $entity['namespace']);
  188.                             break;
  189.                         default:
  190.                             throw new \InvalidArgumentException(sprintf('"%s" is not a recognized driver', $entity['type']));
  191.                             break;
  192.                     }
  193.                 }
  194.                 $config->setMetadataDriverImpl($chain);
  195.  
  196.                 foreach ((array) $options['types'] as $typeName => $typeClass) {
  197.                     if (Type::hasType($typeName)) {
  198.                         Type::overrideType($typeName, $typeClass);
  199.                     } else {
  200.                         Type::addType($typeName, $typeClass);
  201.                     }
  202.                 }
  203.  
  204.                 $configs[$name] = $config;
  205.             }
  206.  
  207.             return $configs;
  208.         };
  209.  
  210.         $container['orm.cache.configurer'] = $container->protect(function ($name, Configuration $config, $options) use ($container) {
  211.             $config->setMetadataCacheImpl($container['orm.cache.locator']($name, 'metadata', $options));
  212.             $config->setQueryCacheImpl($container['orm.cache.locator']($name, 'query', $options));
  213.             $config->setResultCacheImpl($container['orm.cache.locator']($name, 'result', $options));
  214.             $config->setHydrationCacheImpl($container['orm.cache.locator']($name, 'hydration', $options));
  215.         });
  216.  
  217.         $container['orm.cache.locator'] = $container->protect(function ($name, $cacheName, $options) use ($container) {
  218.             $cacheNameKey = $cacheName . '_cache';
  219.  
  220.             if (!isset($options[$cacheNameKey])) {
  221.                 $options[$cacheNameKey] = $container['orm.default_cache'];
  222.             }
  223.  
  224.             if (isset($options[$cacheNameKey]) && !is_array($options[$cacheNameKey])) {
  225.                 $options[$cacheNameKey] = array(
  226.                     'driver' => $options[$cacheNameKey],
  227.                 );
  228.             }
  229.  
  230.             if (!isset($options[$cacheNameKey]['driver'])) {
  231.                 throw new \RuntimeException("No driver specified for '$cacheName'");
  232.             }
  233.  
  234.             $driver = $options[$cacheNameKey]['driver'];
  235.  
  236.             $cacheInstanceKey = 'orm.cache.instances.'.$name.'.'.$cacheName;
  237.             if (isset($container[$cacheInstanceKey])) {
  238.                 return $container[$cacheInstanceKey];
  239.             }
  240.  
  241.             $cache = $container['orm.cache.factory']($driver, $options[$cacheNameKey]);
  242.  
  243.             if (isset($options['cache_namespace']) && $cache instanceof CacheProvider) {
  244.                 $cache->setNamespace($options['cache_namespace']);
  245.             }
  246.  
  247.             return $container[$cacheInstanceKey] = $cache;
  248.         });
  249.  
  250.         $container['orm.cache.factory.backing_memcache'] = $container->protect(function () {
  251.             return new \Memcache;
  252.         });
  253.  
  254.         $container['orm.cache.factory.memcache'] = $container->protect(function ($cacheOptions) use ($container) {
  255.             if (empty($cacheOptions['host']) || empty($cacheOptions['port'])) {
  256.                 throw new \RuntimeException('Host and port options need to be specified for memcache cache');
  257.             }
  258.  
  259.             /** @var \Memcache $memcache */
  260.             $memcache = $container['orm.cache.factory.backing_memcache']();
  261.             $memcache->connect($cacheOptions['host'], $cacheOptions['port']);
  262.  
  263.             $cache = new MemcacheCache;
  264.             $cache->setMemcache($memcache);
  265.  
  266.             return $cache;
  267.         });
  268.  
  269.         $container['orm.cache.factory.backing_memcached'] = $container->protect(function () {
  270.             return new \Memcached;
  271.         });
  272.  
  273.         $container['orm.cache.factory.memcached'] = $container->protect(function ($cacheOptions) use ($container) {
  274.             if (empty($cacheOptions['host']) || empty($cacheOptions['port'])) {
  275.                 throw new \RuntimeException('Host and port options need to be specified for memcached cache');
  276.             }
  277.  
  278.             /** @var \Memcached $memcached */
  279.             $memcached = $container['orm.cache.factory.backing_memcached']();
  280.             $memcached->addServer($cacheOptions['host'], $cacheOptions['port']);
  281.  
  282.             $cache = new MemcachedCache;
  283.             $cache->setMemcached($memcached);
  284.  
  285.             return $cache;
  286.         });
  287.  
  288.         $container['orm.cache.factory.backing_redis'] = $container->protect(function () {
  289.             return new \Redis;
  290.         });
  291.  
  292.         $container['orm.cache.factory.redis'] = $container->protect(function ($cacheOptions) use ($container) {
  293.             if (empty($cacheOptions['host']) || empty($cacheOptions['port'])) {
  294.                 throw new \RuntimeException('Host and port options need to be specified for redis cache');
  295.             }
  296.  
  297.             /** @var \Redis $redis */
  298.             $redis = $container['orm.cache.factory.backing_redis']();
  299.             $redis->connect($cacheOptions['host'], $cacheOptions['port']);
  300.  
  301.             if (isset($cacheOptions['password'])) {
  302.                 $redis->auth($cacheOptions['password']);
  303.             }
  304.  
  305.             $cache = new RedisCache;
  306.             $cache->setRedis($redis);
  307.  
  308.             return $cache;
  309.         });
  310.  
  311.         $container['orm.cache.factory.array'] = $container->protect(function () {
  312.             return new ArrayCache;
  313.         });
  314.  
  315.         $container['orm.cache.factory.apc'] = $container->protect(function () {
  316.             return new ApcCache;
  317.         });
  318.  
  319.         $container['orm.cache.factory.xcache'] = $container->protect(function () {
  320.             return new XcacheCache;
  321.         });
  322.  
  323.         $container['orm.cache.factory.filesystem'] = $container->protect(function ($cacheOptions) {
  324.             if (empty($cacheOptions['path'])) {
  325.                 throw new \RuntimeException('FilesystemCache path not defined');
  326.             }
  327.  
  328.             $cacheOptions += array(
  329.                 'extension' => FilesystemCache::EXTENSION,
  330.                 'umask' => 0002,
  331.             );
  332.             return new FilesystemCache($cacheOptions['path'], $cacheOptions['extension'], $cacheOptions['umask']);
  333.         });
  334.  
  335.         $container['orm.cache.factory.couchbase'] = $container->protect(function($cacheOptions){
  336.           $host='';
  337.           $bucketName='';
  338.           $user='';
  339.           $password='';
  340.           if (empty($cacheOptions['host'])) {
  341.             $host='127.0.0.1';
  342.           }
  343.           if (empty($cacheOptions['bucket'])) {
  344.             $bucketName='default';
  345.           }
  346.           if (!empty($cacheOptions['user'])) {
  347.             $user=$cacheOptions['user'];
  348.           }
  349.           if (!empty($cacheOptions['password'])) {
  350.             $password=$cacheOptions['password'];
  351.           }
  352.  
  353.           $couchbase = new \Couchbase($host,$user,$password,$bucketName);
  354.           $cache = new CouchbaseCache();
  355.           $cache->setCouchbase($couchbase);
  356.           return $cache;
  357.         });
  358.  
  359.         $container['orm.cache.factory'] = $container->protect(function ($driver, $cacheOptions) use ($container) {
  360.             $cacheFactoryKey = 'orm.cache.factory.'.$driver;
  361.             if (!isset($container[$cacheFactoryKey])) {
  362.                 throw new \RuntimeException("Factory '$cacheFactoryKey' for cache type '$driver' not defined (is it spelled correctly?)");
  363.             }
  364.  
  365.             return $container[$cacheFactoryKey]($cacheOptions);
  366.         });
  367.  
  368.         $container['orm.mapping_driver_chain.locator'] = $container->protect(function ($name = null) use ($container) {
  369.             $container['orm.ems.options.initializer']();
  370.  
  371.             if (null === $name) {
  372.                 $name = $container['orm.ems.default'];
  373.             }
  374.  
  375.             $cacheInstanceKey = 'orm.mapping_driver_chain.instances.'.$name;
  376.             if (isset($container[$cacheInstanceKey])) {
  377.                 return $container[$cacheInstanceKey];
  378.             }
  379.  
  380.             return $container[$cacheInstanceKey] = $container['orm.mapping_driver_chain.factory']($name);
  381.         });
  382.  
  383.         $container['orm.mapping_driver_chain.factory'] = $container->protect(function ($name) use ($container) {
  384.             return new MappingDriverChain;
  385.         });
  386.  
  387.         $container['orm.add_mapping_driver'] = $container->protect(function (MappingDriver $mappingDriver, $namespace, $name = null) use ($container) {
  388.             $container['orm.ems.options.initializer']();
  389.  
  390.             if (null === $name) {
  391.                 $name = $container['orm.ems.default'];
  392.             }
  393.  
  394.             /** @var MappingDriverChain $driverChain */
  395.             $driverChain = $container['orm.mapping_driver_chain.locator']($name);
  396.             $driverChain->addDriver($mappingDriver, $namespace);
  397.         });
  398.  
  399.         $container['orm.strategy.naming'] = function($container) {
  400.             return new DefaultNamingStrategy;
  401.         };
  402.  
  403.         $container['orm.strategy.quote'] = function($container) {
  404.             return new DefaultQuoteStrategy;
  405.         };
  406.  
  407.         $container['orm.entity_listener_resolver'] = function($container) {
  408.             return new DefaultEntityListenerResolver;
  409.         };
  410.  
  411.         $container['orm.repository_factory'] = function($container) {
  412.             return new DefaultRepositoryFactory;
  413.         };
  414.  
  415.         $container['orm.em'] = function ($container) {
  416.             $ems = $container['orm.ems'];
  417.  
  418.             return $ems[$container['orm.ems.default']];
  419.         };
  420.  
  421.         $container['orm.em.config'] = function ($container) {
  422.             $configs = $container['orm.ems.config'];
  423.  
  424.             return $configs[$container['orm.ems.default']];
  425.         };
  426.     }
  427.  
  428.     /**
  429.      * Get default ORM configuration settings.
  430.      *
  431.      * @param Container $container
  432.      *
  433.      * @return array
  434.      */
  435.     protected function getOrmDefaults()
  436.     {
  437.         return array(
  438.             'orm.proxies_dir' => __DIR__.'/../../../../../../../../cache/doctrine/proxies',
  439.             'orm.proxies_namespace' => 'DoctrineProxy',
  440.             'orm.auto_generate_proxies' => true,
  441.             'orm.default_cache' => array(
  442.                 'driver' => 'array',
  443.             ),
  444.             'orm.custom.functions.string' => array(),
  445.             'orm.custom.functions.numeric' => array(),
  446.             'orm.custom.functions.datetime' => array(),
  447.             'orm.custom.hydration_modes' => array(),
  448.             'orm.class_metadata_factory_name' => 'Doctrine\ORM\Mapping\ClassMetadataFactory',
  449.             'orm.default_repository_class' => 'Doctrine\ORM\EntityRepository',
  450.         );
  451.     }
  452. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement