<?php
/**
* Setting Provider
*
* @author Vincent van Waasbergen <v.vanwaasbergen@visualmedia.nl>
*/
namespace VisualMedia\LisaBundle\Service;
use VisualMedia\LisaBundle\Component\Interfaces\ServiceInterface;
use VisualMedia\LisaBundle\Component\ManagerData;
use VisualMedia\SettingsBundle\Entity\BaseSetting;
use VisualMedia\SettingsBundle\Manager\BaseSettingManager;
use VisualMedia\SettingsBundle\Setting\TypeFactory\StringTypeFactory;
use VisualMedia\TranslationBundle\Service\DomainProvider;
/**
* Setting Provider
*/
class SettingProvider implements ServiceInterface
{
public const SERVICE_ID = 'visualmedia.lisa.provider.setting';
/**
* @var DomainProvider
*/
protected $domainProvider;
/**
* @var BaseSettingManager
*/
protected $manager;
/**
* @var array
*/
protected $settings = array();
/**
* @param DomainProvider $domainProvider
* @param BaseSettingManager $manager
*/
public function __construct(DomainProvider $domainProvider = null, BaseSettingManager $manager = null)
{
$this->domainProvider = $domainProvider;
$this->manager = $manager;
}
/**
* {@inheritdoc}
*/
public static function getServiceId(): string
{
return static::SERVICE_ID;
}
/**
* The first time the SettingProvider builds a cached array with all the settings from the database.
* When retrieving a setting, it will extract the setting from the cached array,
* or persists an empty setting which is set in the cache afterwards.
*
* If the Manager doesn't exists because the Bundle isn't installed, it will return null.
*
* @param string $reference
* @param string $scope
* @param string $factory
* @return BaseSetting|null
*/
public function get(string $reference, string $scope = BaseSetting::SETTING_DEFAULT, string $factory = StringTypeFactory::NAME): ?BaseSetting
{
if ($this->manager !== null) {
// Build cache.
if (empty($this->settings)) {
foreach ($result = $this->manager->getIndex() as $setting) {
$this->settings[$setting->getScope()][$setting->getReference()] = $setting;
}
}
// Persist setting if none is found.
if (null === $setting = $this->settings[$scope][$reference] ?? null) {
$domain = $this->domainProvider->getCurrentDomain();
$setting = new BaseSetting();
$setting->setName(ucfirst(str_replace('_', ' ', $reference)));
$setting->setReference($reference);
$setting->setScope($scope);
$setting->setFactory($factory);
$this->manager->persist($setting);
$this->manager->flush();
$this->settings[$scope][$reference] = $setting;
}
return $setting;
}
return null;
}
/**
* @param string $reference
* @param string $scope
* @param string $factory
* @return mixed
*/
public function getValue(string $reference, string $scope = BaseSetting::SETTING_DEFAULT, string $factory = StringTypeFactory::NAME)
{
$setting = $this->get($reference, $scope, $factory);
return $setting !== null ? $setting->getValue() : null;
}
}