From f849c812dbd348ef27de3c388606822c0246036c Mon Sep 17 00:00:00 2001 From: Alexander Kamp Date: Tue, 9 Jun 2020 11:57:37 +0200 Subject: [PATCH 1/2] Example helpers code inspection Stats: updated type/exception hints, typos, imports Example mail, method helloEmail: fixed Personalization addTo assignment which has address null (I suppose this was not the intention) Additional notes for examples: - stats: fixed pointing to non-existent class - mail: removed namespace (not needed here), wrap sendKitchenSink example in try-catch, prevent real send if getting null request_body Signed-off-by: Alexander Kamp --- examples/helpers/mail/example.php | 318 +++++++++++++++-------------- examples/helpers/stats/example.php | 9 +- lib/stats/Stats.php | 65 +++--- 3 files changed, 205 insertions(+), 187 deletions(-) diff --git a/examples/helpers/mail/example.php b/examples/helpers/mail/example.php index 9746793ee..0cb481b56 100644 --- a/examples/helpers/mail/example.php +++ b/examples/helpers/mail/example.php @@ -1,8 +1,7 @@ /vendor/autoload.php'; // comment out the above line if not using Composer // require("./sendgrid-php.php"); // If not using Composer, uncomment the above line @@ -44,10 +43,10 @@ function helloEmail() $mail = new Mail($from, $to, $subject, $content); $personalization = new Personalization(); - $personalization->addTo(new To(null, "test2@example.com")); + $personalization->addTo(new To("test2@example.com")); $mail->addPersonalization($personalization); - //echo json_encode($mail, JSON_PRETTY_PRINT), "\n"; + // echo json_encode($mail, JSON_PRETTY_PRINT), "\n"; return $mail; } catch (\Exception $e) { echo $e->getMessage(); @@ -58,150 +57,156 @@ function helloEmail() function kitchenSink() { - $from = new From("test@example.com", "Twilio SendGrid"); - $subject = "Hello World from the Twilio SendGrid PHP Library"; - $to = new To("test1@example.com", "Example User"); - $content = new Content("text/plain", "some text here"); - - $mail = new Mail($from, $to, $subject, $content); - - $personalization0 = new Personalization(); - $personalization0->addTo(new To("test2@example.com", "Example User")); - $personalization0->addCc(new Cc("test3@example.com", "Example User")); - $personalization0->addCc(new Cc("test4@example.com", "Example User")); - $personalization0->addBcc(new Bcc("test5@example.com", "Example User")); - $personalization0->addBcc(new Bcc("test6@example.com", "Example User")); - $personalization0->setSubject(new Subject("Hello World from the Twilio SendGrid PHP Library")); - $personalization0->addHeader(new Header("X-Test", "test")); - $personalization0->addHeader(new Header("X-Mock", "true")); - $personalization0->addSubstitution("%name%", "Example User"); - $personalization0->addSubstitution("%city%", "Denver"); - $personalization0->addSubstitution("%sec1%", "%section1%"); - $personalization0->addCustomArg(new CustomArg("user_id", "343")); - $personalization0->addCustomArg(new CustomArg("type", "marketing")); - $personalization0->setSendAt(new SendAt(1443636843)); - $mail->addPersonalization($personalization0); - - $personalization1 = new Personalization(); - $personalization1->addTo(new To("test7@example.com", "Example User")); - $personalization1->addTo(new To("test8@example.com", "Example User")); - $personalization1->addCc(new Cc("test9@example.com", "Example User")); - $personalization1->addCc(new Cc("test10@example.com", "Example User")); - $personalization1->addBcc(new Bcc("test11@example.com", "Example User")); - $personalization1->addBcc(new Bcc("test12@example.com", "Example User")); - $personalization1->setSubject(new Subject("Hello World from the Twilio SendGrid PHP Library")); - $personalization1->addHeader(new Header("X-Test", "test")); - $personalization1->addHeader(new Header("X-Mock", "true")); - $personalization1->addSubstitution("%name%", "Example User"); - $personalization1->addSubstitution("%city%", "Denver"); - $personalization1->addSubstitution("%sec2%", "%section2%"); - $personalization1->addCustomArg(new CustomArg("user_id", "343")); - $personalization1->addCustomArg(new CustomArg("type", "marketing")); - $personalization1->setSendAt(new SendAt(1443636843)); - $mail->addPersonalization($personalization1); - - //Examples of adding personalization by specifying personalization indexes - $mail->addCc("test13@example.com", "Example User", null, 0); - $mail->addBcc("test14@example.com", "Example User", null, 1); - - $content = new Content("text/html", "some text here"); - $mail->addContent($content); - - $attachment = new Attachment(); - $attachment->setContent("TG9yZW0gaXBzdW0gZG9sb3Igc2l0IGFtZXQsIGNvbnNlY3RldHVyIGFkaXBpc2NpbmcgZWxpdC4gQ3JhcyBwdW12"); - $attachment->setType("application/pdf"); - $attachment->setFilename("balance_001.pdf"); - $attachment->setDisposition("attachment"); - $attachment->setContentId("Balance Sheet"); - $mail->addAttachment($attachment); - - $attachment2 = new Attachment(); - $attachment2->setContent("BwdW"); - $attachment2->setType("image/png"); - $attachment2->setFilename("banner.png"); - $attachment2->setDisposition("inline"); - $attachment2->setContentId("Banner"); - $mail->addAttachment($attachment2); - - $mail->setTemplateId("439b6d66-4408-4ead-83de-5c83c2ee313a"); - - # This must be a valid [batch ID](https://sendgrid.com/docs/API_Reference/SMTP_API/scheduling_parameters.html) to work - # $mail->setBatchID("sendgrid_batch_id"); - - $mail->addSection("%section1%", "Substitution Text for Section 1"); - $mail->addSection("%section2%", "Substitution Text for Section 2"); - - $mail->addHeader("X-Test1", "1"); - $mail->addHeader("X-Test2", "2"); - - $mail->addCategory("May"); - $mail->addCategory("2016"); - - $mail->addCustomArg("campaign", "welcome"); - $mail->addCustomArg("weekday", "morning"); - - $mail->setSendAt(1443636842); - - $asm = new ASM(); - $asm->setGroupId(99); - $asm->setGroupsToDisplay([4,5,6,7,8]); - $mail->setASM($asm); - - $mail->setIpPoolName("23"); - - $mail_settings = new MailSettings(); - $bcc_settings = new BccSettings(); - $bcc_settings->setEnable(true); - $bcc_settings->setEmail("test@example.com"); - $mail_settings->setBccSettings($bcc_settings); - $sandbox_mode = new SandBoxMode(); - $sandbox_mode->setEnable(true); - $mail_settings->setSandboxMode($sandbox_mode); - $bypass_list_management = new BypassListManagement(); - $bypass_list_management->setEnable(true); - $mail_settings->setBypassListManagement($bypass_list_management); - $footer = new Footer(); - $footer->setEnable(true); - $footer->setText("Footer Text"); - $footer->setHtml("Footer Text"); - $mail_settings->setFooter($footer); - $spam_check = new SpamCheck(); - $spam_check->setEnable(true); - $spam_check->setThreshold(1); - $spam_check->setPostToUrl("https://spamcatcher.sendgrid.com"); - $mail_settings->setSpamCheck($spam_check); - $mail->setMailSettings($mail_settings); - - $tracking_settings = new TrackingSettings(); - $click_tracking = new ClickTracking(); - $click_tracking->setEnable(true); - $click_tracking->setEnableText(true); - $tracking_settings->setClickTracking($click_tracking); - $open_tracking = new OpenTracking(); - $open_tracking->setEnable(true); - $open_tracking->setSubstitutionTag("Optional tag to replace with the open image in the body of the message"); - $tracking_settings->setOpenTracking($open_tracking); - $subscription_tracking = new SubscriptionTracking(); - $subscription_tracking->setEnable(true); - $subscription_tracking->setText("text to insert into the text/plain portion of the message"); - $subscription_tracking->setHtml("html to insert into the text/html portion of the message"); - $subscription_tracking->setSubstitutionTag("Optional tag to replace with the open image in the body of the message"); - $tracking_settings->setSubscriptionTracking($subscription_tracking); - $ganalytics = new Ganalytics(); - $ganalytics->setEnable(true); - $ganalytics->setCampaignSource("some source"); - $ganalytics->setCampaignTerm("some term"); - $ganalytics->setCampaignContent("some content"); - $ganalytics->setCampaignName("some name"); - $ganalytics->setCampaignMedium("some medium"); - $tracking_settings->setGanalytics($ganalytics); - $mail->setTrackingSettings($tracking_settings); - - $reply_to = new ReplyTo("test@example.com", "Optional Name"); - $mail->setReplyTo($reply_to); - - //echo json_encode($mail, JSON_PRETTY_PRINT), "\n"; - return $mail; + try { + $from = new From("test@example.com", "Twilio SendGrid"); + $subject = "Hello World from the Twilio SendGrid PHP Library"; + $to = new To("test1@example.com", "Example User"); + $content = new Content("text/plain", "some text here"); + + $mail = new Mail($from, $to, $subject, $content); + + $personalization0 = new Personalization(); + $personalization0->addTo(new To("test2@example.com", "Example User")); + $personalization0->addCc(new Cc("test3@example.com", "Example User")); + $personalization0->addCc(new Cc("test4@example.com", "Example User")); + $personalization0->addBcc(new Bcc("test5@example.com", "Example User")); + $personalization0->addBcc(new Bcc("test6@example.com", "Example User")); + $personalization0->setSubject(new Subject("Hello World from the Twilio SendGrid PHP Library")); + $personalization0->addHeader(new Header("X-Test", "test")); + $personalization0->addHeader(new Header("X-Mock", "true")); + $personalization0->addSubstitution("%name%", "Example User"); + $personalization0->addSubstitution("%city%", "Denver"); + $personalization0->addSubstitution("%sec1%", "%section1%"); + $personalization0->addCustomArg(new CustomArg("user_id", "343")); + $personalization0->addCustomArg(new CustomArg("type", "marketing")); + $personalization0->setSendAt(new SendAt(1443636843)); + $mail->addPersonalization($personalization0); + + $personalization1 = new Personalization(); + $personalization1->addTo(new To("test7@example.com", "Example User")); + $personalization1->addTo(new To("test8@example.com", "Example User")); + $personalization1->addCc(new Cc("test9@example.com", "Example User")); + $personalization1->addCc(new Cc("test10@example.com", "Example User")); + $personalization1->addBcc(new Bcc("test11@example.com", "Example User")); + $personalization1->addBcc(new Bcc("test12@example.com", "Example User")); + $personalization1->setSubject(new Subject("Hello World from the Twilio SendGrid PHP Library")); + $personalization1->addHeader(new Header("X-Test", "test")); + $personalization1->addHeader(new Header("X-Mock", "true")); + $personalization1->addSubstitution("%name%", "Example User"); + $personalization1->addSubstitution("%city%", "Denver"); + $personalization1->addSubstitution("%sec2%", "%section2%"); + $personalization1->addCustomArg(new CustomArg("user_id", "343")); + $personalization1->addCustomArg(new CustomArg("type", "marketing")); + $personalization1->setSendAt(new SendAt(1443636843)); + $mail->addPersonalization($personalization1); + + // Examples of adding personalization by specifying personalization indexes + $mail->addCc("test13@example.com", "Example User", null, 0); + $mail->addBcc("test14@example.com", "Example User", null, 1); + + $content = new Content("text/html", "some text here"); + $mail->addContent($content); + + $attachment = new Attachment(); + $attachment->setContent("TG9yZW0gaXBzdW0gZG9sb3Igc2l0IGFtZXQsIGNvbnNlY3RldHVyIGFkaXBpc2NpbmcgZWxpdC4gQ3JhcyBwdW12"); + $attachment->setType("application/pdf"); + $attachment->setFilename("balance_001.pdf"); + $attachment->setDisposition("attachment"); + $attachment->setContentId("Balance Sheet"); + $mail->addAttachment($attachment); + + $attachment2 = new Attachment(); + $attachment2->setContent("BwdW"); + $attachment2->setType("image/png"); + $attachment2->setFilename("banner.png"); + $attachment2->setDisposition("inline"); + $attachment2->setContentId("Banner"); + $mail->addAttachment($attachment2); + + $mail->setTemplateId("439b6d66-4408-4ead-83de-5c83c2ee313a"); + + # This must be a valid [batch ID](https://sendgrid.com/docs/API_Reference/SMTP_API/scheduling_parameters.html) to work + # $mail->setBatchID("sendgrid_batch_id"); + + $mail->addSection("%section1%", "Substitution Text for Section 1"); + $mail->addSection("%section2%", "Substitution Text for Section 2"); + + $mail->addHeader("X-Test1", "1"); + $mail->addHeader("X-Test2", "2"); + + $mail->addCategory("May"); + $mail->addCategory("2016"); + + $mail->addCustomArg("campaign", "welcome"); + $mail->addCustomArg("weekday", "morning"); + + $mail->setSendAt(1443636842); + + $asm = new ASM(); + $asm->setGroupId(99); + $asm->setGroupsToDisplay([4,5,6,7,8]); + $mail->setASM($asm); + + $mail->setIpPoolName("23"); + + $mail_settings = new MailSettings(); + $bcc_settings = new BccSettings(); + $bcc_settings->setEnable(true); + $bcc_settings->setEmail("test@example.com"); + $mail_settings->setBccSettings($bcc_settings); + $sandbox_mode = new SandBoxMode(); + $sandbox_mode->setEnable(true); + $mail_settings->setSandboxMode($sandbox_mode); + $bypass_list_management = new BypassListManagement(); + $bypass_list_management->setEnable(true); + $mail_settings->setBypassListManagement($bypass_list_management); + $footer = new Footer(); + $footer->setEnable(true); + $footer->setText("Footer Text"); + $footer->setHtml("Footer Text"); + $mail_settings->setFooter($footer); + $spam_check = new SpamCheck(); + $spam_check->setEnable(true); + $spam_check->setThreshold(1); + $spam_check->setPostToUrl("https://spamcatcher.sendgrid.com"); + $mail_settings->setSpamCheck($spam_check); + $mail->setMailSettings($mail_settings); + + $tracking_settings = new TrackingSettings(); + $click_tracking = new ClickTracking(); + $click_tracking->setEnable(true); + $click_tracking->setEnableText(true); + $tracking_settings->setClickTracking($click_tracking); + $open_tracking = new OpenTracking(); + $open_tracking->setEnable(true); + $open_tracking->setSubstitutionTag("Optional tag to replace with the open image in the body of the message"); + $tracking_settings->setOpenTracking($open_tracking); + $subscription_tracking = new SubscriptionTracking(); + $subscription_tracking->setEnable(true); + $subscription_tracking->setText("text to insert into the text/plain portion of the message"); + $subscription_tracking->setHtml("html to insert into the text/html portion of the message"); + $subscription_tracking->setSubstitutionTag("Optional tag to replace with the open image in the body of the message"); + $tracking_settings->setSubscriptionTracking($subscription_tracking); + $ganalytics = new Ganalytics(); + $ganalytics->setEnable(true); + $ganalytics->setCampaignSource("some source"); + $ganalytics->setCampaignTerm("some term"); + $ganalytics->setCampaignContent("some content"); + $ganalytics->setCampaignName("some name"); + $ganalytics->setCampaignMedium("some medium"); + $tracking_settings->setGanalytics($ganalytics); + $mail->setTrackingSettings($tracking_settings); + + $reply_to = new ReplyTo("test@example.com", "Optional Name"); + $mail->setReplyTo($reply_to); + + //echo json_encode($mail, JSON_PRETTY_PRINT), "\n"; + return $mail; + } catch (\Exception $e) { + echo 'Caught exception: ', $e->getMessage(), "\n"; + } + + return null; } function sendHelloEmail() @@ -211,12 +216,17 @@ function sendHelloEmail() $request_body = helloEmail(); + if (!($request_body instanceof Mail)) { + echo 'Invalid request_body to send HelloEmail', "\n"; + return; + } + try { $response = $sg->client->mail()->send()->post($request_body); print $response->statusCode() . "\n"; print_r($response->headers()); print $response->body() . "\n"; - } catch (Exception $e) { + } catch (\Exception $e) { echo 'Caught exception: ', $e->getMessage(), "\n"; } } @@ -228,18 +238,20 @@ function sendKitchenSink() $request_body = kitchenSink(); + if (!($request_body instanceof Mail)) { + echo 'Invalid request_body to send KitchenSink', "\n"; + return; + } + try { $response = $sg->client->mail()->send()->post($request_body); print $response->statusCode() . "\n"; print_r($response->headers()); print $response->body() . "\n"; - } catch (Exception $e) { + } catch (\Exception $e) { echo 'Caught exception: ', $e->getMessage(), "\n"; } } sendHelloEmail(); // this will actually send an email sendKitchenSink(); // this will only send an email if you set SandBox Mode to false -?> - - diff --git a/examples/helpers/stats/example.php b/examples/helpers/stats/example.php index 8f197d941..7886411ff 100644 --- a/examples/helpers/stats/example.php +++ b/examples/helpers/stats/example.php @@ -1,16 +1,19 @@ /vendor/autoload.php'; +// comment out the above line if not using Composer +// require("./sendgrid-php.php"); +// If not using Composer, uncomment the above line $apiKey = getenv('SENDGRID_API_KEY'); $sg = new \SendGrid($apiKey); -$stats = new \SendGrid\Stats('2017-10-18'); +// Provide date in YYYY-MM-DD format +$stats = new \SendGrid\Stats\Stats('2017-10-18'); //$response = $sg->client->categories()->post(['category' => 'cat2']); //$response = $sg->client->categories()->get(null, $query_params); - $globalResponse = $sg->client->stats()->get(null, $stats->getGlobal()); $categoryResponse = $sg->client->categories()->stats()->get(null, $stats->getCategory(['category1', 'category2'])); diff --git a/lib/stats/Stats.php b/lib/stats/Stats.php index fcc537c17..40118013a 100644 --- a/lib/stats/Stats.php +++ b/lib/stats/Stats.php @@ -4,6 +4,9 @@ */ namespace SendGrid\Stats; +use DateTime; +use Exception; + /** * This class is used to retrieve stats from a /mail/send API call * @@ -11,27 +14,30 @@ */ class Stats { + /** @var string Expected date format */ const DATE_FORMAT = 'Y-m-d'; + /** @var string[] Available sort options */ const OPTIONS_SORT_DIRECTION = ['asc', 'desc']; + /** @var string[] Available aggregate options */ const OPTIONS_AGGREGATED_BY = ['day', 'week', 'month']; - // @var string + /** @var string Starting date */ private $startDate; - // @var string + /** @var string|null End date (optional) */ private $endDate; - // @var string + /** @var string|null Desired aggregate option (optional) */ private $aggregatedBy; - /** - * Stats constructor - * - * @param string $startDate YYYYMMDD - * @param string $endDate YYYYMMDD - * @param string $aggregatedBy day|week|month - * @throws \Exception - */ + /** + * Stats constructor + * + * @param string $startDate YYYY-MM-DD + * @param string $endDate YYYY-MM-DD + * @param string $aggregatedBy day|week|month + * @throws Exception + */ public function __construct($startDate, $endDate = null, $aggregatedBy = null) { $this->validateDateFormat($startDate); @@ -71,7 +77,7 @@ public function getGlobal() * @param array $categories * * @return array - * @throws \Exception + * @throws Exception */ public function getCategory($categories) { @@ -88,7 +94,7 @@ public function getCategory($categories) * @param array $subusers Subuser accounts * * @return array - * @throws \Exception + * @throws Exception */ public function getSubuser($subusers) { @@ -109,19 +115,20 @@ public function getSubuser($subusers) * requests|spam_report_drops| * spam_reports|unique_clicks| * unique_opens|unsubscribe_drops| - * unsubsribes + * unsubscribes * @param string $sortByDirection asc|desc * @param integer $limit The number of results to return * @param integer $offset The point in the list to begin * retrieving results * * @return array - * @throws \Exception + * @throws Exception */ public function getSum( $sortByMetric = 'delivered', $sortByDirection = 'desc', - $limit = 5, $offset = 0 + $limit = 5, + $offset = 0 ) { $this->validateOptions( 'sortByDirection', @@ -148,14 +155,14 @@ public function getSum( * requests|spam_report_drops| * spam_reports|unique_clicks| * unique_opens|unsubscribe_drops| - * unsubsribes + * unsubscribes * @param string $sortByDirection asc|desc * @param integer $limit The number of results to return * @param integer $offset The point in the list to begin * retrieving results * * @return array - * @throws \Exception + * @throws Exception */ public function getSubuserMonthly( $subuser = null, @@ -186,13 +193,12 @@ public function getSubuserMonthly( * * @param string $date YYYY-MM-DD * - * @return null - * @throws \Exception + * @throws Exception */ protected function validateDateFormat($date) { - if (false === \DateTime::createFromFormat(self::DATE_FORMAT, $date)) { - throw new \Exception('Date must be in the YYYY-MM-DD format.'); + if (false === DateTime::createFromFormat(self::DATE_FORMAT, $date)) { + throw new Exception('Date must be in the YYYY-MM-DD format.'); } } @@ -203,13 +209,12 @@ protected function validateDateFormat($date) * @param string $value Value of option * @param array $options Array of options * - * @return null - * @throws \Exception + * @throws Exception */ protected function validateOptions($name, $value, $options) { if (!in_array($value, $options)) { - throw new \Exception( + throw new Exception( $name . ' must be one of: ' . implode(', ', $options) ); } @@ -221,13 +226,12 @@ protected function validateOptions($name, $value, $options) * @param string $name Name as a string * @param integer $value Value as an integer * - * @return null - * @throws \Exception + * @throws Exception */ protected function validateInteger($name, $value) { if (!is_integer($value)) { - throw new \Exception($name . ' must be an integer.'); + throw new Exception($name . ' must be an integer.'); } } @@ -237,13 +241,12 @@ protected function validateInteger($name, $value) * @param string $name Name as a string * @param array $value Value as an array of integers * - * @return null - * @throws \Exception + * @throws Exception */ protected function validateNumericArray($name, $value) { if (!is_array($value) || empty($value) || !$this->isNumeric($value)) { - throw new \Exception($name . ' must be a non-empty numeric array.'); + throw new Exception($name . ' must be a non-empty numeric array.'); } } From e3ccebd9a78515031bd2ac2e860957c0a5e75246 Mon Sep 17 00:00:00 2001 From: Alexander Kamp Date: Tue, 9 Jun 2020 12:34:45 +0200 Subject: [PATCH 2/2] Removed spaces (accidentally added) Signed-off-by: Alexander Kamp --- examples/helpers/mail/example.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/examples/helpers/mail/example.php b/examples/helpers/mail/example.php index 0cb481b56..f4cbdd54f 100644 --- a/examples/helpers/mail/example.php +++ b/examples/helpers/mail/example.php @@ -46,7 +46,7 @@ function helloEmail() $personalization->addTo(new To("test2@example.com")); $mail->addPersonalization($personalization); - // echo json_encode($mail, JSON_PRETTY_PRINT), "\n"; + //echo json_encode($mail, JSON_PRETTY_PRINT), "\n"; return $mail; } catch (\Exception $e) { echo $e->getMessage();