2019-05-23 17:04:48 +02:00
|
|
|
<?php
|
|
|
|
|
2020-07-25 15:40:27 +02:00
|
|
|
namespace Ardent\ArdentParameterBundle\Service;
|
2019-05-23 17:04:48 +02:00
|
|
|
|
2020-07-25 16:07:01 +02:00
|
|
|
use Ardent\ParameterBundle\Entity\Parameter;
|
2019-05-23 17:04:48 +02:00
|
|
|
use Doctrine\ORM\EntityManagerInterface;
|
|
|
|
use Symfony\Component\DependencyInjection\ParameterBag\ParameterBagInterface;
|
|
|
|
|
|
|
|
class ParameterService
|
|
|
|
{
|
|
|
|
/** @var EntityManagerInterface */
|
|
|
|
private $em;
|
|
|
|
|
|
|
|
/** @var ParameterBagInterface */
|
|
|
|
private $parameter;
|
|
|
|
|
|
|
|
/**
|
|
|
|
* ParameterService constructor.
|
|
|
|
*
|
|
|
|
* @param EntityManagerInterface $em
|
|
|
|
*/
|
|
|
|
public function __construct(EntityManagerInterface $em, ParameterBagInterface $parameter)
|
|
|
|
{
|
|
|
|
$this->em = $em;
|
|
|
|
$this->parameter = $parameter;
|
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
* @param string $name
|
|
|
|
* @param bool $parse
|
|
|
|
*
|
|
|
|
* @return string
|
|
|
|
*/
|
|
|
|
public function get($name, $parse = true)
|
|
|
|
{
|
|
|
|
$paramRepo = $this->em->getRepository(Parameter::class);
|
|
|
|
$parameter = $paramRepo->findOneBy(['name' => $name]);
|
|
|
|
if ($parameter) {
|
|
|
|
if ($parse) {
|
|
|
|
// find and replace all %parameter% with their value
|
|
|
|
$value = preg_replace_callback('/%([^%\s]+)%/', function ($match) {
|
|
|
|
$key = $match[1];
|
|
|
|
// first try locally
|
|
|
|
if ($value = $this->get($key)) {
|
|
|
|
return $value;
|
|
|
|
}
|
|
|
|
// then try with parameter bag
|
|
|
|
return $this->parameter->get($key);
|
|
|
|
},
|
|
|
|
$parameter->getValue()
|
|
|
|
);
|
|
|
|
} else {
|
|
|
|
$value = $parameter->getValue();
|
|
|
|
}
|
|
|
|
|
|
|
|
return $value;
|
|
|
|
} else {
|
|
|
|
return null;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
* @param $name
|
|
|
|
* @param $value
|
|
|
|
*/
|
|
|
|
public function set($name, $value)
|
|
|
|
{
|
|
|
|
$paramRepo = $this->em->getRepository(Parameter::class);
|
|
|
|
/* @var Parameter $parameter */
|
|
|
|
$parameter = $paramRepo->findOneBy(['name' => $name]);
|
|
|
|
if (!$parameter) {
|
|
|
|
$parameter = (new Parameter())->setName($name);
|
|
|
|
}
|
|
|
|
$parameter->setValue($value);
|
|
|
|
$this->em->persist($parameter);
|
|
|
|
$this->em->flush();
|
|
|
|
}
|
|
|
|
}
|