src/Helper/ConfigHelper.php line 13

Open in your IDE?
  1. <?php
  2. namespace App\Helper;
  3. use App\Entity\System\Config;
  4. use Doctrine\ORM\EntityManagerInterface;
  5. class ConfigHelper
  6. {
  7.     protected $em;
  8.     protected $config;
  9.     public function __construct(EntityManagerInterface $em)
  10.     {
  11.         $this->em $em;
  12.         $this->config = array();
  13.         // Get everything into an array
  14.         $allConfig $this->em->getRepository(Config::class)->findAll();
  15.         foreach($allConfig AS $someConfig)
  16.             $this->config[$someConfig->getKey()] = $someConfig;
  17.     }
  18.     public function getAll()
  19.     {
  20.         return $this->config;
  21.     }
  22.     public function get($key)
  23.     {
  24.         if(!array_key_exists($key$this->config))
  25.             return null;
  26.         else
  27.             return $this->config[$key];
  28.     }
  29.     public function getValue($key$default null)
  30.     {
  31.         if(!array_key_exists($key$this->config))
  32.             return $default;
  33.         else
  34.             return $this->config[$key]->getValue();
  35.     }
  36.     public function setValue($key$value$autoCreate true)
  37.     {
  38.         // Is the value null?
  39.         if($value === null)
  40.             $value "";
  41.         if(!array_key_exists($key$this->config))
  42.         {
  43.             // Should we auto create it?
  44.             if($autoCreate)
  45.             {
  46.                 $this->config[$key] = new Config(array(
  47.                     "key" => $key,
  48.                     "value" => $value
  49.                 ));
  50.             }
  51.             else
  52.                 throw new \Exception("Config item not found: " $key);
  53.         }
  54.         else
  55.             $this->config[$key]->setValue($value);
  56.         // Persist and flush
  57.         $this->em->persist($this->config[$key]);
  58.         $this->em->flush();
  59.     }
  60. }