src/AppBundle/Twig/UserTwigExtension.php line 58

Open in your IDE?
  1. <?php
  2. /**
  3. * Created by IntelliJ IDEA.
  4. * User: stefano
  5. * Date: 29/05/17
  6. * Time: 16.59
  7. */
  8. namespace App\AppBundle\Twig;
  9. use App\AppBundle\Annotations\Frontend;
  10. use App\AppBundle\Entity\CronJob;
  11. use App\AppBundle\Entity\Currency;
  12. use App\AppBundle\Entity\Log;
  13. use App\AppBundle\Entity\MvMycmMyamsDealerGroup;
  14. use App\AppBundle\Entity\MyamsUserProfile;
  15. use App\AppBundle\Entity\User;
  16. use App\AppBundle\Repository\CountryRepository;
  17. use App\AppBundle\Repository\MacroDealerRepository;
  18. use App\AppBundle\Repository\UserRepository;
  19. use App\AppBundle\Controller\DefaultController;
  20. use App\AppBundle\Entity\Application_Data;
  21. use App\AppBundle\Other\Constants;
  22. use App\AppBundle\Services\ImportService;
  23. use App\AppBundle\Services\ThemeService;
  24. use Doctrine\Common\Annotations\AnnotationReader;
  25. use Doctrine\Common\Collections\ArrayCollection;
  26. use Doctrine\ORM\EntityManager;
  27. use Doctrine\ORM\NonUniqueResultException;
  28. use Doctrine\ORM\NoResultException;
  29. use EasyCorp\Bundle\EasyAdminBundle\Configuration\ConfigManager;
  30. use EasyCorp\Bundle\EasyAdminBundle\Twig\EasyAdminTwigExtension;
  31. use ReflectionClass;
  32. use Symfony\Component\HttpFoundation\ParameterBag;
  33. use Symfony\Component\HttpKernel\Exception\HttpException;
  34. use Symfony\Component\Security\Core\Authorization\AuthorizationCheckerInterface;
  35. use Symfony\Component\DependencyInjection\ContainerInterface;
  36. use Twig\TwigFunction;
  37. class UserTwigExtension extends EasyAdminTwigExtension
  38. {
  39. // import tabs
  40. const TYPE_CUSTOMER = "customer";
  41. const TYPE_SELLOUT = "sellout";
  42. const TYPE_CUSTOMER_PARK = "park";
  43. const potentialTabs = ["PSD_Potential", "PSD_Potential_Technicians", "PSD_Customer"];
  44. private ConfigManager $configManager;
  45. private EntityManager $em;
  46. private AuthorizationCheckerInterface $authChecker;
  47. private ThemeService $themeService;
  48. private ContainerInterface $container;
  49. private ArrayCollection $checks;
  50. private ImportService $importService;
  51. public function __construct(ConfigManager $configManager, EntityManager $em, AuthorizationCheckerInterface $ac, ThemeService $themeService, ContainerInterface $container)
  52. {
  53. $this->configManager = $configManager;
  54. $this->em = $em;
  55. $this->authChecker = $ac;
  56. $this->themeService = $themeService;
  57. $this->container = $container;
  58. $this->checks = new ArrayCollection();
  59. $this->importService = $container->get(ImportService::class);
  60. }
  61. public function getFunctions()
  62. {
  63. return array(
  64. new TwigFunction('get_countries', array($this, 'getCountries')),
  65. new TwigFunction('get_macro_dealers', array($this, 'getMacroDealers')),
  66. new TwigFunction('get_macro_dealers_codes', array($this, 'getMacroDealersCodes')),
  67. new TwigFunction('get_countries_in_macrodealer', array($this, 'getCountriesInMacrodealers')),
  68. new TwigFunction('get_allowed_macro_dealers', array($this, 'getAllowedMacroDealers')),
  69. new TwigFunction('get_warehouses', array($this, 'getWarehouse')),
  70. new TwigFunction('get_last_import_date', array($this, 'getLastImportDate')),
  71. new TwigFunction('is_import_in_progress', array($this, 'isImportInProgress')),
  72. new TwigFunction('last_job_exec', array($this, 'getLastJob')),
  73. new TwigFunction('get_currencies', array($this, 'getCurrencies')),
  74. new TwigFunction('get_current_currency_description', array($this, 'getCurrentCurrencyDescription')),
  75. new TwigFunction('get_current_macro_dealer_group_label', array($this, 'getCurrentMacroDealerGroupLabel')),
  76. new TwigFunction('pdf_labels', array($this, 'PDFLabels')),
  77. new TwigFunction('contextual_help', array($this, 'getContextualHelp')),
  78. new TwigFunction('get_macro_datasets', array($this, 'getMacroDatasets')),
  79. new TwigFunction('search_in_array_objects', array($this, 'searchInArrayObjects')),
  80. new TwigFunction('get_user_by_username', array($this, 'getUserByUsername')),
  81. new TwigFunction('get_theme_file_name', array($this, 'getThemeFileName')),
  82. new TwigFunction('get_theme_brand_name', array($this, 'getThemeBrandName')),
  83. new TwigFunction('get_theme_brand_code', array($this, 'getSelectedBrandCodes')),
  84. new TwigFunction('get_switch_to_old', array($this, 'getSwitchToOld')),
  85. new TwigFunction('get_default_url', array($this, 'getDefaultUrl')),
  86. new TwigFunction('get_enable_user_edit', array($this, 'getEnableUserEdit')),
  87. new TwigFunction('get_access_to_new', array($this, 'getAccessToNew')),
  88. new TwigFunction('get_access_to_old', array($this, 'getAccessToOld')),
  89. new TwigFunction('get_sellout_enabled', array($this, 'getSelloutEnabled')),
  90. new TwigFunction('get_label_bulkedit_enabled', array($this, 'getLabelBulkEditEnabled')),
  91. new TwigFunction('get_label_management_enabled', array($this, 'getLabelManagementEnabled')),
  92. new TwigFunction('get_dashboard_enabled', array($this, 'getDashboardEnabled')),
  93. new TwigFunction('get_sellin_enabled', array($this, 'getSellinEnabled')),
  94. new TwigFunction('get_advanced_analytics_enabled', array($this, 'getAdvancedAnalyticsEnabled')),
  95. new TwigFunction('get_stock_and_logistics_enabled', array($this, 'getStockAndLogisticsEnabled')),
  96. new TwigFunction('get_take_rate_enabled', array($this, 'getTakeRateEnabled')),
  97. new TwigFunction('get_prim_enabled', array($this, 'getPrimEnabled')),
  98. new TwigFunction('get_portfolio_enabled', array($this, 'getPortfolioEnabled')),
  99. new TwigFunction('get_distinct_brands', array($this, 'getDistinctBrands')),
  100. new TwigFunction('get_brands', array($this, 'getBrands')),
  101. new TwigFunction('get_dealerships', array($this, 'getDealerships')),
  102. new TwigFunction('get_dealer_groups', array($this, 'getDealerGroups')),
  103. new TwigFunction('get_unique_id', array($this, 'getUniqId')),
  104. new TwigFunction('one_time', array($this, 'oneTime')),
  105. new TwigFunction('get_exposable_entities', array($this, 'getExposableEntities')),
  106. new TwigFunction('get_exposable_entity', array($this, 'getExposableEntity')),
  107. new TwigFunction('get_exposable_name', array($this, 'getExposableName')),
  108. new TwigFunction('is_single_dealership_user', array($this, 'isSingleDealershipUser')),
  109. new TwigFunction('is_user_edit_enabled', array($this, 'isUserEditEnabled')),
  110. new TwigFunction('has_not_connected_dealer_groups', array($this, 'hasNotConnectedDealerGroups')),
  111. new TwigFunction('get_import_tabs', array($this, 'getImportTabs')),
  112. new TwigFunction('get_potential_tabs', array($this, 'getPotentialTabs')),
  113. new TwigFunction('get_full_user', array($this, 'getFullUser')),
  114. new TwigFunction('get_mib_roles', array($this, 'getMibRoles')),
  115. );
  116. }
  117. public function getPotentialTabs(User $user = null) {
  118. $authChecker = $this->container->get('security.authorization_checker');
  119. $tabs = [];
  120. if($authChecker->isGranted('ROLE_GRANT_POTENTIALS')){
  121. $tabs = self::potentialTabs;
  122. }
  123. return $tabs;
  124. }
  125. public function getPortfolioEnabled(User $user = null)
  126. {
  127. return (!$user) ? false : $this->isEnablePortfolio($user);
  128. }
  129. public function getMibRoles()
  130. {
  131. return json_encode(Constants::MIB_ROLES);
  132. }
  133. public function getPrimEnabled(User $user = null){
  134. return (!$user) ? false : $user->isEnablePrim() && $_ENV['ENABLE_PRIM'] === "true";
  135. }
  136. public function getEnableUserEdit(User $user = null){
  137. return (!$user) ? false : $user->isEnableUserEdit();
  138. }
  139. public function getSelloutEnabled(User $user = null){
  140. return (!$user) ? false : $user->isEnableSellout() && $_ENV['ENABLE_SELLOUT'] === "true";
  141. }
  142. public function getLabelBulkEditEnabled(User $user = null) {
  143. return (!$user) ? false : $user->getEnableLabelBulkEdit();
  144. }
  145. public function getLabelManagementEnabled(User $user = null) {
  146. if(!$user)
  147. return false;
  148. /** @var Application_DataRepository $applicationDataRepository */
  149. $applicationDataRepository = $this->em->getRepository(Application_Data::class);
  150. $users = $applicationDataRepository->getValueFromKey('LABEL_MANAGEMENT_ALLOWED_USERS');
  151. if(!$users)
  152. return false;
  153. $users = explode(",", $users["value"]);
  154. $users = array_map('trim', $users);
  155. return in_array($user->getUsername(), $users);
  156. }
  157. public function getDashboardEnabled(User $user = null){
  158. return (!$user) ? false : $user->getEnableDashboard();
  159. }
  160. public function getSellinEnabled(User $user = null){
  161. return (!$user) ? false : $user->getEnableSellIn();
  162. }
  163. public function getAdvancedAnalyticsEnabled(User $user = null){
  164. return (!$user) ? false : $user->getEnableAdvancedAnalytics();
  165. }
  166. public function getStockAndLogisticsEnabled(User $user = null){
  167. return (!$user) ? false : $user->getEnableStockAndLogistics();
  168. }
  169. public function getTakeRateEnabled(User $user = null){
  170. return (!$user) ? false : $user->getEnableTakeRate();
  171. }
  172. public function getSwitchToOld(User $user = null){
  173. return (!$user) ? false : $user->getSwitchToOld();
  174. }
  175. public function getDefaultUrl(User $user = null) {
  176. $menu = $this->configManager->getBackendConfig('design')['menu'];
  177. $authChecker = $this->container->get('security.authorization_checker');
  178. if($authChecker->isGranted('ROLE_GRANT_DASHBOARD')) {
  179. if ($user && !$user->getDefaultUrl()) {
  180. $user->setDefaultUrl($menu);
  181. }
  182. return (!$user) ? false : $user->getDefaultUrl();
  183. } else {
  184. return '/admin/?action=list&entity=User';
  185. }
  186. }
  187. public function getAccessToNew(User $user = null){
  188. return (!$user) ? false : $user->getAccessToNew();
  189. }
  190. public function getAccessToOld(User $user = null){
  191. return (!$user) ? false : $user->getAccessToOld();
  192. }
  193. // Theme selection (CSS and top logo)
  194. public function getThemeBrandName(User $user = null){
  195. return $this->themeService->getTheme($user)->getFullname();
  196. }
  197. public function getThemeFileName(User $user = null){
  198. return $this->themeService->getTheme($user)->getFilepath();
  199. }
  200. public function getImportTabs(User $user = null) {
  201. $authChecker = $this->container->get('security.authorization_checker');
  202. $tabs = [];
  203. if($authChecker->isGranted('ROLE_GRANT_IMPORTER_SELLOUT') && $this->hasNotConnectedDealerGroups($user))
  204. $tabs[] = self::TYPE_SELLOUT;
  205. if($authChecker->isGranted('ROLE_GRANT_IMPORTER_CUSTOMER'))
  206. $tabs[] = self::TYPE_CUSTOMER;
  207. if($authChecker->isGranted('ROLE_GRANT_IMPORTER_PARK'))
  208. $tabs[] = self::TYPE_CUSTOMER_PARK;
  209. return $tabs;
  210. }
  211. // Brand selector
  212. public function getSelectedBrandCodes(User $user = null) {
  213. $brandRepository = $this->em->getRepository('AppBundle:Brand');
  214. $brands = $user->getSelectedBrands();
  215. // select first brand by default
  216. if(!$brands) {
  217. $brands = $brandRepository->getBrandList($user);
  218. $brands = reset($brands);
  219. if(!$brands) {
  220. return null;
  221. }
  222. $brands = $brands["id"];
  223. // Made selection persist
  224. $user->setSelectedBrands($brands);
  225. $this->em->flush($user);
  226. $this->em->persist($user);
  227. }
  228. $brands = explode(',', $brands);
  229. $brands = $brandRepository->findBy(array('id' => $brands));
  230. $brands = array_map(function($brand) {
  231. return $brand->getCode();
  232. }, $brands);
  233. return implode(",", $brands);
  234. }
  235. public function getDistinctBrands(User $user = null){
  236. $brandRepository = $this->em->getRepository('AppBundle:Brand');
  237. $brandlist=$brandRepository->getBrandDistinctList();
  238. return $brandlist;
  239. }
  240. public function getBrands(User $user = null){
  241. $brandRepository = $this->em->getRepository('AppBundle:Brand');
  242. $brandlist=$brandRepository->getBrandList($user);
  243. return $brandlist;
  244. }
  245. public function getFullUser($username)
  246. {
  247. $userRepository = $this->em->getRepository('AppBundle:User');
  248. $user = $userRepository ->findOneByUsername($username);
  249. return $user->getFullUsername();
  250. }
  251. public function getUserByUsername($username)
  252. {
  253. $userRepository = $this->em->getRepository('AppBundle:User');
  254. return $userRepository ->findOneByUsername($username);
  255. }
  256. public function getLastJob()
  257. {
  258. $cronRepo = $this->em->getRepository('AppBundle:CronJob');
  259. /** @var CronJob $job */
  260. $job = $cronRepo->findOneBy(array("active" => 1), array("lastRunAt" => 'DESC'));
  261. $lastRun = $job ? $job->getLastRunAt() : new \DateTime();
  262. return $lastRun->format('Y-m-d H:i:s');
  263. }
  264. public function getCountries(User $user)
  265. {
  266. if(!$user->getCountries()->isEmpty()){
  267. $countries= $user->getCountries();
  268. }else{
  269. /** @var CountryRepository $countryRepo */
  270. $countryRepo = $this->em->getRepository('AppBundle:Country');
  271. $countries = $countryRepo->findBy(array(), array('description' => 'ASC'));
  272. }
  273. return $countries;
  274. }
  275. public function getMacroDealers(User $user)
  276. {
  277. $country = $user->getSelectedCountry();
  278. /** @var MacroDealerRepository $macroDealerRepo */
  279. $macroDealerRepo = $this->em->getRepository('AppBundle:MacroDealer');
  280. $macroDealers = $macroDealerRepo->findBy(array(
  281. "country" => $country
  282. ),
  283. array('description' => 'ASC')
  284. );
  285. return $macroDealers;
  286. }
  287. public function getMacroDealersCodes(User $user){
  288. /** @var ArrayCollection $mds */
  289. $mds =$user->getMacroDealers();
  290. return $mds->map(function ($macrodealer){
  291. return $macrodealer->getCode();
  292. });
  293. }
  294. public function getCountriesInMacrodealers(User $user) {
  295. /** @var MacroDealerRepository $macroDealerRepo */
  296. $macroDealerRepo = $this->em->getRepository('AppBundle:MacroDealer');
  297. $countries= $macroDealerRepo->getCountriesInMacrodealers($user->getMacroDealers());
  298. return $countries;
  299. }
  300. public function getAllowedMacroDealers(User $user){
  301. $country = $user->getSelectedCountry();
  302. return $user->getMacroDealers()
  303. ->filter(
  304. function($entry) use ($country) {
  305. return $entry->getCountry() == $country;
  306. }
  307. );
  308. }
  309. public function getWarehouse(User $user)
  310. {
  311. // $warehouses = $user->getWarehouses();
  312. $warehouses = array();
  313. // if (count($warehouses) < 1) {
  314. /** @var UserRepository $userRepository */
  315. $userRepository = $this->em->getRepository('AppBundle:User');
  316. if ($this->authChecker->isGranted('ROLE_INTERNAL') || $this->authChecker->isGranted('ROLE_ADMIN')) {
  317. $warehouses = $userRepository->getSelectedMacroDealerWharehouses($user);
  318. } else {
  319. $macrodealers = $user->getSelectedMacroDealer()?: $this->getAllowedMacroDealers($user);
  320. $warehouses = $userRepository->getWarehousesAvailable($user,$macrodealers);
  321. }
  322. // }
  323. return $warehouses;
  324. // // NB: Prediligo i Prim che iniziano con F. Ma se ci fosse un whId che non ha Prim che iniziano con F, in questo modo lo prendo lo stesso
  325. // $toreturn = array();
  326. // $F_array = array();
  327. // foreach ($warehouses as $warehouse) {
  328. // if (!in_array($warehouse->getWhId(), $F_array)) {
  329. // $toreturn[$warehouse->getWhId()] = $warehouse;
  330. // if (strrpos($warehouse->getPrim(), 'F') === 0) {
  331. // $F_array[] = $warehouse->getWhId();
  332. // }
  333. // }
  334. // }
  335. // return $toreturn;
  336. }
  337. public function getLastImportDate(User $user)
  338. {
  339. $lastDate=$this->em->getRepository("AppBundle:Warehouse")->getLastDduDateByUser($user);
  340. if(is_null($lastDate)){
  341. return "";
  342. }
  343. $date = \DateTime::createFromFormat('Y-m-d H:i:s', $lastDate);
  344. $date->sub(new \DateInterval('P1D'));
  345. return $date->format("d-m-Y");
  346. }
  347. /**
  348. * Se tra i log trovo un log di tipo TYPE_IMPORT senza la data di fine (endedAt),
  349. * allora c'è un download in corso
  350. */
  351. public function isImportInProgress(){
  352. $logRepository = $this->em->getRepository("AppBundle:Log");
  353. $results = $logRepository->findBy(array(
  354. "type" => Log::TYPE_IMPORT,
  355. "endedAt" => null
  356. ));
  357. return count($results)>0;
  358. }
  359. public function getCurrencies(User $user,$sameCountryFlag = null)
  360. {
  361. //return $this->em->getRepository("AppBundle:Currency")->getDistinctList($user->getSelectedMacroDealer(), $user->getSelectedCountry());
  362. if(!$user->getSwitchToOld()){
  363. return $this->em->getRepository("AppBundle:Currency")->getSelectList();
  364. }
  365. $country = $user->getSelectedCountry() ;
  366. $countryCode = is_null($country) ? $this->container->getParameter("default_country_code") : $country->getCode();
  367. $currencylist = $this->em->getRepository("AppBundle:Currency")->getCountryList($countryCode);
  368. if(!$currencylist || empty($currencylist))
  369. {
  370. // Set euro as defaults
  371. $currencylist = null;
  372. $currencylist = array();
  373. $currencylist[] = [ "code" => 200, "description" => "EUR", "defaultValue" => true ];
  374. }
  375. if(!$sameCountryFlag){
  376. $user->setSelectedCurrencyCode($currencylist[0]['code']);
  377. $this->em->persist($user);
  378. $this->em->flush();
  379. }
  380. return $currencylist;
  381. }
  382. public function getCurrentCurrencyDescription(User $user,$avilablecurrencies)
  383. {
  384. /** @var Currency $currency */
  385. $currencyCode=(array_search($user->getSelectedCurrencyCode(), array_column($avilablecurrencies, 'code')) !==false) ? $user->getSelectedCurrencyCode() : DefaultController::EUR_CURRENCY_CODE;
  386. $currency = $this->em->getRepository("AppBundle:Currency")->findOneByCode($currencyCode);
  387. $description = "Currencies";
  388. if (!is_null($currency)) {
  389. $description = $currency->getDescription();
  390. }
  391. return $description;
  392. }
  393. public function getCurrentMacroDealerGroupLabel($macroDealerGroupId){
  394. return self::getMacroDealaerGroupLabel($macroDealerGroupId);
  395. }
  396. public static function getMacroDealaerGroupLabel($macroDealerGroupId){
  397. if($macroDealerGroupId==User::DOP){
  398. return 'menu.allDOP';
  399. }elseif ($macroDealerGroupId==User::THIRD_PARTS){
  400. return 'menu.allThirdParts';
  401. }
  402. return "";
  403. }
  404. public function PDFLabels($config)
  405. {
  406. if(isset($config->filters)){
  407. foreach($config->filters[0] as $filter){
  408. if($config->activeFilters){
  409. $activeFilter = $config->activeFilters->{$filter->name};
  410. yield array_values(array_filter($filter->values,function($value)use($activeFilter){
  411. return $activeFilter == $value->value;
  412. }))[0]->label;
  413. }else{
  414. yield $filter->values[0]->label;
  415. }
  416. }
  417. }
  418. }
  419. public function getContextualHelp($route,ParameterBag $routeParams,User $user){
  420. if($route=='/admin/'){
  421. $easyAdminName=$routeParams->get('easyadmin')['entity']['name'];
  422. $route=strtolower($easyAdminName);
  423. }
  424. $locale=$user->getSelectedLocale();
  425. if(!$locale || !in_array($locale,array('it','en')))
  426. $locale='en';
  427. return $this->em->getRepository('AppBundle:ContextualHelpImage')->findBy(array(
  428. 'page'=>$route,
  429. 'role'=>$user->getPrettyRole(),
  430. 'locale'=>$locale
  431. ),array('path'=>'asc'));
  432. }
  433. /**
  434. * @param $user User
  435. * @return array
  436. */
  437. public function getMacroDatasets($user)
  438. {
  439. $macroDatasets = array();
  440. $datasets = array();
  441. if(count($user->getDatasets())>0)
  442. {
  443. $datasets = $user->getDatasets() ;
  444. }
  445. else
  446. {
  447. $datasetRepository =$this->em->getRepository("AppBundle:Dataset");
  448. $datasets = $datasetRepository->findAll();
  449. }
  450. usort($datasets, function($a, $b) {return ($a->getId() > $b->getId());});
  451. foreach ($datasets as $dataset){
  452. if(!isset($macroDatasets[$dataset->getMacroDataset()->getId()])){
  453. $macroDatasets[$dataset->getMacroDataset()->getId()] = array("name"=>$dataset->getMacroDataset()->getName(), "datasets"=>array());
  454. }
  455. $macroDatasets[$dataset->getMacroDataset()->getId()]["datasets"][] = array("id"=>$dataset->getId(),"name"=>$dataset->getName());
  456. }
  457. return $macroDatasets;
  458. }
  459. /**
  460. * @param $arrayObjects
  461. * @param $property
  462. * @param $value
  463. */
  464. public function searchInArrayObjects($arrayObjects, $property, $value)
  465. {
  466. $found = false;
  467. foreach ($arrayObjects as $obj){
  468. if($obj[$property] == $value){
  469. $found = true;
  470. break;
  471. }
  472. }
  473. return $found;
  474. }
  475. public function isSingleDealershipUser(User $user)
  476. {
  477. return count($this->getDealerships($user)) == 1 ? '1' : '0';
  478. }
  479. public function isUserEditEnabled(User $user)
  480. {
  481. return $user->isEnableUserEdit();
  482. }
  483. public function getDealerships(User $user) {
  484. return $this->em->getRepository(MyamsUserProfile::class)->GetAllUserDealership($user);
  485. }
  486. public function getDealerGroups(User $user) {
  487. return $this->em->getRepository(MyamsUserProfile::class)->GetAllUserDealerGroups($user);
  488. }
  489. /**
  490. * @throws NonUniqueResultException
  491. * @throws NoResultException
  492. */
  493. public function hasNotConnectedDealerGroups(User $user): bool {
  494. $userDealerGroup = array_column($this->getDealerGroups($user), 'cdDealerGroup');
  495. $notConnected = $this->em->getRepository(MvMycmMyamsDealerGroup::class)
  496. ->countNotConnectedDealerGroups($userDealerGroup);
  497. return (int) $notConnected > 0;
  498. }
  499. public function getUniqId($prefix = "", $more_entropy = false) {
  500. return uniqid($prefix, $more_entropy);
  501. }
  502. public function oneTime($check) {
  503. return !$this->checks->contains($check) && $this->checks->add($check);
  504. }
  505. public function getExposableEntities():array {
  506. $entities = [];
  507. $reader = new AnnotationReader();
  508. $baseFrontend = new Frontend();
  509. $this->importService->addAnnotation(Frontend::class);
  510. foreach($this->em->getMetadataFactory()->getAllMetadata() as $metadata) {
  511. $annotationFrontendClass = $reader->getClassAnnotation($metadata->getReflectionClass(), Frontend::class) ?? $baseFrontend;
  512. $reflectionClass = $metadata->getReflectionClass();
  513. $class = $reflectionClass->getName();
  514. $metadata = $this->importService->calculateMetadata($class, ["expose" => true]);
  515. $exposeName = $annotationFrontendClass->getExposeAs() ?: $class;
  516. if(isset($entities[$exposeName])) throw new HttpException(500, "Mapping \"".($exposeName)."\" is already defined");
  517. if(!empty($metadata)) $entities[$exposeName] = $metadata;
  518. }
  519. return $entities;
  520. }
  521. public function getExposableEntity($class):array {
  522. $this->importService->addAnnotation(Frontend::class);
  523. return $this->importService->calculateMetadata($class, ["expose" => true]);
  524. }
  525. public function getExposableName($class):string {
  526. $reader = new AnnotationReader();
  527. $annotationFrontendClass = $reader->getClassAnnotation(new ReflectionClass($class), Frontend::class) ?? new Frontend();
  528. return $annotationFrontendClass->getExposeAs();
  529. }
  530. public function getFilters() {
  531. return array(
  532. new \Twig_SimpleFilter('attrs', array($this, 'get_attributes'), ["is_safe" => ["html"]]),
  533. new \Twig_SimpleFilter('setProperty', array($this, 'set_property')),
  534. );
  535. }
  536. public function get_attributes($attributes):string {
  537. $attrs = [];
  538. foreach($attributes??[] as $key => $value) {
  539. $attrs[] = "$key=\"$value\"";
  540. }
  541. return implode(" ", $attrs);
  542. }
  543. public function set_property($object, $property, $value = null) {
  544. $object[$property] = $value;
  545. return $object;
  546. }
  547. public function isEnablePortfolio($user) {
  548. if($this->authChecker->isGranted('ROLE_IS_INTERNAL') || $this->authChecker->isGranted('ROLE_IS_ADMIN'))
  549. return true;
  550. elseif($this->authChecker->isGranted('ROLE_IS_DEALER')) {
  551. $dealergroups = $this->getDealerGroups($user);
  552. $marketRegion = array_column($dealergroups,'dsMarketRegion');
  553. if(in_array('UK & ROI',$marketRegion) or in_array('Italy',$marketRegion) )
  554. return true;
  555. }
  556. return false;
  557. }
  558. }