transparent-email/src/TransparentEmail.php

60 lines
1.5 KiB
PHP
Raw Normal View History

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
*/
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();
$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);
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}'!");
}
}
}