2016-09-10 01:41:21 +03:00
|
|
|
<?php
|
|
|
|
|
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-10 02:39:01 +03:00
|
|
|
private $caseSensitiveLocalPart;
|
|
|
|
|
2016-09-23 22:29:25 +03:00
|
|
|
public function __construct(ServiceCollectorInterface $services = null, bool $caseSensitiveLocalPart = false)
|
2016-09-10 01:41:21 +03:00
|
|
|
{
|
2016-09-23 22:29:25 +03:00
|
|
|
$this->services = $services ?: new DefaultServiceCollector();
|
2016-09-10 02:39:01 +03:00
|
|
|
$this->caseSensitiveLocalPart = $caseSensitiveLocalPart;
|
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-10 02:39:01 +03:00
|
|
|
if (!$this->caseSensitiveLocalPart) {
|
|
|
|
$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}'!");
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|