allow vendord
All checks were successful
Build, Push and Deploy / build-and-push (push) Successful in 3m3s
Gitea Actions Demo / Explore-Gitea-Actions (push) Successful in 16s
Build, Push and Deploy / deploy-staging (push) Successful in 32s
Build, Push and Deploy / deploy-production (push) Has been skipped
Build, Push and Deploy / cleanup (push) Successful in 1s

This commit is contained in:
2026-03-30 14:54:57 +07:00
parent 66aed7c4e8
commit b5e3a778ce
21316 changed files with 2777892 additions and 13 deletions

View File

@@ -0,0 +1,10 @@
contact_links:
- name: Twilio Support
url: https://twilio.com/help/contact
about: Get Support
- name: Stack Overflow
url: https://stackoverflow.com/questions/tagged/twilio-php+or+twilio+php
about: Ask questions on Stack Overflow
- name: Documentation
url: https://www.twilio.com/docs/libraries/reference/twilio-php
about: View Reference Documentation

View File

@@ -0,0 +1,21 @@
name: Lint PR
on:
pull_request_target:
types: [ opened, edited, synchronize, reopened ]
jobs:
validate:
name: Validate title
runs-on: ubuntu-latest
steps:
- uses: amannn/action-semantic-pull-request@v5
with:
types: |
chore
docs
fix
feat
misc
test
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}

View File

@@ -0,0 +1,128 @@
name: Test and Deploy
on:
push:
branches: [ '*' ]
tags: [ '*' ]
pull_request:
branches: [ main ]
schedule:
# Run automatically at 8AM PST Monday-Friday
- cron: '0 15 * * 1-5'
workflow_dispatch:
jobs:
test:
name: Test
runs-on: ubuntu-latest
timeout-minutes: 20
strategy:
matrix:
php: [ 7.2, 7.3, 7.4, 8.0, 8.1, 8.2, 8.3, 8.4 ]
dependencies:
- "lowest"
- "highest"
steps:
- name: Checkout twilio-php
uses: actions/checkout@v3
with:
fetch-depth: 0 # Shallow clones should be disabled for a better relevancy of analysis
- name: Setup PHP Action
uses: shivammathur/setup-php@2.15.0
with:
php-version: ${{ matrix.php }}
coverage: xdebug
id: php
- name: Composer webhook config
run: composer config -g github-oauth.github.com ${{ secrets.GITHUB_TOKEN }}
- name: Update Dependencies
if: matrix.dependencies == 'lowest'
run: composer update --prefer-lowest --prefer-stable -n
- name: Run Tests
run: make install test
- name: Fix code coverage paths
run: |
if [ -f "coverage.xml" ]; then
sed -i 's@'$GITHUB_WORKSPACE'@/github/workspace/@g' coverage.xml
fi
- name: Run Cluster Test
if: (!github.event.pull_request.head.repo.fork)
env:
TWILIO_ACCOUNT_SID: ${{ secrets.TWILIO_ACCOUNT_SID }}
TWILIO_API_KEY: ${{ secrets.TWILIO_CLUSTER_TEST_API_KEY}}
TWILIO_API_SECRET: ${{ secrets.TWILIO_CLUSTER_TEST_API_KEY_SECRET }}
TWILIO_FROM_NUMBER: ${{ secrets.TWILIO_FROM_NUMBER }}
TWILIO_TO_NUMBER: ${{ secrets.TWILIO_TO_NUMBER }}
TWILIO_ORGS_CLIENT_ID: ${{ secrets.TWILIO_ORGS_CLIENT_ID }}
TWILIO_ORGS_CLIENT_SECRET: ${{ secrets.TWILIO_ORGS_CLIENT_SECRET }}
TWILIO_ORG_SID: ${{ secrets.TWILIO_ORG_SID }}
TWILIO_CLIENT_ID: ${{ secrets.TWILIO_CLIENT_ID }}
TWILIO_CLIENT_SECRET: ${{ secrets.TWILIO_CLIENT_SECRET }}
TWILIO_MESSAGE_SID: ${{ secrets.TWILIO_MESSAGE_SID }}
run: make cluster-test
- name: Install SonarCloud scanner and run analysis
uses: SonarSource/sonarcloud-github-action@master
if: (github.event_name == 'pull_request' || github.ref_type == 'branch') && !github.event.pull_request.head.repo.fork && matrix.php == '8.1' && matrix.dependencies == 'highest'
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} # Needed to get PR information, if any
SONAR_TOKEN: ${{ secrets.SONAR_TOKEN }}
deploy:
name: Deploy
if: success() && github.ref_type == 'tag'
needs: [ test ]
runs-on: ubuntu-latest
steps:
- name: Checkout twilio-php
uses: actions/checkout@v3
with:
fetch-depth: 0
- name: Install dependencies
run: composer install
- name: Login to Docker Hub
uses: docker/login-action@v2
with:
username: ${{ secrets.DOCKER_USERNAME }}
password: ${{ secrets.DOCKER_AUTH_TOKEN }}
# The expression strips off the shortest match from the front of the string to yield just the tag name as the output
- name: Get tagged version
run: echo "GITHUB_TAG=${GITHUB_REF#refs/*/}" >> $GITHUB_ENV
- name: Create GitHub Release
uses: sendgrid/dx-automator/actions/release@main
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
- name: Build & Push docker image
run: make docker-build docker-push
- name: Submit metric to Datadog
uses: sendgrid/dx-automator/actions/datadog-release-metric@main
env:
DD_API_KEY: ${{ secrets.DATADOG_API_KEY }}
notify-on-failure:
name: Slack notify on failure
if: failure() && github.event_name != 'pull_request' && (github.ref == 'refs/heads/main' || github.ref_type == 'tag')
needs: [ test, deploy ]
runs-on: ubuntu-latest
steps:
- uses: rtCamp/action-slack-notify@v2
env:
SLACK_COLOR: failure
SLACK_ICON_EMOJI: ':github:'
SLACK_MESSAGE: ${{ format('Test *{0}*, Deploy *{1}*, {2}/{3}/actions/runs/{4}', needs.test.result, needs.deploy.result, github.server_url, github.repository, github.run_id) }}
SLACK_TITLE: Action Failure - ${{ github.repository }}
SLACK_USERNAME: GitHub Actions
SLACK_MSG_AUTHOR: twilio-dx
SLACK_FOOTER: Posted automatically using GitHub Actions
SLACK_WEBHOOK: ${{ secrets.SLACK_WEBHOOK }}
MSG_MINIMAL: true

View File

@@ -0,0 +1,8 @@
<?php
$config = new PhpCsFixer\Config();
$config->setRules(['nullable_type_declaration_for_default_null_value' => true,]);
return $config->setFinder(PhpCsFixer\Finder::create()->in(__DIR__.'/src'));

73
vendor/twilio/sdk/CODE_OF_CONDUCT.md vendored Normal file
View File

@@ -0,0 +1,73 @@
# Contributor Covenant Code of Conduct
## Our Pledge
In the interest of fostering an open and welcoming environment, we as
contributors and maintainers pledge to making participation in our project and
our community a harassment-free experience for everyone, regardless of age, body
size, disability, ethnicity, sex characteristics, gender identity and expression,
level of experience, education, socio-economic status, nationality, personal
appearance, race, religion, or sexual identity and orientation.
## Our Standards
Examples of behavior that contributes to creating a positive environment
include:
- Using welcoming and inclusive language
- Being respectful of differing viewpoints and experiences
- Gracefully accepting constructive criticism
- Focusing on what is best for the community
- Showing empathy towards other community members
Examples of unacceptable behavior by participants include:
- The use of sexualized language or imagery and unwelcome sexual attention or
advances
- Trolling, insulting/derogatory comments, and personal or political attacks
- Public or private harassment
- Publishing others' private information, such as a physical or electronic
address, without explicit permission
- Other conduct which could reasonably be considered inappropriate in a
professional setting
## Our Responsibilities
Project maintainers are responsible for clarifying the standards of acceptable
behavior and are expected to take appropriate and fair corrective action in
response to any instances of unacceptable behavior.
Project maintainers have the right and responsibility to remove, edit, or
reject comments, commits, code, wiki edits, issues, and other contributions
that are not aligned to this Code of Conduct, or to ban temporarily or
permanently any contributor for other behaviors that they deem inappropriate,
threatening, offensive, or harmful.
## Scope
This Code of Conduct applies both within project spaces and in public spaces
when an individual is representing the project or its community. Examples of
representing a project or community include using an official project e-mail
address, posting via an official social media account, or acting as an appointed
representative at an online or offline event. Representation of a project may be
further defined and clarified by project maintainers.
## Enforcement
Instances of abusive, harassing, or otherwise unacceptable behavior may be
reported by contacting the project team at open-source@twilio.com. All
complaints will be reviewed and investigated and will result in a response that
is deemed necessary and appropriate to the circumstances. The project team is
obligated to maintain confidentiality with regard to the reporter of an incident.
Further details of specific enforcement policies may be posted separately.
Project maintainers who do not follow or enforce the Code of Conduct in good
faith may face temporary or permanent repercussions as determined by other
members of the project's leadership.
## Attribution
This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4,
available at https://www.contributor-covenant.org/version/1/4/code-of-conduct.html
[homepage]: https://www.contributor-covenant.org

14
vendor/twilio/sdk/Dockerfile vendored Normal file
View File

@@ -0,0 +1,14 @@
FROM php:7.4
RUN apt-get update -y && apt-get install -y zip
RUN mkdir /twilio
WORKDIR /twilio
ENV PATH="vendor/bin:$PATH"
COPY src src
COPY tests tests
COPY composer* ./
COPY --from=composer:latest /usr/bin/composer /usr/local/bin/composer
RUN composer install --prefer-dist

16
vendor/twilio/sdk/Dockerfile-dev vendored Normal file
View File

@@ -0,0 +1,16 @@
ARG version
FROM php:$version
RUN curl --silent --show-error https://getcomposer.org/installer | php
RUN mv composer.phar /usr/local/bin/composer
RUN apt-get update -y && \
apt-get upgrade -y && \
apt-get dist-upgrade -y && \
apt-get -y autoremove && \
apt-get clean
RUN apt-get install -y zip unzip git
ENV COMPOSER_ALLOW_SUPERUSER=1
WORKDIR /twilio

View File

