transparent-email/src/Gordianus.php

73 lines
2.0 KiB
PHP
Raw Normal View History

2016-09-10 01:41:21 +03:00
<?php
namespace bkrukowski\Gordianus;
2016-09-10 11:50:57 +03:00
use bkrukowski\Gordianus\Services\GmailCom;
2016-09-10 13:15:37 +03:00
use bkrukowski\Gordianus\Services\OutlookCom;
2016-09-10 01:41:21 +03:00
use bkrukowski\Gordianus\Services\ServiceInterface;
2016-09-10 11:50:57 +03:00
use bkrukowski\Gordianus\Services\TlenPl;
use bkrukowski\Gordianus\Services\Www33MailCom;
2016-09-10 01:41:21 +03:00
class Gordianus
{
2016-09-10 11:50:57 +03:00
const SERVICE_GMAIL_COM = GmailCom::class;
const SERVICE_TLEN_PL = TlenPl::class;
const SERVICE_WWW_33MAIL_COM = Www33MailCom::class;
2016-09-10 13:15:37 +03:00
const SERVICE_OUTLOOK_COM = OutlookCom::class;
2016-09-10 01:41:21 +03:00
/**
* Constant ALL_SERVICES can contain different values depends on API version
*/
const ALL_SERVICES = [
self::SERVICE_GMAIL_COM,
self::SERVICE_TLEN_PL,
self::SERVICE_WWW_33MAIL_COM,
2016-09-10 13:15:37 +03:00
self::SERVICE_OUTLOOK_COM,
2016-09-10 01:41:21 +03:00
];
private $services;
private $caseSensitiveLocalPart;
public function __construct(array $services = self::ALL_SERVICES, bool $caseSensitiveLocalPart = false)
2016-09-10 01:41:21 +03:00
{
$this->services = $services;
$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;
foreach ($this->services as $serviceClass) {
/** @var ServiceInterface $service */
$service = new $serviceClass();
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}'!");
}
}
}