2016-09-10 01:41:21 +03:00
|
|
|
<?php
|
|
|
|
|
2016-09-23 22:39:33 +03:00
|
|
|
declare(strict_types=1);
|
|
|
|
|
2016-09-10 16:13:55 +03:00
|
|
|
namespace bkrukowski\TransparentEmail;
|
2016-09-10 01:41:21 +03:00
|
|
|
|
2016-09-10 16:13:55 +03:00
|
|
|
use bkrukowski\TransparentEmail\Services\ServiceInterface;
|
2016-09-10 01:41:21 +03:00
|
|
|
|
2016-09-10 16:13:55 +03:00
|
|
|
class TransparentEmail
|
2016-09-10 01:41:21 +03:00
|
|
|
{
|
|
|
|
/**
|
2016-09-23 22:29:25 +03:00
|
|
|
* @var ServiceCollectorInterface|ServiceInterface[]
|
2016-09-10 01:41:21 +03:00
|
|
|
*/
|
|
|
|
private $services;
|
|
|
|
|
2016-09-23 22:29:25 +03:00
|
|
|
/**
|
|
|
|
* @var bool
|
|
|
|
*/
|
2016-09-23 22:46:00 +03:00
|
|
|
private $caseSensitive;
|
2016-09-10 02:39:01 +03:00
|
|
|
|
2016-09-23 22:46:00 +03:00
|
|
|
public function __construct(ServiceCollectorInterface $services = null, bool $caseSensitive = false)
|
2016-09-10 01:41:21 +03:00
|
|
|
{
|
2016-09-23 22:29:25 +03:00
|
|
|
$this->services = $services ?: new DefaultServiceCollector();
|
2016-09-23 22:46:00 +03:00
|
|
|
$this->caseSensitive = $caseSensitive;
|
2016-09-10 01:41:21 +03:00
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
* @param string $email
|
|
|
|
* @return string
|
|
|
|
* @throws InvalidEmailException
|
|
|
|
*/
|
|
|
|
public function getPrimaryEmail(string $email)
|
|
|
|
{
|
|
|
|
$this->validateEmailAddress($email);
|
2016-09-23 22:46:00 +03:00
|
|
|
if (!$this->caseSensitive) {
|
2016-09-10 02:39:01 +03:00
|
|
|
$email = strtolower($email);
|
|
|
|
}
|
|
|
|
$domain = strtolower(explode('@', $email)[1]);
|
2016-09-10 01:41:21 +03:00
|
|
|
$result = $email;
|
|
|
|
|
2016-09-23 22:29:25 +03:00
|
|
|
foreach ($this->services as $service) {
|
2016-09-10 01:41:21 +03:00
|
|
|
if ($service->isDomainSupported($domain)) {
|
|
|
|
$result = $service->getPrimaryEmail($result);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
return $result;
|
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
* @param string $email
|
|
|
|
* @throws InvalidEmailException
|
|
|
|
*/
|
|
|
|
private function validateEmailAddress(string $email)
|
|
|
|
{
|
|
|
|
if (filter_var($email, FILTER_VALIDATE_EMAIL) === false) {
|
|
|
|
throw new InvalidEmailException("Invalid email '{$email}'!");
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|