@@ -0,0 +1,31 @@
<!--
We appreciate the effort for this pull request but before that please make sure you read the contribution guidelines, then fill out the blanks below.
Please format the PR title appropriately based on the type of change:
<type>[!]: <description>
Where <type> is one of: docs, chore, feat, fix, test, misc.
Add a '!' after the type for breaking changes (e.g. feat!: new breaking feature).
**All third-party contributors acknowledge that any contributions they provide will be made under the same open-source license that the open-source project is provided under.**
Please enter each Issue number you are resolving in your PR after one of the following words [Fixes, Closes, Resolves]. This will auto-link these issues and close them when this PR is merged!
e.g.
Fixes #1
Closes #2
-->
# Fixes #
A short description of what this PR does.
### Checklist
- [x] I acknowledge that all my contributions will be made under the project's license
- [ ] I have made a material change to the repo (functionality, testing, spelling, grammar)
- [ ] I have read the [Contribution Guidelines](https://github.com/twilio/twilio-php/blob/main/CONTRIBUTING.md) and my PR follows them
- [ ] I have titled the PR appropriately
- [ ] I have updated my branch with the main branch
- [ ] I have added tests that prove my fix is effective or that my feature works
- [ ] I have added the necessary documentation about the functionality in the appropriate .md file
- [ ] I have added inline documentation to the code I modified
If you have questions, please file a [support ticket](https://twilio.com/help/contact), or create a GitHub Issue in this repository.

View File

@@ -0,0 +1,202 @@
# Custom HTTP Clients for the Twilio PHP Helper Library
If you are working with the Twilio PHP Helper Library and need to modify the HTTP requests that the library makes to the Twilio servers youre in the right place. The most common place you'll need to alter the HTTP request is to connect and authenticate with an enterprises proxy server. Well provide sample code that you can drop right into your app to handle this use case.
## Connect and authenticate with a proxy server
To connect and provide credentials to a proxy server between your app and Twilio, you need a way to modify the HTTP requests that the Twilio helper library makes to invoke the Twilio REST API.
In PHP, the Twilio helper library uses the [cURL](http://php.net/manual/en/book.curl.php) library under the hood to make HTTP requests. The Twilio Helper Library allows you to provide your own `HttpClient` for making API requests.
How do we apply this to a typical Twilio REST API example?
```php
<?php
$twilio = new Client($sid, $token);
$message = $twilio->messages
->create(
"+15558675310",
array(
'body' => "Hey there!",
'from' => "+15017122661"
)
);
```
Where does `HttpClient` get created and used?
Out of the box, the helper library is creating a default `RequestClient` for you, using the Twilio credentials you pass to the `init` method. However, theres nothing stopping you from creating your own `RequestClient`.
Once you have your own `RequestClient`, you can pass it to any Twilio REST API resource action you want. Heres an example of sending an SMS message with a custom client:
```php
<?php
// Update the path below to your autoload.php,
// see https://getcomposer.org/doc/01-basic-usage.md
require_once "./vendor/autoload.php";
require_once "./MyRequestClass.php";
$dotenv = new Dotenv\Dotenv(__DIR__);
$dotenv->load();
use Twilio\Rest\Client;
// Your Account Sid and Auth Token from twilio.com/console
$sid = getenv('ACCOUNT_SID');
$token = getenv('AUTH_TOKEN');
$proxy = getenv('PROXY');
$httpClient = new MyRequestClass($proxy);
$twilio = new Client($sid, $token, null, null, $httpClient);
$message = $twilio->messages
->create(
"+15558675310",
array(
'body' => "Hey there!",
'from' => "+15017122661"
)
);
print("Message SID: {$message->sid}");
```
## Call Twilio through a proxy server
Now that we understand how all the components fit together we can create our own `HttpClient` that can connect through a proxy server. To make this reusable, heres a class that you can use to create this `HttpClient` whenever you need one.
```php
<?php
use Twilio\Http\CurlClient;
use Twilio\Http\Response;
class MyRequestClass extends CurlClient
{
protected $http = null;
protected $proxy = null;
/**
* MyRequestClass constructor.
* @param $proxy Proxy Server
* @param $cainfo CA Info for the proxy
*/
public function __construct($proxy = null, $cainfo = null)
{
$this->proxy = $proxy;
$this->cainfo = $cainfo;
$this->http = new CurlClient();
}
public function request(
$method,
$url,
$params = array(), $data = array(), $headers = array(), $user = null, $password = null, $timeout = null): Response
{
// Here you can change the URL, headers and other request parameters
$options = $this->options(
$method,
$url,
$params,
$data,
$headers,
$user,
$password,
$timeout
);
$curl = curl_init($url);
curl_setopt_array($curl, $options);
if (!empty($this->proxy))
curl_setopt($curl, CURLOPT_PROXY, $this->proxy);
if (!empty($this->cainfo))
curl_setopt($curl, CURLOPT_CAINFO, $this->cainfo);
curl_setopt($curl, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_HEADER, true);
curl_setopt($curl, CURLOPT_HTTPPROXYTUNNEL, true);
$response = curl_exec($curl);
$statusCode = curl_getinfo($curl, CURLINFO_HTTP_CODE);
$headerSize = curl_getinfo($curl, CURLINFO_HEADER_SIZE);
$head = substr($response, 0, $headerSize);
$body = substr($response, $headerSize);
$responseHeaders = array();
$headerLines = preg_split("/\r?\n/", $head);
foreach ($headerLines as $line) {
if (!preg_match("/:/", $line))
continue;
list($key, $value) = explode(':', $line, 2);
$responseHeaders[trim($key)] = trim($value);
}
curl_close($curl);
if (isset($buffer) && is_resource($buffer)) {
fclose($buffer);
}
return new Response($statusCode, $body, $responseHeaders);
}
}
```
In this example, we are using some environment variables loaded at the program startup to retrieve various configuration settings:
- Your Twilio Account Sid and Auth Token ([found here, in the Twilio console](https://console.twilio.com))
- A proxy address in IP:Port form, e.g. `127.0.0.1:8888`
Place these setting in an `.env` file like so:
```env
ACCOUNT_SID=ACxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
AUTH_TOKEN= your_auth_token
PROXY=127.0.0.1:8888
```
Heres the full console program that loads the `.env` file and sends a text message to show everything fitting together.
```php
<?php
// Update the path below to your autoload.php,
// see https://getcomposer.org/doc/01-basic-usage.md
require_once "./vendor/autoload.php";
require_once "./MyRequestClass.php";
$dotenv = new Dotenv\Dotenv(__DIR__);
$dotenv->load();
use Twilio\Rest\Client;
// Your Account Sid and Auth Token from twilio.com/console
$sid = getenv('ACCOUNT_SID');
$token = getenv('AUTH_TOKEN');
$proxy = getenv('PROXY');
$httpClient = new MyRequestClass($proxy);
$twilio = new Client($sid, $token, null, null, $httpClient);
$message = $twilio->messages
->create(
"+15558675310",
array(
'body' => "Hey there!",
'from' => "+15017122661"
)
);
print("Message SID: {$message->sid}");
```
## What else can this technique be used for?
Now that you know how to inject your own httpClient into the Twilio API request pipeline, you could use this technique to add custom HTTP headers and authorization to the requests (perhaps as required by an upstream proxy server).
You could also implement your own httpClient to mock the Twilio API responses so your unit and integration tests can run without the need to make a connection to Twilio. In fact, theres already an example online showing [how to do exactly that with Node.js and Prism](https://www.twilio.com/docs/openapi/mock-api-generation-with-twilio-openapi-spec).
We cant wait to see what you build!

45
vendor/twilio/sdk/composer.json vendored Normal file
View File

@@ -0,0 +1,45 @@
{
"name": "twilio/sdk",
"type": "library",
"description": "A PHP wrapper for Twilio's API",
"keywords": ["twilio", "sms", "api"],
"homepage": "https://github.com/twilio/twilio-php",
"license": "MIT",
"authors": [
{
"name": "Twilio API Team",
"email": "api@twilio.com"
}
],
"require": {
"php": ">=7.1.0"
},
"require-dev": {
"guzzlehttp/guzzle": "^6.3 || ^7.0",
"phpunit/phpunit": ">=7.0 < 10",
"friendsofphp/php-cs-fixer": "^3.0"
},
"suggest": {
"guzzlehttp/guzzle": "An HTTP client to execute the API requests"
},
"autoload": {
"psr-4": {
"Twilio\\": "src/Twilio/"
}
},
"autoload-dev": {
"psr-4": {
"": "src/Twilio/",
"Twilio\\Tests\\": "tests/Twilio/"
}
},
"scripts": {
"php84-fix": [
"@putenv PHP_CS_FIXER_IGNORE_ENV=1",
"vendor/bin/php-cs-fixer -vvv fix --using-cache=no ."
]
},
"config": {
"lock": false
}
}

34
vendor/twilio/sdk/example/call.php vendored Normal file
View File

@@ -0,0 +1,34 @@
<?php
require(__DIR__.'/../src/Twilio/autoload.php');
use Twilio\Rest\Client;
$sid = getenv('TWILIO_ACCOUNT_SID');
$token = getenv('TWILIO_AUTH_TOKEN');
$client = new Client($sid, $token);
// The phone number, SIP address, Client identifier or SIM SID that received this call.
// Phone numbers are in [E.164 format](https://www.twilio.com/docs/glossary/what-e164) (e.g., +16175551212).
// SIP addresses are formatted as name@company.com.
// Client identifiers are formatted client:name.
// SIM SIDs are formatted as sim:sid
$to = "+XXXXXXXXXX";
// The phone number or client identifier to use as the caller id.
// If using a phone number, it must be a Twilio number or a Verified outgoing caller id for your account.
// If the "to" parameter is a phone number, "from" must also be a phone number.
$from = "+XXXXXXXXXX";
// Make a phone call
$call = $client->calls->create(
$to,
$from,
["url" => "https://twilio.com"]
);
print("Call made successfully with sid: ".$call->sid."\n\n");
// Get some calls
$callsList = $client->calls->read([],null,2);
foreach ($callsList as $call) {
print("Call {$call->sid}: {$call->duration} seconds\n");
}

View File

@@ -0,0 +1,29 @@
<?php
require(__DIR__.'/../src/Twilio/autoload.php');
use Twilio\Rest\Client;
$sid = getenv('TWILIO_ACCOUNT_SID');
$token = getenv('TWILIO_AUTH_TOKEN');
$client = new Client($sid, $token);
function buyNumber(): ?Twilio\Rest\Api\V2010\Account\IncomingPhoneNumberInstance{
// Look up some phone numbers
global $client;
// Specify the [ISO country code](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2) of the country
// from which to read phone numbers, eg: "US"
$numbers = $client->availablePhoneNumbers("XX")->local->read();
// Buy the first phone number
if(!empty($numbers)){
$local = $numbers[0];
return $client->incomingPhoneNumbers->create(["phoneNumber" => $local->phoneNumber]);
}
return null;
}
// Get a number
$number = buyNumber();
print("Twilio purchased phoneNumber: ".$number->phoneNumber."\n");

31
vendor/twilio/sdk/example/message.php vendored Normal file
View File

@@ -0,0 +1,31 @@
<?php
require(__DIR__.'/../src/Twilio/autoload.php');
use Twilio\Rest\Client;
$sid = getenv('TWILIO_ACCOUNT_SID');
$token = getenv('TWILIO_AUTH_TOKEN');
$client = new Client($sid, $token);
// Specify the phone numbers in [E.164 format](https://www.twilio.com/docs/glossary/what-e164) (e.g., +16175551212)
// This parameter determines the destination phone number for your SMS message. Format this number with a '+' and a country code
$phoneNumber = "+XXXXXXXXXX";
// This must be a Twilio phone number that you own, formatted with a '+' and country code
$twilioPurchasedNumber = "+XXXXXXXXXX";
// Send a text message
$message = $client->messages->create(
$phoneNumber,
[
'from' => $twilioPurchasedNumber,
'body' => "Hey Jenny! Good luck on the bar exam!"
]
);
print("Message sent successfully with sid = " . $message->sid ."\n\n");
// Print the last 10 messages
$messageList = $client->messages->read([],10);
foreach ($messageList as $msg) {
print("ID:: ". $msg->sid . " | " . "From:: " . $msg->from . " | " . "TO:: " . $msg->to . " | " . " Status:: " . $msg->status . " | " . " Body:: ". $msg->body ."\n");
}

View File

@@ -0,0 +1,54 @@
<?php
require(__DIR__.'/../src/Twilio/autoload.php');
use Twilio\Rest\Client;
use Twilio\Rest\PreviewMessaging\V1\MessageModels;
$sid = getenv('TWILIO_ACCOUNT_SID');
$token = getenv('TWILIO_AUTH_TOKEN');
$client = new Client($sid, $token);
// Specify the phone numbers in [E.164 format](https://www.twilio.com/docs/glossary/what-e164) (e.g., +16175551212)
// This parameter determines the destination phone number for your SMS message. Format this number with a '+' and a country code
$phoneNumber1 = "+XXXXXXXXXX";
$phoneNumber2 = "+XXXXXXXXXX";
// Create message object for the recipients
$message1 = MessageModels::createMessagingV1Message(
[
'to' => $phoneNumber1,
]
);
$message2 = MessageModels::createMessagingV1Message(
[
'to' => $phoneNumber2,
]
);
// Create list of the message objects
$messages = [$message1, $message2];
// This must be a Twilio phone number that you own, formatted with a '+' and country code
$twilioPurchasedNumber = "+XXXXXXXXXX";
// Specify the message to be sent - JSON string supported
$messageBody = "Hello from twilio-php!";
// Create Message Request object
$createMessagesRequest = MessageModels::createCreateMessagesRequest(
[
'messages' => $messages,
'from' => $twilioPurchasedNumber,
'body' => $messageBody,
]
);
// Send a Bulk Message
$message = $client->previewMessaging->v1->messages->create($createMessagesRequest);
// Print how many messages were successful
print($message->successCount . " messages sent successfully!" . "\n\n");
// Print the message details
foreach ($message->messageReceipts as $msg) {
print("ID:: " . $msg["sid"] . " | " . "TO:: " . $msg["to"] . "\n");
}

View File

@@ -0,0 +1,20 @@
<?php
require(__DIR__.'/../src/Twilio/autoload.php');
use Twilio\Rest\Client;
use Twilio\CredentialProvider\OrgsCredentialProviderBuilder;
$clientId = getenv('ORGS_CLIENT_ID');
$clientSecret = getenv('ORGS_CLIENT_SECRET');
$orgSid = getenv('ORG_SID');
$orgsCredentialProvider = (new OrgsCredentialProviderBuilder())->setClientId($clientId)->setClientSecret($clientSecret)->build();
$client = new Client();
$client->setCredentialProvider($orgsCredentialProvider);
//list users
$users = $client->previewIam->organization($orgSid)->users->read();
foreach ($users as $user) {
printf("User SID: %s\n", $user->id);
}

View File

@@ -0,0 +1,22 @@
<?php
require(__DIR__.'/../src/Twilio/autoload.php');
use Twilio\Rest\Client;
use Twilio\CredentialProvider\ClientCredentialProviderBuilder;
$accountSid = getenv('TWILIO_ACCOUNT_SID');
$token = getenv('TWILIO_AUTH_TOKEN');
$clientId = getenv('OAUTH_CLIENT_ID');
$clientSecret = getenv('OAUTH_CLIENT_SECRET');
$clientCredentialProvider = (new ClientCredentialProviderBuilder())->setClientId($clientId)->setClientSecret($clientSecret)->build();
$client = new Client();
$client->setCredentialProvider($clientCredentialProvider);
$client->setAccountSid($accountSid);
$messageList = $client->messages->read([],10);
foreach ($messageList as $msg) {
print("ID:: ". $msg->sid . " | " . "From:: " . $msg->from . " | " . "TO:: " . $msg->to . " | " . " Status:: " . $msg->status . " | " . " Body:: ". $msg->body ."\n");
}

14
vendor/twilio/sdk/example/record.php vendored Normal file
View File

@@ -0,0 +1,14 @@
<?php
require(__DIR__.'/../src/Twilio/autoload.php');
use Twilio\Rest\Client;
$sid = getenv('TWILIO_ACCOUNT_SID');
$token = getenv('TWILIO_AUTH_TOKEN');
$client = new Client($sid, $token);
// Get last 10 records
$recordList = $client->usage->records->read([], 10);
foreach ($recordList as $record) {
print_r("Record(accountSid=" . $record->accountSid . ", apiVersion=" . $record->apiVersion . ", asOf=" . $record->asOf . ", category=" . $record->category . ", count=" . $record->count . ", countUnit=" . $record->countUnit . ", description=" . $record->description . ", endDate=" . $record->endDate->format("Y-m-d H:i:s") . ", price=" . $record->price . ", priceUnit=" . $record->priceUnit . ", startDate=" . $record->startDate->format("Y-m-d H:i:s") . ", uri=" . $record->uri . ", usage=" . $record->usage . ", usageUnit=" . $record->usageUnit . "\n");
}

View File

@@ -0,0 +1,27 @@
<?php
require(__DIR__.'/../src/Twilio/autoload.php');
require(__DIR__.'/../vendor/autoload.php');
use Twilio\Rest\Client;
$sid = getenv('TWILIO_ACCOUNT_SID');
$token = getenv('TWILIO_AUTH_TOKEN');
$client = new Client($sid, $token);
// Create new Signing Key
$signingKey = $client->api->v2010->newSigningKeys->create();
// Switch to guzzle client as the default client
$guzzleClient = new Client($signingKey->sid, $signingKey->secret, $sid, null, new \Twilio\Http\GuzzleClient(new \GuzzleHttp\Client));
// The phone number you are querying in E.164 or national format.
// If the phone number is provided in national format, please also specify the country in the optional parameter CountryCode.
// Otherwise, CountryCode will default to US.
$number = "+XXXXXXXXXX";
// Make REST API requests
$phone_number = $guzzleClient->lookups->v1->phoneNumbers($number)
->fetch([
"type" => ["carrier"]
]);
print_r($phone_number->carrier);

17
vendor/twilio/sdk/example/trunk.php vendored Normal file
View File

@@ -0,0 +1,17 @@
<?php
require(__DIR__.'/../src/Twilio/autoload.php');
use Twilio\Rest\Client;
$sid = getenv('TWILIO_ACCOUNT_SID');
$token = getenv('TWILIO_AUTH_TOKEN');
$client = new Client($sid, $token);
// Create Trunk
$trunk = $client->trunking->v1->trunks->create(
[
"friendlyName" => "shiny trunk",
"secure" => false
]
);
print("\n".$trunk."\n");

43
vendor/twilio/sdk/example/twiML.php vendored Normal file
View File

@@ -0,0 +1,43 @@
<?php
require(__DIR__ . '/../vendor/autoload.php');
use Twilio\TwiML\VoiceResponse;
// TwiML Say and Play
$say = new \Twilio\TwiML\Voice\Say('Hello World!', [
'voice' => 'woman'
]);
$play = new \Twilio\TwiML\Voice\Play("https://api.twilio.com/cowbell.mp3", [
'loop' => 5
]);
$twiml = new VoiceResponse();
$twiml->append($say);
$twiml->append($play);
print("TwiML Say and Play: \n{$twiml->asXML()}\n");
// Gather, Redirect
$twimlResponse = new VoiceResponse();
$gather = $twimlResponse->gather();
$gather->setNumDigits(10);
$gather->say("Press 1");
$twimlResponse->redirect("https://example.com");
print("TwiML Gather and Redirect: \n{$twimlResponse->asXML()}\n");
// Dial
$twimlResponse = new VoiceResponse();
// A valid phone number formatted with a '+' and a country code (e.g., +16175551212)
$callerID = '+XXXXXXXX';
$dial = $twimlResponse->dial('', [
'callerId' => $callerID,
'action' => 'https:///example.com',
'hangupOnStar' => true,
]);
$dial->conference("My Room", ["beep" => "true"]);
print("TwiML Dial: \n{$twimlResponse->asXML()}\n");

11
vendor/twilio/sdk/phpdox.xml vendored Normal file
View File

@@ -0,0 +1,11 @@
<?xml version="1.0" encoding="utf-8" ?>
<phpdox xmlns="http://xml.phpdox.net/config">
<project name="twilio-php" source="${basedir}/src" workdir="${basedir}/docs/xml">
<collector backend="parser"/>
<generator output="${basedir}/docs">
<build engine="html" output="api">
<file extension="html"/>
</build>
</generator>
</project>
</phpdox>

View File

@@ -0,0 +1,11 @@
sonar.projectKey=twilio_twilio-php
sonar.projectName=twilio-php
sonar.organization=twilio
sonar.sources=src/
sonar.exclusions=src/Twilio/Rest/**/*, src/Twilio/TwiML/*/*, src/Twilio/TwiML/*Response.php
sonar.tests=tests/
sonar.test.exclusions=tests/Twilio/Integration/**/*
# For Code Coverage analysis
sonar.php.coverage.reportPaths=coverage.xml

View File

@@ -0,0 +1,50 @@
<?php
namespace Twilio;
use Twilio\Exceptions\RestException;
use Twilio\Exceptions\RestExceptionV1;
use Twilio\Exceptions\TwilioException;
use Twilio\Http\Response;
class ApiV1Version extends Version {
protected $apiVersion;
/**
* @param Domain $domain
* @param ?string $version
*/
public function __construct(Domain $domain, ?string $version) {
parent::__construct($domain);
$this->version = $version;
$this->apiVersion = "V1";
}
/**
* Create the best possible exception for the response as per Twilio API Standard V1.
*
* Attempts to parse the response for Twilio Standard error as defined in Twilio API Standards V1
* and use those to populate the exception, falls back to generic error message and
* HTTP status code.
*
* @param Response $response Error response
* @param string $header Header for exception message
* @return TwilioException
*/
protected function exception(Response $response, string $header): TwilioException {
$message = '[HTTP ' . $response->getStatusCode() . '] ' . $header;
$content = $response->getContent();
if (\is_array($content)) {
$message .= isset($content['message']) ? ': ' . $content['message'] : '';
$code = $content['code'] ?? $response->getStatusCode();
$httpStatusCode = $content['httpStatusCode'] ?? $response->getStatusCode();
$params = $content['params'] ?? [];
$userError = $content['userError'] ?? false;
return new RestExceptionV1($code, $message, $httpStatusCode, $params, $userError);
}
return new RestExceptionV1($response->getStatusCode(), $message, $response->getStatusCode());
}
}

View File

@@ -0,0 +1,27 @@
<?php
namespace Twilio\AuthStrategy;
/**
* Class AuthStrategy
* Abstract parent class for all authentication strategies - Basic, Bearer Token, NoAuth etc.
* @property string $authType The type of authentication strategy
*/
abstract class AuthStrategy {
private $authType;
public function __construct(string $authType) {
$this->authType = $authType;
}
public function getAuthType(): string {
return $this->authType;
}
/**
* Returns the value to be set in the authentication header
*
* @return string the authentication string
*/
abstract public function getAuthString(): string;
}

View File

@@ -0,0 +1,29 @@
<?php
namespace Twilio\AuthStrategy;
/**
* Class BasicAuthStrategy
* Implementation of the AuthStrategy for Basic authentication
* @property string $username
* @property string $password
*/
class BasicAuthStrategy extends AuthStrategy {
private $username;
private $password;
public function __construct(string $username, string $password) {
parent::__construct("basic");
$this->username = $username;
$this->password = $password;
}
/**
* Returns the base64 encoded string concatenating the username and password
*
* @return string the base64 encoded string
*/
public function getAuthString(): string {
return base64_encode($this->username . ':' . $this->password);
}
}

View File

@@ -0,0 +1,23 @@
<?php
namespace Twilio\AuthStrategy;
/**
* Class NoAuthStrategy
* Implementation of the AuthStrategy for No Authentication
*/
class NoAuthStrategy extends AuthStrategy {
public function __construct() {
parent::__construct("noauth");
}
/**
* Returns an empty string since no authentication is required
*
* @return string an empty string
*/
public function getAuthString(): string {
return "";
}
}

View File

@@ -0,0 +1,69 @@
<?php
namespace Twilio\AuthStrategy;
use Twilio\Rest\Client;
use Twilio\Http\BearerToken\TokenManager;
/**
* Class TokenAuthStrategy
* Implementation of the AuthStrategy for Bearer Token Authentication
* @property string $token The bearer token
* @property TokenManager $tokenManager The manager for the bearer token
*/
class TokenAuthStrategy extends AuthStrategy {
private $token;
private $tokenManager;
public function __construct(TokenManager $tokenManager) {
parent::__construct("token");
$this->tokenManager = $tokenManager;
}
/**
* Checks if the token is expired or not
*
* @param string $token the token to be checked
*
* @return bool whether the token is expired or not
*/
public function isTokenExpired(string $token): bool {
// Decode the JWT token
$decodedToken = json_decode(base64_decode(str_replace('_', '/', str_replace('-','+',explode('.', $token)[1]))), true);
$expireField = $decodedToken['exp'];
// If the token doesn't have an expiration, consider it expired
if ($decodedToken === null || $expireField === null) {
return false;
}
// Calculate the expiration time with a buffer of 30 seconds
$expiresAt = $expireField * 1000;
$bufferMilliseconds = 30 * 1000;
$bufferExpiresAt = $expiresAt - $bufferMilliseconds;
// Return true if the current time is after the expiration time with buffer
return round(microtime(true)*1000) > $bufferExpiresAt;
}
/**
* Fetches the bearer token
*
* @return string the bearer token
*/
public function fetchToken(?Client $client = null): string {
if (empty($this->token) || $this->isTokenExpired($this->token)) {
$this->token = $this->tokenManager->fetchToken($client);
}
return $this->token;
}
/**
* Returns the bearer token authentication string
*
* @return string the bearer token authentication string
*/
public function getAuthString(?Client $client = null): string {
return "Bearer " . $this->fetchToken($client);
}
}

View File

@@ -0,0 +1,460 @@
<?php
namespace Twilio\Base;
use Twilio\AuthStrategy\AuthStrategy;
use Twilio\CredentialProvider\CredentialProvider;
use Twilio\Exceptions\ConfigurationException;
use Twilio\Exceptions\TwilioException;
use Twilio\Http\Client as HttpClient;
use Twilio\Http\CurlClient;
use Twilio\Rest\Api;
use Twilio\Security\RequestValidator;
use Twilio\VersionInfo;
/**
* @property \Twilio\Rest\Api\V2010\AccountInstance $account
* @property Api $api
*/
class BaseClient
{
const ENV_ACCOUNT_SID = 'TWILIO_ACCOUNT_SID';
const ENV_AUTH_TOKEN = 'TWILIO_AUTH_TOKEN';
const ENV_REGION = 'TWILIO_REGION';
const ENV_EDGE = 'TWILIO_EDGE';
const DEFAULT_REGION = 'us1';
const ENV_LOG = 'TWILIO_LOG_LEVEL';
protected $username;
protected $password;
protected $credentialProvider;
protected $accountSid;
protected $region;
protected $edge;
protected $httpClient;
protected $environment;
protected $userAgentExtensions;
protected $logLevel;
protected $_account;
/**
* Initializes the Twilio Client
*
* @param ?string $username Username to authenticate with
* @param ?string $password Password to authenticate with
* @param ?string $accountSid Account SID to authenticate with, defaults to
* $username
* @param ?string $region Region to send requests to, defaults to 'us1' if Edge
* provided
* @param ?HttpClient $httpClient HttpClient, defaults to CurlClient
* @param mixed[] $environment Environment to look for auth details, defaults
* to $_ENV
* @param string[] $userAgentExtensions Additions to the user agent string
*/
public function __construct(
?string $username = null,
?string $password = null,
?string $accountSid = null,
?string $region = null,
?HttpClient $httpClient = null,
?array $environment = null,
?array $userAgentExtensions = null
) {
$this->environment = $environment ?: \getenv();
$this->setUsername($this->getArg($username, self::ENV_ACCOUNT_SID));
$this->setPassword($this->getArg($password, self::ENV_AUTH_TOKEN));
$this->region = $this->getArg($region, self::ENV_REGION);
$this->edge = $this->getArg(null, self::ENV_EDGE);
$this->logLevel = $this->getArg(null, self::ENV_LOG);
$this->userAgentExtensions = $userAgentExtensions ?: [];
$this->invalidateOAuth();
$this->setAccountSid($accountSid ?: $this->username);
if ($httpClient) {
$this->httpClient = $httpClient;
} else {
$this->httpClient = new CurlClient();
}
}
public function setUsername(?string $username): void {
$this->username = $username;
}
public function setPassword(?string $password): void {
$this->password = $password;
}
public function setAccountSid(?string $accountSid): void {
$this->accountSid = $accountSid;
}
private function _setCredentialProvider($credentialProvider): void {
$this->credentialProvider = $credentialProvider;
}
public function setCredentialProvider(CredentialProvider $credentialProvider): void {
$this->_setCredentialProvider($credentialProvider);
$this->invalidateBasicAuth();
}
public function invalidateBasicAuth(): void {
$this->setUsername("");
$this->setPassword("");
}
public function invalidateOAuth(): void {
$this->_setCredentialProvider(null);
}
/**
* Determines argument value accounting for environment variables.
*
* @param ?string $arg The constructor argument
* @param string $envVar The environment variable name
* @return ?string Argument value
*/
public function getArg(?string $arg, string $envVar): ?string
{
if ($arg) {
return $arg;
}
if (\array_key_exists($envVar, $this->environment)) {
return $this->environment[$envVar];
}
return null;
}
/**
* Makes a request to the Twilio API using the configured http client
* Authentication information is automatically added if none is provided
*
* @param string $method HTTP Method
* @param string $uri Fully qualified url
* @param string[] $params Query string parameters
* @param string[] $data POST body data
* @param string[] $headers HTTP Headers
* @param ?string $username User for Authentication
* @param ?string $password Password for Authentication
* @param ?int $timeout Timeout in seconds
* @param ?AuthStrategy $authStrategy AuthStrategy for Authentication
* @return \Twilio\Http\Response Response from the Twilio API
* @throws TwilioException
*/
public function request(
string $method,
string $uri,
array $params = [],
array $data = [],
array $headers = [],
?string $username = null,
?string $password = null,
?int $timeout = null,
?AuthStrategy $authStrategy = null
): \Twilio\Http\Response{
$username = $username ?: $this->username;
$password = $password ?: $this->password;
$authStrategy = $authStrategy ?: null;
if ($this->credentialProvider) {
$authStrategy = $this->credentialProvider->toAuthStrategy();
}
if( ($this->edge === null && $this->region !== null) || ($this->edge !== null && $this->region === null) )
{
trigger_error(' For regional processing, DNS is of format product.city.region.twilio.com; otherwise use product.twilio.com.', E_USER_DEPRECATED);
}
if ($this->edge === null && $this->region !== null) {
$regionMap = [
'au1' => 'sydney',
'br1' => 'sao-paulo',
'de1' => 'frankfurt',
'ie1' => 'dublin',
'jp1' => 'tokyo',
'jp2' => 'osaka',
'sg1' => 'singapore',
'us1' => 'ashburn',
'us2' => 'umatilla'
];
if (array_key_exists($this->region, $regionMap)) {
trigger_error(' Setting default `Edge` for the provided `region`.', E_USER_DEPRECATED);
$this->edge = $regionMap[$this->region];
}
if( $this->edge === null )
$this->edge = '';
}
if (!$authStrategy) {
if (!$username) {
throw new ConfigurationException('username is required');
}
if (!$password) {
throw new ConfigurationException("password is required");
}
}
$logLevel = (getenv('DEBUG_HTTP_TRAFFIC') === 'true' ? 'debug' : $this->getLogLevel());
$headers['User-Agent'] = 'twilio-php/' . VersionInfo::string() .
' (' . php_uname("s") . ' ' . php_uname("m") . ')' .
' PHP/' . PHP_VERSION;
$headers['Accept-Charset'] = 'utf-8';
if ($this->userAgentExtensions) {
$headers['User-Agent'] .= ' ' . implode(' ', $this->userAgentExtensions);
}
// skip adding Accept header in case of delete operation
if ($method !== "DELETE" && !\array_key_exists('Accept', $headers)) {
$headers['Accept'] = 'application/json';
}
$uri = $this->buildUri($uri);
if ($logLevel === 'debug') {
error_log('-- BEGIN Twilio API Request --');
error_log('Request Method: ' . $method);
$u = parse_url($uri);
if (isset($u['path'])) {
error_log('Request URL: ' . $u['path']);
}
if (isset($u['query']) && strlen($u['query']) > 0) {
error_log('Query Params: ' . $u['query']);
}
error_log('Request Headers: ');
foreach ($headers as $key => $value) {
if (strpos(strtolower($key), 'authorization') === false) {
error_log("$key: $value");
}
}
error_log('-- END Twilio API Request --');
}
$response = $this->getHttpClient()->request(
$method,
$uri,
$params,
$data,
$headers,
$username,
$password,
$timeout,
$authStrategy
);
if ($logLevel === 'debug') {
error_log('Status Code: ' . $response->getStatusCode());
error_log('Response Headers:');
$responseHeaders = $response->getHeaders();
foreach ($responseHeaders as $key => $value) {
error_log("$key: $value");
}
}
return $response;
}
/**
* Build the final request uri
*
* @param string $uri The original request uri
* @return string Request uri
*/
public function buildUri(string $uri): string
{
if ($this->region == null && $this->edge == null) {
return $uri;
}
$parsedUrl = \parse_url($uri);
$pieces = \explode('.', $parsedUrl['host']);
$product = $pieces[0];
$domain = \implode('.', \array_slice($pieces, -2));
$newEdge = $this->edge;
$newRegion = $this->region;
if (count($pieces) == 4) { // product.region.twilio.com
$newRegion = $newRegion ?: $pieces[1];
} elseif (count($pieces) == 5) { // product.edge.region.twilio.com
$newEdge = $newEdge ?: $pieces[1];
$newRegion = $newRegion ?: $pieces[2];
}
if ($newEdge != null && $newRegion == null) {
$newRegion = self::DEFAULT_REGION;
}
$parsedUrl['host'] = \implode('.', \array_filter([$product, $newEdge, $newRegion, $domain]));
return RequestValidator::unparse_url($parsedUrl);
}
/**
* Magic getter to lazy load domains
*
* @param string $name Domain to return
* @return \Twilio\Domain The requested domain
* @throws TwilioException For unknown domains
*/
public function __get(string $name)
{
$method = 'get' . \ucfirst($name);
if (\method_exists($this, $method)) {
return $this->$method();
}
throw new TwilioException('Unknown domain ' . $name);
}
/**
* Magic call to lazy load contexts
*
* @param string $name Context to return
* @param mixed[] $arguments Context to return
* @return \Twilio\InstanceContext The requested context
* @throws TwilioException For unknown contexts
*/
public function __call(string $name, array $arguments)
{
$method = 'context' . \ucfirst($name);
if (\method_exists($this, $method)) {
return \call_user_func_array([$this, $method], $arguments);
}
throw new TwilioException('Unknown context ' . $name);
}
/**
* Provide a friendly representation
*
* @return string Machine friendly representation
*/
public function __toString(): string
{
return '[Client ' . $this->getAccountSid() . ']';
}
/**
* Validates connection to new SSL certificate endpoint
*
* @param CurlClient $client
* @throws TwilioException if request fails
*/
public function validateSslCertificate(CurlClient $client): void
{
$response = $client->request('GET', 'https://tls-test.twilio.com:443');
if ($response->getStatusCode() < 200 || $response->getStatusCode() > 300) {
throw new TwilioException('Failed to validate SSL certificate');
}
}
/**
* @return \Twilio\Rest\Api\V2010\AccountContext Account provided as the
* authenticating account
*/
public function getAccount(): \Twilio\Rest\Api\V2010\AccountContext
{
return $this->api->v2010->account;
}
/**
* Retrieve the Username
*
* @return string Current Username
*/
public function getUsername(): string
{
return $this->username;
}
/**
* Retrieve the Password
*
* @return string Current Password
*/
public function getPassword(): string
{
return $this->password;
}
/**
* Retrieve the AccountSid
*
* @return string Current AccountSid
*/
public function getAccountSid(): string
{
return $this->accountSid;
}
/**
* Retrieve the Region
*
* @return string Current Region
*/
public function getRegion(): string
{
return $this->region;
}
/**
* Retrieve the Edge
*
* @return string Current Edge
*/
public function getEdge(): string
{
return $this->edge;
}
/**
* Set Edge
*
* @param ?string $edge Edge to use, unsets the Edge when called with no arguments
*/
public function setEdge(?string $edge = null): void
{
$this->edge = $this->getArg($edge, self::ENV_EDGE);
}
/**
* Retrieve the HttpClient
*
* @return HttpClient Current HttpClient
*/
public function getHttpClient(): HttpClient
{
return $this->httpClient;
}
/**
* Set the HttpClient
*
* @param HttpClient $httpClient HttpClient to use
*/
public function setHttpClient(HttpClient $httpClient): void
{
$this->httpClient = $httpClient;
}
/**
* Retrieve the log level
*
* @return ?string Current log level
*/
public function getLogLevel(): ?string
{
return $this->logLevel;
}
/**
* Set log level to debug
*
* @param ?string $logLevel log level to use
*/
public function setLogLevel(?string $logLevel = null): void
{
$this->logLevel = $this->getArg($logLevel, self::ENV_LOG);
}
}

View File

@@ -0,0 +1,80 @@
<?php
namespace Twilio\Base;
use Twilio\Exceptions\TwilioException;
use Twilio\Values;
/**
* @property bool $mms
* @property bool $sms
* @property bool $voice
* @property bool $fax
*/
class PhoneNumberCapabilities
{
protected $mms;
protected $sms;
protected $voice;
protected $fax;
public function __construct(array $capabilities)
{
$this->mms = Values::array_get($capabilities, 'mms', "false");
$this->sms = Values::array_get($capabilities, 'sms', "false");
$this->voice = Values::array_get($capabilities, 'voice', "false");
$this->fax = Values::array_get($capabilities, 'fax', "false");
}
/**
* Access the mms
*/
public function getMms(): bool
{
return $this->mms;
}
/**
* Access the sms
*/
public function getSms(): bool
{
return $this->sms;
}
/**
* Access the voice
*/
public function getVoice(): bool
{
return $this->voice;
}
/**
* Access the fax
*/
public function getFax(): bool
{
return $this->fax;
}
public function __get(string $name)
{
if (\property_exists($this, $name)) {
$method = 'get' . \ucfirst($name);
return $this->$method();
}
throw new TwilioException('Unknown subresource ' . $name);
}
public function __toString(): string
{
return "[Twilio.Base.PhoneNumberCapabilities " .
"(
mms: " . json_encode($this->mms) . ",
sms: " . json_encode($this->sms) . ",
voice: " . json_encode($this->voice) . ",
fax: " . json_encode($this->fax) . "
)]";
}
}

View File

@@ -0,0 +1,93 @@
<?php
namespace Twilio\CredentialProvider;
use Twilio\AuthStrategy\AuthStrategy;
use Twilio\AuthStrategy\TokenAuthStrategy;
use Twilio\Exceptions\TwilioException;
use Twilio\Http\BearerToken\ApiTokenManager;
use Twilio\Http\BearerToken\TokenManager;
/**
* Class ClientCredentialProvider
* Credential provider for OAuth in public apis
*/
class ClientCredentialProvider extends CredentialProvider {
/**
* @var array $options - array of params required for token api
*/
private $options;
/**
* @var TokenManager $tokenManager - handles fetching and refreshing of token
*/
private $tokenManager;
public function __construct() {
parent::__construct("client-credentials");
$this->options = [
"grantType" => "client_credentials",
"clientId" => null,
"clientSecret" => null,
"code" => null,
"redirectUri" =>null,
"audience" => null,
"refreshToken" => null,
"scope" => null
];
}
/**
* @return TokenManager
*/
public function getTokenManager(): TokenManager {
return $this->tokenManager;
}
/**
* @param TokenManager $tokenManager
*/
public function setTokenManager(TokenManager $tokenManager): void {
$this->tokenManager = $tokenManager;
}
/**
* Magic method to get properties - returns the property if it exists in the options array
* @param string $name
* @return mixed value of the property
* @throws TwilioException
*/
public function __get(string $name)
{
if (array_key_exists($name, $this->options)) {
return $this->options[$name];
}
throw new TwilioException('Unknown property ' . $name);
}
/**
* Magic method to set properties - sets the value of the property if it exists in the options array
* @param string $name
* @param $value
* @return void
* @throws TwilioException
*/
public function __set(string $name, $value)
{
if (array_key_exists($name, $this->options)) {
$this->options[$name] = $value;
} else {
throw new TwilioException('Unknown property ' . $name);
}
}
/**
* Returns TokenAuthStrategy using ApiTokenManager
* @return AuthStrategy
*/
public function toAuthStrategy(): AuthStrategy {
if ($this->tokenManager === null) {
$this->tokenManager = new ApiTokenManager($this->options);
}
return new TokenAuthStrategy($this->tokenManager);
}
}

View File

@@ -0,0 +1,44 @@
<?php
namespace Twilio\CredentialProvider;
use Twilio\Http\BearerToken\TokenManager;
/**
* Class ClientCredentialProviderBuilder
* Builder class for ClientCredentialProvider
*/
class ClientCredentialProviderBuilder {
private $instance;
public function __construct() {
$this->instance = new ClientCredentialProvider();
}
public function setGrantType(string $grantType): ClientCredentialProviderBuilder {
$this->instance->grantType = $grantType;
return $this;
}
public function setClientId(string $clientId): ClientCredentialProviderBuilder {
$this->instance->clientId = $clientId;
return $this;
}
public function setClientSecret(string $clientSecret): ClientCredentialProviderBuilder {
$this->instance->clientSecret = $clientSecret;
return $this;
}
public function setTokenManager(TokenManager $tokenManager): ClientCredentialProviderBuilder {
$this->instance->setTokenManager($tokenManager);
return $this;
}
public function build(): ClientCredentialProvider
{
return $this->instance;
}
}

View File

@@ -0,0 +1,29 @@
<?php
namespace Twilio\CredentialProvider;
use Twilio\AuthStrategy\AuthStrategy;
/**
* Class CredentialProvider
* Abstract parent class for all credential providers
* @property string $authType The type of authentication
*/
abstract class CredentialProvider {
private $authType;
public function __construct(string $authType) {
$this->authType = $authType;
}
public function getAuthType(): string {
return $this->authType;
}
/**
* Returns the authentication strategy for the credential provider
*
* @return AuthStrategy the authentication strategy for the credential provider
*/
abstract public function toAuthStrategy(): AuthStrategy;
}

View File

@@ -0,0 +1,25 @@
<?php
namespace Twilio\CredentialProvider;
use Twilio\AuthStrategy\AuthStrategy;
use Twilio\AuthStrategy\NoAuthStrategy;
/**
* Class NoAuthCredentialProvider
* Credential provider for no authentication
*/
class NoAuthCredentialProvider extends CredentialProvider {
public function __construct() {
parent::__construct("noauth");
}
/**
* Returns the authentication strategy for the credential provider
*
* @return AuthStrategy the authentication strategy for the credential provider
*/
public function toAuthStrategy(): AuthStrategy {
return new NoAuthStrategy();
}
}

View File

@@ -0,0 +1,93 @@
<?php
namespace Twilio\CredentialProvider;
use Twilio\AuthStrategy\AuthStrategy;
use Twilio\AuthStrategy\TokenAuthStrategy;
use Twilio\Exceptions\TwilioException;
use Twilio\Http\BearerToken\OrgsTokenManager;
use Twilio\Http\BearerToken\TokenManager;
/**
* Class OrgsCredentialProvider
* Credential provider for OAuth in public apis
*/
class OrgsCredentialProvider extends CredentialProvider {
/**
* @var array $options - array of params required for token api
*/
private $options;
/**
* @var TokenManager $tokenManager - handles fetching and refreshing of token
*/
private $tokenManager;
public function __construct() {
parent::__construct("client-credentials");
$this->options = [
"grantType" => "client_credentials",
"clientId" => null,
"clientSecret" => null,
"code" => null,
"redirectUri" =>null,
"audience" => null,
"refreshToken" => null,
"scope" => null
];
}
/**
* @return TokenManager
*/
public function getTokenManager(): TokenManager {
return $this->tokenManager;
}
/**
* @param TokenManager $tokenManager
*/
public function setTokenManager(TokenManager $tokenManager): void {
$this->tokenManager = $tokenManager;
}
/**
* Magic method to get properties - returns the property if it exists in the options array
* @param string $name
* @return mixed value of the property
* @throws TwilioException
*/
public function __get(string $name)
{
if (array_key_exists($name, $this->options)) {
return $this->options[$name];
}
throw new TwilioException('Unknown property ' . $name);
}
/**
* Magic method to set properties - sets the value of the property if it exists in the options array
* @param string $name
* @param $value
* @return void
* @throws TwilioException
*/
public function __set(string $name, $value)
{
if (array_key_exists($name, $this->options)) {
$this->options[$name] = $value;
} else {
throw new TwilioException('Unknown property ' . $name);
}
}
/**
* Returns TokenAuthStrategy using OrgsTokenManager
* @return AuthStrategy
*/
public function toAuthStrategy(): AuthStrategy {
if ($this->tokenManager === null) {
$this->tokenManager = new OrgsTokenManager($this->options);
}
return new TokenAuthStrategy($this->tokenManager);
}
}

View File

@@ -0,0 +1,44 @@
<?php
namespace Twilio\CredentialProvider;
use Twilio\Http\BearerToken\TokenManager;
/**
* Class OrgsCredentialProviderBuilder
* Builder class for OrgsCredentialProvider
*/
class OrgsCredentialProviderBuilder {
private $instance;
public function __construct() {
$this->instance = new OrgsCredentialProvider();
}
public function setGrantType(string $grantType): OrgsCredentialProviderBuilder {
$this->instance->grantType = $grantType;
return $this;
}
public function setClientId(string $clientId): OrgsCredentialProviderBuilder {
$this->instance->clientId = $clientId;
return $this;
}
public function setClientSecret(string $clientSecret): OrgsCredentialProviderBuilder {
$this->instance->clientSecret = $clientSecret;
return $this;
}
public function setTokenManager(TokenManager $tokenManager): OrgsCredentialProviderBuilder {
$this->instance->setTokenManager($tokenManager);
return $this;
}
public function build(): OrgsCredentialProvider
{
return $this->instance;
}
}

View File

@@ -0,0 +1,51 @@
<?php
namespace Twilio;
use Twilio\Base\PhoneNumberCapabilities;
class Deserialize
{
/**
* Deserialize a string date into a DateTime object
*
* @param ?string $s A date or date and time, can be iso8601, rfc2822,
* YYYY-MM-DD format.
* @return \DateTime|string DateTime corresponding to the input string, in UTC time.
*/
public static function dateTime(?string $s)
{
try {
if ($s) {
return new \DateTime($s, new \DateTimeZone('UTC'));
}
} catch (\Exception $e) {
// no-op
}
return $s;
}
/**
* Deserialize an array into a PhoneNumberCapabilities object
*
* @param array|null $arr An array
* @return PhoneNumberCapabilities|array PhoneNumberCapabilities object corresponding to the input array.
*/
public static function phoneNumberCapabilities(?array $arr)
{
try {
if ($arr) {
$required = ["mms", "sms", "voice", "fax"];
if (count(array_intersect($required, array_keys($arr))) > 0) {
return new PhoneNumberCapabilities($arr);
}
}
} catch (\Exception $e) {
// no-op
}
return $arr;
}
}

82
vendor/twilio/sdk/src/Twilio/Domain.php vendored Normal file
View File

@@ -0,0 +1,82 @@
<?php
namespace Twilio;
use Twilio\Http\Response;
use Twilio\Rest\Client;
/**
* Class Domain
* Abstracts a Twilio sub domain
* @package Twilio
*/
abstract class Domain {
/**
* @var Client Twilio Client
*/
protected $client;
/**
* @var string Base URL for this domain
*/
protected $baseUrl;
/**
* Construct a new Domain
* @param Client $client used to communicate with Twilio
*/
public function __construct(Client $client) {
$this->client = $client;
$this->baseUrl = '';
}
/**
* Translate version relative URIs into absolute URLs
*
* @param string $uri Version relative URI
* @return string Absolute URL for this domain
*/
public function absoluteUrl(string $uri): string {
return \implode('/', [\trim($this->baseUrl, '/'), \trim($uri, '/')]);
}
/**
* Make an HTTP request to the domain
*
* @param string $method HTTP Method to make the request with
* @param string $uri Relative uri to make a request to
* @param array $params Query string arguments
* @param array $data Post form data
* @param array $headers HTTP headers to send with the request
* @param ?string $user User to authenticate as
* @param ?string $password Password
* @param ?int $timeout Request timeout
* @return Response the response for the request
*/
public function request(string $method, string $uri,
array $params = [], array $data = [], array $headers = [],
?string $user = null, ?string $password = null,
?int $timeout = null): Response {
$url = $this->absoluteUrl($uri);
return $this->client->request(
$method,
$url,
$params,
$data,
$headers,
$user,
$password,
$timeout
);
}
public function getClient(): Client {
return $this->client;
}
public function __toString(): string {
return '[Domain]';
}
}

View File

@@ -0,0 +1,9 @@
<?php
namespace Twilio\Exceptions;
class ConfigurationException extends TwilioException {
}

View File

@@ -0,0 +1,9 @@
<?php
namespace Twilio\Exceptions;
class DeserializeException extends TwilioException {
}

View File

@@ -0,0 +1,9 @@
<?php
namespace Twilio\Exceptions;
class EnvironmentException extends TwilioException {
}

View File

@@ -0,0 +1,9 @@
<?php
namespace Twilio\Exceptions;
class HttpException extends TwilioException {
}

View File

@@ -0,0 +1,19 @@
<?php
namespace Twilio\Exceptions;
/**
* Exception thrown when a required key is missing from a response or metadata.
*
* This exception is typically thrown when the expected 'key' field is not present
* in the response data or metadata, which may indicate a malformed or incomplete response.
*
* Example scenarios:
* - When parsing API responses and the 'key' field is missing.
* - When validating metadata and a required key is not found.
*/
class KeyErrorException extends TwilioException {
}

View File

@@ -0,0 +1,52 @@
<?php
namespace Twilio\Exceptions;
class RestException extends TwilioException {
protected $statusCode;
protected $details;
protected $moreInfo;
/**
* Construct the exception. Note: The message is NOT binary safe.
* @link http://php.net/manual/en/exception.construct.php
* @param string $message [optional] The Exception message to throw.
* @param int $code [optional] The Exception code.
* @param int $statusCode [optional] The HTTP Status code.
* @param string $moreInfo [optional] More information about the error.
* @param array $details [optional] Additional details about the error.
* @since 5.1.0
*/
public function __construct(string $message, int $code, int $statusCode, string $moreInfo = '', array $details = []) {
$this->statusCode = $statusCode;
$this->moreInfo = $moreInfo;
$this->details = $details;
parent::__construct($message, $code);
}
/**
* Get the HTTP Status Code of the RestException
* @return int HTTP Status Code
*/
public function getStatusCode(): int {
return $this->statusCode;
}
/**
* Get more information of the RestException
* @return string More error information
*/
public function getMoreInfo(): string {
return $this->moreInfo;
}
/**
* Get the details of the RestException
* @return array details
*/
public function getDetails(): array {
return $this->details;
}
}

View File

@@ -0,0 +1,54 @@
<?php
namespace Twilio\Exceptions;
class RestExceptionV1 extends TwilioException {
protected $code;
protected $message;
protected $httpStatusCode;
protected $params;
protected $userError;
/**
* Construct the exception.
* @param int $code A unique error code.
* @param string $message A human-readable error message.
* @param int $httpStatusCode The HTTP status code.
* @param array $params [optional] More information about the error.
* @param bool $userError [optional] true if it is an error that depends on the end users actions
*/
public function __construct(int $code, string $message, int $httpStatusCode, array $params = [], bool $userError = false) {
$this->code = $code;
$this->message = $message;
$this->httpStatusCode = $httpStatusCode;
$this->params = $params;
$this->userError = $userError;
parent::__construct($message, $code);
}
/**
* Get the HTTP Status Code of the RestException
* @return int HTTP Status Code
*/
public function getHttpStatusCode(): int {
return $this->httpStatusCode;
}
/**
* Get more information to additional information about the error
* @return array additional information about the error
*/
public function getParams(): array {
return $this->params;
}
/**
* Get the user error flag of the RestException
* @return bool user error flag
*/
public function getUserError(): bool {
return $this->userError;
}
}

View File

@@ -0,0 +1,9 @@
<?php
namespace Twilio\Exceptions;
class TwilioException extends \Exception {
}

View File

@@ -0,0 +1,9 @@
<?php
namespace Twilio\Exceptions;
class TwimlException extends TwilioException {
}

View File

@@ -0,0 +1,53 @@
<?php
namespace Twilio\Http\BearerToken;
use Twilio\CredentialProvider\NoAuthCredentialProvider;
use Twilio\Exceptions\TwilioException;
use Twilio\Rest\Client;
use Twilio\Rest\Oauth\V2;
use Twilio\Rest\Oauth\V2\TokenList;
use Twilio\Rest\OauthBase;
/**
* Class ApiTokenManager
* Token manager class for public OAuth
* @property string $token The bearer token
* @property string $tokenManager The manager for the bearer token
*/
class ApiTokenManager extends TokenManager {
private $options;
public function __construct(array $options = []) {
$this->options = $options;
}
public function getOptions(): array {
return $this->options;
}
/**
* Fetches the bearer token
* @throws TwilioException
*/
public function fetchToken(?Client $client = null): string {
if ($client === null) {
$client = new Client();
}
$noAuthCredentialProvider = new NoAuthCredentialProvider();
$client->setCredentialProvider($noAuthCredentialProvider);
$base = new OauthBase($client);
$v2 = new V2($base);
$tokenList = new TokenList($v2);
try {
return $tokenList->create(
$this->options
)->accessToken;
}
catch (TwilioException $e) {
throw new TwilioException($e->getMessage());
}
}
}

View File

@@ -0,0 +1,53 @@
<?php
namespace Twilio\Http\BearerToken;
use Twilio\CredentialProvider\NoAuthCredentialProvider;
use Twilio\Exceptions\TwilioException;
use Twilio\Rest\Client;
use Twilio\Rest\Oauth\V2;
use Twilio\Rest\Oauth\V2\TokenList;
use Twilio\Rest\OauthBase;
/**
* Class OrgsTokenManager
* Token manager class for public OAuth
* @property string $token The bearer token
* @property string $tokenManager The manager for the bearer token
*/
class OrgsTokenManager extends TokenManager {
private $options;
public function __construct(array $options = []) {
$this->options = $options;
}
public function getOptions(): array {
return $this->options;
}
/**
* Fetches the bearer token
* @throws TwilioException
*/
public function fetchToken(?Client $client = null): string {
if ($client === null) {
$client = new Client();
}
$noAuthCredentialProvider = new NoAuthCredentialProvider();
$client->setCredentialProvider($noAuthCredentialProvider);
$base = new OauthBase($client);
$v2 = new V2($base);
$tokenList = new TokenList($v2);
try {
return $tokenList->create(
$this->options
)->accessToken;
}
catch (TwilioException $e) {
throw new TwilioException($e->getMessage());
}
}
}

View File

@@ -0,0 +1,20 @@
<?php
namespace Twilio\Http\BearerToken;
use Twilio\Rest\Client;
/**
* Class TokenManager
* Abstract parent class for all token managers
* @property string $token The bearer token
* @property string $tokenManager The manager for the bearer token
*/
abstract class TokenManager {
/**
* Fetches the bearer token
*
* @return string the bearer token
*/
abstract public function fetchToken(?Client $client = null): string;
}

View File

@@ -0,0 +1,14 @@
<?php
namespace Twilio\Http;
use Twilio\AuthStrategy\AuthStrategy;
interface Client {
public function request(string $method, string $url,
array $params = [], array $data = [], array $headers = [],
?string $user = null, ?string $password = null,
?int $timeout = null, ?AuthStrategy $authStrategy = null): Response;
}

View File

@@ -0,0 +1,267 @@
<?php
namespace Twilio\Http;
use Twilio\AuthStrategy\AuthStrategy;
use Twilio\Exceptions\ConfigurationException;
use Twilio\Exceptions\EnvironmentException;
class CurlClient implements Client {
public const DEFAULT_TIMEOUT = 60;
protected $curlOptions = [];
public $lastRequest;
public $lastResponse;
public function __construct(array $options = []) {
$this->curlOptions = $options;
}
public function request(string $method, string $url,
array $params = [], array $data = [], array $headers = [],
?string $user = null, ?string $password = null,
?int $timeout = null, ?AuthStrategy $authStrategy = null): Response {
$options = $this->options($method, $url, $params, $data, $headers,
$user, $password, $timeout, $authStrategy);
$this->lastRequest = $options;
$this->lastResponse = null;
try {
if (!$curl = \curl_init()) {
throw new EnvironmentException('Unable to initialize cURL');
}
if (!\curl_setopt_array($curl, $options)) {
throw new EnvironmentException(\curl_error($curl));
}
if (!$response = \curl_exec($curl)) {
throw new EnvironmentException(\curl_error($curl));
}
$parts = \explode("\r\n\r\n", $response, 3);
list($head, $body) = (
\preg_match('/\AHTTP\/1.\d 100 Continue\Z/', $parts[0])
|| \preg_match('/\AHTTP\/1.\d 200 Connection established\Z/', $parts[0])
|| \preg_match('/\AHTTP\/1.\d 200 Tunnel established\Z/', $parts[0])
)
? array($parts[1], $parts[2])
: array($parts[0], $parts[1]);
$statusCode = \curl_getinfo($curl, CURLINFO_HTTP_CODE);
$responseHeaders = [];
$headerLines = \explode("\r\n", $head);
\array_shift($headerLines);
foreach ($headerLines as $line) {
list($key, $value) = \explode(':', $line, 2);
$responseHeaders[$key] = $value;
}
if (PHP_MAJOR_VERSION < 8) {
\curl_close($curl);
}
if (isset($options[CURLOPT_INFILE]) && \is_resource($options[CURLOPT_INFILE])) {
\fclose($options[CURLOPT_INFILE]);
}
$this->lastResponse = new Response($statusCode, $body, $responseHeaders);
return $this->lastResponse;
} catch (\ErrorException $e) {
if (PHP_MAJOR_VERSION < 8 && isset($curl) && \is_resource($curl)) {
\curl_close($curl);
}
if (isset($options[CURLOPT_INFILE]) && \is_resource($options[CURLOPT_INFILE])) {
\fclose($options[CURLOPT_INFILE]);
}
throw $e;
}
}
public function options(string $method, string $url,
array $params = [], array $data = [], array $headers = [],
?string $user = null, ?string $password = null,
?int $timeout = null, ?AuthStrategy $authStrategy = null): array {
$timeout = $timeout ?? self::DEFAULT_TIMEOUT;
$options = $this->curlOptions + [
CURLOPT_URL => $url,
CURLOPT_HEADER => true,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_INFILESIZE => Null,
CURLOPT_HTTPHEADER => [],
CURLOPT_TIMEOUT => $timeout,
CURLOPT_PROTOCOLS => CURLPROTO_HTTPS | CURLPROTO_HTTP
];
foreach ($headers as $key => $value) {
$options[CURLOPT_HTTPHEADER][] = "$key: $value";
}
if ($user && $password) {
$options[CURLOPT_HTTPHEADER][] = 'Authorization: Basic ' . \base64_encode("$user:$password");
}
elseif ($authStrategy) {
$options[CURLOPT_HTTPHEADER][] = 'Authorization: ' . $authStrategy->getAuthString();
}
$query = $this->buildQuery($params);
if ($query) {
$options[CURLOPT_URL] .= '?' . $query;
}
$methodName = \strtolower(\trim($method));
// Configure HTTP method-specific options
if ($methodName === 'get') {
$options[CURLOPT_HTTPGET] = true;
} elseif ($methodName === 'head') {
$options[CURLOPT_NOBODY] = true;
} elseif (\in_array($methodName, ['post', 'put', 'patch'])) {
// Handle methods that send data in the request body
$this->configureMethodWithData($options, $methodName, $method, $data, $headers);
} else {
// Handle other HTTP methods (DELETE, etc.)
$options[CURLOPT_CUSTOMREQUEST] = \strtoupper($method);
}
return $options;
}
/**
* Configure cURL options for HTTP methods that send data in the request body
* (POST, PUT, PATCH)
*/
private function configureMethodWithData(array &$options, string $methodName, string $method, array $data, array $headers): void
{
// Set the appropriate cURL option for the HTTP method
if ($methodName === 'post') {
$options[CURLOPT_POST] = true;
} else {
$options[CURLOPT_CUSTOMREQUEST] = \strtoupper($method);
}
// Configure the request body based on data type
if ($this->hasFile($data)) {
// Handle multipart/form-data for file uploads
[$headers, $body] = $this->buildMultipartOptions($data);
$options[CURLOPT_POSTFIELDS] = $body;
$options[CURLOPT_HTTPHEADER] = \array_merge($options[CURLOPT_HTTPHEADER], $headers);
} elseif (isset($headers['Content-Type']) && $headers['Content-Type'] === 'application/json') {
// Handle JSON data
$options[CURLOPT_POSTFIELDS] = \json_encode($data);
} else {
// Handle URL-encoded form data
$options[CURLOPT_POSTFIELDS] = $this->buildQuery($data);
}
}
public function buildQuery(?array $params): string {
$parts = [];
$params = $params ?: [];
foreach ($params as $key => $value) {
if (\is_array($value)) {
foreach ($value as $item) {
$parts[] = $this->encodeQueryComponent((string)$key) . '=' .
$this->encodeQueryComponent((string)$item);
}
} else {
$parts[] = $this->encodeQueryComponent((string)$key) . '=' .
$this->encodeQueryComponent((string)$value);
}
}
return \implode('&', $parts);
}
/**
* Custom encoder for query string components that:
* 1. Encodes spaces as '+' (like urlencode)
* 2. Preserves unreserved characters including tilde (like rawurlencode)
*/
private function encodeQueryComponent(string $string): string {
// Start with rawurlencode to encode as per RFC 3986
$encoded = \rawurlencode($string);
// Convert %20 back to + for query string compatibility
$encoded = \str_replace('%20', '+', $encoded);
return $encoded;
}
private function hasFile(array $data): bool {
foreach ($data as $value) {
if ($value instanceof File) {
return true;
}
}
return false;
}
private function buildMultipartOptions(array $data): array {
$boundary = \uniqid('', true);
$delimiter = "-------------{$boundary}";
$body = '';
foreach ($data as $key => $value) {
if ($value instanceof File) {
$contents = $value->getContents();
if ($contents === null) {
$chunk = \file_get_contents($value->getFileName());
$filename = \basename($value->getFileName());
} elseif (\is_resource($contents)) {
$chunk = '';
while (!\feof($contents)) {
$chunk .= \fread($contents, 8096);
}
$filename = $value->getFileName();
} elseif (\is_string($contents)) {
$chunk = $contents;
$filename = $value->getFileName();
} else {
throw new \InvalidArgumentException('Unsupported content type');
}
$headers = '';
$contentType = $value->getContentType();
if ($contentType !== null) {
$headers .= "Content-Type: {$contentType}\r\n";
}
$body .= \vsprintf("--%s\r\nContent-Disposition: form-data; name=\"%s\"; filename=\"%s\"\r\n%s\r\n%s\r\n", [
$delimiter,
$key,
$filename,
$headers,
$chunk,
]);
} else {
$body .= \vsprintf("--%s\r\nContent-Disposition: form-data; name=\"%s\"\r\n\r\n%s\r\n", [
$delimiter,
$key,
$value,
]);
}
}
$body .= "--{$delimiter}--\r\n";
return [
[
"Content-Type: multipart/form-data; boundary={$delimiter}",
'Content-Length: ' . \strlen($body),
],
$body,
];
}
}

View File

@@ -0,0 +1,47 @@
<?php
declare(strict_types=1);
namespace Twilio\Http;
final class File {
/**
* @var string
*/
private $fileName;
/**
* @var resource|string|mixed|null
*/
private $contents;
/**
* @var string|null
*/
private $contentType;
/**
* @param string $fileName full file path or file name for passed $contents
* @param string|resource|mixed|null $contents
* @param ?string $contentType
*/
public function __construct(string $fileName, $contents = null, ?string $contentType = null) {
$this->fileName = $fileName;
$this->contents = $contents;
$this->contentType = $contentType;
}
/**
* @return resource|string|mixed|null
*/
public function getContents() {
return $this->contents;
}
public function getFileName(): string {
return $this->fileName;
}
public function getContentType(): ?string {
return $this->contentType;
}
}

View File

@@ -0,0 +1,106 @@
<?php
namespace Twilio\Http;
use GuzzleHttp\ClientInterface;
use GuzzleHttp\Exception\BadResponseException;
use GuzzleHttp\Psr7\Query;
use GuzzleHttp\Psr7\Request;
use Twilio\Exceptions\HttpException;
use Twilio\AuthStrategy\AuthStrategy;
final class GuzzleClient implements Client {
/**
* @var ClientInterface
*/
private $client;
public function __construct(ClientInterface $client) {
$this->client = $client;
}
public function request(string $method, string $url,
array $params = [], array $data = [], array $headers = [],
?string $user = null, ?string $password = null,
?int $timeout = null, ?AuthStrategy $authStrategy = null): Response {
try {
$options = [
'timeout' => $timeout,
'allow_redirects' => false,
];
if($user && $password) {
$headers['Authorization'] = 'Basic ' . base64_encode($user . ':' . $password);
}
elseif ($authStrategy) {
$headers['Authorization'] = $authStrategy->getAuthString();
}
if ($params) {
$options['query'] = Query::build($params, PHP_QUERY_RFC1738);
}
if ($method === 'POST' || $method === 'PUT') {
if ($this->hasFile($data)) {
$options['multipart'] = $this->buildMultipartParam($data);
} else {
$options['body'] = Query::build($data, PHP_QUERY_RFC1738);
$headers['Content-Type'] = 'application/x-www-form-urlencoded';
}
}
$response = $this->client->send(new Request($method, $url, $headers), $options);
} catch (BadResponseException $exception) {
$response = $exception->getResponse();
} catch (\Exception $exception) {
throw new HttpException('Unable to complete the HTTP request', 0, $exception);
}
// Casting the body (stream) to a string performs a rewind, ensuring we return the entire response.
// See https://stackoverflow.com/a/30549372/86696
return new Response($response->getStatusCode(), (string)$response->getBody(), $response->getHeaders());
}
private function hasFile(array $data): bool {
foreach ($data as $value) {
if ($value instanceof File) {
return true;
}
}
return false;
}
private function buildMultipartParam(array $data): array {
$multipart = [];
foreach ($data as $key => $value) {
if ($value instanceof File) {
$contents = $value->getContents();
if ($contents === null) {
$contents = fopen($value->getFileName(), 'rb');
}
$chunk = [
'name' => $key,
'contents' => $contents,
'filename' => $value->getFileName(),
];
if ($value->getContentType() !== null) {
$chunk['headers']['Content-Type'] = $value->getContentType();
}
} else {
$chunk = [
'name' => $key,
'contents' => $value,
];
}
$multipart[] = $chunk;
}
return $multipart;
}
}

View File

@@ -0,0 +1,40 @@
<?php
namespace Twilio\Http;
class Response {
protected $headers;
protected $content;
protected $statusCode;
public function __construct(int $statusCode, ?string $content, ?array $headers = []) {
$this->statusCode = $statusCode;
$this->content = $content;
$this->headers = $headers;
}
/**
* @return mixed
*/
public function getContent() {
return \json_decode($this->content, true);
}
public function getStatusCode(): int {
return $this->statusCode;
}
public function getHeaders(): array {
return $this->headers;
}
public function ok(): bool {
return $this->getStatusCode() < 400;
}
public function __toString(): string {
return '[Response] HTTP ' . $this->getStatusCode() . ' ' . $this->content;
}
}

View File

@@ -0,0 +1,19 @@
<?php
namespace Twilio;
class InstanceContext {
protected $version;
protected $solution = [];
protected $uri;
public function __construct(Version $version) {
$this->version = $version;
}
public function __toString(): string {
return '[InstanceContext]';
}
}

View File

@@ -0,0 +1,28 @@
<?php
namespace Twilio;
class InstanceResource {
protected $version;
protected $context;
protected $properties = [];
protected $solution = [];
public function __construct(Version $version) {
$this->version = $version;
}
public function toArray(): array {
return $this->properties;
}
public function __toString(): string {
return '[InstanceResource]';
}
public function __isset($name): bool {
return \array_key_exists($name, $this->properties);
}
}

View File

@@ -0,0 +1,169 @@
<?php
namespace Twilio\Jwt;
use Twilio\Jwt\Grants\Grant;
class AccessToken {
private $signingKeySid;
private $accountSid;
private $secret;
private $ttl;
private $identity;
private $nbf;
private $region;
/** @var Grant[] $grants */
private $grants;
/** @var string[] $customClaims */
private $customClaims;
public function __construct(string $accountSid, string $signingKeySid, string $secret, int $ttl = 3600, ?string $identity = null, ?string $region = null) {
$this->signingKeySid = $signingKeySid;
$this->accountSid = $accountSid;
$this->secret = $secret;
$this->ttl = $ttl;
$this->region = $region;
if ($identity !== null) {
$this->identity = $identity;
}
$this->grants = [];
$this->customClaims = [];
}
/**
* Set the identity of this access token
*
* @param string $identity identity of the grant
*
* @return $this updated access token
*/
public function setIdentity(string $identity): self {
$this->identity = $identity;
return $this;
}
/**
* Returns the identity of the grant
*
* @return string the identity
*/
public function getIdentity(): string {
return $this->identity;
}
/**
* Set the nbf of this access token
*
* @param int $nbf nbf in epoch seconds of the grant
*
* @return $this updated access token
*/
public function setNbf(int $nbf): self {
$this->nbf = $nbf;
return $this;
}
/**
* Returns the nbf of the grant
*
* @return int the nbf in epoch seconds
*/
public function getNbf(): int {
return $this->nbf;
}
/**
* Set the region of this access token
*
* @param string $region Home region of the account sid in this access token
*
* @return $this updated access token
*/
public function setRegion(string $region): self {
$this->region = $region;
return $this;
}
/**
* Returns the region of this access token
*
* @return string Home region of the account sid in this access token
*/
public function getRegion(): string {
return $this->region;
}
/**
* Add a grant to the access token
*
* @param Grant $grant to be added
*
* @return $this the updated access token
*/
public function addGrant(Grant $grant): self {
$this->grants[] = $grant;
return $this;
}
/**
* Allows to set custom claims, which then will be encoded into JWT payload.
*
* @param string $name
* @param string $value
*/
public function addClaim(string $name, string $value): void {
$this->customClaims[$name] = $value;
}
public function toJWT(string $algorithm = 'HS256'): string {
$header = [
'cty' => 'twilio-fpa;v=1',
'typ' => 'JWT'
];
if ($this->region) {
$header['twr'] = $this->region;
}
$now = \time();
$grants = [];
if ($this->identity) {
$grants['identity'] = $this->identity;
}
foreach ($this->grants as $grant) {
$payload = $grant->getPayload();
if (empty($payload)) {
$payload = \json_decode('{}');
}
$grants[$grant->getGrantKey()] = $payload;
}
if (empty($grants)) {
$grants = \json_decode('{}');
}
$payload = \array_merge($this->customClaims, [
'jti' => $this->signingKeySid . '-' . $now,
'iss' => $this->signingKeySid,
'sub' => $this->accountSid,
'exp' => $now + $this->ttl,
'grants' => $grants
]);
if ($this->nbf !== null) {
$payload['nbf'] = $this->nbf;
}
return JWT::encode($payload, $this->secret, $algorithm, $header);
}
public function __toString(): string {
return $this->toJWT();
}
}

View File

@@ -0,0 +1,67 @@
<?php
namespace Twilio\Jwt\Client;
/**
* Scope URI implementation
*
* Simple way to represent configurable privileges in an OAuth
* friendly way. For our case, they look like this:
*
* scope:<service>:<privilege>?<params>
*
* For example:
* scope:client:incoming?name=jonas
*/
class ScopeURI {
public $service;
public $privilege;
public $params;
public function __construct(string $service, string $privilege, array $params = []) {
$this->service = $service;
$this->privilege = $privilege;
$this->params = $params;
}
public function toString(): string {
$uri = "scope:{$this->service}:{$this->privilege}";
if (\count($this->params)) {
$uri .= '?' . \http_build_query($this->params, '', '&');
}
return $uri;
}
/**
* Parse a scope URI into a ScopeURI object
*
* @param string $uri The scope URI
* @return ScopeURI The parsed scope uri
* @throws \UnexpectedValueException
*/
public static function parse(string $uri): ScopeURI {
if (\strpos($uri, 'scope:') !== 0) {
throw new \UnexpectedValueException(
'Not a scope URI according to scheme');
}
$parts = \explode('?', $uri, 1);
$params = null;
if (\count($parts) > 1) {
\parse_str($parts[1], $params);
}
$parts = \explode(':', $parts[0], 2);
if (\count($parts) !== 3) {
throw new \UnexpectedValueException(
'Not enough parts for scope URI');
}
[$scheme, $service, $privilege] = $parts;
return new ScopeURI($service, $privilege, $params);
}
}

View File

@@ -0,0 +1,128 @@
<?php
namespace Twilio\Jwt;
use Twilio\Jwt\Client\ScopeURI;
/**
* Twilio Capability Token generator
*/
class ClientToken {
public $accountSid;
public $authToken;
/** @var ScopeURI[] $scopes */
public $scopes;
public $clientName;
/** @var string[] $customClaims */
private $customClaims;
/**
* Create a new TwilioCapability with zero permissions. Next steps are to
* grant access to resources by configuring this token through the
* functions allowXXXX.
*
* @param string $accountSid the account sid to which this token is granted
* access
* @param string $authToken the secret key used to sign the token. Note,
* this auth token is not visible to the user of the token.
*/
public function __construct(string $accountSid, string $authToken) {
$this->accountSid = $accountSid;
$this->authToken = $authToken;
$this->scopes = [];
$this->clientName = false;
$this->customClaims = [];
}
/**
* If the user of this token should be allowed to accept incoming
* connections then configure the TwilioCapability through this method and
* specify the client name.
*
* @param string $clientName
* @throws \InvalidArgumentException
*/
public function allowClientIncoming(string $clientName): void {
// clientName must be a non-zero length alphanumeric string
if (\preg_match('/\W/', $clientName)) {
throw new \InvalidArgumentException(
'Only alphanumeric characters allowed in client name.');
}
if ($clientName === '') {
throw new \InvalidArgumentException(
'Client name must not be a zero length string.');
}
$this->clientName = $clientName;
$this->allow('client', 'incoming', ['clientName' => $clientName]);
}
/**
* Allow the user of this token to make outgoing connections.
*
* @param string $appSid the application to which this token grants access
* @param mixed[] $appParams signed parameters that the user of this token
* cannot overwrite.
*/
public function allowClientOutgoing(string $appSid, array $appParams = []): void {
$this->allow('client', 'outgoing', [
'appSid' => $appSid,
'appParams' => \http_build_query($appParams, '', '&')
]);
}
/**
* Allow the user of this token to access their event stream.
*
* @param mixed[] $filters key/value filters to apply to the event stream
*/
public function allowEventStream(array $filters = []): void {
$this->allow('stream', 'subscribe', [
'path' => '/2010-04-01/Events',
'params' => \http_build_query($filters, '', '&'),
]);
}
/**
* Allows to set custom claims, which then will be encoded into JWT payload.
*
* @param string $name
* @param string $value
*/
public function addClaim(string $name, string $value): void {
$this->customClaims[$name] = $value;
}
/**
* Generates a new token based on the credentials and permissions that
* previously has been granted to this token.
*
* @param int $ttl the expiration time of the token (in seconds). Default
* value is 3600 (1hr)
* @return string the newly generated token that is valid for $ttl seconds
*/
public function generateToken(int $ttl = 3600): string {
$payload = \array_merge($this->customClaims, [
'scope' => [],
'iss' => $this->accountSid,
'exp' => \time() + $ttl,
]);
$scopeStrings = [];
foreach ($this->scopes as $scope) {
if ($scope->privilege === 'outgoing' && $this->clientName) {
$scope->params['clientName'] = $this->clientName;
}
$scopeStrings[] = $scope->toString();
}
$payload['scope'] = \implode(' ', $scopeStrings);
return JWT::encode($payload, $this->authToken, 'HS256');
}
protected function allow(string $service, string $privilege, array $params): void {
$this->scopes[] = new ScopeURI($service, $privilege, $params);
}
}

View File

@@ -0,0 +1,128 @@
<?php
namespace Twilio\Jwt\Grants;
class ChatGrant implements Grant {
private $serviceSid;
private $endpointId;
private $deploymentRoleSid;
private $pushCredentialSid;
/**
* Returns the service sid
*
* @return string the service sid
*/
public function getServiceSid(): string {
return $this->serviceSid;
}
/**
* Set the service sid of this grant
*
* @param string $serviceSid service sid of the grant
*
* @return $this updated grant
*/
public function setServiceSid(string $serviceSid): self {
$this->serviceSid = $serviceSid;
return $this;
}
/**
* Returns the endpoint id of the grant
*
* @return string the endpoint id
*/
public function getEndpointId(): string {
return $this->endpointId;
}
/**
* Set the endpoint id of the grant
*
* @param string $endpointId endpoint id of the grant
*
* @return $this updated grant
*/
public function setEndpointId(string $endpointId): self {
$this->endpointId = $endpointId;
return $this;
}
/**
* Returns the deployment role sid of the grant
*
* @return string the deployment role sid
*/
public function getDeploymentRoleSid(): string {
return $this->deploymentRoleSid;
}
/**
* Set the role sid of the grant
*
* @param string $deploymentRoleSid role sid of the grant
*
* @return $this updated grant
*/
public function setDeploymentRoleSid(string $deploymentRoleSid): self {
$this->deploymentRoleSid = $deploymentRoleSid;
return $this;
}
/**
* Returns the push credential sid of the grant
*
* @return string the push credential sid
*/
public function getPushCredentialSid(): string {
return $this->pushCredentialSid;
}
/**
* Set the credential sid of the grant
*
* @param string $pushCredentialSid push credential sid of the grant
*
* @return $this updated grant
*/
public function setPushCredentialSid(string $pushCredentialSid): self {
$this->pushCredentialSid = $pushCredentialSid;
return $this;
}
/**
* Returns the grant type
*
* @return string type of the grant
*/
public function getGrantKey(): string {
return 'chat';
}
/**
* Returns the grant data
*
* @return array data of the grant
*/
public function getPayload(): array {
$payload = [];
if ($this->serviceSid) {
$payload['service_sid'] = $this->serviceSid;
}
if ($this->endpointId) {
$payload['endpoint_id'] = $this->endpointId;
}
if ($this->deploymentRoleSid) {
$payload['deployment_role_sid'] = $this->deploymentRoleSid;
}
if ($this->pushCredentialSid) {
$payload['push_credential_sid'] = $this->pushCredentialSid;
}
return $payload;
}
}

View File

@@ -0,0 +1,21 @@
<?php
namespace Twilio\Jwt\Grants;
interface Grant {
/**
* Returns the grant type
*
* @return string type of the grant
*/
public function getGrantKey(): string;
/**
* Returns the grant data
*
* @return array data of the grant
*/
public function getPayload(): array;
}

View File

@@ -0,0 +1,52 @@
<?php
namespace Twilio\Jwt\Grants;
class PlaybackGrant implements Grant {
private $grant;
/**
* Returns the grant
*
* @return array playback grant from the Twilio API
*/
public function getGrant(): array {
return $this->grant;
}
/**
* Set the playback grant that will allow access to a stream
*
* @param array $grant playback grant from Twilio API
* @return $this updated grant
*/
public function setGrant(array $grant): self {
$this->grant = $grant;
return $this;
}
/**
* Returns the grant type
*
* @return string type of the grant
*/
public function getGrantKey(): string {
return 'player';
}
/**
* Returns the grant data
*
* @return array data of the grant
*/
public function getPayload(): array {
$payload = [];
if ($this->grant) {
$payload = $this->grant;
}
return $payload;
}
}

View File

@@ -0,0 +1,126 @@
<?php
namespace Twilio\Jwt\Grants;
class SyncGrant implements Grant {
private $serviceSid;
private $endpointId;
private $deploymentRoleSid;
private $pushCredentialSid;
/**
* Returns the service sid
*
* @return string the service sid
*/
public function getServiceSid(): string {
return $this->serviceSid;
}
/**
* Set the service sid of this grant
*
* @param string $serviceSid service sid of the grant
*
* @return $this updated grant
*/
public function setServiceSid(string $serviceSid): self {
$this->serviceSid = $serviceSid;
return $this;
}
/**
* Returns the endpoint id of the grant
*
* @return string the endpoint id
*/
public function getEndpointId(): string {
return $this->endpointId;
}
/**
* Set the endpoint id of the grant
*
* @param string $endpointId endpoint id of the grant
*
* @return $this updated grant
*/
public function setEndpointId(string $endpointId): self {
$this->endpointId = $endpointId;
return $this;
}
/**
* Returns the deployment role sid of the grant
*
* @return string the deployment role sid
*/
public function getDeploymentRoleSid(): string {
return $this->deploymentRoleSid;
}
/**
* Set the role sid of the grant
*
* @param string $deploymentRoleSid role sid of the grant
*
* @return $this updated grant
*/
public function setDeploymentRoleSid(string $deploymentRoleSid): self {
$this->deploymentRoleSid = $deploymentRoleSid;
return $this;
}
/**
* Returns the push credential sid of the grant
*
* @return string the push credential sid
*/
public function getPushCredentialSid(): string {
return $this->pushCredentialSid;
}
/**
* Set the credential sid of the grant
*
* @param string $pushCredentialSid push credential sid of the grant
*
* @return $this updated grant
*/
public function setPushCredentialSid(string $pushCredentialSid): self {
$this->pushCredentialSid = $pushCredentialSid;
return $this;
}
/**
* Returns the grant type
*
* @return string type of the grant
*/
public function getGrantKey(): string {
return 'data_sync';
}
/**
* Returns the grant data
*
* @return array data of the grant
*/
public function getPayload(): array {
$payload = [];
if ($this->serviceSid) {
$payload['service_sid'] = $this->serviceSid;
}
if ($this->endpointId) {
$payload['endpoint_id'] = $this->endpointId;
}
if ($this->deploymentRoleSid) {
$payload['deployment_role_sid'] = $this->deploymentRoleSid;
}
if ($this->pushCredentialSid) {
$payload['push_credential_sid'] = $this->pushCredentialSid;
}
return $payload;
}
}

View File

@@ -0,0 +1,101 @@
<?php
namespace Twilio\Jwt\Grants;
class TaskRouterGrant implements Grant {
private $workspaceSid;
private $workerSid;
private $role;
/**
* Returns the workspace sid
*
* @return string the workspace sid
*/
public function getWorkspaceSid(): string {
return $this->workspaceSid;
}
/**
* Set the workspace sid of this grant
*
* @param string $workspaceSid workspace sid of the grant
*
* @return $this updated grant
*/
public function setWorkspaceSid(string $workspaceSid): self {
$this->workspaceSid = $workspaceSid;
return $this;
}
/**
* Returns the worker sid
*
* @return string the worker sid
*/
public function getWorkerSid(): string {
return $this->workerSid;
}
/**
* Set the worker sid of this grant
*
* @param string $workerSid worker sid of the grant
*
* @return $this updated grant
*/
public function setWorkerSid(string $workerSid): self {
$this->workerSid = $workerSid;
return $this;
}
/**
* Returns the role
*
* @return string the role
*/
public function getRole(): string {
return $this->role;
}
/**
* Set the role of this grant
*
* @param string $role role of the grant
*
* @return $this updated grant
*/
public function setRole(string $role): self {
$this->role = $role;
return $this;
}
/**
* Returns the grant type
*
* @return string type of the grant
*/
public function getGrantKey(): string {
return 'task_router';
}
/**
* Returns the grant data
*
* @return array data of the grant
*/
public function getPayload(): array {
$payload = [];
if ($this->workspaceSid) {
$payload['workspace_sid'] = $this->workspaceSid;
}
if ($this->workerSid) {
$payload['worker_sid'] = $this->workerSid;
}
if ($this->role) {
$payload['role'] = $this->role;
}
return $payload;
}
}

View File

@@ -0,0 +1,52 @@
<?php
namespace Twilio\Jwt\Grants;
class VideoGrant implements Grant {
private $room;
/**
* Returns the room
*
* @return string room name or sid set in this grant
*/
public function getRoom(): string {
return $this->room;
}
/**
* Set the room to allow access to in the grant
*
* @param string $roomSidOrName room sid or name
* @return $this updated grant
*/
public function setRoom(string $roomSidOrName): self {
$this->room = $roomSidOrName;
return $this;
}
/**
* Returns the grant type
*
* @return string type of the grant
*/
public function getGrantKey(): string {
return 'video';
}
/**
* Returns the grant data
*
* @return array data of the grant
*/
public function getPayload(): array {
$payload = [];
if ($this->room) {
$payload['room'] = $this->room;
}
return $payload;
}
}

View File

@@ -0,0 +1,165 @@
<?php
namespace Twilio\Jwt\Grants;
class VoiceGrant implements Grant {
private $incomingAllow;
private $outgoingApplicationSid;
private $outgoingApplicationParams;
private $pushCredentialSid;
private $endpointId;
/**
* Returns whether incoming is allowed
*
* @return bool whether incoming is allowed
*/
public function getIncomingAllow(): bool {
return $this->incomingAllow;
}
/**
* Set whether incoming is allowed
*
* @param bool $incomingAllow whether incoming is allowed
*
* @return $this updated grant
*/
public function setIncomingAllow(bool $incomingAllow): self {
$this->incomingAllow = $incomingAllow;
return $this;
}
/**
* Returns the outgoing application sid
*
* @return string the outgoing application sid
*/
public function getOutgoingApplicationSid(): string {
return $this->outgoingApplicationSid;
}
/**
* Set the outgoing application sid of the grant
*
* @param string $outgoingApplicationSid outgoing application sid of grant
*
* @return $this updated grant
*/
public function setOutgoingApplicationSid(string $outgoingApplicationSid): self {
$this->outgoingApplicationSid = $outgoingApplicationSid;
return $this;
}
/**
* Returns the outgoing application params
*
* @return array the outgoing application params
*/
public function getOutgoingApplicationParams(): array {
return $this->outgoingApplicationParams;
}
/**
* Set the outgoing application of the the grant
*
* @param string $sid outgoing application sid of the grant
* @param array $params params to pass the the application
*
* @return $this updated grant
*/
public function setOutgoingApplication(string $sid, array $params): self {
$this->outgoingApplicationSid = $sid;
$this->outgoingApplicationParams = $params;
return $this;
}
/**
* Returns the push credential sid
*
* @return string the push credential sid
*/
public function getPushCredentialSid(): string {
return $this->pushCredentialSid;
}
/**
* Set the push credential sid
*
* @param string $pushCredentialSid
*
* @return $this updated grant
*/
public function setPushCredentialSid(string $pushCredentialSid): self {
$this->pushCredentialSid = $pushCredentialSid;
return $this;
}
/**
* Returns the endpoint id
*
* @return string the endpoint id
*/
public function getEndpointId(): string {
return $this->endpointId;
}
/**
* Set the endpoint id
*
* @param string $endpointId endpoint id
*
* @return $this updated grant
*/
public function setEndpointId(string $endpointId): self {
$this->endpointId = $endpointId;
return $this;
}
/**
* Returns the grant type
*
* @return string type of the grant
*/
public function getGrantKey(): string {
return 'voice';
}
/**
* Returns the grant data
*
* @return array data of the grant
*/
public function getPayload(): array {
$payload = [];
if ($this->incomingAllow === true) {
$incoming = [];
$incoming['allow'] = true;
$payload['incoming'] = $incoming;
}
if ($this->outgoingApplicationSid) {
$outgoing = [];
$outgoing['application_sid'] = $this->outgoingApplicationSid;
if ($this->outgoingApplicationParams) {
$outgoing['params'] = $this->outgoingApplicationParams;
}
$payload['outgoing'] = $outgoing;
}
if ($this->pushCredentialSid) {
$payload['push_credential_sid'] = $this->pushCredentialSid;
}
if ($this->endpointId) {
$payload['endpoint_id'] = $this->endpointId;
}
return $payload;
}
}

172
vendor/twilio/sdk/src/Twilio/Jwt/JWT.php vendored Normal file
View File

@@ -0,0 +1,172 @@
<?php
namespace Twilio\Jwt;
/**
* JSON Web Token implementation
*
* Minimum implementation used by Realtime auth, based on this spec:
* http://self-issued.info/docs/draft-jones-json-web-token-01.html.
*
* @author Neuman Vong <neuman@twilio.com>
*/
class JWT {
/**
* @param string $jwt The JWT
* @param string|null $key The secret key
* @param bool $verify Don't skip verification process
* @return object The JWT's payload as a PHP object
* @throws \DomainException
* @throws \UnexpectedValueException
*/
public static function decode(string $jwt, ?string $key = null, bool $verify = true) {
$tks = \explode('.', $jwt);
if (\count($tks) !== 3) {
throw new \UnexpectedValueException('Wrong number of segments');
}
list($headb64, $payloadb64, $cryptob64) = $tks;
if (null === ($header = self::jsonDecode(self::urlsafeB64Decode($headb64)))
) {
throw new \UnexpectedValueException('Invalid segment encoding');
}
if (null === $payload = self::jsonDecode(self::urlsafeB64Decode($payloadb64))
) {
throw new \UnexpectedValueException('Invalid segment encoding');
}
$sig = self::urlsafeB64Decode($cryptob64);
if ($verify) {
if (empty($header->alg)) {
throw new \DomainException('Empty algorithm');
}
if (!hash_equals($sig, self::sign("$headb64.$payloadb64", $key, $header->alg))) {
throw new \UnexpectedValueException('Signature verification failed');
}
}
return $payload;
}
/**
* @param string $jwt The JWT
* @return object The JWT's header as a PHP object
* @throws \UnexpectedValueException
*/
public static function getHeader(string $jwt) {
$tks = \explode('.', $jwt);
if (\count($tks) !== 3) {
throw new \UnexpectedValueException('Wrong number of segments');
}
list($headb64) = $tks;
if (null === ($header = self::jsonDecode(self::urlsafeB64Decode($headb64)))
) {
throw new \UnexpectedValueException('Invalid segment encoding');
}
return $header;
}
/**
* @param object|array $payload PHP object or array
* @param string $key The secret key
* @param string $algo The signing algorithm
* @param array $additionalHeaders Additional keys/values to add to the header
*
* @return string A JWT
*/
public static function encode($payload, string $key, string $algo = 'HS256', array $additionalHeaders = []): string {
$header = ['typ' => 'JWT', 'alg' => $algo];
$header += $additionalHeaders;
$segments = [];
$segments[] = self::urlsafeB64Encode(self::jsonEncode($header));
$segments[] = self::urlsafeB64Encode(self::jsonEncode($payload));
$signing_input = \implode('.', $segments);
$signature = self::sign($signing_input, $key, $algo);
$segments[] = self::urlsafeB64Encode($signature);
return \implode('.', $segments);
}
/**
* @param string $msg The message to sign
* @param string $key The secret key
* @param string $method The signing algorithm
* @return string An encrypted message
* @throws \DomainException
*/
public static function sign(string $msg, string $key, string $method = 'HS256'): string {
$methods = [
'HS256' => 'sha256',
'HS384' => 'sha384',
'HS512' => 'sha512',
];
if (empty($methods[$method])) {
throw new \DomainException('Algorithm not supported');
}
return \hash_hmac($methods[$method], $msg, $key, true);
}
/**
* @param string $input JSON string
* @return object Object representation of JSON string
* @throws \DomainException
*/
public static function jsonDecode(string $input) {
$obj = \json_decode($input);
if (\function_exists('json_last_error') && $errno = \json_last_error()) {
self::handleJsonError($errno);
} else if ($obj === null && $input !== 'null') {
throw new \DomainException('Null result with non-null input');
}
return $obj;
}
/**
* @param object|array $input A PHP object or array
* @return string JSON representation of the PHP object or array
* @throws \DomainException
*/
public static function jsonEncode($input): string {
$json = \json_encode($input);
if (\function_exists('json_last_error') && $errno = \json_last_error()) {
self::handleJsonError($errno);
} else if ($json === 'null' && $input !== null) {
throw new \DomainException('Null result with non-null input');
}
return $json;
}
/**
* @param string $input A base64 encoded string
*
* @return string A decoded string
*/
public static function urlsafeB64Decode(string $input): string {
$padLen = 4 - \strlen($input) % 4;
$input .= \str_repeat('=', $padLen);
return \base64_decode(\strtr($input, '-_', '+/'));
}
/**
* @param string $input Anything really
*
* @return string The base64 encode of what you passed in
*/
public static function urlsafeB64Encode(string $input): string {
return \str_replace('=', '', \strtr(\base64_encode($input), '+/', '-_'));
}
/**
* @param int $errno An error number from json_last_error()
*
* @throws \DomainException
*/
private static function handleJsonError(int $errno): void {
$messages = [
JSON_ERROR_DEPTH => 'Maximum stack depth exceeded',
JSON_ERROR_CTRL_CHAR => 'Unexpected control character found',
JSON_ERROR_SYNTAX => 'Syntax error, malformed JSON'
];
throw new \DomainException($messages[$errno] ?? 'Unknown JSON error: ' . $errno);
}
}

View File

@@ -0,0 +1,161 @@
<?php
namespace Twilio\Jwt\TaskRouter;
use Twilio\Jwt\JWT;
/**
* Twilio TaskRouter Capability assigner
*
* @author Justin Witz <justin.witz@twilio.com>
* @license http://creativecommons.org/licenses/MIT/ MIT
*/
class CapabilityToken {
protected $accountSid;
protected $authToken;
private $friendlyName;
/** @var Policy[] $policies */
private $policies;
protected $baseUrl = 'https://taskrouter.twilio.com/v1';
protected $baseWsUrl = 'https://event-bridge.twilio.com/v1/wschannels';
protected $version = 'v1';
protected $workspaceSid;
protected $channelId;
protected $resourceUrl;
protected $required = ['required' => true];
protected $optional = ['required' => false];
public function __construct(string $accountSid, string $authToken, string $workspaceSid, string $channelId,
?string $resourceUrl = null, ?string $overrideBaseUrl = null, ?string $overrideBaseWSUrl = null) {
$this->accountSid = $accountSid;
$this->authToken = $authToken;
$this->friendlyName = $channelId;
$this->policies = [];
$this->workspaceSid = $workspaceSid;
$this->channelId = $channelId;
if (isset($overrideBaseUrl)) {
$this->baseUrl = $overrideBaseUrl;
}
if (isset($overrideBaseWSUrl)) {
$this->baseWsUrl = $overrideBaseWSUrl;
}
$this->baseUrl .= '/Workspaces/' . $workspaceSid;
$this->validateJWT();
if (!isset($resourceUrl)) {
$this->setupResource();
}
//add permissions to GET and POST to the event-bridge channel
$this->allow($this->baseWsUrl . '/' . $this->accountSid . '/' . $this->channelId, 'GET', null, null);
$this->allow($this->baseWsUrl . '/' . $this->accountSid . '/' . $this->channelId, 'POST', null, null);
//add permissions to fetch the instance resource
$this->allow($this->resourceUrl, 'GET', null, null);
}
protected function setupResource(): void {
}
public function addPolicyDeconstructed(string $url, string $method, ?array $queryFilter = [], ?array $postFilter = [], bool $allow = true): Policy {
$policy = new Policy($url, $method, $queryFilter, $postFilter, $allow);
$this->policies[] = $policy;
return $policy;
}
public function allow(string $url, string $method, ?array $queryFilter = [], ?array $postFilter = []): void {
$this->addPolicyDeconstructed($url, $method, $queryFilter, $postFilter, true);
}
public function deny(string $url, string $method, array $queryFilter = [], array $postFilter = []): void {
$this->addPolicyDeconstructed($url, $method, $queryFilter, $postFilter, false);
}
private function validateJWT(): void {
if (!isset($this->accountSid) || \strpos($this->accountSid, 'AC') !== 0) {
throw new \Exception('Invalid AccountSid provided: ' . $this->accountSid);
}
if (!isset($this->workspaceSid) || \strpos($this->workspaceSid, 'WS') !== 0) {
throw new \Exception('Invalid WorkspaceSid provided: ' . $this->workspaceSid);
}
if (!isset($this->channelId)) {
throw new \Exception('ChannelId not provided');
}
$prefix = \substr($this->channelId, 0, 2);
if ($prefix !== 'WS' && $prefix !== 'WK' && $prefix !== 'WQ') {
throw new \Exception("Invalid ChannelId provided: " . $this->channelId);
}
}
public function allowFetchSubresources(): void {
$method = 'GET';
$queryFilter = [];
$postFilter = [];
$this->allow($this->resourceUrl . '/**', $method, $queryFilter, $postFilter);
}
public function allowUpdates(): void {
$method = 'POST';
$queryFilter = [];
$postFilter = [];
$this->allow($this->resourceUrl, $method, $queryFilter, $postFilter);
}
public function allowUpdatesSubresources(): void {
$method = 'POST';
$queryFilter = [];
$postFilter = [];
$this->allow($this->resourceUrl . '/**', $method, $queryFilter, $postFilter);
}
public function allowDelete(): void {
$method = 'DELETE';
$queryFilter = [];
$postFilter = [];
$this->allow($this->resourceUrl, $method, $queryFilter, $postFilter);
}
public function allowDeleteSubresources(): void {
$method = 'DELETE';
$queryFilter = [];
$postFilter = [];
$this->allow($this->resourceUrl . '/**', $method, $queryFilter, $postFilter);
}
public function generateToken(int $ttl = 3600, array $extraAttributes = []): string {
$payload = [
'version' => $this->version,
'friendly_name' => $this->friendlyName,
'iss' => $this->accountSid,
'exp' => \time() + $ttl,
'account_sid' => $this->accountSid,
'channel' => $this->channelId,
'workspace_sid' => $this->workspaceSid
];
if (\strpos($this->channelId, 'WK') === 0) {
$payload['worker_sid'] = $this->channelId;
} else if (\strpos($this->channelId, 'WQ') === 0) {
$payload['taskqueue_sid'] = $this->channelId;
}
foreach ($extraAttributes as $key => $value) {
$payload[$key] = $value;
}
$policyStrings = [];
foreach ($this->policies as $policy) {
$policyStrings[] = $policy->toArray();
}
$payload['policies'] = $policyStrings;
return JWT::encode($payload, $this->authToken, 'HS256');
}
}

View File

@@ -0,0 +1,54 @@
<?php
namespace Twilio\Jwt\TaskRouter;
/**
* Twilio API Policy constructor
*
* @author Justin Witz <justin.witz@twilio.com>
* @license http://creativecommons.org/licenses/MIT/ MIT
*/
class Policy {
private $url;
private $method;
private $queryFilter;
private $postFilter;
private $allow;
public function __construct(string $url, string $method, ?array $queryFilter = [], ?array $postFilter = [], bool $allow = true) {
$this->url = $url;
$this->method = $method;
$this->queryFilter = $queryFilter;
$this->postFilter = $postFilter;
$this->allow = $allow;
}
public function addQueryFilter($queryFilter): void {
$this->queryFilter[] = $queryFilter;
}
public function addPostFilter($postFilter): void {
$this->postFilter[] = $postFilter;
}
public function toArray(): array {
$policy_array = ['url' => $this->url, 'method' => $this->method, 'allow' => $this->allow];
if ($this->queryFilter !== null) {
if (\count($this->queryFilter) > 0) {
$policy_array['query_filter'] = $this->queryFilter;
} else {
$policy_array['query_filter'] = new \stdClass();
}
}
if ($this->postFilter !== null) {
if (\count($this->postFilter) > 0) {
$policy_array['post_filter'] = $this->postFilter;
} else {
$policy_array['post_filter'] = new \stdClass();
}
}
return $policy_array;
}
}

View File

@@ -0,0 +1,21 @@
<?php
namespace Twilio\Jwt\TaskRouter;
/**
* Twilio TaskRouter TaskQueue Capability assigner
*
* @author Justin Witz <justin.witz@twilio.com>
* @license http://creativecommons.org/licenses/MIT/ MIT
*/
class TaskQueueCapability extends CapabilityToken {
public function __construct(string $accountSid, string $authToken, string $workspaceSid, string $taskQueueSid,
?string $overrideBaseUrl = null, ?string $overrideBaseWSUrl = null) {
parent::__construct($accountSid, $authToken, $workspaceSid, $taskQueueSid, null, $overrideBaseUrl, $overrideBaseWSUrl);
}
protected function setupResource(): void {
$this->resourceUrl = $this->baseUrl . '/TaskQueues/' . $this->channelId;
}
}

View File

@@ -0,0 +1,49 @@
<?php
namespace Twilio\Jwt\TaskRouter;
/**
* Twilio TaskRouter Worker Capability assigner
*
* @author Justin Witz <justin.witz@twilio.com>
* @license http://creativecommons.org/licenses/MIT/ MIT
*/
class WorkerCapability extends CapabilityToken {
private $tasksUrl;
private $workerReservationsUrl;
private $activityUrl;
public function __construct(string $accountSid, string $authToken, string $workspaceSid, string $workerSid,
?string $overrideBaseUrl = null, ?string $overrideBaseWSUrl = null) {
parent::__construct($accountSid, $authToken, $workspaceSid, $workerSid, null, $overrideBaseUrl, $overrideBaseWSUrl);
$this->tasksUrl = $this->baseUrl . '/Tasks/**';
$this->activityUrl = $this->baseUrl . '/Activities';
$this->workerReservationsUrl = $this->resourceUrl . '/Reservations/**';
//add permissions to fetch the list of activities, tasks, and worker reservations
$this->allow($this->activityUrl, 'GET', null, null);
$this->allow($this->tasksUrl, 'GET', null, null);
$this->allow($this->workerReservationsUrl, 'GET', null, null);
}
protected function setupResource(): void {
$this->resourceUrl = $this->baseUrl . '/Workers/' . $this->channelId;
}
public function allowActivityUpdates(): void {
$method = 'POST';
$queryFilter = [];
$postFilter = ['ActivitySid' => $this->required];
$this->allow($this->resourceUrl, $method, $queryFilter, $postFilter);
}
public function allowReservationUpdates(): void {
$method = 'POST';
$queryFilter = [];
$postFilter = [];
$this->allow($this->tasksUrl, $method, $queryFilter, $postFilter);
$this->allow($this->workerReservationsUrl, $method, $queryFilter, $postFilter);
}
}

View File

@@ -0,0 +1,16 @@
<?php
namespace Twilio\Jwt\TaskRouter;
class WorkspaceCapability extends CapabilityToken {
public function __construct(string $accountSid, string $authToken, string $workspaceSid,
?string $overrideBaseUrl = null, ?string $overrideBaseWSUrl = null) {
parent::__construct($accountSid, $authToken, $workspaceSid, $workspaceSid, null, $overrideBaseUrl, $overrideBaseWSUrl);
}
protected function setupResource(): void {
$this->resourceUrl = $this->baseUrl;
}
}

View File

@@ -0,0 +1,19 @@
<?php
namespace Twilio;
class ListResource {
protected $version;
protected $solution = [];
protected $uri;
public function __construct(Version $version) {
$this->version = $version;
}
public function __toString(): string {
return '[ListResource]';
}
}

View File

@@ -0,0 +1,13 @@
<?php
namespace Twilio;
abstract class Options implements \IteratorAggregate {
protected $options = [];
public function getIterator(): \Traversable {
return new \ArrayIterator($this->options);
}
}

203
vendor/twilio/sdk/src/Twilio/Page.php vendored Normal file
View File

@@ -0,0 +1,203 @@
<?php
namespace Twilio;
use Twilio\Exceptions\DeserializeException;
use Twilio\Exceptions\RestException;
use Twilio\Http\Response;
abstract class Page implements \Iterator {
protected static $metaKeys = [
'end',
'first_page_uri',
'next_page_uri',
'last_page_uri',
'page',
'page_size',
'previous_page_uri',
'total',
'num_pages',
'start',
'uri',
'totalResults',
'schemas'
];
protected $version;
protected $payload;
protected $solution;
protected $records;
abstract public function buildInstance(array $payload);
public function __construct(Version $version, Response $response) {
$payload = $this->processResponse($response);
$this->version = $version;
$this->payload = $payload;
$this->solution = [];
$this->records = new \ArrayIterator($this->loadPage());
}
protected function processResponse(Response $response) {
if ($response->getStatusCode() !== 200 && !$this->isPagingEol($response->getContent())) {
$message = '[HTTP ' . $response->getStatusCode() . '] Unable to fetch page';
$code = $response->getStatusCode();
$content = $response->getContent();
$details = [];
$moreInfo = '';
if (\is_array($content)) {
$message .= isset($content['message']) ? ': ' . $content['message'] : '';
$code = $content['code'] ?? $code;
$moreInfo = $content['more_info'] ?? '';
$details = $content['details'] ?? [] ;
}
throw new RestException($message, $code, $response->getStatusCode(), $moreInfo, $details);
}
return $response->getContent();
}
protected function isPagingEol(?array $content): bool {
return $content !== null && \array_key_exists('code', $content) && $content['code'] === 20006;
}
protected function hasMeta(string $key): bool {
return \array_key_exists('meta', $this->payload) && \array_key_exists($key, $this->payload['meta']);
}
protected function getMeta(string $key, ?string $default = null): ?string {
return $this->hasMeta($key) ? $this->payload['meta'][$key] : $default;
}
protected function loadPage(): array {
$key = $this->getMeta('key');
if ($key) {
return $this->payload[$key];
}
$keys = \array_keys($this->payload);
$key = \array_diff($keys, self::$metaKeys);
$key = \array_values($key);
if (\count($key) === 1) {
return $this->payload[$key[0]];
}
// handle end of results error code
if ($this->isPagingEol($this->payload)) {
return [];
}
throw new DeserializeException('Page Records can not be deserialized');
}
public function getPreviousPageUrl(): ?string {
if ($this->hasMeta('previous_page_url')) {
return $this->getMeta('previous_page_url');
}
if (\array_key_exists('previous_page_uri', $this->payload) && $this->payload['previous_page_uri']) {
return $this->getVersion()->getDomain()->absoluteUrl($this->payload['previous_page_uri']);
}
return null;
}
public function getNextPageUrl(): ?string {
if ($this->hasMeta('next_page_url')) {
return $this->getMeta('next_page_url');
}
if (\array_key_exists('next_page_uri', $this->payload) && $this->payload['next_page_uri']) {
return $this->getVersion()->getDomain()->absoluteUrl($this->payload['next_page_uri']);
}
return null;
}
public function nextPage(): ?Page {
if (!$this->getNextPageUrl()) {
return null;
}
$response = $this->getVersion()->getDomain()->getClient()->request('GET', $this->getNextPageUrl());
return new static($this->getVersion(), $response, $this->solution);
}
public function previousPage(): ?Page {
if (!$this->getPreviousPageUrl()) {
return null;
}
$response = $this->getVersion()->getDomain()->getClient()->request('GET', $this->getPreviousPageUrl());
return new static($this->getVersion(), $response, $this->solution);
}
/**
* (PHP 5 &gt;= 5.0.0)<br/>
* Return the current element
* @link http://php.net/manual/en/iterator.current.php
* @return mixed Can return any type.
*/
#[\ReturnTypeWillChange]
public function current() {
return $this->buildInstance($this->records->current());
}
/**
* (PHP 5 &gt;= 5.0.0)<br/>
* Move forward to next element
* @link http://php.net/manual/en/iterator.next.php
* @return void Any returned value is ignored.
*/
public function next(): void {
$this->records->next();
}
/**
* (PHP 5 &gt;= 5.0.0)<br/>
* Return the key of the current element
* @link http://php.net/manual/en/iterator.key.php
* @return mixed scalar on success, or null on failure.
*/
#[\ReturnTypeWillChange]
public function key() {
return $this->records->key();
}
/**
* (PHP 5 &gt;= 5.0.0)<br/>
* Checks if current position is valid
* @link http://php.net/manual/en/iterator.valid.php
* @return bool The return value will be casted to boolean and then evaluated.
* Returns true on success or false on failure.
*/
public function valid(): bool {
return $this->records->valid();
}
/**
* (PHP 5 &gt;= 5.0.0)<br/>
* Rewind the Iterator to the first element
* @link http://php.net/manual/en/iterator.rewind.php
* @return void Any returned value is ignored.
*/
public function rewind(): void {
$this->records->rewind();
}
public function getVersion(): Version {
return $this->version;
}
public function __toString(): string {
return '[Page]';
}
}

View File

@@ -0,0 +1,47 @@
<?php
namespace Twilio\Rest;
use Twilio\Rest\Accounts\V1;
class Accounts extends AccountsBase {
/**
* @deprecated Use v1->authTokenPromotion instead
*/
protected function getAuthTokenPromotion(): \Twilio\Rest\Accounts\V1\AuthTokenPromotionList {
echo "authTokenPromotion is deprecated. Use v1->authTokenPromotion instead.";
return $this->v1->authTokenPromotion;
}
/**
* @deprecated Use v1->authTokenPromotion() instead.
*/
protected function contextAuthTokenPromotion(): \Twilio\Rest\Accounts\V1\AuthTokenPromotionContext {
echo "authTokenPromotion() is deprecated. Use v1->authTokenPromotion() instead.";
return $this->v1->authTokenPromotion();
}
/**
* @deprecated Use v1->credentials instead.
*/
protected function getCredentials(): \Twilio\Rest\Accounts\V1\CredentialList {
echo "credentials is deprecated. Use v1->credentials instead.";
return $this->v1->credentials;
}
/**
* @deprecated Use v1->secondaryAuthToken instead.
*/
protected function getSecondaryAuthToken(): \Twilio\Rest\Accounts\V1\SecondaryAuthTokenList {
echo "secondaryAuthToken is deprecated. Use v1->secondaryAuthToken instead.";
return $this->v1->secondaryAuthToken;
}
/**
* @deprecated Use v1->secondaryAuthToken() instead.
*/
protected function contextSecondaryAuthToken(): \Twilio\Rest\Accounts\V1\SecondaryAuthTokenContext {
echo "secondaryAuthToken() is deprecated. Use v1->secondaryAuthToken() instead.";
return $this->v1->secondaryAuthToken();
}
}

View File

@@ -0,0 +1,160 @@
<?php
/**
* This code was generated by
* ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __
* | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/
* | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \
*
* Twilio - Accounts
* This is the public Twilio REST API.
*
* NOTE: This class is auto generated by OpenAPI Generator.
* https://openapi-generator.tech
* Do not edit the class manually.
*/
namespace Twilio\Rest\Accounts;
use Twilio\Domain;
use Twilio\Exceptions\TwilioException;
use Twilio\InstanceContext;
use Twilio\Rest\Accounts\V1\AuthTokenPromotionList;
use Twilio\Rest\Accounts\V1\BulkConsentsList;
use Twilio\Rest\Accounts\V1\BulkContactsList;
use Twilio\Rest\Accounts\V1\CredentialList;
use Twilio\Rest\Accounts\V1\MessagingGeopermissionsList;
use Twilio\Rest\Accounts\V1\SafelistList;
use Twilio\Rest\Accounts\V1\SecondaryAuthTokenList;
use Twilio\Version;
/**
* @property AuthTokenPromotionList $authTokenPromotion
* @property BulkConsentsList $bulkConsents
* @property BulkContactsList $bulkContacts
* @property CredentialList $credentials
* @property MessagingGeopermissionsList $messagingGeopermissions
* @property SafelistList $safelist
* @property SecondaryAuthTokenList $secondaryAuthToken
*/
class V1 extends Version
{
protected $_authTokenPromotion;
protected $_bulkConsents;
protected $_bulkContacts;
protected $_credentials;
protected $_messagingGeopermissions;
protected $_safelist;
protected $_secondaryAuthToken;
/**
* Construct the V1 version of Accounts
*
* @param Domain $domain Domain that contains the version
*/
public function __construct(Domain $domain)
{
parent::__construct($domain);
$this->version = 'v1';
}
protected function getAuthTokenPromotion(): AuthTokenPromotionList
{
if (!$this->_authTokenPromotion) {
$this->_authTokenPromotion = new AuthTokenPromotionList($this);
}
return $this->_authTokenPromotion;
}
protected function getBulkConsents(): BulkConsentsList
{
if (!$this->_bulkConsents) {
$this->_bulkConsents = new BulkConsentsList($this);
}
return $this->_bulkConsents;
}
protected function getBulkContacts(): BulkContactsList
{
if (!$this->_bulkContacts) {
$this->_bulkContacts = new BulkContactsList($this);
}
return $this->_bulkContacts;
}
protected function getCredentials(): CredentialList
{
if (!$this->_credentials) {
$this->_credentials = new CredentialList($this);
}
return $this->_credentials;
}
protected function getMessagingGeopermissions(): MessagingGeopermissionsList
{
if (!$this->_messagingGeopermissions) {
$this->_messagingGeopermissions = new MessagingGeopermissionsList($this);
}
return $this->_messagingGeopermissions;
}
protected function getSafelist(): SafelistList
{
if (!$this->_safelist) {
$this->_safelist = new SafelistList($this);
}
return $this->_safelist;
}
protected function getSecondaryAuthToken(): SecondaryAuthTokenList
{
if (!$this->_secondaryAuthToken) {
$this->_secondaryAuthToken = new SecondaryAuthTokenList($this);
}
return $this->_secondaryAuthToken;
}
/**
* Magic getter to lazy load root resources
*
* @param string $name Resource to return
* @return \Twilio\ListResource The requested resource
* @throws TwilioException For unknown resource
*/
public function __get(string $name)
{
$method = 'get' . \ucfirst($name);
if (\method_exists($this, $method)) {
return $this->$method();
}
throw new TwilioException('Unknown resource ' . $name);
}
/**
* Magic caller to get resource contexts
*
* @param string $name Resource to return
* @param array $arguments Context parameters
* @return InstanceContext The requested resource context
* @throws TwilioException For unknown resource
*/
public function __call(string $name, array $arguments): InstanceContext
{
$property = $this->$name;
if (\method_exists($property, 'getContext')) {
return \call_user_func_array(array($property, 'getContext'), $arguments);
}
throw new TwilioException('Resource does not have a context');
}
/**
* Provide a friendly representation
*
* @return string Machine friendly representation
*/
public function __toString(): string
{
return '[Twilio.Accounts.V1]';
}
}

View File

@@ -0,0 +1,77 @@
<?php
/**
* This code was generated by
* ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __
* | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/
* | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \
*
* Twilio - Accounts
* This is the public Twilio REST API.
*
* NOTE: This class is auto generated by OpenAPI Generator.
* https://openapi-generator.tech
* Do not edit the class manually.
*/
namespace Twilio\Rest\Accounts\V1;
use Twilio\Exceptions\TwilioException;
use Twilio\Values;
use Twilio\Version;
use Twilio\InstanceContext;
class AuthTokenPromotionContext extends InstanceContext
{
/**
* Initialize the AuthTokenPromotionContext
*
* @param Version $version Version that contains the resource
*/
public function __construct(
Version $version
) {
parent::__construct($version);
// Path Solution
$this->solution = [
];
$this->uri = '/AuthTokens/Promote';
}
/**
* Update the AuthTokenPromotionInstance
*
* @return AuthTokenPromotionInstance Updated AuthTokenPromotionInstance
* @throws TwilioException When an HTTP error occurs.
*/
public function update(): AuthTokenPromotionInstance
{
$headers = Values::of(['Content-Type' => 'application/x-www-form-urlencoded', 'Accept' => 'application/json' ]);
$payload = $this->version->update('POST', $this->uri, [], [], $headers);
return new AuthTokenPromotionInstance(
$this->version,
$payload
);
}
/**
* Provide a friendly representation
*
* @return string Machine friendly representation
*/
public function __toString(): string
{
$context = [];
foreach ($this->solution as $key => $value) {
$context[] = "$key=$value";
}
return '[Twilio.Accounts.V1.AuthTokenPromotionContext ' . \implode(' ', $context) . ']';
}
}

View File

@@ -0,0 +1,122 @@
<?php
/**
* This code was generated by
* ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __
* | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/
* | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \
*
* Twilio - Accounts
* This is the public Twilio REST API.
*
* NOTE: This class is auto generated by OpenAPI Generator.
* https://openapi-generator.tech
* Do not edit the class manually.
*/
namespace Twilio\Rest\Accounts\V1;
use Twilio\Exceptions\TwilioException;
use Twilio\InstanceResource;
use Twilio\Values;
use Twilio\Version;
use Twilio\Deserialize;
/**
* @property string|null $accountSid
* @property string|null $authToken
* @property \DateTime|null $dateCreated
* @property \DateTime|null $dateUpdated
* @property string|null $url
*/
class AuthTokenPromotionInstance extends InstanceResource
{
/**
* Initialize the AuthTokenPromotionInstance
*
* @param Version $version Version that contains the resource
* @param mixed[] $payload The response payload
*/
public function __construct(Version $version, array $payload)
{
parent::__construct($version);
// Marshaled Properties
$this->properties = [
'accountSid' => Values::array_get($payload, 'account_sid'),
'authToken' => Values::array_get($payload, 'auth_token'),
'dateCreated' => Deserialize::dateTime(Values::array_get($payload, 'date_created')),
'dateUpdated' => Deserialize::dateTime(Values::array_get($payload, 'date_updated')),
'url' => Values::array_get($payload, 'url'),
];
$this->solution = [];
}
/**
* Generate an instance context for the instance, the context is capable of
* performing various actions. All instance actions are proxied to the context
*
* @return AuthTokenPromotionContext Context for this AuthTokenPromotionInstance
*/
protected function proxy(): AuthTokenPromotionContext
{
if (!$this->context) {
$this->context = new AuthTokenPromotionContext(
$this->version
);
}
return $this->context;
}
/**
* Update the AuthTokenPromotionInstance
*
* @return AuthTokenPromotionInstance Updated AuthTokenPromotionInstance
* @throws TwilioException When an HTTP error occurs.
*/
public function update(): AuthTokenPromotionInstance
{
return $this->proxy()->update();
}
/**
* Magic getter to access properties
*
* @param string $name Property to access
* @return mixed The requested property
* @throws TwilioException For unknown properties
*/
public function __get(string $name)
{
if (\array_key_exists($name, $this->properties)) {
return $this->properties[$name];
}
if (\property_exists($this, '_' . $name)) {
$method = 'get' . \ucfirst($name);
return $this->$method();
}
throw new TwilioException('Unknown property: ' . $name);
}
/**
* Provide a friendly representation
*
* @return string Machine friendly representation
*/
public function __toString(): string
{
$context = [];
foreach ($this->solution as $key => $value) {
$context[] = "$key=$value";
}
return '[Twilio.Accounts.V1.AuthTokenPromotionInstance ' . \implode(' ', $context) . ']';
}
}

View File

@@ -0,0 +1,61 @@
<?php
/**
* This code was generated by
* ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __
* | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/
* | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \
*
* Twilio - Accounts
* This is the public Twilio REST API.
*
* NOTE: This class is auto generated by OpenAPI Generator.
* https://openapi-generator.tech
* Do not edit the class manually.
*/
namespace Twilio\Rest\Accounts\V1;
use Twilio\ListResource;
use Twilio\Version;
class AuthTokenPromotionList extends ListResource
{
/**
* Construct the AuthTokenPromotionList
*
* @param Version $version Version that contains the resource
*/
public function __construct(
Version $version
) {
parent::__construct($version);
// Path Solution
$this->solution = [
];
}
/**
* Constructs a AuthTokenPromotionContext
*/
public function getContext(
): AuthTokenPromotionContext
{
return new AuthTokenPromotionContext(
$this->version
);
}
/**
* Provide a friendly representation
*
* @return string Machine friendly representation
*/
public function __toString(): string
{
return '[Twilio.Accounts.V1.AuthTokenPromotionList]';
}
}

View File

@@ -0,0 +1,55 @@
<?php
/**
* This code was generated by
* ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __
* | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/
* | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \
*
* Twilio - Accounts
* This is the public Twilio REST API.
*
* NOTE: This class is auto generated by OpenAPI Generator.
* https://openapi-generator.tech
* Do not edit the class manually.
*/
namespace Twilio\Rest\Accounts\V1;
use Twilio\Http\Response;
use Twilio\Page;
use Twilio\Version;
class AuthTokenPromotionPage extends Page
{
/**
* @param Version $version Version that contains the resource
* @param Response $response Response from the API
* @param array $solution The context solution
*/
public function __construct(Version $version, Response $response, array $solution)
{
parent::__construct($version, $response);
// Path Solution
$this->solution = $solution;
}
/**
* @param array $payload Payload response from the API
* @return AuthTokenPromotionInstance \Twilio\Rest\Accounts\V1\AuthTokenPromotionInstance
*/
public function buildInstance(array $payload): AuthTokenPromotionInstance
{
return new AuthTokenPromotionInstance($this->version, $payload);
}
/**
* Provide a friendly representation
*
* @return string Machine friendly representation
*/
public function __toString(): string
{
return '[Twilio.Accounts.V1.AuthTokenPromotionPage]';
}
}

View File

@@ -0,0 +1,80 @@
<?php
/**
* This code was generated by
* ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __
* | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/
* | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \
*
* Twilio - Accounts
* This is the public Twilio REST API.
*
* NOTE: This class is auto generated by OpenAPI Generator.
* https://openapi-generator.tech
* Do not edit the class manually.
*/
namespace Twilio\Rest\Accounts\V1;
use Twilio\Exceptions\TwilioException;
use Twilio\InstanceResource;
use Twilio\Values;
use Twilio\Version;
/**
* @property array|null $items
*/
class BulkConsentsInstance extends InstanceResource
{
/**
* Initialize the BulkConsentsInstance
*
* @param Version $version Version that contains the resource
* @param mixed[] $payload The response payload
*/
public function __construct(Version $version, array $payload)
{
parent::__construct($version);
// Marshaled Properties
$this->properties = [
'items' => Values::array_get($payload, 'items'),
];
$this->solution = [];
}
/**
* Magic getter to access properties
*
* @param string $name Property to access
* @return mixed The requested property
* @throws TwilioException For unknown properties
*/
public function __get(string $name)
{
if (\array_key_exists($name, $this->properties)) {
return $this->properties[$name];
}
if (\property_exists($this, '_' . $name)) {
$method = 'get' . \ucfirst($name);
return $this->$method();
}
throw new TwilioException('Unknown property: ' . $name);
}
/**
* Provide a friendly representation
*
* @return string Machine friendly representation
*/
public function __toString(): string
{
return '[Twilio.Accounts.V1.BulkConsentsInstance]';
}
}

View File

@@ -0,0 +1,79 @@
<?php
/**
* This code was generated by
* ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __
* | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/
* | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \
*
* Twilio - Accounts
* This is the public Twilio REST API.
*
* NOTE: This class is auto generated by OpenAPI Generator.
* https://openapi-generator.tech
* Do not edit the class manually.
*/
namespace Twilio\Rest\Accounts\V1;
use Twilio\Exceptions\TwilioException;
use Twilio\ListResource;
use Twilio\Values;
use Twilio\Version;
use Twilio\Serialize;
class BulkConsentsList extends ListResource
{
/**
* Construct the BulkConsentsList
*
* @param Version $version Version that contains the resource
*/
public function __construct(
Version $version
) {
parent::__construct($version);
// Path Solution
$this->solution = [
];
$this->uri = '/Consents/Bulk';
}
/**
* Create the BulkConsentsInstance
*
* @param array[] $items This is a list of objects that describes a contact's opt-in status. Each object contains the following fields: `contact_id`, which must be a string representing phone number in [E.164 format](https://www.twilio.com/docs/glossary/what-e164); `correlation_id`, a unique 32-character UUID used to uniquely map the request item with the response item; `sender_id`, which can be either a valid messaging service SID or a from phone number; `status`, a string representing the consent status. Can be one of [`opt-in`, `opt-out`]; `source`, a string indicating the medium through which the consent was collected. Can be one of [`website`, `offline`, `opt-in-message`, `opt-out-message`, `others`]; `date_of_consent`, an optional datetime string field in ISO-8601 format that captures the exact date and time when the user gave or revoked consent. If not provided, it will be empty.
* @return BulkConsentsInstance Created BulkConsentsInstance
* @throws TwilioException When an HTTP error occurs.
*/
public function create(array $items): BulkConsentsInstance
{
$data = Values::of([
'Items' =>
Serialize::map($items,function ($e) { return Serialize::jsonObject($e); }),
]);
$headers = Values::of(['Content-Type' => 'application/x-www-form-urlencoded', 'Accept' => 'application/json' ]);
$payload = $this->version->create('POST', $this->uri, [], $data, $headers);
return new BulkConsentsInstance(
$this->version,
$payload
);
}
/**
* Provide a friendly representation
*
* @return string Machine friendly representation
*/
public function __toString(): string
{
return '[Twilio.Accounts.V1.BulkConsentsList]';
}
}

View File

@@ -0,0 +1,55 @@
<?php
/**
* This code was generated by
* ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __
* | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/
* | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \
*
* Twilio - Accounts
* This is the public Twilio REST API.
*
* NOTE: This class is auto generated by OpenAPI Generator.
* https://openapi-generator.tech
* Do not edit the class manually.
*/
namespace Twilio\Rest\Accounts\V1;
use Twilio\Http\Response;
use Twilio\Page;
use Twilio\Version;
class BulkConsentsPage extends Page
{
/**
* @param Version $version Version that contains the resource
* @param Response $response Response from the API
* @param array $solution The context solution
*/
public function __construct(Version $version, Response $response, array $solution)
{
parent::__construct($version, $response);
// Path Solution
$this->solution = $solution;
}
/**
* @param array $payload Payload response from the API
* @return BulkConsentsInstance \Twilio\Rest\Accounts\V1\BulkConsentsInstance
*/
public function buildInstance(array $payload): BulkConsentsInstance
{
return new BulkConsentsInstance($this->version, $payload);
}
/**
* Provide a friendly representation
*
* @return string Machine friendly representation
*/
public function __toString(): string
{
return '[Twilio.Accounts.V1.BulkConsentsPage]';
}
}

View File

@@ -0,0 +1,80 @@
<?php
/**
* This code was generated by
* ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __
* | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/
* | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \
*
* Twilio - Accounts
* This is the public Twilio REST API.
*
* NOTE: This class is auto generated by OpenAPI Generator.
* https://openapi-generator.tech
* Do not edit the class manually.
*/
namespace Twilio\Rest\Accounts\V1;
use Twilio\Exceptions\TwilioException;
use Twilio\InstanceResource;
use Twilio\Values;
use Twilio\Version;
/**
* @property array|null $items
*/
class BulkContactsInstance extends InstanceResource
{
/**
* Initialize the BulkContactsInstance
*
* @param Version $version Version that contains the resource
* @param mixed[] $payload The response payload
*/
public function __construct(Version $version, array $payload)
{
parent::__construct($version);
// Marshaled Properties
$this->properties = [
'items' => Values::array_get($payload, 'items'),
];
$this->solution = [];
}
/**
* Magic getter to access properties
*
* @param string $name Property to access
* @return mixed The requested property
* @throws TwilioException For unknown properties
*/
public function __get(string $name)
{
if (\array_key_exists($name, $this->properties)) {
return $this->properties[$name];
}
if (\property_exists($this, '_' . $name)) {
$method = 'get' . \ucfirst($name);
return $this->$method();
}
throw new TwilioException('Unknown property: ' . $name);
}
/**
* Provide a friendly representation
*
* @return string Machine friendly representation
*/
public function __toString(): string
{
return '[Twilio.Accounts.V1.BulkContactsInstance]';
}
}

View File

@@ -0,0 +1,79 @@
<?php
/**
* This code was generated by
* ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __
* | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/
* | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \
*
* Twilio - Accounts
* This is the public Twilio REST API.
*
* NOTE: This class is auto generated by OpenAPI Generator.
* https://openapi-generator.tech
* Do not edit the class manually.
*/
namespace Twilio\Rest\Accounts\V1;
use Twilio\Exceptions\TwilioException;
use Twilio\ListResource;
use Twilio\Values;
use Twilio\Version;
use Twilio\Serialize;
class BulkContactsList extends ListResource
{
/**
* Construct the BulkContactsList
*
* @param Version $version Version that contains the resource
*/
public function __construct(
Version $version
) {
parent::__construct($version);
// Path Solution
$this->solution = [
];
$this->uri = '/Contacts/Bulk';
}
/**
* Create the BulkContactsInstance
*
* @param array[] $items A list of objects where each object represents a contact's details. Each object includes the following fields: `contact_id`, which must be a string representing phone number in [E.164 format](https://www.twilio.com/docs/glossary/what-e164); `correlation_id`, a unique 32-character UUID that maps the response to the original request; `country_iso_code`, a string representing the country using the ISO format (e.g., US for the United States); and `zip_code`, a string representing the postal code.
* @return BulkContactsInstance Created BulkContactsInstance
* @throws TwilioException When an HTTP error occurs.
*/
public function create(array $items): BulkContactsInstance
{
$data = Values::of([
'Items' =>
Serialize::map($items,function ($e) { return Serialize::jsonObject($e); }),
]);
$headers = Values::of(['Content-Type' => 'application/x-www-form-urlencoded', 'Accept' => 'application/json' ]);
$payload = $this->version->create('POST', $this->uri, [], $data, $headers);
return new BulkContactsInstance(
$this->version,
$payload
);
}
/**
* Provide a friendly representation
*
* @return string Machine friendly representation
*/
public function __toString(): string
{
return '[Twilio.Accounts.V1.BulkContactsList]';
}
}

View File

@@ -0,0 +1,55 @@
<?php
/**
* This code was generated by
* ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __
* | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/
* | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \
*
* Twilio - Accounts
* This is the public Twilio REST API.
*
* NOTE: This class is auto generated by OpenAPI Generator.
* https://openapi-generator.tech
* Do not edit the class manually.
*/
namespace Twilio\Rest\Accounts\V1;
use Twilio\Http\Response;
use Twilio\Page;
use Twilio\Version;
class BulkContactsPage extends Page
{
/**
* @param Version $version Version that contains the resource
* @param Response $response Response from the API
* @param array $solution The context solution
*/
public function __construct(Version $version, Response $response, array $solution)
{
parent::__construct($version, $response);
// Path Solution
$this->solution = $solution;
}
/**
* @param array $payload Payload response from the API
* @return BulkContactsInstance \Twilio\Rest\Accounts\V1\BulkContactsInstance
*/
public function buildInstance(array $payload): BulkContactsInstance
{
return new BulkContactsInstance($this->version, $payload);
}
/**
* Provide a friendly representation
*
* @return string Machine friendly representation
*/
public function __toString(): string
{
return '[Twilio.Accounts.V1.BulkContactsPage]';
}
}

View File

@@ -0,0 +1,126 @@
<?php
/**
* This code was generated by
* ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __
* | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/
* | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \
*
* Twilio - Accounts
* This is the public Twilio REST API.
*
* NOTE: This class is auto generated by OpenAPI Generator.
* https://openapi-generator.tech
* Do not edit the class manually.
*/
namespace Twilio\Rest\Accounts\V1\Credential;
use Twilio\Exceptions\TwilioException;
use Twilio\Options;
use Twilio\Values;
use Twilio\Version;
use Twilio\InstanceContext;
class AwsContext extends InstanceContext
{
/**
* Initialize the AwsContext
*
* @param Version $version Version that contains the resource
* @param string $sid The Twilio-provided string that uniquely identifies the AWS resource to delete.
*/
public function __construct(
Version $version,
$sid
) {
parent::__construct($version);
// Path Solution
$this->solution = [
'sid' =>
$sid,
];
$this->uri = '/Credentials/AWS/' . \rawurlencode($sid)
.'';
}
/**
* Delete the AwsInstance
*
* @return bool True if delete succeeds, false otherwise
* @throws TwilioException When an HTTP error occurs.
*/
public function delete(): bool
{
$headers = Values::of(['Content-Type' => 'application/x-www-form-urlencoded' ]);
return $this->version->delete('DELETE', $this->uri, [], [], $headers);
}
/**
* Fetch the AwsInstance
*
* @return AwsInstance Fetched AwsInstance
* @throws TwilioException When an HTTP error occurs.
*/
public function fetch(): AwsInstance
{
$headers = Values::of(['Content-Type' => 'application/x-www-form-urlencoded', 'Accept' => 'application/json' ]);
$payload = $this->version->fetch('GET', $this->uri, [], [], $headers);
return new AwsInstance(
$this->version,
$payload,
$this->solution['sid']
);
}
/**
* Update the AwsInstance
*
* @param array|Options $options Optional Arguments
* @return AwsInstance Updated AwsInstance
* @throws TwilioException When an HTTP error occurs.
*/
public function update(array $options = []): AwsInstance
{
$options = new Values($options);
$data = Values::of([
'FriendlyName' =>
$options['friendlyName'],
]);
$headers = Values::of(['Content-Type' => 'application/x-www-form-urlencoded', 'Accept' => 'application/json' ]);
$payload = $this->version->update('POST', $this->uri, [], $data, $headers);
return new AwsInstance(
$this->version,
$payload,
$this->solution['sid']
);
}
/**
* Provide a friendly representation
*
* @return string Machine friendly representation
*/
public function __toString(): string
{
$context = [];
foreach ($this->solution as $key => $value) {
$context[] = "$key=$value";
}
return '[Twilio.Accounts.V1.AwsContext ' . \implode(' ', $context) . ']';
}
}

View File

@@ -0,0 +1,152 @@
<?php
/**
* This code was generated by
* ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __
* | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/
* | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \
*
* Twilio - Accounts
* This is the public Twilio REST API.
*
* NOTE: This class is auto generated by OpenAPI Generator.
* https://openapi-generator.tech
* Do not edit the class manually.
*/
namespace Twilio\Rest\Accounts\V1\Credential;
use Twilio\Exceptions\TwilioException;
use Twilio\InstanceResource;
use Twilio\Options;
use Twilio\Values;
use Twilio\Version;
use Twilio\Deserialize;
/**
* @property string|null $sid
* @property string|null $accountSid
* @property string|null $friendlyName
* @property \DateTime|null $dateCreated
* @property \DateTime|null $dateUpdated
* @property string|null $url
*/
class AwsInstance extends InstanceResource
{
/**
* Initialize the AwsInstance
*
* @param Version $version Version that contains the resource
* @param mixed[] $payload The response payload
* @param string $sid The Twilio-provided string that uniquely identifies the AWS resource to delete.
*/
public function __construct(Version $version, array $payload, ?string $sid = null)
{
parent::__construct($version);
// Marshaled Properties
$this->properties = [
'sid' => Values::array_get($payload, 'sid'),
'accountSid' => Values::array_get($payload, 'account_sid'),
'friendlyName' => Values::array_get($payload, 'friendly_name'),
'dateCreated' => Deserialize::dateTime(Values::array_get($payload, 'date_created')),
'dateUpdated' => Deserialize::dateTime(Values::array_get($payload, 'date_updated')),
'url' => Values::array_get($payload, 'url'),
];
$this->solution = ['sid' => $sid ?: $this->properties['sid'], ];
}
/**
* Generate an instance context for the instance, the context is capable of
* performing various actions. All instance actions are proxied to the context
*
* @return AwsContext Context for this AwsInstance
*/
protected function proxy(): AwsContext
{
if (!$this->context) {
$this->context = new AwsContext(
$this->version,
$this->solution['sid']
);
}
return $this->context;
}
/**
* Delete the AwsInstance
*
* @return bool True if delete succeeds, false otherwise
* @throws TwilioException When an HTTP error occurs.
*/
public function delete(): bool
{
return $this->proxy()->delete();
}
/**
* Fetch the AwsInstance
*
* @return AwsInstance Fetched AwsInstance
* @throws TwilioException When an HTTP error occurs.
*/
public function fetch(): AwsInstance
{
return $this->proxy()->fetch();
}
/**
* Update the AwsInstance
*
* @param array|Options $options Optional Arguments
* @return AwsInstance Updated AwsInstance
* @throws TwilioException When an HTTP error occurs.
*/
public function update(array $options = []): AwsInstance
{
return $this->proxy()->update($options);
}
/**
* Magic getter to access properties
*
* @param string $name Property to access
* @return mixed The requested property
* @throws TwilioException For unknown properties
*/
public function __get(string $name)
{
if (\array_key_exists($name, $this->properties)) {
return $this->properties[$name];
}
if (\property_exists($this, '_' . $name)) {
$method = 'get' . \ucfirst($name);
return $this->$method();
}
throw new TwilioException('Unknown property: ' . $name);
}
/**
* Provide a friendly representation
*
* @return string Machine friendly representation
*/
public function __toString(): string
{
$context = [];
foreach ($this->solution as $key => $value) {
$context[] = "$key=$value";
}
return '[Twilio.Accounts.V1.AwsInstance ' . \implode(' ', $context) . ']';
}
}

View File

@@ -0,0 +1,196 @@
<?php
/**
* This code was generated by
* ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __
* | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/
* | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \
*
* Twilio - Accounts
* This is the public Twilio REST API.
*
* NOTE: This class is auto generated by OpenAPI Generator.
* https://openapi-generator.tech
* Do not edit the class manually.
*/
namespace Twilio\Rest\Accounts\V1\Credential;
use Twilio\Exceptions\TwilioException;
use Twilio\ListResource;
use Twilio\Options;
use Twilio\Stream;
use Twilio\Values;
use Twilio\Version;
class AwsList extends ListResource
{
/**
* Construct the AwsList
*
* @param Version $version Version that contains the resource
*/
public function __construct(
Version $version
) {
parent::__construct($version);
// Path Solution
$this->solution = [
];
$this->uri = '/Credentials/AWS';
}
/**
* Create the AwsInstance
*
* @param string $credentials A string that contains the AWS access credentials in the format `<AWS_ACCESS_KEY_ID>:<AWS_SECRET_ACCESS_KEY>`. For example, `AKIAIOSFODNN7EXAMPLE:wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY`
* @param array|Options $options Optional Arguments
* @return AwsInstance Created AwsInstance
* @throws TwilioException When an HTTP error occurs.
*/
public function create(string $credentials, array $options = []): AwsInstance
{
$options = new Values($options);
$data = Values::of([
'Credentials' =>
$credentials,
'FriendlyName' =>
$options['friendlyName'],
'AccountSid' =>
$options['accountSid'],
]);
$headers = Values::of(['Content-Type' => 'application/x-www-form-urlencoded', 'Accept' => 'application/json' ]);
$payload = $this->version->create('POST', $this->uri, [], $data, $headers);
return new AwsInstance(
$this->version,
$payload
);
}
/**
* Reads AwsInstance records from the API as a list.
* Unlike stream(), this operation is eager and will load `limit` records into
* memory before returning.
*
* @param int $limit Upper limit for the number of records to return. read()
* guarantees to never return more than limit. Default is no
* limit
* @param mixed $pageSize Number of records to fetch per request, when not set
* will use the default value of 50 records. If no
* page_size is defined but a limit is defined, read()
* will attempt to read the limit with the most
* efficient page size, i.e. min(limit, 1000)
* @return AwsInstance[] Array of results
*/
public function read(?int $limit = null, $pageSize = null): array
{
return \iterator_to_array($this->stream($limit, $pageSize), false);
}
/**
* Streams AwsInstance records from the API as a generator stream.
* This operation lazily loads records as efficiently as possible until the
* limit
* is reached.
* The results are returned as a generator, so this operation is memory
* efficient.
*
* @param int $limit Upper limit for the number of records to return. stream()
* guarantees to never return more than limit. Default is no
* limit
* @param mixed $pageSize Number of records to fetch per request, when not set
* will use the default value of 50 records. If no
* page_size is defined but a limit is defined, stream()
* will attempt to read the limit with the most
* efficient page size, i.e. min(limit, 1000)
* @return Stream stream of results
*/
public function stream(?int $limit = null, $pageSize = null): Stream
{
$limits = $this->version->readLimits($limit, $pageSize);
$page = $this->page($limits['pageSize']);
return $this->version->stream($page, $limits['limit'], $limits['pageLimit']);
}
/**
* Retrieve a single page of AwsInstance records from the API.
* Request is executed immediately
*
* @param mixed $pageSize Number of records to return, defaults to 50
* @param string $pageToken PageToken provided by the API
* @param mixed $pageNumber Page Number, this value is simply for client state
* @return AwsPage Page of AwsInstance
*/
public function page(
$pageSize = Values::NONE,
string $pageToken = Values::NONE,
$pageNumber = Values::NONE
): AwsPage
{
$params = Values::of([
'PageToken' => $pageToken,
'Page' => $pageNumber,
'PageSize' => $pageSize,
]);
$headers = Values::of(['Content-Type' => 'application/x-www-form-urlencoded', 'Accept' => 'application/json']);
$response = $this->version->page('GET', $this->uri, $params, [], $headers);
return new AwsPage($this->version, $response, $this->solution);
}
/**
* Retrieve a specific page of AwsInstance records from the API.
* Request is executed immediately
*
* @param string $targetUrl API-generated URL for the requested results page
* @return AwsPage Page of AwsInstance
*/
public function getPage(string $targetUrl): AwsPage
{
$response = $this->version->getDomain()->getClient()->request(
'GET',
$targetUrl
);
return new AwsPage($this->version, $response, $this->solution);
}
/**
* Constructs a AwsContext
*
* @param string $sid The Twilio-provided string that uniquely identifies the AWS resource to delete.
*/
public function getContext(
string $sid
): AwsContext
{
return new AwsContext(
$this->version,
$sid
);
}
/**
* Provide a friendly representation
*
* @return string Machine friendly representation
*/
public function __toString(): string
{
return '[Twilio.Accounts.V1.AwsList]';
}
}

View File

@@ -0,0 +1,152 @@
<?php
/**
* This code was generated by
* ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __
* | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/
* | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \
*
* Twilio - Accounts
* This is the public Twilio REST API.
*
* NOTE: This class is auto generated by OpenAPI Generator.
* https://openapi-generator.tech
* Do not edit the class manually.
*/
namespace Twilio\Rest\Accounts\V1\Credential;
use Twilio\Options;
use Twilio\Values;
abstract class AwsOptions
{
/**
* @param string $friendlyName A descriptive string that you create to describe the resource. It can be up to 64 characters long.
* @param string $accountSid The SID of the Subaccount that this Credential should be associated with. Must be a valid Subaccount of the account issuing the request.
* @return CreateAwsOptions Options builder
*/
public static function create(
string $friendlyName = Values::NONE,
string $accountSid = Values::NONE
): CreateAwsOptions
{
return new CreateAwsOptions(
$friendlyName,
$accountSid
);
}
/**
* @param string $friendlyName A descriptive string that you create to describe the resource. It can be up to 64 characters long.
* @return UpdateAwsOptions Options builder
*/
public static function update(
string $friendlyName = Values::NONE
): UpdateAwsOptions
{
return new UpdateAwsOptions(
$friendlyName
);
}
}
class CreateAwsOptions extends Options
{
/**
* @param string $friendlyName A descriptive string that you create to describe the resource. It can be up to 64 characters long.
* @param string $accountSid The SID of the Subaccount that this Credential should be associated with. Must be a valid Subaccount of the account issuing the request.
*/
public function __construct(
string $friendlyName = Values::NONE,
string $accountSid = Values::NONE
) {
$this->options['friendlyName'] = $friendlyName;
$this->options['accountSid'] = $accountSid;
}
/**
* A descriptive string that you create to describe the resource. It can be up to 64 characters long.
*
* @param string $friendlyName A descriptive string that you create to describe the resource. It can be up to 64 characters long.
* @return $this Fluent Builder
*/
public function setFriendlyName(string $friendlyName): self
{
$this->options['friendlyName'] = $friendlyName;
return $this;
}
/**
* The SID of the Subaccount that this Credential should be associated with. Must be a valid Subaccount of the account issuing the request.
*
* @param string $accountSid The SID of the Subaccount that this Credential should be associated with. Must be a valid Subaccount of the account issuing the request.
* @return $this Fluent Builder
*/
public function setAccountSid(string $accountSid): self
{
$this->options['accountSid'] = $accountSid;
return $this;
}
/**
* Provide a friendly representation
*
* @return string Machine friendly representation
*/
public function __toString(): string
{
$options = \http_build_query(Values::of($this->options), '', ' ');
return '[Twilio.Accounts.V1.CreateAwsOptions ' . $options . ']';
}
}
class UpdateAwsOptions extends Options
{
/**
* @param string $friendlyName A descriptive string that you create to describe the resource. It can be up to 64 characters long.
*/
public function __construct(
string $friendlyName = Values::NONE
) {
$this->options['friendlyName'] = $friendlyName;
}
/**
* A descriptive string that you create to describe the resource. It can be up to 64 characters long.
*
* @param string $friendlyName A descriptive string that you create to describe the resource. It can be up to 64 characters long.
* @return $this Fluent Builder
*/
public function setFriendlyName(string $friendlyName): self
{
$this->options['friendlyName'] = $friendlyName;
return $this;
}
/**
* Provide a friendly representation
*
* @return string Machine friendly representation
*/
public function __toString(): string
{
$options = \http_build_query(Values::of($this->options), '', ' ');
return '[Twilio.Accounts.V1.UpdateAwsOptions ' . $options . ']';
}
}

View File

@@ -0,0 +1,55 @@
<?php
/**
* This code was generated by
* ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __
* | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/
* | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \
*
* Twilio - Accounts
* This is the public Twilio REST API.
*
* NOTE: This class is auto generated by OpenAPI Generator.
* https://openapi-generator.tech
* Do not edit the class manually.
*/
namespace Twilio\Rest\Accounts\V1\Credential;
use Twilio\Http\Response;
use Twilio\Page;
use Twilio\Version;
class AwsPage extends Page
{
/**
* @param Version $version Version that contains the resource
* @param Response $response Response from the API
* @param array $solution The context solution
*/
public function __construct(Version $version, Response $response, array $solution)
{
parent::__construct($version, $response);
// Path Solution
$this->solution = $solution;
}
/**
* @param array $payload Payload response from the API
* @return AwsInstance \Twilio\Rest\Accounts\V1\Credential\AwsInstance
*/
public function buildInstance(array $payload): AwsInstance
{
return new AwsInstance($this->version, $payload);
}
/**
* Provide a friendly representation
*
* @return string Machine friendly representation
*/
public function __toString(): string
{
return '[Twilio.Accounts.V1.AwsPage]';
}
}

View File

@@ -0,0 +1,126 @@
<?php
/**
* This code was generated by
* ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __
* | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/
* | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \
*
* Twilio - Accounts
* This is the public Twilio REST API.
*
* NOTE: This class is auto generated by OpenAPI Generator.
* https://openapi-generator.tech
* Do not edit the class manually.
*/
namespace Twilio\Rest\Accounts\V1\Credential;
use Twilio\Exceptions\TwilioException;
use Twilio\Options;
use Twilio\Values;
use Twilio\Version;
use Twilio\InstanceContext;
class PublicKeyContext extends InstanceContext
{
/**
* Initialize the PublicKeyContext
*
* @param Version $version Version that contains the resource
* @param string $sid The Twilio-provided string that uniquely identifies the PublicKey resource to delete.
*/
public function __construct(
Version $version,
$sid
) {
parent::__construct($version);
// Path Solution
$this->solution = [
'sid' =>
$sid,
];
$this->uri = '/Credentials/PublicKeys/' . \rawurlencode($sid)
.'';
}
/**
* Delete the PublicKeyInstance
*
* @return bool True if delete succeeds, false otherwise
* @throws TwilioException When an HTTP error occurs.
*/
public function delete(): bool
{
$headers = Values::of(['Content-Type' => 'application/x-www-form-urlencoded' ]);
return $this->version->delete('DELETE', $this->uri, [], [], $headers);
}
/**
* Fetch the PublicKeyInstance
*
* @return PublicKeyInstance Fetched PublicKeyInstance
* @throws TwilioException When an HTTP error occurs.
*/
public function fetch(): PublicKeyInstance
{
$headers = Values::of(['Content-Type' => 'application/x-www-form-urlencoded', 'Accept' => 'application/json' ]);
$payload = $this->version->fetch('GET', $this->uri, [], [], $headers);
return new PublicKeyInstance(
$this->version,
$payload,
$this->solution['sid']
);
}
/**
* Update the PublicKeyInstance
*
* @param array|Options $options Optional Arguments
* @return PublicKeyInstance Updated PublicKeyInstance
* @throws TwilioException When an HTTP error occurs.
*/
public function update(array $options = []): PublicKeyInstance
{
$options = new Values($options);
$data = Values::of([
'FriendlyName' =>
$options['friendlyName'],
]);
$headers = Values::of(['Content-Type' => 'application/x-www-form-urlencoded', 'Accept' => 'application/json' ]);
$payload = $this->version->update('POST', $this->uri, [], $data, $headers);
return new PublicKeyInstance(
$this->version,
$payload,
$this->solution['sid']
);
}
/**
* Provide a friendly representation
*
* @return string Machine friendly representation
*/
public function __toString(): string
{
$context = [];
foreach ($this->solution as $key => $value) {
$context[] = "$key=$value";
}
return '[Twilio.Accounts.V1.PublicKeyContext ' . \implode(' ', $context) . ']';
}
}

View File

@@ -0,0 +1,152 @@
<?php
/**
* This code was generated by
* ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __
* | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/
* | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \
*
* Twilio - Accounts
* This is the public Twilio REST API.
*
* NOTE: This class is auto generated by OpenAPI Generator.
* https://openapi-generator.tech
* Do not edit the class manually.
*/
namespace Twilio\Rest\Accounts\V1\Credential;
use Twilio\Exceptions\TwilioException;
use Twilio\InstanceResource;
use Twilio\Options;
use Twilio\Values;
use Twilio\Version;
use Twilio\Deserialize;
/**
* @property string|null $sid
* @property string|null $accountSid
* @property string|null $friendlyName
* @property \DateTime|null $dateCreated
* @property \DateTime|null $dateUpdated
* @property string|null $url
*/
class PublicKeyInstance extends InstanceResource
{
/**
* Initialize the PublicKeyInstance
*
* @param Version $version Version that contains the resource
* @param mixed[] $payload The response payload
* @param string $sid The Twilio-provided string that uniquely identifies the PublicKey resource to delete.
*/
public function __construct(Version $version, array $payload, ?string $sid = null)
{
parent::__construct($version);
// Marshaled Properties
$this->properties = [
'sid' => Values::array_get($payload, 'sid'),
'accountSid' => Values::array_get($payload, 'account_sid'),
'friendlyName' => Values::array_get($payload, 'friendly_name'),
'dateCreated' => Deserialize::dateTime(Values::array_get($payload, 'date_created')),
'dateUpdated' => Deserialize::dateTime(Values::array_get($payload, 'date_updated')),
'url' => Values::array_get($payload, 'url'),
];
$this->solution = ['sid' => $sid ?: $this->properties['sid'], ];
}
/**
* Generate an instance context for the instance, the context is capable of
* performing various actions. All instance actions are proxied to the context
*
* @return PublicKeyContext Context for this PublicKeyInstance
*/
protected function proxy(): PublicKeyContext
{
if (!$this->context) {
$this->context = new PublicKeyContext(
$this->version,
$this->solution['sid']
);
}
return $this->context;
}
/**
* Delete the PublicKeyInstance
*
* @return bool True if delete succeeds, false otherwise
* @throws TwilioException When an HTTP error occurs.
*/
public function delete(): bool
{
return $this->proxy()->delete();
}
/**
* Fetch the PublicKeyInstance
*
* @return PublicKeyInstance Fetched PublicKeyInstance
* @throws TwilioException When an HTTP error occurs.
*/
public function fetch(): PublicKeyInstance
{
return $this->proxy()->fetch();
}
/**
* Update the PublicKeyInstance
*
* @param array|Options $options Optional Arguments
* @return PublicKeyInstance Updated PublicKeyInstance
* @throws TwilioException When an HTTP error occurs.
*/
public function update(array $options = []): PublicKeyInstance
{
return $this->proxy()->update($options);
}
/**
* Magic getter to access properties
*
* @param string $name Property to access
* @return mixed The requested property
* @throws TwilioException For unknown properties
*/
public function __get(string $name)
{
if (\array_key_exists($name, $this->properties)) {
return $this->properties[$name];
}
if (\property_exists($this, '_' . $name)) {
$method = 'get' . \ucfirst($name);
return $this->$method();
}
throw new TwilioException('Unknown property: ' . $name);
}
/**
* Provide a friendly representation
*
* @return string Machine friendly representation
*/
public function __toString(): string
{
$context = [];
foreach ($this->solution as $key => $value) {
$context[] = "$key=$value";
}
return '[Twilio.Accounts.V1.PublicKeyInstance ' . \implode(' ', $context) . ']';
}
}

View File

@@ -0,0 +1,196 @@
<?php
/**
* This code was generated by
* ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __
* | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/
* | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \
*
* Twilio - Accounts
* This is the public Twilio REST API.
*
* NOTE: This class is auto generated by OpenAPI Generator.
* https://openapi-generator.tech
* Do not edit the class manually.
*/
namespace Twilio\Rest\Accounts\V1\Credential;
use Twilio\Exceptions\TwilioException;
use Twilio\ListResource;
use Twilio\Options;
use Twilio\Stream;
use Twilio\Values;
use Twilio\Version;
class PublicKeyList extends ListResource
{
/**
* Construct the PublicKeyList
*
* @param Version $version Version that contains the resource
*/
public function __construct(
Version $version
) {
parent::__construct($version);
// Path Solution
$this->solution = [
];
$this->uri = '/Credentials/PublicKeys';
}
/**
* Create the PublicKeyInstance
*
* @param string $publicKey A URL encoded representation of the public key. For example, `-----BEGIN PUBLIC KEY-----MIIBIjANB.pa9xQIDAQAB-----END PUBLIC KEY-----`
* @param array|Options $options Optional Arguments
* @return PublicKeyInstance Created PublicKeyInstance
* @throws TwilioException When an HTTP error occurs.
*/
public function create(string $publicKey, array $options = []): PublicKeyInstance
{
$options = new Values($options);
$data = Values::of([
'PublicKey' =>
$publicKey,
'FriendlyName' =>
$options['friendlyName'],
'AccountSid' =>
$options['accountSid'],
]);
$headers = Values::of(['Content-Type' => 'application/x-www-form-urlencoded', 'Accept' => 'application/json' ]);
$payload = $this->version->create('POST', $this->uri, [], $data, $headers);
return new PublicKeyInstance(
$this->version,
$payload
);
}
/**
* Reads PublicKeyInstance records from the API as a list.
* Unlike stream(), this operation is eager and will load `limit` records into
* memory before returning.
*
* @param int $limit Upper limit for the number of records to return. read()
* guarantees to never return more than limit. Default is no
* limit
* @param mixed $pageSize Number of records to fetch per request, when not set
* will use the default value of 50 records. If no
* page_size is defined but a limit is defined, read()
* will attempt to read the limit with the most
* efficient page size, i.e. min(limit, 1000)
* @return PublicKeyInstance[] Array of results
*/
public function read(?int $limit = null, $pageSize = null): array
{
return \iterator_to_array($this->stream($limit, $pageSize), false);
}
/**
* Streams PublicKeyInstance records from the API as a generator stream.
* This operation lazily loads records as efficiently as possible until the
* limit
* is reached.
* The results are returned as a generator, so this operation is memory
* efficient.
*
* @param int $limit Upper limit for the number of records to return. stream()
* guarantees to never return more than limit. Default is no
* limit
* @param mixed $pageSize Number of records to fetch per request, when not set
* will use the default value of 50 records. If no
* page_size is defined but a limit is defined, stream()
* will attempt to read the limit with the most
* efficient page size, i.e. min(limit, 1000)
* @return Stream stream of results
*/
public function stream(?int $limit = null, $pageSize = null): Stream
{
$limits = $this->version->readLimits($limit, $pageSize);
$page = $this->page($limits['pageSize']);
return $this->version->stream($page, $limits['limit'], $limits['pageLimit']);
}
/**
* Retrieve a single page of PublicKeyInstance records from the API.
* Request is executed immediately
*
* @param mixed $pageSize Number of records to return, defaults to 50
* @param string $pageToken PageToken provided by the API
* @param mixed $pageNumber Page Number, this value is simply for client state
* @return PublicKeyPage Page of PublicKeyInstance
*/
public function page(
$pageSize = Values::NONE,
string $pageToken = Values::NONE,
$pageNumber = Values::NONE
): PublicKeyPage
{
$params = Values::of([
'PageToken' => $pageToken,
'Page' => $pageNumber,
'PageSize' => $pageSize,
]);
$headers = Values::of(['Content-Type' => 'application/x-www-form-urlencoded', 'Accept' => 'application/json']);
$response = $this->version->page('GET', $this->uri, $params, [], $headers);
return new PublicKeyPage($this->version, $response, $this->solution);
}
/**
* Retrieve a specific page of PublicKeyInstance records from the API.
* Request is executed immediately
*
* @param string $targetUrl API-generated URL for the requested results page
* @return PublicKeyPage Page of PublicKeyInstance
*/
public function getPage(string $targetUrl): PublicKeyPage
{
$response = $this->version->getDomain()->getClient()->request(
'GET',
$targetUrl
);
return new PublicKeyPage($this->version, $response, $this->solution);
}
/**
* Constructs a PublicKeyContext
*
* @param string $sid The Twilio-provided string that uniquely identifies the PublicKey resource to delete.
*/
public function getContext(
string $sid
): PublicKeyContext
{
return new PublicKeyContext(
$this->version,
$sid
);
}
/**
* Provide a friendly representation
*
* @return string Machine friendly representation
*/
public function __toString(): string
{
return '[Twilio.Accounts.V1.PublicKeyList]';
}
}

View File

@@ -0,0 +1,152 @@
<?php
/**
* This code was generated by
* ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __
* | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/
* | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \
*
* Twilio - Accounts
* This is the public Twilio REST API.
*
* NOTE: This class is auto generated by OpenAPI Generator.
* https://openapi-generator.tech
* Do not edit the class manually.
*/
namespace Twilio\Rest\Accounts\V1\Credential;
use Twilio\Options;
use Twilio\Values;
abstract class PublicKeyOptions
{
/**
* @param string $friendlyName A descriptive string that you create to describe the resource. It can be up to 64 characters long.
* @param string $accountSid The SID of the Subaccount that this Credential should be associated with. Must be a valid Subaccount of the account issuing the request
* @return CreatePublicKeyOptions Options builder
*/
public static function create(
string $friendlyName = Values::NONE,
string $accountSid = Values::NONE
): CreatePublicKeyOptions
{
return new CreatePublicKeyOptions(
$friendlyName,
$accountSid
);
}
/**
* @param string $friendlyName A descriptive string that you create to describe the resource. It can be up to 64 characters long.
* @return UpdatePublicKeyOptions Options builder
*/
public static function update(
string $friendlyName = Values::NONE
): UpdatePublicKeyOptions
{
return new UpdatePublicKeyOptions(
$friendlyName
);
}
}
class CreatePublicKeyOptions extends Options
{
/**
* @param string $friendlyName A descriptive string that you create to describe the resource. It can be up to 64 characters long.
* @param string $accountSid The SID of the Subaccount that this Credential should be associated with. Must be a valid Subaccount of the account issuing the request
*/
public function __construct(
string $friendlyName = Values::NONE,
string $accountSid = Values::NONE
) {
$this->options['friendlyName'] = $friendlyName;
$this->options['accountSid'] = $accountSid;
}
/**
* A descriptive string that you create to describe the resource. It can be up to 64 characters long.
*
* @param string $friendlyName A descriptive string that you create to describe the resource. It can be up to 64 characters long.
* @return $this Fluent Builder
*/
public function setFriendlyName(string $friendlyName): self
{
$this->options['friendlyName'] = $friendlyName;
return $this;
}
/**
* The SID of the Subaccount that this Credential should be associated with. Must be a valid Subaccount of the account issuing the request
*
* @param string $accountSid The SID of the Subaccount that this Credential should be associated with. Must be a valid Subaccount of the account issuing the request
* @return $this Fluent Builder
*/
public function setAccountSid(string $accountSid): self
{
$this->options['accountSid'] = $accountSid;
return $this;
}
/**
* Provide a friendly representation
*
* @return string Machine friendly representation
*/
public function __toString(): string
{
$options = \http_build_query(Values::of($this->options), '', ' ');
return '[Twilio.Accounts.V1.CreatePublicKeyOptions ' . $options . ']';
}
}
class UpdatePublicKeyOptions extends Options
{
/**
* @param string $friendlyName A descriptive string that you create to describe the resource. It can be up to 64 characters long.
*/
public function __construct(
string $friendlyName = Values::NONE
) {
$this->options['friendlyName'] = $friendlyName;
}
/**
* A descriptive string that you create to describe the resource. It can be up to 64 characters long.
*
* @param string $friendlyName A descriptive string that you create to describe the resource. It can be up to 64 characters long.
* @return $this Fluent Builder
*/
public function setFriendlyName(string $friendlyName): self
{
$this->options['friendlyName'] = $friendlyName;
return $this;
}
/**
* Provide a friendly representation
*
* @return string Machine friendly representation
*/
public function __toString(): string
{
$options = \http_build_query(Values::of($this->options), '', ' ');
return '[Twilio.Accounts.V1.UpdatePublicKeyOptions ' . $options . ']';
}
}

View File

@@ -0,0 +1,55 @@
<?php
/**
* This code was generated by
* ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __
* | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/
* | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \
*
* Twilio - Accounts
* This is the public Twilio REST API.
*
* NOTE: This class is auto generated by OpenAPI Generator.
* https://openapi-generator.tech
* Do not edit the class manually.
*/
namespace Twilio\Rest\Accounts\V1\Credential;
use Twilio\Http\Response;
use Twilio\Page;
use Twilio\Version;
class PublicKeyPage extends Page
{
/**
* @param Version $version Version that contains the resource
* @param Response $response Response from the API
* @param array $solution The context solution
*/
public function __construct(Version $version, Response $response, array $solution)
{
parent::__construct($version, $response);
// Path Solution
$this->solution = $solution;
}
/**
* @param array $payload Payload response from the API
* @return PublicKeyInstance \Twilio\Rest\Accounts\V1\Credential\PublicKeyInstance
*/
public function buildInstance(array $payload): PublicKeyInstance
{
return new PublicKeyInstance($this->version, $payload);
}
/**
* Provide a friendly representation
*
* @return string Machine friendly representation
*/
public function __toString(): string
{
return '[Twilio.Accounts.V1.PublicKeyPage]';
}
}

View File

@@ -0,0 +1,71 @@
<?php
/**
* This code was generated by
* ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __
* | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/
* | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \
*
* Twilio - Accounts
* This is the public Twilio REST API.
*
* NOTE: This class is auto generated by OpenAPI Generator.
* https://openapi-generator.tech
* Do not edit the class manually.
*/
namespace Twilio\Rest\Accounts\V1;
use Twilio\Exceptions\TwilioException;
use Twilio\InstanceResource;
use Twilio\Version;
class CredentialInstance extends InstanceResource
{
/**
* Initialize the CredentialInstance
*
* @param Version $version Version that contains the resource
* @param mixed[] $payload The response payload
*/
public function __construct(Version $version, array $payload)
{
parent::__construct($version);
$this->solution = [];
}
/**
* Magic getter to access properties
*
* @param string $name Property to access
* @return mixed The requested property
* @throws TwilioException For unknown properties
*/
public function __get(string $name)
{
if (\array_key_exists($name, $this->properties)) {
return $this->properties[$name];
}
if (\property_exists($this, '_' . $name)) {
$method = 'get' . \ucfirst($name);
return $this->$method();
}
throw new TwilioException('Unknown property: ' . $name);
}
/**
* Provide a friendly representation
*
* @return string Machine friendly representation
*/
public function __toString(): string
{
return '[Twilio.Accounts.V1.CredentialInstance]';
}
}

View File

@@ -0,0 +1,123 @@
<?php
/**
* This code was generated by
* ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __
* | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/
* | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \
*
* Twilio - Accounts
* This is the public Twilio REST API.
*
* NOTE: This class is auto generated by OpenAPI Generator.
* https://openapi-generator.tech
* Do not edit the class manually.
*/
namespace Twilio\Rest\Accounts\V1;
use Twilio\Exceptions\TwilioException;
use Twilio\ListResource;
use Twilio\Version;
use Twilio\InstanceContext;
use Twilio\Rest\Accounts\V1\Credential\AwsList;
use Twilio\Rest\Accounts\V1\Credential\PublicKeyList;
/**
* @property AwsList $aws
* @property PublicKeyList $publicKey
* @method \Twilio\Rest\Accounts\V1\Credential\PublicKeyContext publicKey(string $sid)
* @method \Twilio\Rest\Accounts\V1\Credential\AwsContext aws(string $sid)
*/
class CredentialList extends ListResource
{
protected $_aws = null;
protected $_publicKey = null;
/**
* Construct the CredentialList
*
* @param Version $version Version that contains the resource
*/
public function __construct(
Version $version
) {
parent::__construct($version);
// Path Solution
$this->solution = [
];
}
/**
* Access the aws
*/
protected function getAws(): AwsList
{
if (!$this->_aws) {
$this->_aws = new AwsList(
$this->version
);
}
return $this->_aws;
}
/**
* Access the publicKey
*/
protected function getPublicKey(): PublicKeyList
{
if (!$this->_publicKey) {
$this->_publicKey = new PublicKeyList(
$this->version
);
}
return $this->_publicKey;
}
/**
* Magic getter to lazy load subresources
*
* @param string $name Subresource to return
* @return \Twilio\ListResource The requested subresource
* @throws TwilioException For unknown subresources
*/
public function __get(string $name)
{
if (\property_exists($this, '_' . $name)) {
$method = 'get' . \ucfirst($name);
return $this->$method();
}
throw new TwilioException('Unknown subresource ' . $name);
}
/**
* Magic caller to get resource contexts
*
* @param string $name Resource to return
* @param array $arguments Context parameters
* @return InstanceContext The requested resource context
* @throws TwilioException For unknown resource
*/
public function __call(string $name, array $arguments): InstanceContext
{
$property = $this->$name;
if (\method_exists($property, 'getContext')) {
return \call_user_func_array(array($property, 'getContext'), $arguments);
}
throw new TwilioException('Resource does not have a context');
}
/**
* Provide a friendly representation
*
* @return string Machine friendly representation
*/
public function __toString(): string
{
return '[Twilio.Accounts.V1.CredentialList]';
}
}

View File

@@ -0,0 +1,55 @@
<?php
/**
* This code was generated by
* ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __
* | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/
* | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \
*
* Twilio - Accounts
* This is the public Twilio REST API.
*
* NOTE: This class is auto generated by OpenAPI Generator.
* https://openapi-generator.tech
* Do not edit the class manually.
*/
namespace Twilio\Rest\Accounts\V1;
use Twilio\Http\Response;
use Twilio\Page;
use Twilio\Version;
class CredentialPage extends Page
{
/**
* @param Version $version Version that contains the resource
* @param Response $response Response from the API
* @param array $solution The context solution
*/
public function __construct(Version $version, Response $response, array $solution)
{
parent::__construct($version, $response);
// Path Solution
$this->solution = $solution;
}
/**
* @param array $payload Payload response from the API
* @return CredentialInstance \Twilio\Rest\Accounts\V1\CredentialInstance
*/
public function buildInstance(array $payload): CredentialInstance
{
return new CredentialInstance($this->version, $payload);
}
/**
* Provide a friendly representation
*
* @return string Machine friendly representation
*/
public function __toString(): string
{
return '[Twilio.Accounts.V1.CredentialPage]';
}
}

Some files were not shown because too many files have changed in this diff Show More