Initial commit

This commit is contained in:
Local Administrator
2025-04-18 10:32:42 +02:00
commit b83134aca3
29643 changed files with 3045897 additions and 0 deletions

View File

@@ -0,0 +1,14 @@
tmp/*
[Cc]onfig/core.php
[Cc]onfig/database.php
app/tmp/*
app/[Cc]onfig/core.php
app/[Cc]onfig/database.php
.DS_Store
!empty
composer.phar
vendor/*
composer.lock
/.metadata/
.idea
/.phpunit.result.cache

142
vendor/mailjet/mailjet-apiv3-php/.php_cs vendored Normal file
View File

@@ -0,0 +1,142 @@
<?php
use PhpCsFixer\Config;
use PhpCsFixer\Finder;
$rules = [
'array_syntax' => ['syntax' => 'short'],
'binary_operator_spaces' => [
'default' => 'single_space',
'operators' => ['=>' => null]
],
'blank_line_after_namespace' => true,
'blank_line_after_opening_tag' => true,
'blank_line_before_statement' => [
'statements' => ['return', 'if']
],
'braces' => true,
'cast_spaces' => true,
'class_attributes_separation' => [
'elements' => ['method']
],
'class_definition' => true,
'concat_space' => [
'spacing' => 'none'
],
'declare_equal_normalize' => true,
'elseif' => true,
'encoding' => true,
'full_opening_tag' => true,
'fully_qualified_strict_types' => true,
'function_declaration' => true,
'function_typehint_space' => true,
'return_type_declaration' => true,
'heredoc_to_nowdoc' => true,
'include' => true,
'increment_style' => ['style' => 'post'],
'indentation_type' => true,
'linebreak_after_opening_tag' => true,
'line_ending' => true,
'lowercase_cast' => true,
'lowercase_constants' => true,
'lowercase_keywords' => true,
'lowercase_static_reference' => true,
'magic_method_casing' => true,
'magic_constant_casing' => true,
'method_argument_space' => true,
'native_function_casing' => true,
'no_alias_functions' => true,
'no_extra_blank_lines' => [
'tokens' => [
'extra',
'throw',
'use',
'use_trait',
]
],
'no_blank_lines_after_class_opening' => true,
'no_blank_lines_after_phpdoc' => true,
'no_closing_tag' => true,
'no_empty_phpdoc' => true,
'no_empty_statement' => true,
'no_leading_import_slash' => true,
'no_leading_namespace_whitespace' => true,
'no_mixed_echo_print' => [
'use' => 'echo'
],
'no_multiline_whitespace_around_double_arrow' => true,
'multiline_whitespace_before_semicolons' => [
'strategy' => 'no_multi_line'
],
'no_short_bool_cast' => true,
'no_singleline_whitespace_before_semicolons' => true,
'no_spaces_after_function_name' => true,
'no_spaces_around_offset' => true,
'no_spaces_inside_parenthesis' => true,
'no_trailing_comma_in_list_call' => true,
'no_trailing_comma_in_singleline_array' => true,
'no_trailing_whitespace' => true,
'no_trailing_whitespace_in_comment' => true,
'no_unneeded_control_parentheses' => true,
'no_unreachable_default_argument_value' => true,
'no_useless_return' => true,
'no_whitespace_before_comma_in_array' => true,
'no_whitespace_in_blank_line' => true,
'normalize_index_brace' => true,
'not_operator_with_successor_space' => false,
'object_operator_without_whitespace' => true,
'ordered_imports' => ['sortAlgorithm' => 'alpha'],
'phpdoc_indent' => true,
'phpdoc_inline_tag' => true,
'phpdoc_no_access' => true,
'phpdoc_no_package' => true,
'phpdoc_no_useless_inheritdoc' => true,
'phpdoc_scalar' => true,
'phpdoc_single_line_var_spacing' => true,
'phpdoc_summary' => true,
'phpdoc_to_comment' => true,
'phpdoc_trim' => true,
'phpdoc_types' => true,
'phpdoc_var_without_name' => true,
'psr4' => true,
'self_accessor' => true,
'short_scalar_cast' => true,
'simplified_null_return' => false,
'single_blank_line_at_eof' => true,
'single_blank_line_before_namespace' => true,
'single_class_element_per_statement' => true,
'single_import_per_statement' => true,
'single_line_after_imports' => true,
'single_line_comment_style' => [
'comment_types' => ['hash']
],
'single_quote' => true,
'space_after_semicolon' => true,
'standardize_not_equals' => true,
'switch_case_semicolon_to_colon' => true,
'switch_case_space' => true,
'ternary_operator_spaces' => true,
'trailing_comma_in_multiline_array' => true,
'trim_array_spaces' => true,
'unary_operator_spaces' => true,
'visibility_required' => [
'elements' => ['method', 'property']
],
'whitespace_after_comma_in_array' => true,
];
$project_path = getcwd();
$finder = Finder::create()
->in([
$project_path . '/src',
$project_path . '/test',
])
->name('*.php')
->ignoreDotFiles(true)
->ignoreVCS(true);
return Config::create()
->setFinder($finder)
->setRules($rules)
->setRiskyAllowed(true)
->setUsingCache(true);

View File

@@ -0,0 +1,15 @@
language: php
dist: trusty
php:
- 7.2
- 7.3
- 7.4
- 8.0
install:
- composer install
script: vendor/bin/phpunit --coverage-clover build/logs/clover.xml
after_success:
- travis_retry vendor/bin/coveralls -v
notifications:
slack:
secure: woxqf55Y5XlEOr9WrXalAMQEay8Rqpd9RdvQXw28AZsySVIYP2btfdA7OJRTiC7znIaSXQZqAeIZhKYXCLUv6QqG/saNe9sV5MC9o6sC4FgqdaPU493X2C7KSiwMqeyY9v0bbeUUI9O/g0cnaQGD/NJmVIpvaYz6Tu0MM06fB4c=

View File

@@ -0,0 +1,21 @@
The MIT License (MIT)
Copyright (c) 2014 Mailjet
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

View File

@@ -0,0 +1,448 @@
[doc]: http://dev.mailjet.com/guides/?php#
[ref]: http://dev.mailjet.com/reference/
[api_credential]: https://app.mailjet.com/account/apikeys
[mailjet]: http://www.mailjet.com
[smsDashboard]:https://app.mailjet.com/sms
![alt text](https://www.mailjet.com/images/email/transac/logo_header.png "Mailjet")
# Official Mailjet PHP Wrapper
[![Codacy Badge](https://api.codacy.com/project/badge/grade/3fa729f3750849ce8e0471b0487439cb)](https://www.codacy.com/app/gbadi/mailjet-apiv3-php)
[![Build Status](https://travis-ci.org/mailjet/mailjet-apiv3-php.svg?branch=master)](https://travis-ci.org/mailjet/mailjet-apiv3-php)
![MIT License](https://img.shields.io/badge/license-MIT-007EC7.svg?style=flat-square)
![Current Version](https://img.shields.io/badge/version-1.4.1-green.svg)
## Overview
This repository contains the official PHP wrapper for the Mailjet API.
Check out all the resources and PHP code examples in the [Offical Documentation](https://dev.mailjet.com/guides/?php#getting-started).
## Table of contents
- [Compatibility](#compatibility)
- [Installation](#installation)
- [Authentication](#authentication)
- [Make your first call](#make-your-first-call)
- [Client / Call configuration specifics](#client--call-configuration-specifics)
- [Options](#options)
- [API versioning](#api-versioning)
- [Base URL](#base-url)
- [Disable API call](#disable-api-call)
- [List of resources](#list-of-resources)
- [Request examples](#request-examples)
- [POST request](#post-request)
- [Simple POST request](#simple-post-request)
- [Using actions](#using-actions)
- [GET request](#get-request)
- [Retrieve all objects](#retrieve-all-objects)
- [Use filtering](#use-filtering)
- [Retrieve a single object](#retrieve-a-single-object)
- [PUT request](#put-request)
- [DELETE request](#delete-request)
- [Response](#response)
- [API resources helpers](#api-resources-helpers)
- [SMS API](#sms-api)
- [Token authentication](#token-authentication)
- [Example Request](#example-request)
- [Contribute](#contribute)
### Compatibility
This library requires **PHP v5.4** or higher.
### Installation
Use the below code to install the wrapper:
`composer require mailjet/mailjet-apiv3-php`
If you are not using [Composer](https://getcomposer.org/), clone or download [this repository](https://github.com/mailjet/mailjet-apiv3-php-no-composer) that already contains all the dependencies and the `vendor/autoload.php` file. If you encounter an issue, please post it here and not on the mirror repository.
### Authentication
The Mailjet Email API uses your API and Secret keys for authentication. [Grab][api_credential] and save your Mailjet API credentials.
```bash
export MJ_APIKEY_PUBLIC='your API key'
export MJ_APIKEY_PRIVATE='your API secret'
```
> Note: For the SMS API the authorization is based on a Bearer token. See information about it in the [SMS API](#sms-api) section of the readme.
Initialize your [Mailjet][mailjet] Client:
```php
use \Mailjet\Resources;
// getenv will allow us to get the MJ_APIKEY_PUBLIC/PRIVATE variables we created before:
$apikey = getenv('MJ_APIKEY_PUBLIC');
$apisecret = getenv('MJ_APIKEY_PRIVATE');
$mj = new \Mailjet\Client($apikey, $apisecret);
// or, without using environment variables:
$apikey = 'your API key';
$apisecret = 'your API secret';
$mj = new \Mailjet\Client($apikey, $apisecret);
```
### Make your first call
Here's an example on how to send an email:
```php
<?php
require 'vendor/autoload.php';
use \Mailjet\Resources;
// Use your saved credentials, specify that you are using Send API v3.1
$mj = new \Mailjet\Client(getenv('MJ_APIKEY_PUBLIC'), getenv('MJ_APIKEY_PRIVATE'),true,['version' => 'v3.1']);
// Define your request body
$body = [
'Messages' => [
[
'From' => [
'Email' => "$SENDER_EMAIL",
'Name' => "Me"
],
'To' => [
[
'Email' => "$RECIPIENT_EMAIL",
'Name' => "You"
]
],
'Subject' => "My first Mailjet Email!",
'TextPart' => "Greetings from Mailjet!",
'HTMLPart' => "<h3>Dear passenger 1, welcome to <a href=\"https://www.mailjet.com/\">Mailjet</a>!</h3>
<br />May the delivery force be with you!"
]
]
];
// All resources are located in the Resources class
$response = $mj->post(Resources::$Email, ['body' => $body]);
// Read the response
$response->success() && var_dump($response->getData());
?>
```
## Client / Call Configuration Specifics
To instantiate the library you can use the following constructor:
`new \Mailjet\Client($MJ_APIKEY_PUBLIC, $MJ_APIKEY_PRIVATE,$CALL,$OPTIONS);`
- `$MJ_APIKEY_PUBLIC` : public Mailjet API key
- `$MJ_APIKEY_PRIVATE` : private Mailjet API key
- `$CALL` : boolean to enable the API call to Mailjet API server (should be `true` to run the API call)
- `$OPTIONS` : associative PHP array describing the connection options (see Options bellow for full list)
### Options
#### API Versioning
The Mailjet API is spread among three distinct versions:
- `v3` - The Email API
- `v3.1` - Email Send API v3.1, which is the latest version of our Send API
- `v4` - SMS API
Since most Email API endpoints are located under `v3`, it is set as the default one and does not need to be specified when making your request. For the others you need to specify the version using `version`. For example, if using Send API `v3.1`:
```php
$mj = new \Mailjet\Client(getenv('MJ_APIKEY_PUBLIC'), getenv('MJ_APIKEY_PRIVATE'),true,['version' => 'v3.1']);
```
For additional information refer to our [API Reference](https://dev.preprod.mailjet.com/reference/overview/versioning/).
#### Base URL
The default base domain name for the Mailjet API is api.mailjet.com. You can modify this base URL by setting a value for `url` in your call:
```php
$mj = new \Mailjet\Client(getenv('MJ_APIKEY_PUBLIC'),
getenv('MJ_APIKEY_PRIVATE'), true,
['url' => "api.us.mailjet.com"]
);
```
If your account has been moved to Mailjet's US architecture, the URL value you need to set is `api.us.mailjet.com`.
### Disable API call
By default the API call parameter is always enabled. However, you may want to disable it during testing to prevent unnecessary calls to the Mailjet API. This is done by setting the third parameter to `false`:
```php
$mj = new \Mailjet\Client(getenv('MJ_APIKEY_PUBLIC'), getenv('MJ_APIKEY_PRIVATE'), false);
```
## List of resources
You can find the list of all available resources for this library in [/src/Mailjet/Resources.php](https://github.com/mailjet/mailjet-apiv3-php/blob/master/src/Mailjet/Resources.php). The file lists the names of the PHP resources and the corresponding names in the [API reference][ref].
## Request Examples
### POST Request
Use the `post` method of the Mailjet CLient (i.e. `$mj->post($resource, $params)`)
`$params` will be a PHP associative array with the following keys :
- `body`: associative PHP array defining the object to create. The properties correspond to the property of the JSON Payload)
- `id` : ID you want to apply a POST request to (used in case of action on a resource)
#### Simple POST request
```php
<?php
/*
Create a new contact:
*/
require 'vendor/autoload.php';
use \Mailjet\Resources;
$mj = new \Mailjet\Client(getenv('MJ_APIKEY_PUBLIC'), getenv('MJ_APIKEY_PRIVATE'));
$body = [
'Email' => "email@example.com"
];
$response = $mj->post(Resources::$Contact, ['body' => $body]);
$response->success() && var_dump($response->getData());?>
```
#### Using actions
```php
<?php
/*
Manage the subscription status of a contact to multiple lists
*/
require 'vendor/autoload.php';
use \Mailjet\Resources;
$mj = new \Mailjet\Client(getenv('MJ_APIKEY_PUBLIC'), getenv('MJ_APIKEY_PRIVATE'));
$body = [
'ContactsLists' => [
[
'ListID' => "$ListID_1",
'Action' => "addnoforce"
],
[
'ListID' => "$ListID_2",
'Action' => "addforce"
]
]
];
$response = $mj->post(Resources::$ContactManagecontactslists, ['id' => $id, 'body' => $body]);
$response->success() && var_dump($response->getData());
?>
```
### GET Request
Use the `get` method of the Mailjet CLient (i.e. `$mj->get($ressource, $params)`)
`$param` will be a PHP associative array with the following keys :
- `id` : Unique ID of the element you want to get (optional)
- `filters`: associative array listing the query parameters you want to apply to your get (optional)
#### Retrieve all objects
```php
<?php
/*
Retrieve all contacts:
*/
require 'vendor/autoload.php';
use \Mailjet\Resources;
$mj = new \Mailjet\Client(getenv('MJ_APIKEY_PUBLIC'), getenv('MJ_APIKEY_PRIVATE'));
$response = $mj->get(Resources::$Contact);
$response->success() && var_dump($response->getData());
?>
```
#### Use filtering
```php
<?php
/*
Retrieve all contacts that are not in the campaign exclusion list :
*/
require 'vendor/autoload.php';
use \Mailjet\Resources;
$mj = new \Mailjet\Client(getenv('MJ_APIKEY_PUBLIC'), getenv('MJ_APIKEY_PRIVATE'));
$filters = [
'IsExcludedFromCampaigns' => 'false'
];
$response = $mj->get(Resources::$Contact, ['filters' => $filters]);
$response->success() && var_dump($response->getData());
?>
```
#### Use paging and sorting
```php
<?php
/*
Retrieve a specific contact ID :
*/
require 'vendor/autoload.php';
use \Mailjet\Resources;
$mj = new \Mailjet\Client(getenv('MJ_APIKEY_PUBLIC'), getenv('MJ_APIKEY_PRIVATE'));
$filters = [
'Limit'=>40, // default is 10, max is 1000
'Offset'=>20,
'Sort'=>'ArrivedAt DESC',
'Contact'=>$contact->ID,
'showSubject'=>true
];
$response = $mj->get(Resources::$Message, ['filters'=>$filters]);
$response->success() && var_dump($response->getData());
?>
```
#### Retrieve a single object
```php
<?php
/*
Retrieve a specific contact ID :
*/
require 'vendor/autoload.php';
use \Mailjet\Resources;
$mj = new \Mailjet\Client(getenv('MJ_APIKEY_PUBLIC'), getenv('MJ_APIKEY_PRIVATE'));
$response = $mj->get(Resources::$Contact, ['id' => $id]);
$response->success() && var_dump($response->getData());
?>
```
### PUT Request
Use the `put` method of the Mailjet CLient (i.e. `$mj->put($ressource, $params)`)
`$param` will be a PHP associative array with the following keys :
- `id` : Unique ID of the element you want to modify
- `body`: associative array representing the object property to update
A `PUT` request in the Mailjet API will work as a `PATCH` request - the update will affect only the specified properties. The other properties of an existing resource will neither be modified, nor deleted. It also means that all non-mandatory properties can be omitted from your payload.
Here's an example of a PUT request:
```php
<?php
/*
Update the contact properties for a contact:
*/
require 'vendor/autoload.php';
use \Mailjet\Resources;
$mj = new \Mailjet\Client(getenv('MJ_APIKEY_PUBLIC'), getenv('MJ_APIKEY_PRIVATE'));
$body = [
'first_name' => "John",
'last_name' => "Smith"
];
$response = $mj->put(Resources::$ContactData, ['id' => $id, 'body' => $body]);
$response->success() && var_dump($response->getData());
?>
```
### DELETE Request
Use the `delete` method of the Mailjet CLient (i.e. `$mj->delete($ressource, $params)`)
Upon a successful `DELETE` request the response will not include a response body, but only a `204 No Content` response code.
Here's an example of a `DELETE` request:
```php
<?php
/*
Delete an email template:
*/
require 'vendor/autoload.php';
use \Mailjet\Resources;
$mj = new \Mailjet\Client(getenv('MJ_APIKEY_PUBLIC'), getenv('MJ_APIKEY_PRIVATE'));
$response = $mj->delete(Resources::$Template, ['id' => $id]);
$response->success() && var_dump($response->getData());
?>
```
### Response
The `get`, `post`, `put` and `delete` method will return a `Response` object with the following available methods:
- `success()` : returns a boolean indicating if the API call was successful
- `getStatus()` : http status code (ie: 200,400 ...)
- `getData()` : content of the property `data` of the JSON response payload if exist or the full JSON payload returned by the API call. This will be PHP associative array.
- `getCount()` : number of elements returned in the response
- `getReasonPhrase()` : http response message phrases ("OK", "Bad Request" ...)
### API resources helpers
All API resources are listed in the `Resources` object. It will make it easy to find the resources and actions aliases.
```
$response = $mj->delete(Resources::$Template, ['id' => $id]);
$response = $mj->put(Resources::$ContactData, ['id' => $id, 'body' => $body]);
$response = $mj->post(Resources::$ContactManagecontactslists, ['id' => $id, 'body' => $body]);
```
## SMS API
### Token Authentication
Authentication for the SMS API endpoints is done using a bearer token. The bearer token is generated in the [SMS section](https://app.mailjet.com/sms) of your Mailjet account.
To create a new instance of the Mailjet client with token authentication, the token should be provided as the first parameter, and the second must be NULL:
```php
$mj = new \Mailjet\Client(getenv('MJ_APITOKEN'),
NULL, true,
['url' => "api.mailjet.com", 'version' => 'v4', 'call' => false]
);
```
### Example Request
Here's an example SMS API request:
```php
//Send an SMS
$mj = new \Mailjet\Client(getenv('MJ_APITOKEN'),
NULL, true,
['url' => "api.mailjet.com", 'version' => 'v4', 'call' => false]
);
$body = [
'Text' => "Have a nice SMS flight with Mailjet !",
'To' => "+336000000000",
'From' => "MJ Pilot",
];
$response = $mj->post(Resources::$SmsSend, ['body' => $body]);
$response->success() && var_dump($response->getData());
```
## Contribute
Mailjet loves developers. You can be part of this project!
This wrapper is a great introduction to the open source world, check out the code!
Feel free to ask anything, and contribute:
- Fork the project.
- Create a new branch.
- Implement your feature or bug fix.
- Add documentation to it.
- Commit, push, open a pull request and voila.
If you have suggestions on how to improve the guides, please submit an issue in our [Official API Documentation repo](https://github.com/mailjet/api-documentation).

View File

@@ -0,0 +1,37 @@
{
"name": "mailjet/mailjet-apiv3-php",
"description": "PHP wrapper for the Mailjet API",
"keywords": ["mailjet", "api", "v3", "php", "email"],
"homepage": "https://github.com/mailjet/mailjet-apiv3-php/",
"license": "MIT",
"authors": [
{
"name": "Mailjet",
"email": "dev@mailjet.com",
"homepage": "https://dev.mailjet.com"
}
],
"require": {
"php": "^7.2|^8.0",
"ext-json": "*",
"guzzlehttp/guzzle": "^7.4.4",
"psr/http-client": "^1.0"
},
"require-dev": {
"phpunit/phpunit": "^8|^9",
"mockery/mockery": "^1.4",
"php-coveralls/php-coveralls": "^2.0",
"phpcompatibility/php-compatibility": "*",
"phpstan/phpstan": "^1.10",
"squizlabs/php_codesniffer": "*"
},
"autoload": {
"psr-0": {
"Mailjet": "src/"
}
},
"scripts": {
"post-install-cmd": "\"vendor/bin/phpcs\" --config-set installed_paths vendor/phpcompatibility/php-compatibility",
"post-update-cmd" : "\"vendor/bin/phpcs\" --config-set installed_paths vendor/phpcompatibility/php-compatibility"
}
}

View File

@@ -0,0 +1,16 @@
<?xml version="1.0" encoding="UTF-8"?>
<phpunit xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" colors="true" bootstrap="./vendor/autoload.php" xsi:noNamespaceSchemaLocation="https://schema.phpunit.de/9.3/phpunit.xsd">
<coverage>
<include>
<directory suffix=".php">src/</directory>
</include>
</coverage>
<testsuites>
<!-- <testsuite name="Mailjet APIv3 PHP wrapper test suite">
<file>./test/Mailjet/test.php</file>
</testsuite>-->
<testsuite name="apiv3-wrapper">
<file>./test/Mailjet/MailjetApiv3Test.php</file>
</testsuite>
</testsuites>
</phpunit>

View File

@@ -0,0 +1,445 @@
<?php
declare(strict_types=1);
/*
* Copyright (C) 2013 Mailgun
*
* This software may be modified and distributed under the terms
* of the MIT license. See the LICENSE file for details.
*/
namespace Mailjet;
class Client
{
public const WRAPPER_VERSION = Config::WRAPPER_VERSION;
/**
* connect_timeout: (float, default=2) Float describing the number of
* seconds to wait while trying to connect to a server. Use 0 to wait
* indefinitely (the default behavior).
*/
public const CONNECT_TIMEOUT = 'connect_timeout';
/**
* timeout: (float, default=15) Float describing the timeout of the
* request in seconds. Use 0 to wait indefinitely (the default behavior).
*/
public const TIMEOUT = 'timeout';
/**
* proxy: (array, default=none) Array describing the proxy options used by guzzle client
* See guzzle-http for specification.
*/
public const PROXY = 'proxy';
private $apikey;
private $apisecret;
private $apitoken;
private $version = Config::MAIN_VERSION;
private $url = Config::MAIN_URL;
private $secure = Config::SECURED;
private $call = true;
private $settings = [];
private $changed = false;
/**
* @var int[]
*/
private $requestOptions = [
self::TIMEOUT => 15,
self::CONNECT_TIMEOUT => 2,
];
/**
* @var string[]
*/
private $smsResources = [
'send',
'sms',
'sms-send',
];
/**
* @var string[]
*/
private $dataAction = [
'csverror/text:csv',
'csvdata/text:plain',
'JSONError/application:json/LAST',
];
/**
* Client constructor requires:.
*
* @param string $key Mailjet API Key
* @param string|null $secret Mailjet API Secret
* @param bool $call performs the call or not
* @param array $settings
*/
public function __construct(string $key, string $secret = null, bool $call = true, array $settings = [])
{
$this->setAuthentication($key, $secret, $call, $settings);
}
/**
* Trigger a POST request.
*
* @param array $resource Mailjet Resource/Action pair
* @param array $args Request arguments
* @param array $options
* @return Response
*/
public function post(array $resource, array $args = [], array $options = []): Response
{
if (!empty($options)) {
$this->setOptions($options, $resource);
}
$result = $this->_call('POST', $resource[0], $resource[1], $args);
if (!empty($this->changed)) {
$this->setSettings();
}
return $result;
}
/**
* Trigger a GET request.
*
* @param array $resource Mailjet Resource/Action pair
* @param array $args Request arguments
* @param array $options
* @return Response
*/
public function get(array $resource, array $args = [], array $options = []): Response
{
if (!empty($options)) {
$this->setOptions($options, $resource);
}
$result = $this->_call('GET', $resource[0], $resource[1], $args);
if (!empty($this->changed)) {
$this->setSettings();
}
return $result;
}
/**
* Trigger a POST request.
*
* @param array $resource Mailjet Resource/Action pair
* @param array $args Request arguments
* @param array $options
* @return Response
*/
public function put(array $resource, array $args = [], array $options = []): Response
{
if (!empty($options)) {
$this->setOptions($options, $resource);
}
$result = $this->_call('PUT', $resource[0], $resource[1], $args);
if (!empty($this->changed)) {
$this->setSettings();
}
return $result;
}
/**
* Trigger a GET request.
*
* @param array $resource Mailjet Resource/Action pair
* @param array $args Request arguments
* @param array $options
* @return Response
*/
public function delete(array $resource, array $args = [], array $options = []): Response
{
if (!empty($options)) {
$this->setOptions($options, $resource);
}
$result = $this->_call('DELETE', $resource[0], $resource[1], $args);
if (!empty($this->changed)) {
$this->setSettings();
}
return $result;
}
/**
* Sets if we need to use https or http protocol while using API Url.
*
* @param bool|mixed $bIsSecured True use https / false use http
* @return bool true if we set value false otherwise
*/
public function setSecureProtocol($bIsSecured = null): bool
{
if (\is_bool($bIsSecured)) {
$this->secure = $bIsSecured;
return true;
}
return false;
}
/**
* Set HTTP request Timeout.
*
* @param int $timeout
*/
public function setTimeout(int $timeout): void
{
$this->requestOptions[self::TIMEOUT] = $timeout;
}
/**
* Set HTTP proxy options
* See: http://docs.guzzlephp.org/en/stable/request-options.html#proxy.
*
* @param array $proxyArray
*/
public function setHttpProxy(array $proxyArray): void
{
$this->requestOptions[self::PROXY] = $proxyArray;
}
/**
* Set HTTP connection Timeout.
*
* @param int $timeout
*/
public function setConnectionTimeout(int $timeout): void
{
$this->requestOptions[self::CONNECT_TIMEOUT] = $timeout;
}
/**
* Get HTTP request Timeout
* $return int|null.
*/
public function getTimeout(): ?int
{
return $this->requestOptions[self::TIMEOUT];
}
/**
* Get HTTP connection Timeout
* $return int|null.
*/
public function getConnectionTimeout(): ?int
{
return $this->requestOptions[self::CONNECT_TIMEOUT];
}
/**
* Add a HTTP request option.
*
* @param string $key
* @param mixed $value
* [IMPORTANT]Default options will be overwritten
* if such option is provided
* @see \GuzzleHttp\RequestOptions for a list of available request options.
*/
public function addRequestOption(string $key, $value): void
{
if ($key && (null !== $value)) {
$this->requestOptions[$key] = $value;
}
}
/**
* Get HTTP connection options
* $return array.
*/
public function getRequestOptions(): array
{
return $this->requestOptions;
}
/**
* Set auth.
*
* @param string $key
* @param string|null $secret
* @param bool $call
* @param array $settings
*/
public function setAuthentication(string $key, ?string $secret, bool $call, array $settings = []): void
{
$isBasicAuth = $this->isBasicAuthentication($key, $secret);
if ($isBasicAuth) {
$this->apikey = $key;
$this->apisecret = $secret;
} else {
$this->apitoken = $key;
$this->version = Config::SMS_VERSION;
}
$this->initSettings($call, $settings);
$this->setSettings();
}
// phpcs:disable
/**
* Magic method to call a mailjet resource.
* @param string $method Http method
* @param string $resource mailjet resource
* @param string $action mailjet resource action
* @param array $args Request arguments
* @return Response server response
*/
private function _call(string $method, string $resource, string $action, array $args): Response
{
$args = array_merge([
'id' => '',
'actionid' => '',
'filters' => [],
'body' => 'GET' === $method ? null : '{}',
], array_change_key_case($args));
$url = $this->buildURL($resource, $action, (string)$args['id'], $args['actionid']);
$contentType = 'application/json';
if ('csvdata/text:plain' === $action) {
$contentType = 'text/plain';
} elseif ('csverror/text:csv' === $action) {
$contentType = 'text/csv';
}
$isBasicAuth = $this->isBasicAuthentication($this->apikey, $this->apisecret);
$auth = $isBasicAuth ? [$this->apikey, $this->apisecret] : [$this->apitoken];
$request = new Request(
$auth,
$method,
$url,
$args['filters'],
$args['body'],
$contentType,
$this->requestOptions
);
return $request->call($this->call);
}
// phpcs:enable
/**
* Build the base API url depending on wether user need a secure connection
* or not.
*
* @return string the API url;
*/
private function getApiUrl(): string
{
$h = true === $this->secure ? 'https' : 'http';
return sprintf('%s://%s/%s/', $h, $this->url, $this->version);
}
/**
* Checks that both parameters are strings, which means
* that basic authentication will be required.
*
* @param mixed $key
* @param mixed $secret
* @return bool flag
*/
private function isBasicAuthentication($key, $secret): bool
{
return !empty($key) && !empty($secret);
}
/**
* Build the final call url without query strings.
*
* @param string $resource Mailjet resource
* @param string $action Mailjet resource action
* @param string $id mailjet resource id
* @param string $actionid mailjet resource actionid
* @return string final call url
*/
private function buildURL(string $resource, string $action, string $id, string $actionid): string
{
$path = 'REST';
if (\in_array($resource, $this->smsResources, true)) {
$path = '';
} elseif (\in_array($action, $this->dataAction, true)) {
$path = 'DATA';
} elseif ('v4' === $this->version) {
$path = '';
}
$arrayFilter = [$path, $resource, $id, $action, $actionid];
return $this->getApiUrl() . implode('/', array_filter($arrayFilter));
}
/**
* Temporary set the variables generating the url.
*
* @param array $options contain temporary modifications for the client
* @param array $resource may contain the version linked to the resource
*/
private function setOptions(array $options, array $resource): void
{
if (isset($options['version'])) {
$this->version = $options['version'];
} elseif (isset($resource[2])) {
$this->version = $resource[2];
}
$this->url = (string)($options['url'] ?? Config::MAIN_URL);
$this->secure = $options['secured'] ?? Config::SECURED;
$this->call = $options['call'] ?? true;
$this->changed = true;
}
/**
* set back the variables generating the url.
*/
private function setSettings(): void
{
if (!empty($this->settings['url']) && \is_string($this->settings['url'])) {
$this->url = $this->settings['url'];
}
if (!empty($this->settings['version']) && \is_string($this->settings['version'])) {
$this->version = $this->settings['version'];
}
if (isset($this->settings['call']) && \is_bool($this->settings['call'])) {
$this->call = $this->settings['call'];
}
if (isset($this->settings['secured']) && \is_bool($this->settings['secured'])) {
$this->secure = $this->settings['secured'];
}
$this->changed = false;
}
/**
* Set a backup if the variables generating the url are change during a call.
*
* @param bool $call
* @param array $settings
*/
private function initSettings(bool $call, array $settings = []): void
{
$this->settings['url'] = $settings['url'] ?? $this->url;
$this->settings['version'] = $settings['version'] ?? $this->version;
$this->settings['call'] = $call;
$this->settings['secured'] = $settings['secured'] ?? $this->secure;
$this->changed = false;
}
}

View File

@@ -0,0 +1,22 @@
<?php
declare(strict_types=1);
/*
* Copyright (C) 2013 Mailgun
*
* This software may be modified and distributed under the terms
* of the MIT license. See the LICENSE file for details.
*/
namespace Mailjet;
class Config
{
public const WRAPPER_VERSION = 'v2.0.0';
public const USER_AGENT = 'mailjet-apiv3-php/';
public const MAIN_VERSION = 'v3';
public const MAIN_URL = 'api.mailjet.com';
public const SECURED = true;
public const SMS_VERSION = 'v4';
}

View File

@@ -0,0 +1,250 @@
<?php
declare(strict_types=1);
/*
* Copyright (C) 2013 Mailgun
*
* This software may be modified and distributed under the terms
* of the MIT license. See the LICENSE file for details.
*/
namespace Mailjet;
use GuzzleHttp\Client as GuzzleClient;
use GuzzleHttp\ClientTrait as GuzzleClientTrait;
use GuzzleHttp\Exception\ClientException;
use GuzzleHttp\Exception\ServerException;
use GuzzleHttp\Exception\GuzzleException;
use GuzzleHttp\Promise\PromiseInterface;
use Psr\Http\Client\ClientExceptionInterface;
use Psr\Http\Message\RequestInterface;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\UriInterface;
class Request
{
use GuzzleClientTrait;
/**
* @var string
*/
private $method;
/**
* @var string
*/
private $url;
/**
* @var array
*/
private $filters;
/**
* @var array
*/
private $body;
/**
* @var array
*/
private $auth;
/**
* @var string
*/
private $type;
/**
* @var array
*/
private $requestOptions = [];
/**
* @var GuzzleClient
*/
private $guzzleClient;
/**
* Build a new Http request.
*
* @param array $auth [apikey, apisecret]
* @param string $method http method
* @param string $url call url
* @param array $filters Mailjet resource filters
* @param mixed $body Mailjet resource body
* @param string $type Request Content-type
* @param array $requestOptions
*/
public function __construct(
array $auth,
string $method,
string $url,
array $filters,
$body,
string $type,
array $requestOptions = []
) {
$this->type = $type;
$this->auth = $auth;
$this->method = $method;
$this->url = $url;
$this->filters = $filters;
$this->body = $body;
$this->requestOptions = $requestOptions;
$this->guzzleClient = new GuzzleClient(
['defaults' => [
'headers' => [
'user-agent' => Config::USER_AGENT . PHP_VERSION . '/' . Client::WRAPPER_VERSION,
],
],
]
);
}
/**
* Trigger the actual call
*
* @param $call
* @return Response the call response
*/
public function call($call): Response
{
$payload = [
'query' => $this->filters,
('application/json' === $this->type ? 'json' : 'body') => $this->body,
];
$authArgsCount = \count($this->auth);
$headers = [
'content-type' => $this->type,
];
if ($authArgsCount > 1) {
$payload['auth'] = $this->auth;
} else {
$headers['Authorization'] = 'Bearer ' . $this->auth[0];
}
$payload['headers'] = $headers;
if ((!empty($this->requestOptions)) && (\is_array($this->requestOptions))) {
$payload = array_merge_recursive($payload, $this->requestOptions);
}
$response = null;
if ($call) {
try {
$response = call_user_func([$this, strtolower($this->method)], $this->url, $payload);
} catch (ClientException|ServerException $e) {
$response = $e->getResponse();
}
}
return new Response($this, $response);
}
/**
* Filters getters.
*
* @return array Request filters
*/
public function getFilters(): array
{
return $this->filters;
}
/**
* Http method getter.
*
* @return string Request method
*/
public function getMethod(): string
{
return $this->method;
}
/**
* Call Url getter.
*
* @return string Request Url
*/
public function getUrl(): string
{
return $this->url;
}
/**
* Request body getter.
*
* @return array request body
*/
public function getBody(): array
{
return $this->body;
}
/**
* Auth getter. to discuss.
*
* @return array Request auth
*/
public function getAuth(): array
{
return $this->auth;
}
/**
* @param RequestInterface $request Request to send
* @param array $options Request options to apply to the given
* request and to the transfer.
* @throws GuzzleException
*/
public function send(RequestInterface $request, array $options = []): ResponseInterface
{
return $this->guzzleClient->send($request, $options);
}
/**
* @param RequestInterface $request
* @return ResponseInterface
* @throws ClientExceptionInterface
*/
public function sendRequest(RequestInterface $request): ResponseInterface
{
return $this->guzzleClient->sendRequest($request);
}
/**
* @param RequestInterface $request Request to send
* @param array $options Request options to apply to the given
* request and to the transfer.
*/
public function sendAsync(RequestInterface $request, array $options = []): PromiseInterface
{
return $this->guzzleClient->sendAsync($request, $options);
}
/**
* @param string $method HTTP method.
* @param string|UriInterface $uri URI object or string.
* @param array $options Request options to apply.
* @throws GuzzleException
*/
public function request(string $method, $uri, array $options = []): ResponseInterface
{
return $this->guzzleClient->request($method, $uri, $options);
}
/**
* @param string $method HTTP method
* @param string|UriInterface $uri URI object or string.
* @param array $options Request options to apply.
*/
public function requestAsync(string $method, $uri, array $options = []): PromiseInterface
{
return $this->guzzleClient->requestAsync($method, $uri, $options);
}
}

View File

@@ -0,0 +1,121 @@
<?php
declare(strict_types=1);
/*
* Copyright (C) 2013 Mailgun
*
* This software may be modified and distributed under the terms
* of the MIT license. See the LICENSE file for details.
*/
namespace Mailjet;
/**
* PHP version 7.2.
*
* This is the Mailjet Resources Class
*
* @category Mailjet_API
*
* @author Guillaume Badi <gbadi@mailjet.com>
* @license MIT https://opensource.org/licenses/MIT
*
* @see dev.mailjet.com
*/
class Resources
{
public static $Email = ['send', ''/*, 'v3.1'*/];
public static $Aggregategraphstatistics = ['aggregategraphstatistics', ''];
public static $Apikey = ['apikey', ''];
public static $Apikeyaccess = ['apikeyaccess', ''];
public static $Apikeytotals = ['apikeytotals', ''];
public static $Apitoken = ['apitoken', ''];
public static $Axtesting = ['axtesting', ''];
public static $Batchjob = ['batchjob', ''];
public static $BatchjobCsverror = ['batchjob', 'csverror/text:csv'];
public static $BatchjobJsonerror = ['batchjob', 'JSONError/application:json/LAST'];
public static $Bouncestatistics = ['bouncestatistics', ''];
public static $Campaign = ['campaign', ''];
public static $Campaignaggregate = ['campaignaggregate', ''];
public static $Campaigndraft = ['campaigndraft', ''];
public static $CampaigndraftSchedule = ['campaigndraft', 'schedule'];
public static $CampaigndraftStatus = ['campaigndraft', 'status'];
public static $CampaigndraftSend = ['campaigndraft', 'send'];
public static $CampaigndraftTest = ['campaigndraft', 'test'];
public static $CampaigndraftDetailcontent = ['campaigndraft', 'detailcontent'];
public static $Campaigngraphstatistics = ['campaigngraphstatistics', ''];
public static $Campaignoverview = ['campaignoverview', ''];
public static $Campaignstatistics = ['campaignstatistics', ''];
public static $Clickstatistics = ['clickstatistics', ''];
public static $Contact = ['contact', ''];
public static $ContactManagecontactslists = ['contact', 'managecontactslists'];
public static $ContactGetcontactslists = ['contact', 'getcontactslists'];
public static $ContactManagemanycontacts = ['contact', 'managemanycontacts'];
public static $Contactdata = ['contactdata', ''];
public static $Contactfilter = ['contactfilter', ''];
public static $Contacthistorydata = ['contacthistorydata', ''];
public static $Contactmetadata = ['contactmetadata', ''];
public static $Contactslist = ['contactslist', ''];
public static $ContactslistCsvdata = ['contactslist', 'csvdata/text:plain'];
public static $ContactslistManagecontact = ['contactslist', 'ManageContact'];
public static $ContactslistManagemanycontacts = ['contactslist', 'ManageManyContacts'];
public static $ContactslistImportlist = ['contactslist', 'ImportList'];
public static $Contactslistsignup = ['contactslistsignup', ''];
public static $Contactstatistics = ['contactstatistics', ''];
public static $Csvimport = ['csvimport', ''];
public static $Dns = ['dns', ''];
public static $DnsCheck = ['dns', 'check'];
public static $Domainstatistics = ['domainstatistics', ''];
public static $Eventcallbackurl = ['eventcallbackurl', ''];
public static $Geostatistics = ['geostatistics', ''];
public static $Graphstatistics = ['graphstatistics', ''];
public static $Listrecipient = ['listrecipient', ''];
public static $Listrecipientstatistics = ['listrecipientstatistics', ''];
public static $Liststatistics = ['liststatistics', ''];
public static $Message = ['message', ''];
public static $Messagehistory = ['messagehistory', ''];
public static $Messageinformation = ['messageinformation', ''];
public static $Messagesentstatistics = ['messagesentstatistics', ''];
public static $Messagestate = ['messagestate', ''];
public static $Messagestatistics = ['messagestatistics', ''];
public static $Metadata = ['metadata', ''];
public static $Metasender = ['metasender', ''];
public static $Myprofile = ['myprofile', ''];
public static $Newsletter = ['newsletter', ''];
public static $NewsletterSchedule = ['newsletter', 'schedule'];
public static $NewsletterStatus = ['newsletter', 'status'];
public static $NewsletterSend = ['newsletter', 'send'];
public static $NewsletterTest = ['newsletter', 'test'];
public static $NewsletterDetailcontent = ['newsletter', 'detailcontent'];
public static $Newslettertemplate = ['newslettertemplate', ''];
public static $Newslettertemplatecategory = ['newslettertemplatecategory', ''];
public static $Openinformation = ['openinformation', ''];
public static $Openstatistics = ['openstatistics', ''];
public static $Parseroute = ['parseroute', ''];
public static $Preferences = ['preferences', ''];
public static $Preset = ['preset', ''];
public static $Sender = ['sender', ''];
public static $SenderValidate = ['sender', 'validate'];
public static $Senderstatistics = ['senderstatistics', ''];
public static $Template = ['template', ''];
public static $TemplateDetailcontent = ['template', 'detailcontent'];
public static $TemplateDetailpreviews = ['template', 'detailpreviews'];
public static $TemplateDisplaypreview = ['template', 'displaypreview'];
public static $TemplateDetailthumbnail = ['template', 'detailthumbnail'];
public static $TemplateDisplaythumbnail = ['template', 'displaythumbnail'];
public static $Toplinkclicked = ['toplinkclicked', ''];
public static $Trigger = ['trigger', ''];
public static $User = ['user', ''];
public static $UserActivate = ['user', 'activate'];
public static $Useragentstatistics = ['useragentstatistics', ''];
public static $Widget = ['widget', ''];
public static $Widgetcustomvalue = ['widgetcustomvalue', ''];
public static $Statcounters = ['statcounters', ''];
public static $StatisticsLinkclick = ['statistics', 'link-click'];
public static $StatisticsRecipientesp = ['statistics', 'recipient-esp'];
public static $Sms = ['sms', ''];
public static $SmsSend = ['sms-send', ''];
public static $SmsExport = ['sms', 'export'];
public static $SmsCount = ['sms', 'count'];
}

View File

@@ -0,0 +1,148 @@
<?php
declare(strict_types=1);
/*
* Copyright (C) 2013 Mailgun
*
* This software may be modified and distributed under the terms
* of the MIT license. See the LICENSE file for details.
*/
namespace Mailjet;
use Psr\Http\Message\ResponseInterface;
class Response
{
/**
* @var int|null
*/
private $status = null;
/**
* @var bool|null
*/
private $success = null;
/**
* @var array
*/
private $body = [];
/**
* @var ResponseInterface|null
*/
private $rawResponse = null;
/**
* @var Request
*/
private $request;
/**
* Construct a Mailjet response.
*
* @param Request $request Mailjet actual request
* @param ResponseInterface|null $response Guzzle response
*/
public function __construct(Request $request, ?ResponseInterface $response)
{
$this->request = $request;
if ($response) {
$this->rawResponse = $response;
$this->status = $response->getStatusCode();
$this->body = $this->decodeBody($response->getBody()->getContents());
$this->success = 2 == floor($this->status / 100);
}
}
/**
* Status Getter
* return the http status code.
*
* @return int|null status
*/
public function getStatus(): ?int
{
return $this->status;
}
/**
* Status Getter
* return the entire response array.
*/
public function getBody(): array
{
return $this->body;
}
/**
* Data Getter
* The data returned by the mailjet call.
*
* @return array data
*/
public function getData(): array
{
return $this->body['Data'] ?? $this->body;
}
/**
* Count getter
* return the resulting array size.
*/
public function getCount(): ?int
{
return $this->body['Count'] ?? null;
}
/**
* Error Reason getter
* return the resulting error message.
*
* @return string|null
*/
public function getReasonPhrase(): ?string
{
return $this->rawResponse ? $this->rawResponse->getReasonPhrase() : null;
}
/**
* Total getter
* return the total count of all results.
*
* @return int|null count
*/
public function getTotal(): ?int
{
return $this->body['Total'] ?? null;
}
/**
* Success getter.
*
* @return bool|null true is return code is 2**
*/
public function success(): ?bool
{
return $this->success;
}
public function getRequest(): Request
{
return $this->request;
}
/**
* Decodes a mailjet string response to an object representing that response.
*
* @param string $body The mailjet response as string
* @return array Object representing the mailjet response
*/
protected function decodeBody(string $body): array
{
return json_decode($body, true, 512, JSON_BIGINT_AS_STRING) ?: [];
}
}

View File

@@ -0,0 +1,237 @@
<?php
declare(strict_types=1);
/*
* Copyright (C) 2013 Mailgun
*
* This software may be modified and distributed under the terms
* of the MIT license. See the LICENSE file for details.
*/
namespace Mailjet;
use Mockery;
use PHPUnit\Framework\TestCase;
/**
* @runTestsInSeparateProcesses
* @preserveGlobalState disabled
*/
final class ClientTest extends TestCase
{
/**
* @var Client
*/
private $client;
/**
* @var Request
*/
private $requestMock;
public function setUp(): void
{
$this->requestMock = Mockery::mock('overload:' . Request::class);
$responseMock = Mockery::mock(Response::class);
$responseMock->shouldReceive('getData')
->andReturn(
[
'status' => 'test',
]
);
$this->requestMock->shouldReceive('call')
->andReturn($responseMock);
$this->client = new Client('testkey', 'testsecret', false);
}
public function testPost()
{
$expectedArguments = [
[
'testkey', 'testsecret'
],
'POST',
'https://api.mailjet.com/v3/REST/testresource',
[
'fkey' => 'fvalue',
],
[
'bkey' => 'bvalue',
],
'application/json',
[
'timeout' => 15,
'connect_timeout' => 2,
],
];
$this->requestMock->shouldReceive('__construct')
->once()
->withArgs($expectedArguments);
$response = $this->client->post(
['testresource', ''],
[
'filters' => ['fkey' => 'fvalue'],
'body' => ['bkey' => 'bvalue'],
]
);
$this->assertEquals(['status' => 'test',], $response->getData());
}
public function testGet()
{
$expectedArguments = [
[
'testkey', 'testsecret'
],
'GET',
'https://api.mailjet.com/v3/REST/testresource2',
[
'fkey2' => 'fvalue2',
],
[
'bkey2' => 'bvalue2',
],
'application/json',
[
'timeout' => 10,
'connect_timeout' => 20,
],
];
$this->requestMock->shouldReceive('__construct')
->once()
->withArgs($expectedArguments);
$this->client->setTimeout(10);
$this->client->setConnectionTimeout(20);
$response = $this->client->get(
['testresource2', ''],
[
'filters' => ['fkey2' => 'fvalue2'],
'body' => ['bkey2' => 'bvalue2'],
]
);
$this->assertEquals(['status' => 'test',], $response->getData());
}
public function testPut()
{
$expectedArguments = [
[
'testkey', 'testsecret'
],
'PUT',
'https://api.mailjet.com/v3/REST/testresource3',
[
'fkey3' => 'fvalue3',
],
[
'bkey3' => 'bvalue3',
],
'application/json',
[
'timeout' => 15,
'connect_timeout' => 2,
],
];
$this->requestMock->shouldReceive('__construct')
->once()
->withArgs($expectedArguments);
$response = $this->client->put(
['testresource3', ''],
[
'filters' => ['fkey3' => 'fvalue3'],
'body' => ['bkey3' => 'bvalue3'],
]
);
$this->assertEquals(['status' => 'test',], $response->getData());
}
public function testDelete()
{
$expectedArguments = [
[
'testkey', 'testsecret'
],
'DELETE',
'http://api.mailjet.com/v3/REST/testresource4',
[
'fkey4' => 'fvalue4',
],
[
'bkey4' => 'bvalue4',
],
'application/json',
[
'timeout' => 15,
'connect_timeout' => 2,
],
];
$this->requestMock->shouldReceive('__construct')
->once()
->withArgs($expectedArguments);
$this->client->setSecureProtocol(false);
$response = $this->client->delete(
['testresource4', ''],
[
'filters' => ['fkey4' => 'fvalue4'],
'body' => ['bkey4' => 'bvalue4'],
]
);
$this->assertEquals(['status' => 'test',], $response->getData());
}
public function testSetSecureProtocol()
{
$result = $this->client->setSecureProtocol(true);
$this->assertTrue($result);
$result = $this->client->setSecureProtocol(false);
$this->assertTrue($result);
$result = $this->client->setSecureProtocol(null);
$this->assertFalse($result);
}
public function testSetTimeout()
{
$this->client->setTimeout(100);
$this->assertEquals(100, $this->client->getRequestOptions()['timeout']);
$this->assertEquals(100, $this->client->getTimeout());
}
public function testSetHttpProxy()
{
$this->client->setHttpProxy(['test']);
$this->assertEquals(['test'], $this->client->getRequestOptions()['proxy']);
}
public function testSetConnectionTimeout()
{
$this->client->setConnectionTimeout(50);
$this->assertEquals(50, $this->client->getRequestOptions()['connect_timeout']);
$this->assertEquals(50, $this->client->getConnectionTimeout());
}
public function testAddRequestOption()
{
$this->client->addRequestOption('test', 'value');
$this->assertEquals('value', $this->client->getRequestOptions()['test']);
}
}

View File

@@ -0,0 +1,224 @@
<?php
declare(strict_types=1);
/*
* Copyright (C) 2013 Mailgun
*
* This software may be modified and distributed under the terms
* of the MIT license. See the LICENSE file for details.
*/
namespace Mailjet;
use PHPUnit\Framework\TestCase;
/**
* @internal
* @coversNothing
*/
final class MailjetApiv3Test extends TestCase
{
const API_BASE_URL = 'https://api.mailjet.com/';
const VERSION = 'v3';
private $publicKey = 'apikey';
private $secretKey = 'secretkey';
public function testGet()
{
$client = new Client($this->publicKey, $this->secretKey, true);
$this->assertUrl('/REST/contact', $client->get(Resources::$Contact));
$this->assertFilters(
['id' => 2], $client->get(
Resources::$Contact, [
'filters' => ['id' => 2],
], ['version' => 'v3.1']
)
);
$response = $client->get(Resources::$ContactGetcontactslists, ['id' => 2]);
$this->assertUrl('/REST/contact/2/getcontactslists', $response);
// error on sort !
$response = $client->get(
Resources::$Contact, [
'filters' => ['sort' => 'email+DESC'],
]
);
$this->assertUrl('/REST/contact', $response);
$this->assertUrl('/REST/contact/2', $client->get(Resources::$Contact, ['id' => 2]));
$this->assertUrl(
'/REST/contact/test@mailjet.com',
$client->get(Resources::$Contact, ['id' => 'test@mailjet.com'])
);
$this->assertHttpMethod('GET', $response);
$this->assertGetAuth($response);
$this->assertGetStatus(401, $response);
$this->assertGetBody(null, '', $response);
$this->assertGetData(null, '', $response);
$this->assertGetCount(null, $response);
$this->assertGetReasonPhrase('Unauthorized', $response);
$this->assertGetTotal(null, $response);
$this->assertSuccess(false, $response);
$this->assertSetSecureProtocol($client);
}
public function testPost()
{
$client = new Client($this->publicKey, $this->secretKey, true);
$email = [
'FromName' => 'Mailjet PHP test',
'FromEmail' => 'gbadi@student.42.fr',
'Text-Part' => 'Simple Email test',
'Subject' => 'PHPunit',
'Html-Part' => '<h3>Simple Email Test</h3>',
'Recipients' => [['Email' => 'test@mailjet.com']],
'MJ-custom-ID' => 'Hello ID',
];
$ret = $client->post(Resources::$Email, ['body' => $email]);
$this->assertUrl('/send', $ret);
$this->assertPayload($email, $ret);
$this->assertHttpMethod('POST', $ret);
$this->assertGetAuth($ret);
$this->assertGetStatus(401, $ret);
$this->assertGetBody(null, 'StatusCode', $ret);
$this->assertGetData(null, 'StatusCode', $ret);
$this->assertGetCount(null, $ret);
$this->assertGetReasonPhrase('Unauthorized', $ret);
$this->assertGetTotal(null, $ret);
$this->assertSuccess(false, $ret);
}
public function testPostV31()
{
$client = new Client($this->publicKey, $this->secretKey, false, ['version' => 'v3.1']);
$email = [
'Messages' => [[
'From' => ['Email' => 'test@mailjet.com', 'Name' => 'Mailjet PHP test'],
'TextPart' => 'Simple Email test',
'To' => [['Email' => 'test@mailjet.com', 'Name' => 'Test']],
]],
];
$ret = $client->post(Resources::$Email, ['body' => $email], ['timeout' => 1]);
$this->assertUrl('/send', $ret, 'v3.1');
$this->assertPayload($email, $ret);
$this->assertHttpMethod('POST', $ret);
$this->assertGetAuth($ret);
$this->assertGetStatus(401, $ret);
$this->assertGetBody(401, 'StatusCode', $ret);
$this->assertGetData(401, 'StatusCode', $ret);
$this->assertGetCount(null, $ret);
$this->assertGetReasonPhrase('Unauthorized', $ret);
$this->assertGetTotal(null, $ret);
$this->assertSuccess(false, $ret);
}
public function testClientHasOptions()
{
$client = new Client($this->publicKey, $this->secretKey, false);
$client->setTimeout(3);
$client->setConnectionTimeout(5);
$client->addRequestOption('delay', 23);
static::assertSame(3, $client->getTimeout());
static::assertSame(5, $client->getConnectionTimeout());
static::assertSame(23, $client->getRequestOptions()['delay']);
}
private function assertUrl($url, $response, $version = self::VERSION)
{
static::assertSame(self::API_BASE_URL.$version.$url, $response->getRequest()->getUrl());
}
private function assertPayload($payload, $response)
{
static::assertSame($payload, $response->getRequest()->getBody());
}
private function assertFilters($shouldBe, $response)
{
static::assertSame($shouldBe, $response->getRequest()->getFilters());
}
private function assertHttpMethod($payload, $response)
{
static::assertSame($payload, $response->getRequest()->getMethod());
}
private function assertGetAuth($response)
{
static::assertSame($this->publicKey, $response->getRequest()->getAuth()[0]);
static::assertSame($this->secretKey, $response->getRequest()->getAuth()[1]);
}
private function assertGetStatus($payload, $response)
{
static::assertSame($payload, $response->getStatus());
}
private function assertGetBody($payload, $keyName, $response)
{
$result = null;
if (false === empty($response->getBody()[$keyName])) {
$result = $response->getBody()[$keyName];
}
static::assertSame($payload, $result);
}
private function assertGetData($payload, $keyName, $response)
{
$result = null;
if (false === empty($response->getData()[$keyName])) {
$result = $response->getData()[$keyName];
}
static::assertSame($payload, $result);
}
private function assertGetCount($payload, $response)
{
static::assertSame($payload, $response->getCount());
}
private function assertGetReasonPhrase($payload, $response)
{
static::assertSame($payload, $response->getReasonPhrase());
}
private function assertGetTotal($payload, $response)
{
static::assertSame($payload, $response->getTotal());
}
private function assertSuccess($payload, $response)
{
static::assertSame($payload, $response->success());
}
private function assertSetSecureProtocol($client)
{
static::assertTrue($client->setSecureProtocol(true));
static::assertFalse($client->setSecureProtocol('not boolean type'));
}
}

View File

@@ -0,0 +1,32 @@
<?php
declare(strict_types=1);
/*
* Copyright (C) 2013 Mailgun
*
* This software may be modified and distributed under the terms
* of the MIT license. See the LICENSE file for details.
*/
namespace Mailjet;
use PHPUnit\Framework\TestCase;
/**
* @runTestsInSeparateProcesses
* @preserveGlobalState disabled
*/
final class RequestTest extends TestCase
{
public function testRequest()
{
$request = new Request(['test', 'test2'], 'GET', 'test.com', ['fkey' => 'fvalue'], ['bkey' => 'bvalue'], 'test', ['rok' => 'rov']);
$this->assertEquals(['fkey' => 'fvalue'], $request->getFilters());
$this->assertEquals('GET', $request->getMethod());
$this->assertEquals('test.com', $request->getUrl());
$this->assertEquals(['bkey' => 'bvalue'], $request->getBody());
$this->assertEquals(['test', 'test2'], $request->getAuth());
}
}

View File

@@ -0,0 +1,51 @@
<?php
declare(strict_types=1);
/*
* Copyright (C) 2013 Mailgun
*
* This software may be modified and distributed under the terms
* of the MIT license. See the LICENSE file for details.
*/
namespace Mailjet;
use PHPUnit\Framework\TestCase;
/**
* @runTestsInSeparateProcesses
* @preserveGlobalState disabled
*/
final class ResponseTest extends TestCase
{
public function testResponse()
{
$request = new Request(['test', 'test2'], 'GET', 'test.com', [], [], 'test', []);
$response = new Response(
$request,
new \GuzzleHttp\Psr7\Response(200, ['X-Foo' => 'Bar'], '{"Data": {"test": true}, "Count": 100, "Total": 200}')
);
$this->assertEquals(200, $response->getStatus());
$this->assertEquals(['Data' => ['test' => true], 'Count' => 100, 'Total' => 200], $response->getBody());
$this->assertEquals(['test' => true], $response->getData());
$this->assertEquals('OK', $response->getReasonPhrase());
$this->assertEquals(200, $response->getTotal());
}
public function testNullResponse()
{
$request = new Request(['test', 'test2'], 'GET', 'test.com', [], [], 'test', []);
// Response without a response interface as second parameter
$response = new Response($request, null);
$this->assertNull($response->getStatus());
$this->assertEquals([], $response->getBody());
$this->assertEquals([], $response->getData());
$this->assertNull($response->getReasonPhrase());
$this->assertNull($response->getTotal());
}
}

View File

@@ -0,0 +1,206 @@
<?php
declare(strict_types=1);
/*
* Copyright (C) 2013 Mailgun
*
* This software may be modified and distributed under the terms
* of the MIT license. See the LICENSE file for details.
*/
namespace Mailjet;
use PHPUnit\Framework\TestCase;
/**
* @internal
* @coversNothing
*/
final class test extends TestCase
{
public function assertPayload($payload, $response)
{
static::assertSame($payload, $response->request->getBody());
}
public function assertFilters($shouldBe, $response)
{
static::assertSame($shouldBe, $response->request->getFilters());
}
public function assertHttpMethod($payload, $response)
{
static::assertSame($payload, $response->request->getMethod());
}
public function assertGetAuth($payload, $response)
{
static::assertSame($payload, $response->request->getAuth()[0]);
static::assertSame($payload, $response->request->getAuth()[1]);
}
public function assertGetStatus($payload, $response)
{
static::assertSame($payload, $response->getStatus());
}
public function assertGetBody($payload, $keyName, $response)
{
static::assertSame($payload, $response->getBody()[$keyName]);
}
public function assertGetData($payload, $keyName, $response)
{
static::assertSame($payload, $response->getData()[$keyName]);
}
public function assertGetCount($payload, $response)
{
static::assertSame($payload, $response->getCount());
}
public function assertGetReasonPhrase($payload, $response)
{
static::assertSame($payload, $response->getReasonPhrase());
}
public function assertGetTotal($payload, $response)
{
static::assertSame($payload, $response->getTotal());
}
public function assertSuccess($payload, $response)
{
static::assertSame($payload, $response->success());
}
public function assertSetSecureProtocol($client)
{
static::assertTrue($client->setSecureProtocol(true));
static::assertFalse($client->setSecureProtocol('not boolean type'));
}
public function testGet()
{
$client = new Client('', '', false);
$this->assertUrl('/REST/contact', $client->get(Resources::$Contact));
$this->assertFilters(
['id' => 2], $client->get(
Resources::$Contact, [
'filters' => ['id' => 2],
], ['version' => 'v3.1']
)
);
$response = $client->get(Resources::$ContactGetcontactslists, ['id' => 2]);
$this->assertUrl('/REST/contact/2/getcontactslists', $response);
// error on sort !
$response = $client->get(
Resources::$Contact, [
'filters' => ['sort' => 'email+DESC'],
]
);
$this->assertUrl('/REST/contact', $response);
$this->assertUrl('/REST/contact/2', $client->get(Resources::$Contact, ['id' => 2]));
$this->assertUrl(
'/REST/contact/test@mailjet.com',
$client->get(Resources::$Contact, ['id' => 'test@mailjet.com'])
);
$this->assertHttpMethod('GET', $response);
$this->assertGetAuth('', $response);
$this->assertGetStatus(401, $response);
$this->assertGetBody('', '', $response);
$this->assertGetData('', '', $response);
$this->assertGetCount('', $response);
$this->assertGetReasonPhrase('Unauthorized', $response);
$this->assertGetTotal('', $response);
$this->assertSuccess('', $response);
$this->assertSetSecureProtocol($client);
}
public function testPost()
{
$client = new Client('', '', false);
$email = [
'FromName' => 'Mailjet PHP test',
'FromEmail' => 'gbadi@student.42.fr',
'Text-Part' => 'Simple Email test',
'Subject' => 'PHPunit',
'Html-Part' => '<h3>Simple Email Test</h3>',
'Recipients' => [['Email' => 'test@mailjet.com']],
'MJ-custom-ID' => 'Hello ID',
];
$ret = $client->post(Resources::$Email, ['body' => $email]);
$this->assertUrl('/send', $ret);
$this->assertPayload($email, $ret);
$this->assertHttpMethod('POST', $ret);
$this->assertGetAuth('', $ret);
$this->assertGetStatus(401, $ret);
$this->assertGetBody('', 'StatusCode', $ret);
$this->assertGetData('', 'StatusCode', $ret);
$this->assertGetCount('', $ret);
$this->assertGetReasonPhrase('Unauthorized', $ret);
$this->assertGetTotal('', $ret);
$this->assertSuccess('', $ret);
}
public function testPostV31()
{
$client = new Client('', '', false);
$email = [
'Messages' => [[
'From' => ['Email' => 'test@mailjet.com', 'Name' => 'Mailjet PHP test'],
'TextPart' => 'Simple Email test',
'To' => [['Email' => 'test@mailjet.com', 'Name' => 'Test']],
]],
];
$ret = $client->post(Resources::$Email, ['body' => $email], ['version' => 'v3.1']);
$this->assertUrl('/send', $ret, 'v3.1');
$this->assertPayload($email, $ret);
$this->assertHttpMethod('POST', $ret);
$this->assertGetAuth('', $ret);
$this->assertGetStatus(401, $ret);
$this->assertGetBody(401, 'StatusCode', $ret);
$this->assertGetData(401, 'StatusCode', $ret);
$this->assertGetCount('', $ret);
$this->assertGetReasonPhrase('Unauthorized', $ret);
$this->assertGetTotal('', $ret);
$this->assertSuccess('', $ret);
}
public function testClientHasOptions()
{
$client = new Client('', '', false);
$client->setTimeout(3);
$client->setConnectionTimeout(5);
$client->addRequestOption('delay', 23);
static::assertSame(3, $client->getTimeout());
static::assertSame(5, $client->getConnectionTimeout());
static::assertSame(23, $client->getRequestOptions()['delay']);
}
private function assertUrl($url, $response, $version = 'v3')
{
static::assertSame('https://api.mailjet.com/'.$version.$url, $response->request->getUrl());
}
}