<?php
namespace App\Helper;
use App\Entity\System\Config;
use Doctrine\ORM\EntityManagerInterface;
class ConfigHelper
{
protected $em;
protected $config;
public function __construct(EntityManagerInterface $em)
{
$this->em = $em;
$this->config = array();
// Get everything into an array
$allConfig = $this->em->getRepository(Config::class)->findAll();
foreach($allConfig AS $someConfig)
$this->config[$someConfig->getKey()] = $someConfig;
}
public function getAll()
{
return $this->config;
}
public function get($key)
{
if(!array_key_exists($key, $this->config))
return null;
else
return $this->config[$key];
}
public function getValue($key, $default = null)
{
if(!array_key_exists($key, $this->config))
return $default;
else
return $this->config[$key]->getValue();
}
public function setValue($key, $value, $autoCreate = true)
{
// Is the value null?
if($value === null)
$value = "";
if(!array_key_exists($key, $this->config))
{
// Should we auto create it?
if($autoCreate)
{
$this->config[$key] = new Config(array(
"key" => $key,
"value" => $value
));
}
else
throw new \Exception("Config item not found: " . $key);
}
else
$this->config[$key]->setValue($value);
// Persist and flush
$this->em->persist($this->config[$key]);
$this->em->flush();
}
}