ActionDispatcher.php
1 month ago
AmplitudeLoader.php
1 month ago
AmplitudeManager.php
1 month ago
Rest.php
1 month ago
ActionDispatcher.php
78 lines
| 1 | <?php |
| 2 | |
| 3 | namespace Hostinger\Amplitude; |
| 4 | |
| 5 | use Hostinger\Amplitude\AmplitudeManager; |
| 6 | use Hostinger\WpHelper\Config; |
| 7 | use Hostinger\WpHelper\Requests\Client; |
| 8 | use Hostinger\WpHelper\Utils as Helper; |
| 9 | |
| 10 | class ActionDispatcher |
| 11 | { |
| 12 | private const TRANSIENT_KEY = 'hostinger_login_data'; |
| 13 | private const EXPIRATION_TIME_SECONDS = 10800; // 3 hours |
| 14 | private const AMPLITUDE_LOGIN_ACTION = 'wordpress.autologin.success'; |
| 15 | |
| 16 | private Config $configHandler; |
| 17 | private Client $client; |
| 18 | private Helper $helper; |
| 19 | |
| 20 | public function __construct( |
| 21 | Helper $helper, |
| 22 | Config $configHandler, |
| 23 | Client $client |
| 24 | ) { |
| 25 | $this->helper = $helper; |
| 26 | $this->configHandler = $configHandler; |
| 27 | $this->client = $client; |
| 28 | |
| 29 | add_action('hostinger_autologin_user_logged_in', [ $this, 'userAlreadyLoggedIn' ]); |
| 30 | add_action('hostinger_autologin', [ $this, 'handleAutoLogin' ]); |
| 31 | add_action('wp_logout', [ $this, 'clearLoginData' ]); |
| 32 | } |
| 33 | |
| 34 | public function handleAutoLogin(array $data): void |
| 35 | { |
| 36 | $this->processLoginData($data); |
| 37 | $this->loginEvent($this->helper, $this->configHandler, $this->client, 'new_login'); |
| 38 | } |
| 39 | |
| 40 | public function userAlreadyLoggedIn(array $data): void |
| 41 | { |
| 42 | $this->processLoginData($data); |
| 43 | $this->loginEvent($this->helper, $this->configHandler, $this->client, 'logged_in'); |
| 44 | } |
| 45 | |
| 46 | |
| 47 | public function processLoginData(array $data): void |
| 48 | { |
| 49 | $sanitized_data = $this->sanitizeLoginData($data); |
| 50 | set_transient(self::TRANSIENT_KEY, $sanitized_data, self::EXPIRATION_TIME_SECONDS); |
| 51 | } |
| 52 | |
| 53 | public function loginEvent(Helper $helper, Config $config, Client $client, string $status): void |
| 54 | { |
| 55 | $amplitudeManager = new AmplitudeManager($helper, $config, $client); |
| 56 | $params = [ |
| 57 | 'action' => self::AMPLITUDE_LOGIN_ACTION, |
| 58 | 'status' => $status, |
| 59 | ]; |
| 60 | |
| 61 | $amplitudeManager->sendRequest($amplitudeManager::AMPLITUDE_ENDPOINT, $params); |
| 62 | } |
| 63 | |
| 64 | private function sanitizeLoginData(array $data): array |
| 65 | { |
| 66 | if (! is_array($data)) { |
| 67 | return []; |
| 68 | } |
| 69 | |
| 70 | return array_map('sanitize_text_field', $data); |
| 71 | } |
| 72 | |
| 73 | public function clearLoginData(): void |
| 74 | { |
| 75 | delete_transient(self::TRANSIENT_KEY); |
| 76 | } |
| 77 | } |
| 78 |