<?php
namespace App\Controller\Backend;
use Symfony\Contracts\Cache\CacheInterface;
use FOS\RestBundle\Controller\AbstractFOSRestController;
use App\Service\BaseService;
class BaseController extends AbstractFOSRestController
{
public function __construct(
BaseService $baseService,
CacheInterface $appCache
) {
$this->baseService = $baseService;
$this->entityManager = $baseService->getEntityManager();
$this->commonService = $baseService->commonService;
$this->cache = $appCache;
}
public function getUser() {
return $this->baseService->getUser();
}
public function __get($propertyName) {
$entityName = $this->commonService->getClassName($this, true);
if($propertyName == 'currentService') {
return $this
->baseService->serviceLocator
->get('App\Service\\' . ucfirst($entityName) . 'Service');
}
if($propertyName == 'currentRepo') {
return $this
->baseService->serviceLocator
->get('App\Service\\' . ucfirst($entityName) . 'Service')
->repository;
}
preg_match('/([a-zA-Z0-9]+)Service/i', $propertyName, $serviceMatches);
if(count($serviceMatches) > 0) {
return $this
->baseService->serviceLocator
->get('App\Service\\' . ucfirst($serviceMatches[1]) . 'Service');
}
preg_match('/([a-zA-Z0-9]+)Repo/i', $propertyName, $repositoryMatches);
if(count($repositoryMatches) > 0) {
return $this
->baseService->serviceLocator
->get('App\Service\\' . ucfirst($repositoryMatches[1]) . 'Service')
->repository;
}
$cacheKey = 'Const.' . $entityName . '.' . $propertyName;
$cachedConstantItem = $this->cache->getItem($cacheKey);
if($cachedConstantItem->isHit()) {
return $cachedConstantItem->get();
}
$constant = @constant('App\Entity\\' . $entityName . '::' . $propertyName);
if(!is_null($constant)) {
$cachedConstantItem->set($constant);
$this->cache->save($cachedConstantItem);
return $constant;
}
$metas = $this->entityManager->getMetadataFactory()->getAllMetadata();
foreach ($metas as $meta) {
$classPath = $meta->getName();
$name = strtoupper($this->commonService->toSnakeCase(str_replace('App\Entity\\', '', $classPath)));
preg_match('/(' . $name . ')_(.+)/i', $propertyName, $matches);
if(count($matches) > 0) {
$prop = $matches[2];
$constant = @constant($classPath . '::' . $prop);
if(!is_null($constant)) {
$cachedConstantItem->set($constant);
$this->cache->save($cachedConstantItem);
return $constant;
}
}
}
trigger_error('Could not found property "' . $propertyName . '" in ' . $this->commonService->getClassName($this), E_USER_ERROR);
}
}