KeyValueFactory.php 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. <?php
  2. namespace Drupal\Core\KeyValueStore;
  3. use Symfony\Component\DependencyInjection\ContainerInterface;
  4. /**
  5. * Defines the key/value store factory.
  6. */
  7. class KeyValueFactory implements KeyValueFactoryInterface {
  8. /**
  9. * The specific setting name prefix.
  10. *
  11. * The collection name will be prefixed with this constant and used as a
  12. * setting name. The setting value will be the id of a service.
  13. */
  14. const SPECIFIC_PREFIX = 'keyvalue_service_';
  15. /**
  16. * The default setting name.
  17. *
  18. * This is a setting name that will be used if the specific setting does not
  19. * exist. The setting value will be the id of a service.
  20. */
  21. const DEFAULT_SETTING = 'default';
  22. /**
  23. * The default service id.
  24. *
  25. * If the default setting does not exist, this is the default service id.
  26. */
  27. const DEFAULT_SERVICE = 'keyvalue.database';
  28. /**
  29. * Instantiated stores, keyed by collection name.
  30. *
  31. * @var array
  32. */
  33. protected $stores = [];
  34. /**
  35. * @var \Symfony\Component\DependencyInjection\ContainerInterface
  36. */
  37. protected $container;
  38. /**
  39. * @param \Symfony\Component\DependencyInjection\ContainerInterface $container
  40. * The service container.
  41. * @param array $options
  42. * (optional) Collection-specific storage override options.
  43. */
  44. public function __construct(ContainerInterface $container, array $options = []) {
  45. $this->container = $container;
  46. $this->options = $options;
  47. }
  48. /**
  49. * {@inheritdoc}
  50. */
  51. public function get($collection) {
  52. if (!isset($this->stores[$collection])) {
  53. if (isset($this->options[$collection])) {
  54. $service_id = $this->options[$collection];
  55. }
  56. elseif (isset($this->options[static::DEFAULT_SETTING])) {
  57. $service_id = $this->options[static::DEFAULT_SETTING];
  58. }
  59. else {
  60. $service_id = static::DEFAULT_SERVICE;
  61. }
  62. $this->stores[$collection] = $this->container->get($service_id)->get($collection);
  63. }
  64. return $this->stores[$collection];
  65. }
  66. }