1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
declare(strict_types=1); |
4
|
|
|
|
5
|
|
|
namespace Charcoal\Email\Api\V1; |
6
|
|
|
|
7
|
|
|
// From 'psr/http-message' (PSR-7) |
8
|
|
|
use Psr\Http\Message\ServerRequestInterface as Request; |
9
|
|
|
use Psr\Http\Message\ResponseInterface as Response; |
10
|
|
|
|
11
|
|
|
// From 'locomotivemtl/charcoal-factory' |
12
|
|
|
use Charcoal\Factory\FactoryInterface; |
13
|
|
|
|
14
|
|
|
use Charcoal\Email\Objects\Link; |
15
|
|
|
use Charcoal\Email\Services\Tracker; |
16
|
|
|
|
17
|
|
|
/** |
18
|
|
|
* Track link clicks. |
19
|
|
|
* |
20
|
|
|
* Open a link by ID, log the event into the database and redirect to the actual destination. |
21
|
|
|
*/ |
22
|
|
|
class LinkAction |
23
|
|
|
{ |
24
|
|
|
/** |
25
|
|
|
* @var string |
26
|
|
|
*/ |
27
|
|
|
private $linkId; |
28
|
|
|
|
29
|
|
|
/** |
30
|
|
|
* @var Tracker |
31
|
|
|
*/ |
32
|
|
|
private $tracker; |
33
|
|
|
|
34
|
|
|
/** |
35
|
|
|
* @var FactoryInterface |
36
|
|
|
*/ |
37
|
|
|
private $modelFactory; |
38
|
|
|
|
39
|
|
|
/** |
40
|
|
|
* @param string $linkId Link ID. |
41
|
|
|
* @param Tracker $tracker Tracker service. |
42
|
|
|
* @param FactoryInterface $modelFactory Model factory, to create Link objects. |
43
|
|
|
*/ |
44
|
|
|
public function __construct(string $linkId, Tracker $tracker, FactoryInterface $modelFactory) |
45
|
|
|
{ |
46
|
|
|
$this->linkId = $linkId; |
47
|
|
|
$this->tracker = $tracker; |
48
|
|
|
$this->modelFactory = $modelFactory; |
49
|
|
|
} |
50
|
|
|
|
51
|
|
|
/** |
52
|
|
|
* @param Request $request PSR-7 Request. |
53
|
|
|
* @param Response $response PSR-7 Response. |
54
|
|
|
* @return Response |
55
|
|
|
*/ |
56
|
|
|
public function __invoke(Request $request, Response $response) : Response |
57
|
|
|
{ |
58
|
|
|
$ip = $request->getAttribute('client-ip'); |
59
|
|
|
$this->tracker->trackLink($this->linkId, $ip); |
60
|
|
|
|
61
|
|
|
$link = $this->modelFactory->create(Link::class); |
62
|
|
|
$link->load($this->linkId); |
63
|
|
|
if (!$link->id()) { |
64
|
|
|
return $response->withStatus(404); |
65
|
|
|
} |
66
|
|
|
$url = $link['url']; |
67
|
|
|
|
68
|
|
|
return $response |
69
|
|
|
->withStatus(301) |
70
|
|
|
->withHeader('Location', $url); |
71
|
|
|
} |
72
|
|
|
} |
73
|
|
|
|