[ Index ] |
PHP Cross Reference of Phabricator |
[Summary view] [Print] [Text view]
1 <?php 2 3 final class PhabricatorSMSImplementationTwilioAdapter 4 extends PhabricatorSMSImplementationAdapter { 5 6 public function getProviderShortName() { 7 return 'twilio'; 8 } 9 10 /** 11 * @phutil-external-symbol class Services_Twilio 12 */ 13 private function buildClient() { 14 $root = dirname(phutil_get_library_root('phabricator')); 15 require_once $root.'/externals/twilio-php/Services/Twilio.php'; 16 $account_sid = PhabricatorEnv::getEnvConfig('twilio.account-sid'); 17 $auth_token = PhabricatorEnv::getEnvConfig('twilio.auth-token'); 18 return new Services_Twilio($account_sid, $auth_token); 19 } 20 21 /** 22 * @phutil-external-symbol class Services_Twilio_RestException 23 */ 24 public function send() { 25 $client = $this->buildClient(); 26 27 try { 28 $message = $client->account->sms_messages->create( 29 $this->formatNumberForSMS($this->getFrom()), 30 $this->formatNumberForSMS($this->getTo()), 31 $this->getBody(), 32 array()); 33 } catch (Services_Twilio_RestException $e) { 34 $message = sprintf( 35 'HTTP Code %d: %s', 36 $e->getStatus(), 37 $e->getMessage()); 38 39 // Twilio tries to provide a link to more specific details if they can. 40 if ($e->getInfo()) { 41 $message .= sprintf(' For more information, see %s.', $e->getInfo()); 42 } 43 throw new PhabricatorWorkerPermanentFailureException($message); 44 } 45 return $message; 46 } 47 48 public function getSMSDataFromResult($result) { 49 return array($result->sid, $this->getSMSStatus($result->status)); 50 } 51 52 public function pollSMSSentStatus(PhabricatorSMS $sms) { 53 $client = $this->buildClient(); 54 $message = $client->account->messages->get($sms->getProviderSMSID()); 55 56 return $this->getSMSStatus($message->status); 57 } 58 59 /** 60 * See https://www.twilio.com/docs/api/rest/sms#sms-status-values. 61 */ 62 private function getSMSStatus($twilio_status) { 63 switch ($twilio_status) { 64 case 'failed': 65 $status = PhabricatorSMS::STATUS_FAILED; 66 break; 67 case 'sent': 68 $status = PhabricatorSMS::STATUS_SENT; 69 break; 70 case 'sending': 71 case 'queued': 72 default: 73 $status = PhabricatorSMS::STATUS_SENT_UNCONFIRMED; 74 break; 75 } 76 return $status; 77 } 78 79 /** 80 * We expect numbers to be plainly entered - i.e. the preg_replace here 81 * should do nothing - but try hard to format anyway. 82 * 83 * Twilio uses E164 format, e.g. +15551234567 84 */ 85 private function formatNumberForSMS($number) { 86 $number = preg_replace('/[^0-9]/', '', $number); 87 $first_char = substr($number, 0, 1); 88 switch ($first_char) { 89 case '1': 90 $prepend = '+'; 91 break; 92 default: 93 $prepend = '+1'; 94 break; 95 } 96 return $prepend.$number; 97 } 98 99 }
title
Description
Body
title
Description
Body
title
Description
Body
title
Body
Generated: Sun Nov 30 09:20:46 2014 | Cross-referenced by PHPXref 0.7.1 |