src/WebBundle/Service/ReviewsService.php line 351

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