Commit c79856b1 authored by Mikael Löwgren's avatar Mikael Löwgren

Initial structure, not implemented all actions yet.

parents
MIT License
Copyright (c) 2019 QBNK Company AB
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.
# Marketo Api Wrapper
A simple API wrapper for Marketo https://www.marketo.com Allows for simple communication from PHP with Marketo with
minimal setup.
## Requirements
* PHP 7.2+
* Guzzle 6.1+
## Installation
`composer require qbnk/marketo-apiwrapper ^0.1`
## Authorization
Marketo's API uses OAuth2 with the client credentials flow. This means that you will need a *client id* and a *client
secret* to be able to authorize with and use the API. The *client id* and *client secret* is available in the
Marketo administration.
### Example
To create an instance that can authorize with the API, simply pass a `Credentials` instance with the *client id* and
*client secret* to the `MarketoApi` constructor. The library will then handle the rest.
```php
$api = new MarketoApi(new Credentials('customer', 'client secret'));
```
## FAQ
{
"name": "qbnk/marketo-apiwrapper",
"description": "An API wrapper for Marketo",
"minimum-stability": "stable",
"prefer-stable": true,
"license": "MIT",
"authors": [
{
"name": "Mikael Löwgren",
"email": "mikael.lowgren@qbank.se"
}
],
"autoload": {
"psr-4": {
"QBNK\\MarketoApi\\": "src"
}
},
"require": {
"php" : "~7.2",
"ext-json": "*",
"guzzlehttp/guzzle": "~6.1",
"sainsburys/guzzle-oauth2-plugin": "~3.0"
},
"require-dev": {
"roave/security-advisories": "dev-master"
}
}
\ No newline at end of file
<?php
declare(strict_types=1);
namespace QBNK\MarketoApi\Controller;
use GuzzleHttp\Client;
class BaseController {
/** @var Client */
protected $apiHttpClient;
public function __construct($apiHttpClient) {
$this->apiHttpClient = $apiHttpClient;
}
}
\ No newline at end of file
<?php
declare(strict_types=1);
namespace QBNK\MarketoApi\Controller;
use QBNK\MarketoApi\Model\Folder;
use QBNK\MarketoApi\Model\FolderResponse;
class FolderController extends BaseController {
/**
* @param string|null $parentFolderId
* @param string|null $navigationPath Hierarchical path identifying a parent folder
* @return FolderResponse[]
*/
public function list(string $parentFolderId = null, string $navigationPath = null): array {
$queryParameters = ['libraryId' => 'Image'];
if ($parentFolderId !== null) {
$queryParameters['parentFolderId'] = $parentFolderId;
}
if ($navigationPath !== null) {
$queryParameters['navigationPath'] = $navigationPath;
}
$response = $this->apiHttpClient->get('/rest/asset/v1/folders.json', ['query' => $queryParameters]);
$responseData = \GuzzleHttp\json_decode($response->getBody(), true);
$result = [];
foreach ($responseData as $rawFolder) {
$result[] = FolderResponse::fromArray($rawFolder);
}
return $result;
}
/**
* TODO: Implement for Marketo. ../folders.json might not be the correct create for folders
* @param Folder $folder
* @return FolderResponse
*/
public function create(Folder $folder): FolderResponse {
$response = $this->apiHttpClient->post('/rest/asset/v1/folders.json', ['json' => $folder]);
$folderId = \GuzzleHttp\json_decode($response->getBody(), true);
return FolderResponse::fromArray([
'id' => $folderId,
'name' => $folder->getName(),
'parentFolderId' => $folder->getParentFolderId(),
'navigationPath' => ''
]);
}
/**
* TODO: Check API for get operation. This is not correct.
* @param string $id
* @return FolderResponse
*/
public function get(string $id): FolderResponse {
$response = $this->apiHttpClient->get('/rest/asset/v1/folders.json'.$id);
$responseData = \GuzzleHttp\json_decode($response->getBody(), true);
return FolderResponse::fromArray($responseData);
}
/**
* TODO: Check API for correct operation. This is not correct.
* @param string $id
* @return FolderResponse
*/
public function update(string $id, Folder $folder): void {
$this->apiHttpClient->put('folders/'.$id, ['json' => $folder]);
}
/**
* TODO: Check API for correct operation. This is not correct.
* @param string $id
* @return FolderResponse
*/
public function delete(string $id): void {
$this->apiHttpClient->delete('/folders/'.$id);
}
}
\ No newline at end of file
<?php
declare(strict_types=1);
namespace QBNK\MarketoApi\Controller;
use GuzzleHttp\Exception\ClientException;
use GuzzleHttp\Exception\TransferException;
use QBNK\MarketoApi\Model\Image;
use QBNK\MarketoApi\Model\ImageResponse;
class ImageController extends BaseController {
/**
*
* Sample query: folders.json?root={ "id": 15,
"type": "Folder"
}&maxDepth=2&maxReturn=40&offset=0&workspace
* @param string|null $folderId
* @param string|null $navigationPath
* @param string|null $searchQuery
* @param int|null $pageNumber
* @param int|null $pageSize
* @return ImageResponse[]
*/
public function list(string $folderId = null, string $navigationPath = null, string $searchQuery = null, int $pageNumber = null, int $pageSize = null): array {
$queryParameters = [];
if ($folderId !== null) {
$queryParameters['root'] = '{ \"id\":'.$folderId.', \"type\":\”Folder\" }';
}
//TODO not applicable for Marketo
if ($navigationPath !== null) {
$queryParameters['navigationPath'] = $navigationPath;
}
//TODO not applicable for Marketo
if ($searchQuery !== null) {
$queryParameters['searchQuery'] = $searchQuery;
}
if ($pageNumber !== null) {
$queryParameters['offset'] = $pageNumber;
}
if ($pageSize !== null) {
$queryParameters['maxReturn'] = $pageSize;
}
$response = $this->apiHttpClient->get('/rest/asset/v1/files.json', ['query' => $queryParameters]);
$responseData = \GuzzleHttp\json_decode($response->getBody(), true);
$result = [];
foreach ($responseData as $rawFolder) {
$result[] = ImageResponse::fromArray($rawFolder);
}
return $result;
}
/**
* File content needs to be in top of multipart (according to documentation, not tested)
* File max size 100MB
* Filename can't contain comma.
* TODO Implement description property
* @param Image $image
* @param string $pathToFile
* @return ImageResponse
*/
public function create(Image $image, string $pathToFile): ImageResponse {
$response = $this->apiHttpClient->post('/rest/asset/v1/files.json', [
'multipart' => [
['name' => 'filename', 'contents' => $image->getName()],
['name' => 'file', 'contents' => fopen($pathToFile, 'r')],
['name' => 'name', 'contents' => $image->getName()],
['name' => 'folder', 'contents' => '{ \"id\":'.$image->getFolderId().', \"type\":\”Folder\" }'],
//['name' => 'tags', 'contents' => $image->getTags()],
//['name' => 'tags', 'contents' => $image->getTags()],
['name' => 'insertOnly', 'contents' => 'true']
],
'headers' => null //Might need headers Content-Type text/plain
]);
if ($response->getStatusCode() !== 201) {
throw new TransferException('Non-successful response to upload: '.$response->getStatusCode().' '.$response->getReasonPhrase());
}
$assetUrl = $response->getHeader('Location')[0];
$imageId = str_replace('https://api-v1.templafy.com/images/', '', $assetUrl); //TODO Need to understand why replace here
// Sometimes the API doesn't realize the image we just uploaded exists. Retry up to 5 times.
return $this->retryGuzzle(5, function() use ($imageId) { return $this->get($imageId); });
}
public function get(string $id): ImageResponse {
$response = $this->apiHttpClient->get('/images/'.$id);
$responseData = \GuzzleHttp\json_decode($response->getBody(), true);
return ImageResponse::fromArray($responseData);
}
public function update(string $id, Image $image, string $pathToFile): ImageResponse {
$response = $this->apiHttpClient->patch('/images/'.$id, [
'multipart' => [
['name' => 'name', 'contents' => $image->getName()],
['name' => 'folderId', 'contents' => $image->getFolderId()],
['name' => 'tags', 'contents' => $image->getTags()],
['name' => 'externalData', 'contents' => $image->getExternalData()],
['name' => 'file', 'contents' => fopen($pathToFile, 'r')]
],
'headers' => null
]);
return $this->get($id);
}
public function delete(string $id): void {
$this->apiHttpClient->delete('/images/'.$id);
}
/**
* Retries $fn up to $retries times with exponential back off when 4xx responses are returned.
* @param int $retries
* @param callable $fn
* @throws ClientException Thrown when $retries attempts has been made. Is the last real ClientException.
* @return mixed The return value from $fn
*/
protected function retryGuzzle(int $retries, callable $fn) {
$attempts = 1;
beginning:
try {
return $fn();
} catch (ClientException $ce) {
if (!$retries) {
throw $ce;
}
$retries--;
sleep(2 ** $attempts); // Exponential back off
$attempts++;
goto beginning;
}
}
}
\ No newline at end of file
<?php
declare(strict_types=1);
namespace QBNK\MarketoApi;
class Credentials
{
/** @var string */
protected $clientId;
/** @var string */
protected $username;
/**
* @param string $clientId
* @param string $clientSecret
*/
public function __construct($clientId, $clientSecret) {
$this->clientId = $clientId;
$this->clientSecret($clientSecret);
}
/**
* Gets or sets the internal value
* @internal Hack to hide value from dumping and possibly exposing by mistake.
* @param string|null $newClientSecret
* @return string
*/
protected function clientSecret($newClientSecret = null): string {
static $clientSecret;
if ($newClientSecret !== null) {
$clientSecret = $newClientSecret;
}
return $clientSecret ?? '';
}
public function getClientId(): string {
return $this->clientId;
}
public function getClientSecret(): string {
return $this->clientSecret();
}
}
\ No newline at end of file
<?php
declare(strict_types=1);
namespace QBNK\MarketoApi;
use GuzzleHttp\Client;
use GuzzleHttp\HandlerStack;
use QBNK\MarketoApi\Controller\FolderController;
use QBNK\MarketoApi\Controller\ImageController;
use Sainsburys\Guzzle\Oauth2\GrantType\ClientCredentials;
use Sainsburys\Guzzle\Oauth2\GrantType\RefreshToken;
use Sainsburys\Guzzle\Oauth2\Middleware\OAuthMiddleware;
class MarketoApi
{
public const API_URL = 'https://509-APS-230.mktorest.com'; //Aptio instance, need to be property for future?
public const API_TOKEN_URL = 'oauth2/token'; //Not sure if this is applicable for marketo
/** @var Credentials */
protected $credentials;
/** @var Client */
protected $apiClient;
/** @var OAuthMiddleware */
protected $oauth2Middleware;
/** @var FolderController */
protected $folderController;
/** @var ImageController */
protected $imageController;
public function __construct(Credentials $credentials, array $options = []) {
$this->credentials = $credentials;
}
public function getHttpClient(): Client {
if (!($this->apiClient instanceof Client)) {
$handlerStack = HandlerStack::create();
$oauthClient = new Client([
'base_uri' => self::API_URL,
'verify' => true,
'headers' => [
'User-Agent' => 'marketo-apiwrapper/1 (guzzle: 6)',
],
]);
$config = [
ClientCredentials::CONFIG_CLIENT_ID => $this->credentials->getClientId(),
ClientCredentials::CONFIG_CLIENT_SECRET => $this->credentials->getClientSecret(),
ClientCredentials::CONFIG_TOKEN_URL => self::API_TOKEN_URL
];
$this->oauth2Middleware = new OAuthMiddleware(
$oauthClient,
new ClientCredentials($oauthClient, $config),
new RefreshToken($oauthClient, $config)
);
$handlerStack->push($this->oauth2Middleware->onBefore());
$handlerStack->push($this->oauth2Middleware->onFailure(3));
$apiClient = new Client([
'handler' => $handlerStack,
'auth' => 'oauth2',
'base_uri' => self::API_URL,
'headers' => [
'Accept' => 'application/json',
'Content-type' => 'application/json',
'User-Agent' => 'marketo-apiwrapper/1 (guzzle: 6)',
]
]);
$this->apiClient = $apiClient;
}
return $this->apiClient;
}
public function folders(): FolderController {
if (!($this->folderController instanceof FolderController)) {
$this->folderController = new FolderController($this->getHttpClient());
}
return $this->folderController;
}
public function images(): ImageController {
if (!($this->imageController instanceof ImageController)) {
$this->imageController = new ImageController($this->getHttpClient());
}
return $this->imageController;
}
}
\ No newline at end of file
<?php
namespace QBNK\MarketoApi\Model;
use JsonSerializable;
class Folder implements JsonSerializable {
/** @var string */
protected $name;
/** @var string */
protected $parentFolderId;
/**
* @param string $name
* @return self
*/
public function setName(string $name) {
$this->name = $name;
return $this;
}
/**
* @return string
*/
public function getName(): string {
return $this->name ?? '';
}
/**
* @param string $parentFolderId
* @return self
*/
public function setParentFolderId(string $parentFolderId) {
$this->parentFolderId = $parentFolderId;
return $this;
}
/**
* @return string
*/
public function getParentFolderId(): string {
return $this->parentFolderId ?? '';
}
public static function fromArray(array $data) {
$instance = new static();
$instance
->setName($data['name'])
->setParentFolderId($data['parentFolderId'])
;
return $instance;
}
/**
* Specify data which should be serialized to JSON
* @link https://php.net/manual/en/jsonserializable.jsonserialize.php
* @return mixed data which can be serialized by <b>json_encode</b>,
* which is a value of any type other than a resource.
* @since 5.4.0
*/
public function jsonSerialize() {
return [
'name' => $this->getName(),
'parentFolderId' => $this->getParentFolderId()
];
}
}
\ No newline at end of file
<?php
namespace QBNK\MarketoApi\Model;
class FolderResponse extends Folder {
/** @var string */
protected $id;
/** @var string */
protected $navigationPath;
/**
* @param string $id
* @return self
*/
protected function setId(string $id) {
$this->id = $id;
return $this;
}
/**
* @return string
*/
public function getId(): string {
return $this->id ?? '';
}
/**
* @param string $navigationPath
* @return self
*/
protected function setNavigationPath(string $navigationPath) {
$this->navigationPath = $navigationPath;
return $this;
}
/**
* @return string
*/
public function getNavigationPath(): string {
return $this->navigationPath ?? '';
}
public static function fromArray(array $data) {
$instance = parent::fromArray($data);
$instance
->setId($data['id'])
->setNavigationPath($data['navigationPath'])
;
return $instance;
}
}
\ No newline at end of file
<?php
declare(strict_types=1);
namespace QBNK\MarketoApi\Model;
use JsonSerializable;
class Image implements JsonSerializable
{
/** @var string */
protected $name;
/** @var string */
protected $folderId;
/** @var string */
protected $tags;
/** @var string */
protected $externalData;
/**
* @param string $name
* @return Image
*/
public function setName(string $name): Image {
$this->name = $name;
return $this;
}
/**
* @return string
*/
public function getName(): string {
return $this->name;