src/Controller/BaseController.php line 59

Open in your IDE?
  1. <?php
  2. /**
  3.  * Created by PhpStorm.
  4.  * User: Ronald
  5.  * Date: 12/23/2019
  6.  * Time: 4:31 PM
  7.  */
  8. namespace App\Controller;
  9. use Api\Entity\Country;
  10. use Api\Entity\State;
  11. use Api\Entity\City;
  12. use Api\Entity\ZipCode;
  13. use App\COREapi\NamingStrategy;
  14. use App\Entity\CustomerAccount;
  15. use App\Entity\Quote;
  16. use App\Entity\QuoteItem;
  17. use App\Entity\User;
  18. use App\GoogleAPI\GoogleApi;
  19. use Doctrine\Persistence\ManagerRegistry;
  20. use JMS\Serializer\Naming\SerializedNameAnnotationStrategy;
  21. use JMS\Serializer\SerializationContext;
  22. use JMS\Serializer\SerializerBuilder;
  23. use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
  24. use Symfony\Component\Asset\Packages;
  25. use Symfony\Component\Filesystem\Filesystem;
  26. use Symfony\Component\HttpFoundation\BinaryFileResponse;
  27. use Symfony\Component\HttpFoundation\File\Exception\FileException;
  28. use Symfony\Component\HttpFoundation\JsonResponse;
  29. use Symfony\Component\HttpFoundation\Request;
  30. use Symfony\Component\HttpFoundation\ResponseHeaderBag;
  31. abstract class BaseController extends AbstractController
  32. {
  33.     const FORMAT_NUMBER_EXCEL_REPORT ='#,##';
  34.     const FORMAT_NUMBER_FLOAT_EXCEL_REPORT ='#,##0.00';
  35.     private $error;
  36.     private $jmsSerializer;
  37.     private $doctrine;
  38.     public function __construct(ManagerRegistry $doctrine)
  39.     {
  40.         $this->doctrine $doctrine;
  41.     }
  42.     public function getDoctrine(): ManagerRegistry
  43.     {
  44.         return $this->doctrine;
  45.     }
  46.     private function resetSessionVar()
  47.     {
  48.         //Reset session vars
  49.         $this->container->get('session')->set('customerAccountDomain'null);
  50.     }
  51.     protected function initSessionVar()
  52.     {
  53.         //Reset session vars
  54.         $this->resetSessionVar();
  55.         $this->getLogoByDomain();
  56.     }
  57.     /**
  58.      * @return \Symfony\Component\HttpFoundation\RedirectResponse|void
  59.      * @throws \Psr\Container\ContainerExceptionInterface
  60.      * @throws \Psr\Container\NotFoundExceptionInterface
  61.      */
  62.     public function getLogoByDomain(){
  63.         try{
  64.             //Find what logo by the domain (host)
  65.             $customerAccountDomain $this->getDoctrine()->getRepository(CustomerAccount::class)->findCustomerAccountByDomain($_SERVER['SERVER_NAME']);
  66.             $this->container->get('session')->set('customerAccountDomain'$customerAccountDomain);
  67.             if($user=$this->getUser()){
  68.                 //Already login
  69.                 if($customerAccountDomain){
  70.                     //Check that the customer account for the domain is the same as the user (or its parent) that the one that wants to do login.
  71.                     if(!$user->getCustomerAccount()->isRelatedWithCustomerAccount($customerAccountDomain)){
  72.                         //Check if the user has a customer account with a domain OR its parent has a domain
  73.                         throw new \Exception(User::ERROR_PERMISSION);
  74.                     }
  75.                 }
  76.                 else{
  77.                     //The domain does not exist or it is OLG
  78.                     if($user->getCustomerAccount()->getDomain1()){
  79.                         //Check if the user has a customer account with a domain OR its parent has a domain
  80.                         throw new \Exception(User::ERROR_PERMISSION);
  81.                     }
  82.                     //It is a OLG
  83.                 }
  84.             }
  85.         }
  86.         catch (\Exception $e){
  87.             $this->resetSessionVar();
  88.             $this->addFlash('error'$e->getMessage());
  89.             //Do logout
  90.             return $this->redirectToRoute("app_logout");
  91.         }
  92.     }
  93.     /**
  94.      * @param string $fileLocation
  95.      * @param string $filename
  96.      * @return bool
  97.      */
  98.     public function deleteFileDir($fileLocation,$filename)
  99.     {
  100. //        $fileLocation = $base_dir. '/public/uploads/tempImages/hotels/';
  101.         try {
  102.             if (!is_dir($fileLocation)) {
  103.                 throw new \Exception("File location does not exist.");
  104.             }
  105.             //Remove temp image
  106.             $fileToDelete "$fileLocation/$filename";
  107.             if(!file_exists($fileToDelete)) {
  108.                 throw new \Exception("File does not exist.");
  109.             }
  110.             if (!unlink($fileToDelete)) {
  111.                 throw new \Exception("There was a problem deleting the file.");
  112.             }
  113.             return true;
  114.         }
  115.         catch (\Exception $e){
  116.             $this->addFlash('error''The file could not be deleted. '.$e->getMessage());
  117.         }
  118.         return false;
  119.     }
  120.     /**
  121.      * @param $formImageFile
  122.      * @param string $dir
  123.      * @return false|string
  124.      */
  125.     public function uploadImageDir($formImageFile,$dir){
  126.         try {
  127.             $validFileTypes = array(
  128.                 'image/ief',
  129.                 'image/png',
  130.                 'image/bmp',
  131.                 'image/tiff',
  132.                 'image/jpeg');
  133.             $finfo finfo_open(FILEINFO_MIME_TYPE);
  134.             $type finfo_file($finfo$formImageFile);
  135.             if (!in_array($type$validFileTypes)) {
  136.                 throw new \Exception("Invalid file type");
  137.             }
  138.             $newFilename random_int(1000PHP_INT_MAX) . '.' $formImageFile->guessExtension();
  139.             try {
  140.                 $formImageFile->move(
  141.                     $dir,
  142.                     $newFilename
  143.                 );
  144.             } catch (FileException $e) {
  145.                 $this->addFlash('error'"The image couldn't be upload. Error: " $e->getMessage());
  146.                 return false;
  147.             }
  148.             return $newFilename;
  149.         }
  150.         catch (\Exception $e) {
  151.             $this->addFlash('error'"The image couldn't be upload. Error: " $e->getMessage());
  152.         }
  153.         return false;
  154.     }
  155.     protected function json($dataint $status 200, array $headers = [], array $moreGroups = []): JsonResponse
  156.     {
  157.         $this->jmsSerializer = new SerializerBuilder();
  158.         $this->jmsSerializer->setPropertyNamingStrategy(new SerializedNameAnnotationStrategy(new NamingStrategy()));
  159.         $this->jmsSerializer $this->jmsSerializer->build();
  160.         $context = new SerializationContext();
  161.         $context->setSerializeNull(true);
  162.         $context->enableMaxDepthChecks();
  163.         $groups = array('Default');
  164.         if ($moreGroups) {
  165.             if (is_array($moreGroups)) {
  166.                 foreach ($moreGroups as $gr) {
  167.                     $groups[] = $gr;
  168.                 }
  169.             } else
  170.                 $groups[] = $moreGroups;
  171.         }
  172.         $context->setGroups($groups);
  173.         if ($this->container->has('serializer')) {
  174.             $json $this->jmsSerializer->serialize($data'json'$context);
  175.             return new JsonResponse($json$status$headerstrue);
  176.         }
  177.         return new JsonResponse($data$status$headers);
  178.     }
  179.     /**
  180.      * Return a simple array with the values without any object.
  181.      * @param array
  182.      * @return array
  183.      */
  184.     public function removeNullElemslOnTheArrayToSearchOnDoctrine($params)
  185.     {
  186.         if(!$params){
  187.             return array();
  188.         }
  189.         foreach ($params as $key=>$value){
  190.             if(is_string($value)){
  191.                 $value=trim($value);
  192.             }
  193.             if(is_null($value) || ($value=="") || (empty($value) && ($value!=="0"))){
  194.                 unset($params[$key]);
  195.             }
  196.         }
  197.         if(!isset($params) || !$params){
  198.             return array();
  199.         }
  200.         return $params;
  201.     }
  202.     /**
  203.      * @param array $params
  204.      * @return string
  205.      */
  206.     public function excelSearchPath(array $params){
  207.         $search="";
  208.         foreach($params as $key=>$value){
  209.             if($value!="") {
  210.                 if(is_array($value)){
  211.                     foreach( $value as $subValue){
  212.                         $search .= "&" $key "[]=" $subValue;
  213.                     }
  214.                 } else {
  215.                     $search .= "&" $key "=" $value;
  216.                 }
  217.             }
  218.         }
  219.         if($search){
  220.             $search="?".$search;
  221.         }
  222.         return $search;
  223.     }
  224.     /**
  225.      * @param $url
  226.      * @return bool
  227.      */
  228.     public function remoteFileExists($url)
  229.     {
  230.         $ch curl_init($url);
  231.         curl_setopt($chCURLOPT_NOBODYtrue);
  232.         curl_exec($ch);
  233.         $status curl_getinfo($chCURLINFO_HTTP_CODE);
  234.         curl_close($ch);
  235.         return $status === 200 true false;
  236.     }
  237.     /**
  238.      * @param $text
  239.      * @param string $filename
  240.      */
  241.     public function debugAjax($text,$filename='ajax'){
  242.         if(is_array($text)){
  243.             $text=print_r($text,true);
  244.         }
  245.         $text=json_encode($text);
  246.         $now = new \DateTime("now");
  247.         $logPath 'C:\wamp64\www\debug\logs\ajax\\';
  248.         if(is_dir($logPath))
  249.         {
  250.             $file fopen($logPath.$filename.date_format($now'Ymd').".txt""a") or die("Unable to open file!");
  251.             $txt date_format($now'Y-m-d H:i:s').' '.$text."\n";
  252.             fwrite($file$txt);
  253.             fclose($file);
  254.         }
  255.     }
  256.     /**
  257.      * @return \Doctrine\Common\Persistence\ObjectManager|object
  258.      */
  259.     function getEntityManagerAPI()
  260.     {
  261.         return $this->getDoctrine()->getManager("api");
  262.     }
  263.     /**
  264.      * @return bool
  265.      */
  266.     function checkAPIDatabaseConnection(){
  267.         try {
  268.             $em $this->getEntityManagerAPI();
  269.             $em->getConnection()->connect();
  270.             if(!$em->getConnection()->isConnected()) {
  271.                 throw new \Exception("Please, contact IT department. No database connection.");
  272.             }
  273.             return true;
  274.         }
  275.         catch (\Exception $e){
  276.             $msg=$e->getMessage();
  277.             if(strpos($e->getMessage(),'No connection could be made because the target machine actively refused it')){
  278.                 $msg="Please, contact IT department. No database connection could be made because the server refused it. Check the tunnel connection.";
  279.             }
  280.             $this->setError($msg$e->getCode(),$e->getCode(), $e->getTraceAsString());
  281.             return false;
  282.         }
  283.     }
  284.     /**
  285.      * @param string $msg
  286.      * @param string $code
  287.      * @param string $errorCode
  288.      * @param null $fullErrorResponse
  289.      * @internal param array $error
  290.      */
  291.     public function setError($msg 'Something is not Right '$code 'no error code'$errorCode 'X'$fullErrorResponse null)
  292.     {
  293.         $this->error['msg'] =  ucwords($msg);
  294.         $this->error['errorCode'] = $errorCode;
  295.         $this->error['code'] = $code;
  296.         $this->error['fullErrorResponse'] = $fullErrorResponse;
  297.     }
  298.     public function getError(){
  299.         return $this->error;
  300.     }
  301.     public function getErrorMsg(){
  302.         if($this->error){
  303.             return $this->error['msg'];
  304.         }
  305.         return "";
  306.     }
  307.     /**
  308.      * @param \DateTime $startDate
  309.      * @param \DateTime $endDate
  310.      * @return false|float|int
  311.      */
  312.     public function getDiffDay(\DateTime $startDate,\DateTime  $endDate){
  313.         $startDate->setTime(000);
  314.         $endDate->setTime(000);
  315.         //Get total days
  316.         $diff $startDate->diff($endDate);
  317.         $days=$diff->days;
  318.         if($startDate>$endDate){
  319.             return $days*(-1);
  320.         }
  321.         return $days;
  322.     }
  323.     /**
  324.      * @param \DateTime $date
  325.      * @param int $days
  326.      * @return \DateTime
  327.      * @throws \Exception
  328.      */
  329.     public function calculateDate(\DateTime $dateint $days){
  330.         if($days<0){
  331.             $date->sub(new \DateInterval('P' $days*(-1) . 'D'));
  332.         }
  333.         else {
  334.             $date->add(new \DateInterval('P' $days 'D'));
  335.         }
  336.         return $date;
  337.     }
  338.     /**
  339.      * @param array $suppliers
  340.      * @param array $hotels
  341.      * @param QuoteItem $quoteItem
  342.      * @return string[]
  343.      */
  344.     public function getSupplierInfo(array $suppliers, array $hotelsQuoteItem $quoteItem)
  345.     {
  346.         $type=$quoteItem->getType();
  347.         $supplier =["name"=>"","cityName"=>""];
  348.         if ($type) {
  349.             switch ($type) {
  350.                 case 'villa':
  351.                 case 'activity':
  352.                 case 'transfer':
  353.                 case 'carRental':
  354.                     $vendorId=$quoteItem->getVendorId();
  355.                     if(key_exists($vendorId,$suppliers)){
  356.                         $supplier["name"] = $suppliers[$vendorId]["name"];
  357.                         if(key_exists("cityName",$suppliers[$vendorId])) {
  358.                             $supplier["cityName"] = $suppliers[$vendorId]["cityName"];
  359.                         }
  360.                     }
  361.                     break;
  362.                 case 'hotel':
  363. //                    dd($quoteItem->getIdProduct(),$hotels);
  364.                     if($quoteItem->isHotelWithDifferentBillingSupplier()){
  365.                         $vendorId=$quoteItem->getAdditionalInformation()['billing_supplier'];
  366.                         if(key_exists($vendorId,$suppliers)){
  367.                             $supplier["name"] = $suppliers[$vendorId]["name"];
  368.                             if(key_exists("cityName",$suppliers[$vendorId])) {
  369.                                 $supplier["cityName"] = $suppliers[$vendorId]["cityName"];
  370.                             }
  371.                         }
  372.                     }
  373.                     else {
  374.                         $vendorId=$quoteItem->getVendorId();
  375.                         if(key_exists($vendorId,$hotels)){
  376.                             $supplier["name"] = $hotels[$vendorId]["name"];
  377.                             if(key_exists("city",$hotels[$vendorId])) {
  378.                                 $supplier["cityName"] = $hotels[$vendorId]["city"];
  379.                             }
  380.                         }
  381.                     }
  382.                 default:
  383.                     break;
  384.             }
  385.         }
  386.         return $supplier;
  387.     }
  388.     protected function getLogoPath(\Symfony\Component\Asset\Packages $assetsManagerQuote $quote){
  389.         $customerAccountLogo "";
  390.         if($logoImg $quote->getCustomerAccount()->getLogo()) {
  391.             $customerAccountLogo $assetsManager->getUrl('uploads/customerAccountLogo/' $logoImg);
  392.         }
  393. //        if($this->container && $customerAccountDomain = $this->container->get('session')->get('customerAccountDomain')){
  394. //            if($customerAccountDomain->getWebsiteLogo()){
  395. //                $logoImg = $customerAccountDomain->getWebsiteLogo();
  396. //                $customerAccountLogo = $assetsManager->getUrl('uploads/customerAccountLogo/logoWebsite/' . $logoImg);
  397. //            }
  398. //        }
  399.         if($quote->getCreatedBy() && !$quote->getCreatedBy()->getCustomerAccount()->isOLG()){
  400.             $customerAccountDomain=$quote->getCreatedBy()->getCustomerAccount();
  401.             $customerAccountDomain $customerAccountDomain->getMainParentCustomerAccount();
  402.             if($logoImg $customerAccountDomain->getWebsiteLogo()) {
  403.                 $customerAccountLogo $assetsManager->getUrl('uploads/customerAccountLogo/logoWebsite/' $logoImg);
  404.             }
  405.         }
  406.         if($logoImg){
  407.             //Log to test path
  408.             $path = (new \App\Kernel($_ENV['APP_ENV'],false))->getProjectDir() .'/var/log';
  409.             @mkdir($path);
  410.             $fileSystem = new Filesystem();
  411.             $fileSystem->appendToFile($path '/voucherLogo.txt'"Customer Account Logo: ".$customerAccountLogo."\n" );
  412.             //END Log to test path
  413.             //Check if the file exist
  414.             if (!$this->remoteFileExists($customerAccountLogo)) {
  415.                 $customerAccountLogo "";
  416.             }
  417.             //Log to test path
  418.             $fileSystem->appendToFile($path '/voucherLogo.txt'"Customer Account Logo (AFTER CHECK IF EXIST): ".$customerAccountLogo."\n" );
  419.             //END Log to test path
  420.         }
  421.         return $customerAccountLogo;
  422.     }
  423.     /**
  424.      * @param Quote $quote
  425.      * @param $returnException
  426.      * @return bool
  427.      * @throws \Exception
  428.      */
  429.     public function checkIfGrantedToSeeQuote(Quote $quote,$returnException=true){
  430.         //Validation for ALC (A La Carta...). Show his own quotes and/or his team quotes
  431.         if(!$this->isGranted("ROLE_VIEW_QUOTE_LIMITED_INFO")){
  432.             return true;
  433.         }
  434.         $user $this->getUser();
  435.         //If he creates the quote and/or he is the owner...
  436.         if ($user->getId() == $quote->getCreatedBy()->getId() || ($quote->getOwner() && $user->getId() == $quote->getOwner()->getId()) ) {
  437.             return true;
  438.         }
  439.         //Check his team quotes
  440.         $teamQuotes=[];
  441.         if($user->getTeam()) {
  442.             $teamQuotes=$user->getTeam()->getQuotesOwned();
  443.         }
  444.         foreach ($teamQuotes as $teamQuote){
  445.             if($teamQuote->getId()==$quote->getId()){
  446.                 return true;
  447.             }
  448.         }
  449.         if($returnException){
  450.             throw new \Exception('Unauthorized to see this quote');
  451.         }
  452.         return false;
  453.     }
  454.     /**
  455.      * @param GoogleApi $googleApi
  456.      * @param $object
  457.      * @param bool $isAPI
  458.      * @return void
  459.      */
  460.     public function setAddressFromGoogle(GoogleApi $googleApi,&$object,$isAPI=false){
  461.         $addressStr "";
  462.         $objectClass get_class($object);
  463.         if (method_exists($objectClass'getAddressLine1')) {
  464.             $addressStr $object->getAddressLine1();
  465.         } else if (method_exists($objectClass'getAddress')) {
  466.             $addressStr $object->getAddress();
  467.         }
  468.         if ($addressStr) {
  469.             if ($addressArray $googleApi->getAddressArray($addressStr)) {
  470.                 $em $this->getDoctrine()->getManager();
  471.                 if ($isAPI) {
  472.                     $em $this->getEntityManagerAPI();
  473.                 }
  474.                 //Reset Values
  475.                 if(method_exists($object,'setLatitude')){
  476.                     $object->setLatitude(null);
  477.                     $object->setLongitude(null);
  478.                 }
  479.                 $object->setCountry(null);
  480.                 $object->setState(null);
  481.                 $object->setCity(null);
  482.                 $object->setZipCode(null);
  483.                 //Find the values for each address field.
  484.                 if (method_exists($object,'setLatitude') && key_exists('location'$addressArray) && key_exists('lat'$addressArray['location'])) {
  485.                     if(method_exists($object,'setLatitude')){
  486.                         $object->setLatitude($addressArray['location']['lat']);
  487.                         $object->setLongitude($addressArray['location']['lng']);
  488.                     }
  489.                 }
  490.                 if (key_exists('country'$addressArray) && $addressArray['country']) {
  491.                     $name ucwords($addressArray['country']);
  492.                     if (!$country $em->getRepository($isAPI Country::class : \App\Entity\Country::class)->findOneBy(['name' => $name])) {
  493.                         //Add the country
  494.                         $country $isAPI ? new Country() : new \App\Entity\Country();
  495.                         $country->setName($name);
  496.                         $em->persist($country);
  497.                         $em->flush();
  498.                     }
  499.                     $object->setCountry($country);
  500.                     if (key_exists('state'$addressArray) && $addressArray['state']) {
  501.                         $name ucwords($addressArray['state']);
  502.                         if (!$state $em->getRepository($isAPI State::class : \App\Entity\State::class)->findOneBy(['country' => $country->getId(), 'name' => $name])) {
  503.                             //Add the state
  504.                             $state $isAPI ? new State() : new \App\Entity\State();
  505.                             $state->setCountry($country);
  506.                             $state->setName($name);
  507.                             $em->persist($state);
  508.                             $em->flush();
  509.                         }
  510.                         $object->setState($state);
  511.                     }
  512.                     if (key_exists('city'$addressArray) && $addressArray['city']) {
  513.                         $name ucwords($addressArray['city']);
  514.                         if ($isAPI) {
  515.                             if (!$city $em->getRepository(City::class)->findOneBy(['country' => $country->getId(), 'state' => $state->getId(), 'name' => $name])) {
  516.                                 //Add the city
  517.                                 $city = new City();
  518.                                 $city->setCountry($country);
  519.                                 $city->setState($state);
  520.                                 $city->setName($name);
  521.                                 $em->persist($city);
  522.                                 $em->flush();
  523.                             }
  524.                             $object->setCity($city);
  525.                         } else {
  526.                             //it is a string
  527.                             $object->setCity($name);
  528.                         }
  529.                     }
  530.                 }
  531.                 if (key_exists('zipCode'$addressArray) && $addressArray['zipCode']) {
  532.                     $zipCodeStr ucwords($addressArray['zipCode']);
  533.                     if ($isAPI) {
  534.                         if (!$zipCode $em->getRepository(ZipCode::class)->findOneBy(['zipCode' => $zipCodeStr])) {
  535.                             $zipCode = new ZipCode();
  536.                             $zipCode->setZipCode($zipCodeStr);
  537.                             $em->persist($zipCode);
  538.                             $em->flush();
  539.                         }
  540.                         $object->setZipCode($zipCode);
  541.                     } else {
  542.                         //it is a string
  543.                         $object->setZipCode($zipCodeStr);
  544.                     }
  545.                 }
  546.             }
  547.         }
  548.     }
  549.     /**
  550.      * @param string|array $content
  551.      * @param string $fileName
  552.      * @return \Exception|\Symfony\Component\HttpFoundation\BinaryFileResponse
  553.      */
  554.     public function createAndDownloadTxtFile(string|array $content,string $fileName="file.txt")
  555.     {
  556.         try {
  557.             if(is_array($content)){
  558.                 $content json_encode($contentJSON_FORCE_OBJECT JSON_PRETTY_PRINT );
  559.             }
  560.             $tmpFileName = (new Filesystem())->tempnam(sys_get_temp_dir(), 'sb_');
  561.             $tmpFile fopen($tmpFileName'wb+');
  562.             if (!\is_resource($tmpFile)) {
  563.                 throw new \RuntimeException('Unable to create a temporary file.');
  564.             }
  565.             fwrite($tmpFile$content);
  566.             $mime_type finfo_file(finfo_open(FILEINFO_MIME_TYPE), $tmpFileName);
  567.             $response $this->file($tmpFileName$fileName);
  568.             $response->headers->set('Content-type'$mime_type);
  569.             fclose($tmpFile);
  570.             return $response;
  571.         }
  572.         catch (\Exception $e){
  573.             return $e;
  574.         }
  575.     }
  576.     /**
  577.      * @param array $contentArray
  578.      * @param $zipFileName
  579.      * @return \Exception|BinaryFileResponse
  580.      */
  581.     public function createZip(array $contentArray,$zipFileName='files.zip'){
  582.         try {
  583.             $zip = new \ZipArchive();
  584.             $zipName tempnam(sys_get_temp_dir(), 'zip');
  585.             $zip->open($zipName\ZipArchive::CREATE);
  586.             foreach ($contentArray as $key=>$content){
  587.                 if(is_array($content)) {
  588.                     $content json_encode($contentJSON_FORCE_OBJECT JSON_PRETTY_PRINT);
  589.                 }
  590.                 $zip->addFromString($key$content);
  591.             }
  592.             $zip->close();
  593.             $response = new BinaryFileResponse($zipName);
  594.             $response->headers->set('Content-Type''application/zip');
  595.             $response->setContentDisposition(ResponseHeaderBag::DISPOSITION_ATTACHMENT$zipFileName);
  596.             return $response;
  597.         }
  598.         catch (\Exception $e){
  599.             return $e;
  600.         }
  601.     }
  602.     /**
  603.      * Check that can see his children (This case is for GTN)
  604.      * @param CustomerAccount $customerAccount
  605.      * @return bool
  606.      */
  607.     protected function isCustomerAccountHostUser(CustomerAccount $customerAccount){
  608. //        if($this->getUser()->getCustomerAccount()->getId() != $customerAccount->getId()) {
  609.         if(!$this->getUser()->getCustomerAccount()->isOlg()) {
  610.             //Check that can see his children (This case is for GTN)
  611.             if ($this->isGranted('ROLE_CUSTOMER_ACCOUNT_CREATE_HOST')) {
  612.                 if ($customerAccountDomain $this->container->get('session')->get('customerAccountDomain')) {
  613.                     //Check that this account is one of its children
  614.                     if(!$customerAccount->getId()){
  615.                         return true;
  616.                     }
  617.                     else if ($customerAccountsHierarchy $this->getDoctrine()->getRepository(CustomerAccount::class)->findCustomerAccountsHierarchy($customerAccount->getId(), falsefalse)) {
  618.                         foreach ($customerAccountsHierarchy as $customerAccountHierarchy) {
  619.                             if ($customerAccountHierarchy->getParentCustomerAccount() && $customerAccountHierarchy->getParentCustomerAccount()->getId() == $customerAccountDomain->getId()) {
  620.                                 return true;
  621.                             }
  622.                         }
  623.                     }
  624.                 }
  625.             }
  626.         }
  627.         return false;
  628.     }
  629.     /**
  630.      * Check user (This case is for GTN)
  631.      * @param CustomerAccount $customerAccount
  632.      * @return bool
  633.      */
  634.     protected function isUserHost(User $user){
  635.         if(!$user->getCustomerAccount()->isOlg()) {
  636.             $customerAccount=$user->getCustomerAccount();
  637.             if($customerAccount->getDomain1() ||
  638.                 ($customerAccount->getParentCustomerAccount() && $customerAccount->getParentCustomerAccount()->getDomain1())){
  639.                 return true;
  640.             }
  641.         }
  642.         return false;
  643.     }
  644.     /**
  645.      * Check user is main host (This case is for GTN)
  646.      * @param User $user
  647.      * @return bool
  648.      */
  649.     protected function isUserMainHost(User $user){
  650.         if(!$user->getCustomerAccount()->isOlg() ) {
  651.             if($customerAccountDomain $this->container->get('session')->get('customerAccountDomain') ) {
  652.                 if($user->getCustomerAccount()->getId()==$customerAccountDomain->getId()){
  653.                     return true;
  654.                 }
  655.             }
  656.         }
  657.         return false;
  658.     }
  659.     public function insertArrayAtPosition$array$insert$position ): array
  660.     {
  661.         $newArray = [];
  662.         foreach($array as $key => $val){
  663.             if($key == $position){
  664.                 $newArray[] = $insert;
  665.             }
  666.             $newArray[] = $val;
  667.         }
  668.         return $newArray;
  669.     }
  670.     /**
  671.      * @param $getId
  672.      * @return false|mixed
  673.      * @throws \Psr\Container\ContainerExceptionInterface
  674.      * @throws \Psr\Container\NotFoundExceptionInterface
  675.      */
  676.     public function getCustomerAccountDomain($getId=false)
  677.     {
  678.         if(!$customerAccount=$this->container->get('session')->get('customerAccountDomain')){
  679.             return false;
  680.         }
  681.         if($getId){
  682.             return $customerAccount->getId();
  683.         }
  684.         return $customerAccount;
  685.     }
  686.     public function doFilterByCustomerAccount($returnIdsAsString=true)
  687.     {
  688.         //Check what can see (This case is for GTN)
  689.         if($this->getUser()) {
  690.             $customerAccount $this->getUser()->getCustomerAccount();
  691.             $isHostCustomerAccountUser=$this->isCustomerAccountHostUser($customerAccount);
  692.         }
  693.         else{
  694.             if(!$customerAccount=$this->container->get('session')->get('customerAccountDomain')){
  695.                 return false;
  696.             }
  697.             $isHostCustomerAccountUser=true;
  698.         }
  699.         if($isHostCustomerAccountUser){
  700.             //This case is for GTN
  701.             //Filter by Customer account
  702.             /**
  703.              * @var $customerAccount CustomerAccount
  704.              */
  705.             $ids=[];
  706.             $ids[]=$customerAccount->getId();
  707.             if($childrenCustomerAccounts=$customerAccount->getChildrenCustomerAccounts()){
  708.                 foreach($childrenCustomerAccounts as $childrenCustomerAccount){
  709.                     $ids[]=$childrenCustomerAccount->getId();
  710.                 }
  711.             }
  712.             if($returnIdsAsString){
  713.                 return implode(",",$ids);
  714.             }
  715.             return $ids;
  716.         }
  717.         //Show everything
  718.         return false;
  719.     }
  720.     public function getLogoDirByHost(Packages $assetsManager){
  721.         $logo $this->getParameter('ovn_logo_directory') . "/overseas-xpress-logo-scondary.png";
  722.         if ($customerAccountDomain $this->container->get('session')->get('customerAccountDomain')) {
  723.             //dir to get the logo image
  724.             $imgPath $this->getParameter('customer_account_logo_website_directory')."/".$customerAccountDomain->getWebsiteLogo();
  725.             //url to get the logo image
  726.             $pathCustomerAccountLogo $assetsManager->getUrl('uploads/customerAccountLogo/logoWebsite/'.$customerAccountDomain->getWebsiteLogo());
  727.             //Check if the file exist
  728.             if ($this->remoteFileExists($pathCustomerAccountLogo)) {
  729.                 $logo $imgPath;
  730.             }
  731.         }
  732.         return $logo;
  733.     }
  734. }