vendor/pimcore/pimcore/bundles/AdminBundle/Controller/Admin/DataObject/QuantityValueController.php line 250

Open in your IDE?
  1. <?php
  2. /**
  3.  * Pimcore
  4.  *
  5.  * This source file is available under two different licenses:
  6.  * - GNU General Public License version 3 (GPLv3)
  7.  * - Pimcore Commercial License (PCL)
  8.  * Full copyright and license information is available in
  9.  * LICENSE.md which is distributed with this source code.
  10.  *
  11.  *  @copyright  Copyright (c) Pimcore GmbH (http://www.pimcore.org)
  12.  *  @license    http://www.pimcore.org/license     GPLv3 and PCL
  13.  */
  14. namespace Pimcore\Bundle\AdminBundle\Controller\Admin\DataObject;
  15. use Pimcore\Bundle\AdminBundle\Controller\AdminController;
  16. use Pimcore\Model\DataObject\Data\QuantityValue;
  17. use Pimcore\Model\DataObject\QuantityValue\Unit;
  18. use Pimcore\Model\DataObject\QuantityValue\UnitConversionService;
  19. use Pimcore\Model\Translation;
  20. use Symfony\Component\HttpFoundation\JsonResponse;
  21. use Symfony\Component\HttpFoundation\Request;
  22. use Symfony\Component\Routing\Annotation\Route;
  23. /**
  24.  * @Route("/quantity-value", name="pimcore_admin_dataobject_quantityvalue_")
  25.  *
  26.  * @internal
  27.  */
  28. class QuantityValueController extends AdminController
  29. {
  30.     /**
  31.      * @Route("/unit-proxy", name="unitproxyget", methods={"GET"})
  32.      *
  33.      * @param Request $request
  34.      *
  35.      * @return JsonResponse
  36.      *
  37.      * @throws \Exception
  38.      */
  39.     public function unitProxyGetAction(Request $request)
  40.     {
  41.         $list = new Unit\Listing();
  42.         $order = ['ASC', 'ASC', 'ASC'];
  43.         $orderKey = ['baseunit', 'factor', 'abbreviation'];
  44.         $allParams = array_merge($request->request->all(), $request->query->all());
  45.         $sortingSettings = \Pimcore\Bundle\AdminBundle\Helper\QueryParams::extractSortingSettings($allParams);
  46.         // Prepend user-requested sorting settings but keep the others to keep secondary order of quantity values in respective order
  47.         if ($sortingSettings['orderKey']) {
  48.             array_unshift($orderKey, $sortingSettings['orderKey']);
  49.         }
  50.         if ($sortingSettings['order']) {
  51.             array_unshift($order, $sortingSettings['order']);
  52.         }
  53.         $list->setOrder($order);
  54.         $list->setOrderKey($orderKey);
  55.         $list->setLimit($request->get('limit'));
  56.         $list->setOffset($request->get('start'));
  57.         $condition = '1 = 1';
  58.         if ($request->get('filter')) {
  59.             $filterString = $request->get('filter');
  60.             $filters = json_decode($filterString);
  61.             $db = \Pimcore\Db::get();
  62.             foreach ($filters as $f) {
  63.                 if ($f->type == 'string') {
  64.                     $condition .= ' AND ' . $db->quoteIdentifier($f->property) . ' LIKE ' . $db->quote('%' . $f->value . '%');
  65.                 } elseif ($f->type == 'numeric') {
  66.                     $operator = $this->getOperator($f->comparison);
  67.                     $condition .= ' AND ' . $db->quoteIdentifier($f->property) . ' ' . $operator . ' ' . $db->quote($f->value);
  68.                 }
  69.             }
  70.             $list->setCondition($condition);
  71.         }
  72.         $units = [];
  73.         foreach ($list->getUnits() as $u) {
  74.             $units[] = $u->getObjectVars();
  75.         }
  76.         return $this->adminJson(['data' => $units, 'success' => true, 'total' => $list->getTotalCount()]);
  77.     }
  78.     /**
  79.      * @Route("/unit-proxy", name="unitproxy", methods={"POST", "PUT"})
  80.      *
  81.      * @param Request $request
  82.      *
  83.      * @return JsonResponse
  84.      *
  85.      * @throws \Exception
  86.      */
  87.     public function unitProxyAction(Request $request)
  88.     {
  89.         if ($request->get('data')) {
  90.             if ($request->get('xaction') == 'destroy') {
  91.                 $data = json_decode($request->get('data'), true);
  92.                 $id = $data['id'];
  93.                 $unit = \Pimcore\Model\DataObject\QuantityValue\Unit::getById($id);
  94.                 if (!empty($unit)) {
  95.                     $unit->delete();
  96.                     return $this->adminJson(['data' => [], 'success' => true]);
  97.                 } else {
  98.                     throw new \Exception('Unit with id ' . $id . ' not found.');
  99.                 }
  100.             } elseif ($request->get('xaction') == 'update') {
  101.                 $data = json_decode($request->get('data'), true);
  102.                 $unit = Unit::getById($data['id']);
  103.                 if (!empty($unit)) {
  104.                     if (($data['baseunit'] ?? null) == -1) {
  105.                         $data['baseunit'] = null;
  106.                     }
  107.                     $unit->setValues($data);
  108.                     $unit->save();
  109.                     return $this->adminJson(['data' => $unit->getObjectVars(), 'success' => true]);
  110.                 } else {
  111.                     throw new \Exception('Unit with id ' . $data['id'] . ' not found.');
  112.                 }
  113.             } elseif ($request->get('xaction') == 'create') {
  114.                 $data = json_decode($request->get('data'), true);
  115.                 if (isset($data['baseunit']) && $data['baseunit'] === -1) {
  116.                     $data['baseunit'] = null;
  117.                 }
  118.                 $id = $data['id'];
  119.                 if (Unit::getById($id)) {
  120.                     throw new \Exception('unit with ID [' . $id . '] already exists');
  121.                 }
  122.                 if (mb_strlen($id) > 50) {
  123.                     throw new \Exception('The maximal character length for the unit ID is 50 characters, the provided ID has ' . mb_strlen($id) . ' characters.');
  124.                 }
  125.                 $unit = new Unit();
  126.                 $unit->setValues($data);
  127.                 $unit->save();
  128.                 return $this->adminJson(['data' => $unit->getObjectVars(), 'success' => true]);
  129.             }
  130.         }
  131.         return $this->adminJson(['success' => false]);
  132.     }
  133.     /**
  134.      * @param string $comparison
  135.      *
  136.      * @return string
  137.      */
  138.     private function getOperator($comparison)
  139.     {
  140.         $mapper = [
  141.             'lt' => '<',
  142.             'gt' => '>',
  143.             'eq' => '=',
  144.         ];
  145.         return $mapper[$comparison];
  146.     }
  147.     /**
  148.      * @Route("/unit-list", name="unitlist", methods={"GET"})
  149.      *
  150.      * @param Request $request
  151.      *
  152.      * @return JsonResponse
  153.      */
  154.     public function unitListAction(Request $request)
  155.     {
  156.         $list = new Unit\Listing();
  157.         $list->setOrderKey(['baseunit', 'factor', 'abbreviation']);
  158.         $list->setOrder(['ASC', 'ASC', 'ASC']);
  159.         if ($request->get('filter')) {
  160.             $array = explode(',', $request->get('filter'));
  161.             $quotedArray = [];
  162.             $db = \Pimcore\Db::get();
  163.             foreach ($array as $a) {
  164.                 $quotedArray[] = $db->quote($a);
  165.             }
  166.             $string = implode(',', $quotedArray);
  167.             $list->setCondition('id IN (' . $string . ')');
  168.         }
  169.         $result = [];
  170.         $units = $list->getUnits();
  171.         foreach ($units as &$unit) {
  172.             try {
  173.                 if ($unit->getAbbreviation()) {
  174.                     $unit->setAbbreviation(\Pimcore\Model\Translation::getByKeyLocalized($unit->getAbbreviation(), Translation::DOMAIN_ADMIN,
  175.                         true, true));
  176.                 }
  177.                 if ($unit->getLongname()) {
  178.                     $unit->setLongname(\Pimcore\Model\Translation::getByKeyLocalized($unit->getLongname(), Translation::DOMAIN_ADMIN, true,
  179.                         true));
  180.                 }
  181.                 $result[] = $unit->getObjectVars();
  182.             } catch (\Exception $e) {
  183.                 // nothing to do ...
  184.             }
  185.         }
  186.         return $this->adminJson(['data' => $result, 'success' => true, 'total' => $list->getTotalCount()]);
  187.     }
  188.     /**
  189.      * @Route("/convert", name="convert", methods={"GET"})
  190.      *
  191.      * @param Request $request
  192.      * @param UnitConversionService $conversionService
  193.      *
  194.      * @return JsonResponse
  195.      */
  196.     public function convertAction(Request $request, UnitConversionService $conversionService)
  197.     {
  198.         $fromUnitId = $request->get('fromUnit');
  199.         $toUnitId = $request->get('toUnit');
  200.         $fromUnit = Unit::getById($fromUnitId);
  201.         $toUnit = Unit::getById($toUnitId);
  202.         if (!$fromUnit instanceof Unit || !$toUnit instanceof Unit) {
  203.             return $this->adminJson(['success' => false]);
  204.         }
  205.         try {
  206.             $convertedValue = $conversionService->convert(new QuantityValue($request->get('value'), $fromUnit), $toUnit);
  207.         } catch (\Exception $e) {
  208.             return $this->adminJson(['success' => false]);
  209.         }
  210.         return $this->adminJson(['value' => $convertedValue->getValue(), 'success' => true]);
  211.     }
  212.     /**
  213.      * @Route("/convert-all", name="convertall", methods={"GET"})
  214.      *
  215.      * @param Request $request
  216.      * @param UnitConversionService $conversionService
  217.      *
  218.      * @return JsonResponse
  219.      */
  220.     public function convertAllAction(Request $request, UnitConversionService $conversionService)
  221.     {
  222.         $unitId = $request->get('unit');
  223.         $fromUnit = Unit::getById($unitId);
  224.         if (!$fromUnit instanceof Unit) {
  225.             return $this->adminJson(['success' => false]);
  226.         }
  227.         $baseUnit = $fromUnit->getBaseunit() ?? $fromUnit;
  228.         $units = new Unit\Listing();
  229.         $units->setCondition('baseunit = '.$units->quote($baseUnit->getId()).' AND id != '.$units->quote($fromUnit->getId()));
  230.         $convertedValues = [];
  231.         foreach ($units->getUnits() as $targetUnit) {
  232.             try {
  233.                 $convertedValue = $conversionService->convert(new QuantityValue($request->get('value'), $fromUnit), $targetUnit);
  234.                 $convertedValues[] = ['unit' => $targetUnit->getAbbreviation(), 'unitName' => $targetUnit->getLongname(), 'value' => round($convertedValue->getValue(), 4)];
  235.             } catch (\Exception $e) {
  236.                 return $this->adminJson(['success' => false, 'message' => $e->getMessage()]);
  237.             }
  238.         }
  239.         return $this->adminJson(['value' => $request->get('value'), 'fromUnit' => $fromUnit->getAbbreviation(), 'values' => $convertedValues, 'success' => true]);
  240.     }
  241. }