1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
declare(strict_types=1); |
4
|
|
|
|
5
|
|
|
namespace Odiseo\SyliusReferralsPlugin\Controller\Shop; |
6
|
|
|
|
7
|
|
|
use Odiseo\SyliusReferralsPlugin\Repository\AffiliateViewRepositoryInterface; |
8
|
|
|
use Odiseo\SyliusReferralsPlugin\Repository\OrderRepositoryInterface; |
9
|
|
|
use Sylius\Component\Core\Model\CustomerInterface; |
10
|
|
|
use Sylius\Component\Customer\Context\CustomerContextInterface; |
11
|
|
|
use Symfony\Component\HttpFoundation\Request; |
12
|
|
|
use Symfony\Component\HttpFoundation\Response; |
13
|
|
|
use Symfony\Component\HttpKernel\Exception\HttpException; |
14
|
|
|
use Twig\Environment; |
15
|
|
|
|
16
|
|
|
final class StatisticsAffiliateAction |
17
|
|
|
{ |
18
|
|
|
private CustomerContextInterface $customerContext; |
19
|
|
|
private OrderRepositoryInterface $orderRepository; |
20
|
|
|
private AffiliateViewRepositoryInterface $affiliateViewRepository; |
21
|
|
|
private Environment $twig; |
22
|
|
|
|
23
|
|
|
public function __construct( |
24
|
|
|
CustomerContextInterface $customerContext, |
25
|
|
|
OrderRepositoryInterface $orderRepository, |
26
|
|
|
AffiliateViewRepositoryInterface $affiliateViewRepository, |
27
|
|
|
Environment $twig |
28
|
|
|
) { |
29
|
|
|
$this->customerContext = $customerContext; |
30
|
|
|
$this->orderRepository = $orderRepository; |
31
|
|
|
$this->affiliateViewRepository = $affiliateViewRepository; |
32
|
|
|
$this->twig = $twig; |
33
|
|
|
} |
34
|
|
|
|
35
|
|
|
public function __invoke(Request $request): Response |
36
|
|
|
{ |
37
|
|
|
/** @var CustomerInterface|null $customer */ |
38
|
|
|
$customer = $this->customerContext->getCustomer(); |
39
|
|
|
if (null === $customer) { |
40
|
|
|
throw new HttpException(Response::HTTP_UNAUTHORIZED); |
41
|
|
|
} |
42
|
|
|
|
43
|
|
|
$sales = $this->orderRepository->countSalesByCustomer($customer); |
44
|
|
|
$visits = $this->affiliateViewRepository->countViewsByCustomer($customer); |
45
|
|
|
$average = $this->getAverage($sales, $visits); |
46
|
|
|
|
47
|
|
|
$data = [ |
48
|
|
|
'sales' => $sales, |
49
|
|
|
'visits' => $visits, |
50
|
|
|
'average' => $average |
51
|
|
|
]; |
52
|
|
|
|
53
|
|
|
$content = $this->twig->render( |
54
|
|
|
'@OdiseoSyliusReferralsPlugin/Shop/Account/Affiliate/Index/Statistics/_template.html.twig', |
55
|
|
|
$data |
56
|
|
|
); |
57
|
|
|
|
58
|
|
|
return new Response($content); |
59
|
|
|
} |
60
|
|
|
|
61
|
|
|
private function getAverage(int $sales, int $visits): int |
62
|
|
|
{ |
63
|
|
|
if ($sales == 0 || $visits == 0) { |
64
|
|
|
return 0; |
65
|
|
|
} |
66
|
|
|
|
67
|
|
|
return (int) (($sales / $visits) * 100); |
68
|
|
|
} |
69
|
|
|
} |
70
|
|
|
|