Skip to content

Instantly share code, notes, and snippets.

@mordonez
Created September 26, 2023 22:40
Show Gist options
  • Save mordonez/f4da841be6f622c3935513a7b321cadd to your computer and use it in GitHub Desktop.
Save mordonez/f4da841be6f622c3935513a7b321cadd to your computer and use it in GitHub Desktop.
Drupal: Service and PHPUnit tests
<?php
// src/OfferingSyncSendgridService.php
namespace Drupal\offering_sync_sendgrid;
use Drupal\Core\Config\ConfigFactoryInterface;
use Drupal\Core\StringTranslation\StringTranslationTrait;
use Psr\Log\LoggerInterface;
use SendGrid\Client;
class OfferingSyncSendgridService
{
use StringTranslationTrait;
/**
* A configuration object.
*
* @var \Drupal\Core\Config\ImmutableConfig
*/
protected $config;
/**
* A configuration object.
*
* @var \Drupal\Core\Config\ImmutableConfig
*/
protected $configSendgridIntegration;
/**
* A logger instance.
*
* @var \Psr\Log\LoggerInterface
*/
protected $logger;
/**
* {@inheritdoc}
*
* @param \Drupal\Core\Config\ConfigFactoryInterface $config_factory
* The configuration factory.
* @param \Psr\Log\LoggerInterface $logger
* A logger instance.
*/
public function __construct(ConfigFactoryInterface $config_factory, LoggerInterface $logger)
{
$this->config = $config_factory->get('offering_sync_sendgrid.settings');
$this->configSendgridIntegration = $config_factory->get('sendgrid_integration.settings');
$this->logger = $logger;
}
public function addContactsToSendgrid($emails)
{
$list = $this->config->get('list');
$apikey = $this->configSendgridIntegration->get('apikey');
$sendgrid = new Client($apikey, [
"endpoint" => '/v3/marketing/contacts',
]);
$emailsData = [];
foreach ($emails as $index => $email) {
array_push($emailsData, [
'email' => $email,
]);
}
$data = [
'list_ids' => [$list],
'contacts' => $emailsData,
];
try {
$response = $sendgrid->client->put($sendgrid->endpoint, [
'json' => $data,
]);
$status = $response->getStatusCode();
$responseBody = $response->getBody()->getContents();
return [
'status' => $status,
'responseBody' => $responseBody,
];
} catch (\GuzzleHttp\Exception\RequestException $th) {
$this->logger->warning($th->getMessage());
return;
}
}
public function removeContactsfromList($emails)
{
try {
$ids = $this->getContactsSengridId($emails);
if (empty($ids)) {
return [];
}
$list = $this->config->get('list');
$apikey = $this->configSendgridIntegration->get('apikey');
$sendgrid = new Client($apikey, [
"endpoint" => '/v3/marketing/lists/' . $list . '/contacts',
]);
$queryParams = [
'query' => [
'contact_ids' => implode(",", $ids),
],
];
$result = $sendgrid->client->delete($sendgrid->endpoint, $queryParams);
} catch (\Exception $exception) {
$this->logger->error(
' removeContactsfromList %message ids: %ids',
[
'%message' => $exception->getMessage(),
'%ids' => implode(",", $ids)
]
);
return [];
}
return json_decode($result->getBody()->getContents());
}
public function searchContactsSendgrid($emails)
{
$apikey = $this->configSendgridIntegration->get('apikey');
$sendgrid = new Client($apikey, [
"endpoint" => '/v3/marketing/contacts/search/emails',
]);
try {
$response = $sendgrid->client->post($sendgrid->endpoint, [
'json' => [
'emails' => $emails
],
]);
} catch (\Exception $exception) {
$this->logger->warning(
' searchContactsSendgrid %message %emails',
['%message' => $exception->getMessage(), '%emails' => implode(",", $emails)]
);
return [];
}
return json_decode($response->getBody()->getContents());
}
public function getContactsSengridId($emails)
{
$response = $this->searchContactsSendgrid($emails);
if (empty($response)) {
return [];
}
$ids = [];
foreach ($response->result as $index => $data) {
if (property_exists($data, "contact")) {
array_push($ids, $data->contact->id);
}
}
return $ids;
}
}
<?php
//tests/src/Unit/OfferingSyncSendgridServiceTest.php
namespace Drupal\Tests\offering_sync_sendgrid\Unit;
use Drupal\Core\Config\ConfigFactoryInterface;
use Drupal\Core\Config\ImmutableConfig;
use Drupal\Core\DependencyInjection\ContainerBuilder;
use Drupal\Tests\UnitTestCase;
use Drupal\offering_sync_sendgrid\OfferingSyncSendgridService;
use Psr\Log\LoggerInterface;
/**
* Tests the OfferingSyncSendgridServiceTest class.
*
* @group offering_sync_sendgrid
*/
class OfferingSyncSendgridServiceTest extends UnitTestCase
{
const EMAIL_EXIST = 'test@example.com';
const EMAILS_EXIST = ['test@example.com', 'test2@example.com'];
const EMAIL_NOT_EXIST = 'test+notexist@example.com';
/**
* The mocked logger instance.
*
* @var \Psr\Log\LoggerInterface|\PHPUnit_Framework_MockObject_MockObject
*/
protected $logger;
/**
* The mocked config factory instance.
*
* @var \Drupal\Core\Config\ConfigFactoryInterface|\PHPUnit_Framework_MockObject_MockObject
*/
protected $configFactory;
/**
* The Sync Sendgrid service.
*
* @var \Drupal\offering_sync_sendgrid\OfferingSyncSendgridService
*/
protected $syncSendgrid;
protected $container;
/**
* Instance of ImmutableConfig.
*
* @var config
*/
private $config;
private $configSendgridIntegration;
/**
* {@inheritdoc}
*/
protected function setUp(): void
{
parent::setUp();
$this->logger = $this->prophesize(LoggerInterface::class);
$this->config = $this->prophesize(ImmutableConfig::class);
$this->config->get('list')->willReturn(getenv('SENDGRID_LIST'));
$this->configSendgridIntegration = $this->prophesize(ImmutableConfig::class);
$this->configSendgridIntegration->get('apikey')->willReturn(getenv('SENDGRID_API_KEY'));
// Initialize the ConfigFactoryInterface mock.
$this->configFactory = $this->prophesize(ConfigFactoryInterface::class);
// Will return instance of Immutable config.
$this->configFactory->get('sendgrid_integration.settings')->willReturn($this->configSendgridIntegration->reveal());
$this->configFactory->get('offering_sync_sendgrid.settings')->willReturn($this->config->reveal());
// Inject the mock of ConfigFactoryInterface.
$this->syncSendgrid = new OfferingSyncSendgridService($this->configFactory->reveal(), $this->logger->reveal());
}
/**
* {@inheritdoc}
*/
public static function setUpBeforeClass(): void
{
if (!getenv('SENDGRID_API_KEY') || !getenv('SENDGRID_LIST')) {
self::markTestSkipped('Es necesario las variables SENDGRID_API_KEY y SENDGRID_LIST en el phpunit.xml');
}
}
public function testAddContactSendGrid()
{
$result = $this->syncSendgrid->addContactsToSendgrid([self::EMAIL_EXIST]);
$this->assertEquals($result['status'], 202);
}
public function testAddContactsSendGrid()
{
$result = $this->syncSendgrid->addContactsToSendgrid(self::EMAILS_EXIST);
$this->assertEquals($result['status'], 202);
}
public function testSearchContactsSendgrid()
{
$response = $this->syncSendgrid->searchContactsSendgrid([self::EMAIL_EXIST]);
$emailReturned = $response->result->{self::EMAIL_EXIST}->contact->email;
$this->assertEquals($emailReturned, self::EMAIL_EXIST);
$this->assertIsString($response->result->{self::EMAIL_EXIST}->contact->id);
// NOT Exists
$result = $this->syncSendgrid->searchContactsSendgrid([self::EMAIL_NOT_EXIST]);
$this->assertEmpty($result);
// BAD EMAIL
$result = $this->syncSendgrid->searchContactsSendgrid(["BADEMAIL"]);
$this->assertEmpty($result);
}
public function testRemoveContactListSendgrid()
{
$result = $this->syncSendgrid->addContactsToSendgrid(self::EMAILS_EXIST);
$result = $this->syncSendgrid->removeContactsfromList(self::EMAILS_EXIST);
$this->assertIsObject($result);
$this->assertIsString($result->job_id);
$result = $this->syncSendgrid->removeContactsfromList([self::EMAIL_EXIST, self::EMAIL_NOT_EXIST]);
$this->assertIsObject($result);
$this->assertIsString($result->job_id);
$result = $this->syncSendgrid->removeContactsfromList([self::EMAIL_NOT_EXIST]);
$this->assertEmpty($result);
}
public function testgetContactsSengridId()
{
$result = $this->syncSendgrid->getContactsSengridId([self::EMAIL_EXIST]);
$this->assertIsArray($result);
$this->assertCount(1, $result);
$result = $this->syncSendgrid->getContactsSengridId([self::EMAIL_NOT_EXIST]);
$this->assertEmpty($result);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment