src/WebBundle/Service/ReviewsService.php line 335

Open in your IDE?
  1. <?php
  2. namespace WebBundle\Service;
  3. use Doctrine\ORM\EntityManager;
  4. use Doctrine\ORM\EntityRepository;
  5. use Exception;
  6. use SoapClient;
  7. use SoapFault;
  8. use Symfony\Component\DependencyInjection\ContainerInterface;
  9. use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
  10. use WebBundle\Entity\Factory;
  11. use WebBundle\Entity\ProductReviewsCache;
  12. use WebBundle\Helper\App;
  13. use WebBundle\Helper\SoapHelper;
  14. use WebBundle\Helper\StrHelper;
  15. use WebBundle\Helper\TrustpilotHelper;
  16. use WebBundle\Repository\ListCountryRepository;
  17. use WebBundle\Repository\ProductReviewsCacheRepository;
  18. use WebBundle\Repository\ReviewsCacheRepository;
  19. use WebBundle\Repository\ReviewsTotalCacheRepository;
  20. class ReviewsService
  21. {
  22.     /** @required */
  23.     public ProductReviewsCacheRepository $productReviewsCacheRepository;
  24.     /** @required */
  25.     public ReviewsCacheRepository $reviewsCacheRepository;
  26.     /** @required */
  27.     public ListCountryRepository $listCountryRepository;
  28.     protected EntityManager $em;
  29.     protected ContainerInterface $container;
  30.     /**
  31.      * Хранится репозиторий суммарных дынных отзывов
  32.      */
  33.     protected $repoSummaries null;
  34.     /**
  35.      * Хранится репозиторий отзывов
  36.      */
  37.     protected $repoReviews null;
  38.     private array $totals = [];
  39.     private array $reviews = [];
  40.     private string $serviceType 'trustpilot';
  41.     private string $reviewsType 'service';
  42.     /**
  43.      * @param ContainerInterface $container
  44.      * @param EntityManager $entityManager
  45.      */
  46.     public function __construct(ContainerInterface $containerEntityManager $entityManager)
  47.     {
  48.         $this->container $container;
  49.         $this->em $entityManager;
  50.     }
  51.     /**
  52.      * @return string
  53.      */
  54.     public function getServiceType()
  55.     {
  56.         return $this->serviceType;
  57.     }
  58.     /**
  59.      * @param string $serviceType
  60.      * @return ReviewsService
  61.      */
  62.     public function setServiceType(string $serviceType)
  63.     {
  64.         $this->serviceType $serviceType;
  65.         return $this;
  66.     }
  67.     /**
  68.      * @return string
  69.      */
  70.     public function getReviewsType()
  71.     {
  72.         return $this->reviewsType;
  73.     }
  74.     /**
  75.      * @param string $reviewsType
  76.      * @return ReviewsService
  77.      */
  78.     public function setReviewsType(string $reviewsType)
  79.     {
  80.         $this->reviewsType $reviewsType;
  81.         return $this;
  82.     }
  83.     /**
  84.      * Получить суммарные данные из Интерета
  85.      * @param array $options
  86.      * @return bool|null|array
  87.      * @throws Exception
  88.      */
  89.     public function getSummariesFromInternet(array $options)
  90.     {
  91.         if ($this->serviceType === 'trustpilot') {
  92.             if ($this->reviewsType === 'service') {
  93.                 // Получаем данные из интернета
  94.                 return $this->totals['new'] = TrustpilotHelper::getInstance()->getTotal();
  95.             } elseif ($this->reviewsType === 'product') {
  96.                 if (isset($options['sku']) && !empty($options['sku'])) {
  97.                     return $this->totals['new'] = TrustpilotHelper::getInstance()->getProductTotal([
  98.                         'sku' => $options['sku'],
  99.                     ]);
  100.                 }
  101.                 return $this->totals['new'] = TrustpilotHelper::getInstance()->getProductTotalList();
  102.             }
  103.         }
  104.         return null;
  105.     }
  106.     /**
  107.      * Получить сумарные данные по отзывам из БД
  108.      * @param array $options
  109.      * @return array|null
  110.      */
  111.     public function getSummariesToDB(array $options): ?array
  112.     {
  113.         if ($this->serviceType === 'trustpilot') {
  114.             if ($this->reviewsType === 'service') {
  115.                 /** @var ReviewsTotalCacheRepository $repoReviews */
  116.                 $repoReviews $this->getRepoSummaries();
  117.                 if ($options['hash'] ?? null) {
  118.                     return $this->totals['db'] = $repoReviews->findBy([
  119.                         'hash' => $options['hash'],
  120.                     ]);
  121.                 }
  122.                 return $this->totals['db'] = $repoReviews->getTotal();
  123.             } elseif ($this->reviewsType === 'product') {
  124.                 /** @var ProductReviewsCacheRepository $repoService */
  125.                 $repoService $this->getRepoSummaries();
  126.                 if (!empty($param['sku'])) {
  127.                     return $this->totals['db'] = $repoService->getReviews([
  128.                         'sku' => $options['sku'],
  129.                     ]);
  130.                 }
  131.                 return $this->totals['db'] = $repoService->getReviews();
  132.             }
  133.         }
  134.         return null;
  135.     }
  136.     /**
  137.      * Возвращает отзывы суммарной информации отзывов
  138.      * @return mixed
  139.      */
  140.     public function getRepoSummaries(): EntityRepository
  141.     {
  142.         $repoSummaries $this->repoSummaries;
  143.         if ($this->serviceType === 'trustpilot') {
  144.             if ($this->reviewsType === 'service') {
  145.                 /** @var ReviewsTotalCacheRepository $repoSummaries */
  146.                 $repoSummaries $this->em
  147.                     ->getRepository('WebBundle:ReviewsTotalCache');
  148.             } elseif ($this->reviewsType === 'product') {
  149.                 $repoSummaries $this->productReviewsCacheRepository;
  150.             }
  151.             $this->repoSummaries $repoSummaries;
  152.         }
  153.         return $this->repoSummaries;
  154.     }
  155.     /**
  156.      * Получить данные отзывов из Интерета
  157.      * @param array $options
  158.      * @return bool|null|array
  159.      * @throws Exception
  160.      */
  161.     public function getReviewsFromInternet(array $options)
  162.     {
  163.         if ($this->serviceType === 'trustpilot') {
  164.             if ($this->reviewsType === 'service') {
  165.                 // Получаем данные из интернета
  166.                 return $this->reviews['new'] = TrustpilotHelper::getInstance()->getReviews();
  167.             } elseif ($this->reviewsType === 'product') {
  168.                 $this->reviews['new'] = TrustpilotHelper::getInstance()->getProductReviews();
  169.                 return $this->reviews['new'];
  170.             }
  171.         }
  172.         return null;
  173.     }
  174.     /**
  175.      * Получить список отзывов из БД
  176.      * @param array $options
  177.      * @return array|bool|null
  178.      */
  179.     public function getListReviewsToDB(array $options)
  180.     {
  181.         if ($this->serviceType === 'trustpilot') {
  182.             if ($this->reviewsType === 'service') {
  183.                 // Если установлены лимиты
  184.                 if (isset($options['current'])) {
  185.                     $options['start_with'] = $options['current'];
  186.                 }
  187.                 $reviews $this->getRepoReviews()->getReviews($options);
  188.                 // https://te2.remote.team/discus/D5467D43-C08A-85DB-AF3F-6BED74D781DA
  189.                 array_walk(
  190.                     $reviews,
  191.                     function (array &$item) {
  192.                         $item['url'] = str_replace('#''/'$item['url']);
  193.                         if ($item['country'] === 'DA') {
  194.                             $item['country'] = 'DK';
  195.                         }
  196.                     }
  197.                 );
  198.                 return $this->reviews['db'] = $reviews;
  199.             } elseif ($this->reviewsType === 'product') {
  200.                 $params = [];
  201.                 if (!empty($options['sku'])) {
  202.                     $params = [
  203.                         'sku' => $options['sku'],
  204.                     ];
  205.                 }
  206.                 $res $this->getRepoReviews()->getReviews($params);
  207.                 return $this->reviews['db'] = $res;
  208.             }
  209.         }
  210.         return null;
  211.     }
  212.     /**
  213.      * Возвращает репозитории отзывов
  214.      * @return mixed
  215.      */
  216.     public function getRepoReviews(): EntityRepository
  217.     {
  218.         $repoReviews $this->repoReviews;
  219.         if ($this->serviceType === 'trustpilot') {
  220.             if ($this->reviewsType === 'service') {
  221.                 $repoReviews $this->reviewsCacheRepository;
  222.             } elseif ($this->reviewsType === 'product') {
  223.                 $repoReviews $this->productReviewsCacheRepository;
  224.             }
  225.             $this->repoReviews $repoReviews;
  226.         }
  227.         return $this->repoReviews;
  228.     }
  229.     /**
  230.      * Получает страну
  231.      * @param $id
  232.      * @return string|null
  233.      * @throws SoapFault|Exception
  234.      */
  235.     public function getCountryReview($id)
  236.     {
  237.         /** @var SoapClient $client */
  238.         $client SoapHelper::client(App::getContainer()->getParameter('orderApi_wsdl'));
  239.         if (!$client) {
  240.             return null;
  241.         }
  242.         $response $client->GetCountryOrder(['Number' => $id]);
  243.         if (is_string($response->return)) {
  244.             $result json_decode($response->returntrue);
  245.             if (isset($result['Code'])) {
  246.                 return StrHelper::toUpper($result['Code']);
  247.             }
  248.         } else {
  249.             // Вторая попытка
  250.             $response $client->GetCountryOrder(['Number' => $id]);
  251.             if (is_string($response->return)) {
  252.                 $result json_decode($response->returntrue);
  253.                 if (isset($result['Code'])) {
  254.                     return StrHelper::toUpper($result['Code']);
  255.                 }
  256.             }
  257.         }
  258.         return null;
  259.     }
  260.     public function getReviewsByCollectionId(int $collectionId): array
  261.     {
  262.         $reviewsData $this->productReviewsCacheRepository->findBy(['collection' => $collectionId], ['id' => 'DESC']);
  263.         $reviewsDataArr = [];
  264.         /** @var ProductReviewsCache $review */
  265.         foreach ($reviewsData as $review) {
  266.             if ($review->isAnonymous) {
  267.                 $review->setUsername('');
  268.             }
  269.             $reviewsDataArr[] = $review->toArray();
  270.         }
  271.         return $this->getRevData($reviewsDataArr);
  272.     }
  273.     public function getReviewByCollection($code): array // старый вариант - в будущем будет удален
  274.     {
  275.         $reviewsData $this->productReviewsCacheRepository->getReviews(['sku' => $code]);
  276.         return $this->getRevData($reviewsData);
  277.     }
  278.     /**
  279.      * @param array $codes
  280.      * @return array
  281.      */
  282.     public function getReviewForFactory(array $codes): array
  283.     {
  284.         $reviewsData $this->productReviewsCacheRepository->getReviews(['sku' => array_keys($codes)]);
  285.         $data = [
  286.             'prcCount' => 0,
  287.             'prcVote' => 0,
  288.             'list' => [],
  289.         ];
  290.         foreach ($reviewsData as $row) {
  291.             if (empty($codes[$row['sku']])) {
  292.                 continue;
  293.             }
  294.             //App::dumpExit($row);
  295.             if (empty($data[$row['sku']])) {
  296.                 $data[$row['sku']] = [
  297.                     'prcCount' => 0,
  298.                     'prcVote' => 0,
  299.                 ];
  300.             }
  301.             $data['list'][] = [
  302.                 'star' => 5,
  303.                 'date' => date('Y-d-m H:i:s'1479934546),
  304.                 'content' => 'répond aux attentes, pas de commentaire.',
  305.                 'username' => 'Delmoitié',
  306.             ];
  307.             $data['prcCount']++;
  308.             $data['prcVote'] += $row['star'];
  309.             $data[$row['sku']]['prcCount']++;
  310.             $data[$row['sku']]['prcVote'] += $row['star'];
  311.             $data[$row['sku']]['name'] = $codes[$row['sku']]['name'];
  312.             $data[$row['sku']]['url'] = $codes[$row['sku']]['url'];
  313.         }
  314.         return $data;
  315.     }
  316.     /**
  317.      * @param array $reviewsData
  318.      * @return array
  319.      * @throws Exception
  320.      */
  321.     public function getRevData(array $reviewsData): array
  322.     {
  323.         $percent = [
  324.             '1' => 0,
  325.             '2' => 0,
  326.             '3' => 0,
  327.             '4' => 0,
  328.             '5' => 0,
  329.             'all' => 0,
  330.             'd' => 0,
  331.         ];
  332.         $starsCount = [
  333.             => 0,
  334.             => 0,
  335.             => 0,
  336.             => 0,
  337.             => 0,
  338.         ];
  339.         foreach ($reviewsData as $row) {
  340.             $percent['all']++;
  341.             $percent[$row['star']]++;
  342.             $percent['d'] = $percent['d'] + $row['star'];
  343.         }
  344.         $starsCount $percent;
  345.         unset($starsCount['all']);
  346.         unset($starsCount['d']);
  347.         $data = [
  348.             'list' => $reviewsData,
  349.             'count' => $percent['all'],
  350.             'percent' => [
  351.                 '1' => 0,
  352.                 '2' => 0,
  353.                 '3' => 0,
  354.                 '4' => 0,
  355.                 '5' => 0,
  356.                 'd' => 0,
  357.             ],
  358.             'starsDistribution' => $starsCount,
  359.             // новая версия
  360.             'stars' => [
  361.                 => 0,
  362.                 => 0,
  363.                 => 0,
  364.                 => 0,
  365.                 => 0,
  366.             ],
  367.             'common' => 0,
  368.         ];
  369.         if ($percent['all'] > 0) {
  370.             $data['percent'] = [
  371.                 '1' => (100 $percent['all'] * $percent[1]),
  372.                 '2' => (100 $percent['all'] * $percent[2]),
  373.                 '3' => (100 $percent['all'] * $percent[3]),
  374.                 '4' => (100 $percent['all'] * $percent[4]),
  375.                 '5' => (100 $percent['all'] * $percent[5]),
  376.                 'd' => round($percent['d'] / $percent['all'], 1),
  377.             ];
  378.             $data['stars'] = [
  379.                 => (100 $percent['all'] * $percent[1]),
  380.                 => (100 $percent['all'] * $percent[2]),
  381.                 => (100 $percent['all'] * $percent[3]),
  382.                 => (100 $percent['all'] * $percent[4]),
  383.                 => (100 $percent['all'] * $percent[5]),
  384.             ];
  385.             $data['common'] = round($percent['d'] / $percent['all'], 1);
  386.         }
  387.         foreach ($data['list'] as &$review) {
  388.             $review['replyUrl'] = App::generateUrl('app_product_review_reply', ['id' => $review['id']]);
  389.         }
  390.         $percentRound $data['percent'];
  391.         unset($percentRound['d']);
  392.         foreach ($percentRound as $key => $value) {
  393.             $percentRound[$key] = round($value2);
  394.         }
  395.         $data['percentRound'] = $percentRound;
  396.         return $data;
  397.     }
  398.     public function getReviewsByFactory(Factory $factory): array
  399.     {
  400.         $published 1;
  401.         $collections App::getRepository('WebBundle:Collection')->findBy(['factory' => $factory->getId(), 'status' => $published]);
  402.         return $this->getReviewsByCollections($collections);
  403.     }
  404.     public function getReviewsByCollections(array $collections): array
  405.     {
  406.         $reviews $this->productReviewsCacheRepository->findBy(['collection' => $collections]);
  407.         $reviewsByCollections = [];
  408.         foreach ($reviews as $review) {
  409.             /** @var ProductReviewsCache $review */
  410.             $reviewsByCollections[$review->getCollection()->getId()]['collectionName'] = $review->getCollection()->getName();
  411.             $reviewsByCollections[$review->getCollection()->getId()]['collectionId'] = $review->getCollection()->getId();
  412.             $reviewsByCollections[$review->getCollection()->getId()]['collection_url'] = App::generateUrl(
  413.                 'app_collection',
  414.                 [
  415.                     'collectionUrl' => $review->getCollection()->getUrl(),
  416.                     'factoryUrl' => $review->getCollection()->getFactoryUrl(),
  417.                 ],
  418.                 UrlGeneratorInterface::ABSOLUTE_URL
  419.             );
  420.             $reviewsByCollections[$review->getCollection()->getId()]['reviews'][] = $review->toArray();
  421.         }
  422.         return $reviewsByCollections;
  423.     }
  424. }