Loading src/Services/HubspotAPI.php +153 −76 Original line number Diff line number Diff line Loading @@ -5,24 +5,35 @@ namespace Drupal\hubspot_integration\Services; use Drupal\Component\Utility\UrlHelper; use Drupal\Core\Database\Connection; use Symfony\Component\HttpFoundation\Session\Session; use Exception; use Drupal\Core\Config\ConfigFactory; use Drupal\taxonomy\Entity\Term; use Drupal\taxonomy\Entity\Vocabulary; /** * Hubspot API service. */ class HubspotAPI { /* * @var \Drupal\Core\Database\Connection $database /** * The database service. * * @var \Drupal\Core\Database\Connection */ protected $database; /* * @var \Symfony\Component\HttpFoundation\Session\Session $session /** * The session service. * * @var \Symfony\Component\HttpFoundation\Session\Session */ protected $session; /* * @var \Drupal\Core\Config\ConfigFactory $config_factory /** * The Config Factory service. * * @var \Drupal\Core\Config\ConfigFactory */ protected $config_factory; protected $configFactory; /** * Static cache for cookies. Loading @@ -33,14 +44,18 @@ class HubspotAPI { /** * Constructs a new HubspotAPI object. * * @param \Drupal\Core\Database\Connection $connection * The connection service. * @param \Symfony\Component\HttpFoundation\Session\Session $session * The session service. * @param \Drupal\Core\Config\ConfigFactory $config_factory * The config factory service;. */ public function __construct(Connection $connection, Session $session, ConfigFactory $config_factory) { $this->database = $connection; $this->session = $session; $this->config_factory = $config_factory; $this->configFactory = $config_factory; } /** Loading @@ -55,7 +70,6 @@ class HubspotAPI { public function getCookie($cookieName = 'hubspotutk') { if (!isset($this->cookies[$cookieName])) { $this->cookies[$cookieName] = \Drupal::request()->cookies->get($cookieName); // Ensure data in cookie is authorized / safe for hubspot_integration. if (($cookieName == 'hubspot_integration') && ($tids = explode('_', ltrim($this->cookies[$cookieName], 'hubspot_'))) Loading @@ -69,7 +83,6 @@ class HubspotAPI { } } } $tids = array_intersect($tids, $allowedValues); $this->cookies[$cookieName] = 'hubspot_' . implode('_', $tids); } Loading @@ -79,7 +92,7 @@ class HubspotAPI { } /** * Get current session * Get current session. */ public function getSession() { return $this->session; Loading @@ -93,10 +106,8 @@ class HubspotAPI { */ public function isContact() { $result = FALSE; if ($user = $this->getContactInfo()) { $property = 'is-contact'; if (isset($user->{$property})) { $result = $user->{$property}; } Loading @@ -106,12 +117,15 @@ class HubspotAPI { } /** * Get Husbspot values for the current user * Get Husbspot values for the current user. * * @param bool $forced_update * The forced update boolean. * * @param boolean $forced_update * @return NULL|mixed * @return null|mixed * Null. */ public function getContactInfo($forced_update=false) { public function getContactInfo($forced_update = FALSE) { $user = NULL; if (!$this->isDemoMode() && !$forced_update && $this->session->get('hubspot_integration.user')) { $user = $this->session->get('hubspot_integration.user'); Loading @@ -126,108 +140,130 @@ class HubspotAPI { } /** * Get the config name for the hubspot integration module settings * Get the config name for the hubspot integration module settings. * * @param unknown $name * @return mixed|NULL|array|\Drupal\Component\Render\MarkupInterface|string|unknown[]|array[] * @param string $name * The name. * * @return mixed|null|array|\Drupal\Component\Render\MarkupInterface|string|unknown[]|array[] * The value. */ public function getConfig($name) { return $this->config_factory->get('hubspot_integration.settings')->get($name); public function getConfig(string $name) { return $this->configFactory->get('hubspot_integration.settings')->get($name); } /** * Set the config name for the hubspot integration module settings * Set te config name for the hubspot integration module settings. * * @param string $name * The name. * @param string $value * The value. * * @param unknown $name * @return mixed|NULL|array|\Drupal\Component\Render\MarkupInterface|string|unknown[]|array[] * @return \Drupal\Core\Config\Config|\Drupal\Core\Config\ImmutableConfig * The config. */ public function setConfig($name, $value) { return $this->config_factory->getEditable('hubspot_integration.settings')->set($name, $value)->save(); public function setConfig(string $name, string $value) { return $this->configFactory->getEditable('hubspot_integration.settings')->set($name, $value)->save(); } /** * Get the list of the possible contact properties and their definitions * Get the list of the possible contact properties and their definitions. * * @return mixed * The contact properties. */ public function getContactProperties() { return $this->request('properties/v1/contacts/properties'); } /** * Function to make calls on hubspot * Function to make calls on hubspot. * * @param unknown $api * @return mixed * @param string $api * The API. * @param array $options * The options. * @param string $type * The type. * @param array $datas * Tha datas. * * @return mixed|null * The response. */ public function request($api, $options = [], $type='GET', $datas = []) { public function request(string $api, array $options = [], string $type = 'GET', array $datas = []) { $token_private_app = $this->getConfig('token_private_app'); $headers = [ 'Content-Type' => 'application/json', 'Authorization' => 'Bearer ' . $token_private_app, ]; $ret = NULL; if (!empty($token_private_app)) { $hub_url = 'https://api.hubapi.com/'; $query_str = UrlHelper::buildQuery($options); $url = $hub_url . $api . '?' . $query_str; try { switch ($type) { case 'GET': $request = \Drupal::httpClient()->get($url, ['headers' => $headers]); break; case 'POST': $request = \Drupal::httpClient()->post($url, ['json' => $datas, 'headers' => $headers], $options); $request = \Drupal::httpClient()->post( $url, ['json' => $datas, 'headers' => $headers], ); break; } $ret = json_decode($request->getBody()); } catch (Exception $e) { catch (\Exception $e) { \Drupal::logger('hubspot_integration')->error('Error : ' . $e->getCode() . ' : ' . $e->getMessage()); } } return $ret; } /** * Get the mapping done between Drupal and Hubspot * Get the mapping done between Drupal and Hubspot. * * @return mixed * The config. */ public function getMapping() { return $this->getConfig('mapping'); } /** * Get the sort configuration * Get the sort configuration. * * @return mixed * The config. */ public function getSort($tids = array()) { public function getSort($tids = []) { return $this->getConfig('sort'); } /** * Get the sort configuration * Get the sort configuration. * * @param array $tids * The tids. * * @return mixed * @return array * The sorted tids. */ public function getTidsSort($tids) { public function getTidsSort(array $tids) { $sort = $this->getConfig('sort'); $tids_sort = array(); if (!empty($tids[0])) { // compile the sort in order to get the min values for the tids $tids_sort = []; // Compile the sort in order to get the min values for the tids. if (!empty($tids[0])) { foreach ($tids as $tid) { /** @var \Drupal\taxonomy\TermInterface $term */ $term = Term::load($tid); $vid = $term->bundle(); foreach ($sort[$vid][$tid] as $term_weight_id => $term_weight) { if (!isset($tids_sort[$term_weight_id])) { $tids_sort[$term_weight_id] = $sort[$vid][$tid][$term_weight_id]; Loading @@ -243,23 +279,29 @@ class HubspotAPI { } /** * Utility function to transform a text as a machine name * Utility function to transform a text as a machine name. * * @param string $string * The string. * * @param unknown $string * @return string * The name. */ public static function machineName($string) { public static function machineName(string $string) { return preg_replace('@[^a-z0-9-]+@', '-', strtolower($string)); } /** * Utility function to check a vocabulary is mapped with hubspot * Utility function to check a vocabulary is mapped with hubspot. * * @param string $vocabulary * @return boolean * The vocabulary. * * @return bool * The boolean. */ public function isVocabularyMapped($vocabulary) { $mapping = $this->getMapping(); if (!empty($mapping)) { foreach ($mapping as $mapping) { if (isset($mapping['#vocabulary']) && $mapping['#vocabulary'] === $vocabulary) { Loading @@ -268,17 +310,18 @@ class HubspotAPI { } } return false; return FALSE; } /** * Utility function to get mapped vocabularies * Utility function to get mapped vocabularies. * * @return array * The list of vocabularies. */ function getMappedVocabularies() { public function getMappedVocabularies() { $vocabularies = Vocabulary::loadMultiple(); $vocabulariesList = []; foreach ($vocabularies as $vid => $vocablary) { if ($this->isVocabularyMapped($vid)) { $vocabulariesList[$vid] = $vocablary->get('name'); Loading @@ -288,29 +331,45 @@ class HubspotAPI { return $vocabulariesList; } /** * Retrieve the demo mode config. */ public function isDemoMode() { return $this->getConfig('demo_mode'); } /** * Retrieve the anonymous_contact config. */ public function anonymousContactCreationEnabled() { return $this->getConfig('anonymous_contact'); } public function demoMessage($message) { /** * Display a message. * * @param string $message * The message. */ public function demoMessage(string $message) { if ($this->isDemoMode()) { \Drupal::messenger()->addStatus("Demo Hubspot : $message"); } } /** * Get user terms. * * @return array * The term ids. */ public function getUserTids() { $tids = []; if (($hub_user = $this->getContactInfo()) && ($mapping = $this->getMapping()) && !empty($mapping) ) { $taxonomy = []; foreach ($mapping as $hub_voc => $map) { if (isset($hub_user->properties->{$hub_voc})) { foreach ($map['#terms'] as $hub_term_id => $taxonomy_term_id) { Loading @@ -321,7 +380,6 @@ class HubspotAPI { } } } foreach ($taxonomy as $tid => $vocab) { $tids[] = $tid; } Loading @@ -330,8 +388,17 @@ class HubspotAPI { return $tids; } public function getAnonymousContactNumber($update = false) { if ($update == true) { /** * Get the number of anonymous contact. * * @param bool $update * The update status. * * @return array|array[]|\Drupal\Component\Render\MarkupInterface|\Drupal\hubspot_integration\Services\unknown[]|int|mixed|string|null * The anonymous contact count. */ public function getAnonymousContactNumber(bool $update = FALSE) { if ($update) { $request = $this->request('contacts/v1/search/query', ['q' => $this->getAnonymousContactMailTemplate('*')]); if (!empty($request)) { $this->setConfig('anonymous_contacts_count', $request->total); Loading @@ -346,12 +413,22 @@ class HubspotAPI { } } public function getAnonymousContactMailTemplate($hub_cookie=NULL) { /** * Get the mail template for anonymous. * * @param string|null $hub_cookie * The hub cookie. * * @return array|array[]|\Drupal\Component\Render\MarkupInterface|\Drupal\hubspot_integration\Services\unknown[]|mixed|string|string[]|null * The template. */ public function getAnonymousContactMailTemplate(string $hub_cookie = NULL) { $template = $this->getConfig('anonymous_mail_template'); if (!empty($hub_cookie)) { $template = str_replace('[hub_cookie]', $hub_cookie, $template); } return $template; } } Loading
src/Services/HubspotAPI.php +153 −76 Original line number Diff line number Diff line Loading @@ -5,24 +5,35 @@ namespace Drupal\hubspot_integration\Services; use Drupal\Component\Utility\UrlHelper; use Drupal\Core\Database\Connection; use Symfony\Component\HttpFoundation\Session\Session; use Exception; use Drupal\Core\Config\ConfigFactory; use Drupal\taxonomy\Entity\Term; use Drupal\taxonomy\Entity\Vocabulary; /** * Hubspot API service. */ class HubspotAPI { /* * @var \Drupal\Core\Database\Connection $database /** * The database service. * * @var \Drupal\Core\Database\Connection */ protected $database; /* * @var \Symfony\Component\HttpFoundation\Session\Session $session /** * The session service. * * @var \Symfony\Component\HttpFoundation\Session\Session */ protected $session; /* * @var \Drupal\Core\Config\ConfigFactory $config_factory /** * The Config Factory service. * * @var \Drupal\Core\Config\ConfigFactory */ protected $config_factory; protected $configFactory; /** * Static cache for cookies. Loading @@ -33,14 +44,18 @@ class HubspotAPI { /** * Constructs a new HubspotAPI object. * * @param \Drupal\Core\Database\Connection $connection * The connection service. * @param \Symfony\Component\HttpFoundation\Session\Session $session * The session service. * @param \Drupal\Core\Config\ConfigFactory $config_factory * The config factory service;. */ public function __construct(Connection $connection, Session $session, ConfigFactory $config_factory) { $this->database = $connection; $this->session = $session; $this->config_factory = $config_factory; $this->configFactory = $config_factory; } /** Loading @@ -55,7 +70,6 @@ class HubspotAPI { public function getCookie($cookieName = 'hubspotutk') { if (!isset($this->cookies[$cookieName])) { $this->cookies[$cookieName] = \Drupal::request()->cookies->get($cookieName); // Ensure data in cookie is authorized / safe for hubspot_integration. if (($cookieName == 'hubspot_integration') && ($tids = explode('_', ltrim($this->cookies[$cookieName], 'hubspot_'))) Loading @@ -69,7 +83,6 @@ class HubspotAPI { } } } $tids = array_intersect($tids, $allowedValues); $this->cookies[$cookieName] = 'hubspot_' . implode('_', $tids); } Loading @@ -79,7 +92,7 @@ class HubspotAPI { } /** * Get current session * Get current session. */ public function getSession() { return $this->session; Loading @@ -93,10 +106,8 @@ class HubspotAPI { */ public function isContact() { $result = FALSE; if ($user = $this->getContactInfo()) { $property = 'is-contact'; if (isset($user->{$property})) { $result = $user->{$property}; } Loading @@ -106,12 +117,15 @@ class HubspotAPI { } /** * Get Husbspot values for the current user * Get Husbspot values for the current user. * * @param bool $forced_update * The forced update boolean. * * @param boolean $forced_update * @return NULL|mixed * @return null|mixed * Null. */ public function getContactInfo($forced_update=false) { public function getContactInfo($forced_update = FALSE) { $user = NULL; if (!$this->isDemoMode() && !$forced_update && $this->session->get('hubspot_integration.user')) { $user = $this->session->get('hubspot_integration.user'); Loading @@ -126,108 +140,130 @@ class HubspotAPI { } /** * Get the config name for the hubspot integration module settings * Get the config name for the hubspot integration module settings. * * @param unknown $name * @return mixed|NULL|array|\Drupal\Component\Render\MarkupInterface|string|unknown[]|array[] * @param string $name * The name. * * @return mixed|null|array|\Drupal\Component\Render\MarkupInterface|string|unknown[]|array[] * The value. */ public function getConfig($name) { return $this->config_factory->get('hubspot_integration.settings')->get($name); public function getConfig(string $name) { return $this->configFactory->get('hubspot_integration.settings')->get($name); } /** * Set the config name for the hubspot integration module settings * Set te config name for the hubspot integration module settings. * * @param string $name * The name. * @param string $value * The value. * * @param unknown $name * @return mixed|NULL|array|\Drupal\Component\Render\MarkupInterface|string|unknown[]|array[] * @return \Drupal\Core\Config\Config|\Drupal\Core\Config\ImmutableConfig * The config. */ public function setConfig($name, $value) { return $this->config_factory->getEditable('hubspot_integration.settings')->set($name, $value)->save(); public function setConfig(string $name, string $value) { return $this->configFactory->getEditable('hubspot_integration.settings')->set($name, $value)->save(); } /** * Get the list of the possible contact properties and their definitions * Get the list of the possible contact properties and their definitions. * * @return mixed * The contact properties. */ public function getContactProperties() { return $this->request('properties/v1/contacts/properties'); } /** * Function to make calls on hubspot * Function to make calls on hubspot. * * @param unknown $api * @return mixed * @param string $api * The API. * @param array $options * The options. * @param string $type * The type. * @param array $datas * Tha datas. * * @return mixed|null * The response. */ public function request($api, $options = [], $type='GET', $datas = []) { public function request(string $api, array $options = [], string $type = 'GET', array $datas = []) { $token_private_app = $this->getConfig('token_private_app'); $headers = [ 'Content-Type' => 'application/json', 'Authorization' => 'Bearer ' . $token_private_app, ]; $ret = NULL; if (!empty($token_private_app)) { $hub_url = 'https://api.hubapi.com/'; $query_str = UrlHelper::buildQuery($options); $url = $hub_url . $api . '?' . $query_str; try { switch ($type) { case 'GET': $request = \Drupal::httpClient()->get($url, ['headers' => $headers]); break; case 'POST': $request = \Drupal::httpClient()->post($url, ['json' => $datas, 'headers' => $headers], $options); $request = \Drupal::httpClient()->post( $url, ['json' => $datas, 'headers' => $headers], ); break; } $ret = json_decode($request->getBody()); } catch (Exception $e) { catch (\Exception $e) { \Drupal::logger('hubspot_integration')->error('Error : ' . $e->getCode() . ' : ' . $e->getMessage()); } } return $ret; } /** * Get the mapping done between Drupal and Hubspot * Get the mapping done between Drupal and Hubspot. * * @return mixed * The config. */ public function getMapping() { return $this->getConfig('mapping'); } /** * Get the sort configuration * Get the sort configuration. * * @return mixed * The config. */ public function getSort($tids = array()) { public function getSort($tids = []) { return $this->getConfig('sort'); } /** * Get the sort configuration * Get the sort configuration. * * @param array $tids * The tids. * * @return mixed * @return array * The sorted tids. */ public function getTidsSort($tids) { public function getTidsSort(array $tids) { $sort = $this->getConfig('sort'); $tids_sort = array(); if (!empty($tids[0])) { // compile the sort in order to get the min values for the tids $tids_sort = []; // Compile the sort in order to get the min values for the tids. if (!empty($tids[0])) { foreach ($tids as $tid) { /** @var \Drupal\taxonomy\TermInterface $term */ $term = Term::load($tid); $vid = $term->bundle(); foreach ($sort[$vid][$tid] as $term_weight_id => $term_weight) { if (!isset($tids_sort[$term_weight_id])) { $tids_sort[$term_weight_id] = $sort[$vid][$tid][$term_weight_id]; Loading @@ -243,23 +279,29 @@ class HubspotAPI { } /** * Utility function to transform a text as a machine name * Utility function to transform a text as a machine name. * * @param string $string * The string. * * @param unknown $string * @return string * The name. */ public static function machineName($string) { public static function machineName(string $string) { return preg_replace('@[^a-z0-9-]+@', '-', strtolower($string)); } /** * Utility function to check a vocabulary is mapped with hubspot * Utility function to check a vocabulary is mapped with hubspot. * * @param string $vocabulary * @return boolean * The vocabulary. * * @return bool * The boolean. */ public function isVocabularyMapped($vocabulary) { $mapping = $this->getMapping(); if (!empty($mapping)) { foreach ($mapping as $mapping) { if (isset($mapping['#vocabulary']) && $mapping['#vocabulary'] === $vocabulary) { Loading @@ -268,17 +310,18 @@ class HubspotAPI { } } return false; return FALSE; } /** * Utility function to get mapped vocabularies * Utility function to get mapped vocabularies. * * @return array * The list of vocabularies. */ function getMappedVocabularies() { public function getMappedVocabularies() { $vocabularies = Vocabulary::loadMultiple(); $vocabulariesList = []; foreach ($vocabularies as $vid => $vocablary) { if ($this->isVocabularyMapped($vid)) { $vocabulariesList[$vid] = $vocablary->get('name'); Loading @@ -288,29 +331,45 @@ class HubspotAPI { return $vocabulariesList; } /** * Retrieve the demo mode config. */ public function isDemoMode() { return $this->getConfig('demo_mode'); } /** * Retrieve the anonymous_contact config. */ public function anonymousContactCreationEnabled() { return $this->getConfig('anonymous_contact'); } public function demoMessage($message) { /** * Display a message. * * @param string $message * The message. */ public function demoMessage(string $message) { if ($this->isDemoMode()) { \Drupal::messenger()->addStatus("Demo Hubspot : $message"); } } /** * Get user terms. * * @return array * The term ids. */ public function getUserTids() { $tids = []; if (($hub_user = $this->getContactInfo()) && ($mapping = $this->getMapping()) && !empty($mapping) ) { $taxonomy = []; foreach ($mapping as $hub_voc => $map) { if (isset($hub_user->properties->{$hub_voc})) { foreach ($map['#terms'] as $hub_term_id => $taxonomy_term_id) { Loading @@ -321,7 +380,6 @@ class HubspotAPI { } } } foreach ($taxonomy as $tid => $vocab) { $tids[] = $tid; } Loading @@ -330,8 +388,17 @@ class HubspotAPI { return $tids; } public function getAnonymousContactNumber($update = false) { if ($update == true) { /** * Get the number of anonymous contact. * * @param bool $update * The update status. * * @return array|array[]|\Drupal\Component\Render\MarkupInterface|\Drupal\hubspot_integration\Services\unknown[]|int|mixed|string|null * The anonymous contact count. */ public function getAnonymousContactNumber(bool $update = FALSE) { if ($update) { $request = $this->request('contacts/v1/search/query', ['q' => $this->getAnonymousContactMailTemplate('*')]); if (!empty($request)) { $this->setConfig('anonymous_contacts_count', $request->total); Loading @@ -346,12 +413,22 @@ class HubspotAPI { } } public function getAnonymousContactMailTemplate($hub_cookie=NULL) { /** * Get the mail template for anonymous. * * @param string|null $hub_cookie * The hub cookie. * * @return array|array[]|\Drupal\Component\Render\MarkupInterface|\Drupal\hubspot_integration\Services\unknown[]|mixed|string|string[]|null * The template. */ public function getAnonymousContactMailTemplate(string $hub_cookie = NULL) { $template = $this->getConfig('anonymous_mail_template'); if (!empty($hub_cookie)) { $template = str_replace('[hub_cookie]', $hub_cookie, $template); } return $template; } }