Commit 50772c0f authored by Mikael Löwgren's avatar Mikael Löwgren

Implemented folder, file get, put file

parent c79856b1
Pipeline #397 failed with stages
This diff is collapsed.
......@@ -3,29 +3,38 @@ declare(strict_types=1);
namespace QBNK\MarketoApi\Controller;
use GuzzleHttp\RequestOptions;
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
* @param string|null $rootFolderId
* @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]);
public function list(string $rootFolderId = null ): array {
//$queryParameters = ['libraryId' => 'Image'];
//root={
// "id": 10092,
// "type": "Folder"
// }&maxDepth=2&maxReturn=20&offset=0&workspace
$queryParameters['root'] = "{ \"id\":".$parentFolderId.", \"type\":\"Folder\"}";
//$queryParameters['root'] = "{ \"id\":10092, \"type\":\"Folder\"}";
$queryParameters['maxDepth'] = '2';
$queryParameters['maxReturn'] = '20';
$queryParameters['offset'] = '0';
$queryParameters['workspace'] = '';
//var_dump( $this->apiHttpClient->getConfig() );
$response = $this->apiHttpClient->get('/rest/asset/v1/folders.json', [RequestOptions::QUERY => $queryParameters]);
$responseData = \GuzzleHttp\json_decode($response->getBody(), true);
$result = [];
foreach ($responseData as $rawFolder) {
var_dump( $responseData['result'] );
foreach ($responseData['result'] as $rawFolder) {
$result[] = FolderResponse::fromArray($rawFolder);
}
......
......@@ -7,46 +7,31 @@ namespace QBNK\MarketoApi\Controller;
use GuzzleHttp\Exception\ClientException;
use GuzzleHttp\Exception\TransferException;
use GuzzleHttp\RequestOptions;
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
* Sample query: https://509-APS-230.mktorest.com/rest/asset/v1/files.json?folder={ "id": 10092,"type": "Folder" }
* @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 {
public function list(string $folderId = null ): array {
$queryParameters = [];
if ($folderId !== null) {
$queryParameters['root'] = '{ \"id\":'.$folderId.', \"type\":\”Folder\" }';
$queryParameters['folder'] = "{ \"id\":".$folderId.", \"type\":\"Folder\" }";
//$queryParameters['folder'] = "{ \"id\":10092, \"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]);
var_dump( $queryParameters );
$response = $this->apiHttpClient->get('/rest/asset/v1/files.json', [RequestOptions::QUERY => $queryParameters]);
$responseData = \GuzzleHttp\json_decode($response->getBody(), true);
$result = [];
foreach ($responseData as $rawFolder) {
var_dump( $responseData );
foreach ($responseData['result'] as $rawFolder) {
$result[] = ImageResponse::fromArray($rawFolder);
}
......@@ -64,27 +49,36 @@ class ImageController extends BaseController {
*/
public function create(Image $image, string $pathToFile): ImageResponse {
$response = $this->apiHttpClient->post('/rest/asset/v1/files.json', [
$options = [
'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' => 'folder', 'contents' => "{ \"id\":".$image->getFolderId().", \"type\":\"Folder\" }"],
//['name' => 'tags', 'contents' => $image->getTags()],
//['name' => 'tags', 'contents' => $image->getTags()],
['name' => 'description', 'contents' => 'My Description'],
['name' => 'insertOnly', 'contents' => 'true']
],
'headers' => null //Might need headers Content-Type text/plain
]);
if ($response->getStatusCode() !== 201) {
'headers' => ['name' => 'Content-Type', 'contents' => 'text/plain' ] //Might need headers Content-Type text/plain
];
var_dump( $options );
$response = $this->apiHttpClient->post('/rest/asset/v1/files.json', $options);
if ($response->getStatusCode() !== 200) {
throw new TransferException('Non-successful response to upload: '.$response->getStatusCode().' '.$response->getReasonPhrase());
}
var_dump( $response->getBody()->getContents() );
/*
$assetUrl = $response->getHeader('Location')[0];
$imageId = str_replace('https://api-v1.templafy.com/images/', '', $assetUrl); //TODO Need to understand why replace here
$imageId = str_replace('https://api-v1/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); });
return $this->retryGuzzle(5, function() use ($imageId) { return $this->get($imageId); });*/
$responseData = \GuzzleHttp\json_decode($response->getBody(), true);
var_dump( $responseData );
return ImageResponse::fromArray( reset($responseData['result']) );
}
public function get(string $id): ImageResponse {
......
......@@ -6,8 +6,10 @@ namespace QBNK\MarketoApi;
use GuzzleHttp\Client;
use GuzzleHttp\HandlerStack;
use GuzzleHttp\RequestOptions;
use QBNK\MarketoApi\Controller\FolderController;
use QBNK\MarketoApi\Controller\ImageController;
use QBNK\MarketoApi\OAuth\MarketoClientCredentials;
use Sainsburys\Guzzle\Oauth2\GrantType\ClientCredentials;
use Sainsburys\Guzzle\Oauth2\GrantType\RefreshToken;
use Sainsburys\Guzzle\Oauth2\Middleware\OAuthMiddleware;
......@@ -18,7 +20,7 @@ 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
public const API_TOKEN_URL = 'identity/oauth/token'; //Not sure if this is applicable for marketo
/** @var Credentials */
protected $credentials;
......@@ -53,11 +55,14 @@ class MarketoApi
$config = [
ClientCredentials::CONFIG_CLIENT_ID => $this->credentials->getClientId(),
ClientCredentials::CONFIG_CLIENT_SECRET => $this->credentials->getClientSecret(),
ClientCredentials::CONFIG_TOKEN_URL => self::API_TOKEN_URL
ClientCredentials::CONFIG_AUTH_LOCATION => RequestOptions::QUERY,
ClientCredentials::CONFIG_TOKEN_URL => self::API_URL."/".self::API_TOKEN_URL
];
$this->oauth2Middleware = new OAuthMiddleware(
$oauthClient,
new ClientCredentials($oauthClient, $config),
new MarketoClientCredentials($oauthClient, $config),
new RefreshToken($oauthClient, $config)
);
$handlerStack->push($this->oauth2Middleware->onBefore());
......@@ -67,7 +72,7 @@ class MarketoApi
$apiClient = new Client([
'handler' => $handlerStack,
'auth' => 'oauth2',
'base_uri' => self::API_URL,
'base_uri' => self::API_URL.'/rest/assets/v1/folders.json',
'headers' => [
'Accept' => 'application/json',
'Content-type' => 'application/json',
......
......@@ -13,6 +13,14 @@ class Folder implements JsonSerializable {
/** @var string */
protected $parentFolderId;
/** @var string */
protected $folderId;
/** @var string */
protected $description;
/**
* @param string $name
* @return self
......@@ -49,7 +57,9 @@ class Folder implements JsonSerializable {
$instance = new static();
$instance
->setName($data['name'])
->setParentFolderId($data['parentFolderId'])
->setParentFolderId($data['parent']['id'])
->setFolderId($data['folderId']['id'])
// ->setDescription( $data['description'] ?? '' )
;
return $instance;
}
......@@ -64,7 +74,41 @@ class Folder implements JsonSerializable {
public function jsonSerialize() {
return [
'name' => $this->getName(),
'description' => $this->getDescription(),
'folderId' => $this->getFolderId(),
'parentFolderId' => $this->getParentFolderId()
];
}
/**
* @return string
*/
public function getFolderId(): string
{
return $this->folderId;
}
/**
* @param string $folderId
*/
public function setFolderId(string $folderId): void
{
$this->folderId = $folderId;
}
/**
* @return string
*/
public function getDescription(): string
{
return $this->description;
}
/**
* @param string $description
*/
public function setDescription(string $description): void
{
$this->description = $description;
}
}
\ No newline at end of file
......@@ -47,7 +47,7 @@ class FolderResponse extends Folder {
$instance = parent::fromArray($data);
$instance
->setId($data['id'])
->setNavigationPath($data['navigationPath'])
->setNavigationPath($data['url'])
;
return $instance;
}
......
......@@ -16,12 +16,32 @@ class Image implements JsonSerializable
/** @var string */
protected $folderId;
/** @var string */
protected $tags;
protected $description;
/** @var string */
protected $externalData;
/** @var string */
protected $id;
/**
* @return string
*/
public function getId(): string {
return $this->id;
}
/**
* @param string $id
* @return Image
*/
protected function setId(string $id): Image {
$this->id = $id;
return $this;
}
/**
* @param string $name
* @return Image
......@@ -92,12 +112,15 @@ class Image implements JsonSerializable
* @return Image
*/
public static function fromArray(array $data) {
var_dump( $data );
/** @var $instance Image */
$instance = new static();
$instance
->setId( (string)$data['id'] )
->setName((string)$data['name'])
->setTags((string)$data['tags'])
->setFolderId((string)$data['folderId'])
->setExternalData((string)$data['externalData'])
->setDescription((string)$data['description'])
->setFolderId((string)$data['folder']['id'])
//->setExternalData((string)$data['externalData'])
; //TODO: Check if tags are applicable for Marketo
return $instance;
}
......@@ -114,8 +137,26 @@ class Image implements JsonSerializable
return [
'name' => $this->getName(),
'folderId' => $this->getFolderId(),
'tags' => $this->getTags(),
'description' => $this->getDescription(),
'externalData' => $this->getExternalData()
];
}
/**
* @return string
*/
public function getDescription(): string
{
return $this->description;
}
/**
* @param string $description
* @return Image
*/
public function setDescription(string $description): Image
{
$this->description = $description;
return $this;
}
}
\ No newline at end of file
......@@ -8,36 +8,17 @@ namespace QBNK\MarketoApi\Model;
class ImageResponse extends Image
{
/** @var string */
protected $id;
/** @var string */
protected $mimeType;
/** @var int */
protected $width;
/** @var int */
protected $height;
/** @var int */
protected $fileSize;
/** @var string */
protected $checksum;
/** @var string */
protected $previewUrl;
/** @var string */
protected $downloadUrl;
/**
* @return string
*/
public function getId(): string {
return $this->id;
}
/**
* @return string
......@@ -46,19 +27,6 @@ class ImageResponse extends Image
return $this->mimeType;
}
/**
* @return int
*/
public function getWidth(): int {
return $this->width;
}
/**
* @return int
*/
public function getHeight(): int {
return $this->height;
}
/**
* @return int
......@@ -67,13 +35,6 @@ class ImageResponse extends Image
return $this->fileSize;
}
/**
* @return string
*/
public function getChecksum(): string {
return $this->checksum;
}
/**
* @return string
*/
......@@ -81,21 +42,7 @@ class ImageResponse extends Image
return $this->previewUrl;
}
/**
* @return string
*/
public function getDownloadUrl(): string {
return $this->downloadUrl;
}
/**
* @param string $id
* @return ImageResponse
*/
protected function setId(string $id): ImageResponse {
$this->id = $id;
return $this;
}
/**
* @param string $mimeType
......@@ -106,23 +53,6 @@ class ImageResponse extends Image
return $this;
}
/**
* @param int $width
* @return ImageResponse
*/
protected function setWidth(int $width): ImageResponse {
$this->width = $width;
return $this;
}
/**
* @param int $height
* @return ImageResponse
*/
protected function setHeight(int $height): ImageResponse {
$this->height = $height;
return $this;
}
/**
* @param int $fileSize
......@@ -133,14 +63,6 @@ class ImageResponse extends Image
return $this;
}
/**
* @param string $checksum
* @return ImageResponse
*/
protected function setChecksum(string $checksum): ImageResponse {
$this->checksum = $checksum;
return $this;
}
/**
* @param string $previewUrl
......@@ -151,30 +73,23 @@ class ImageResponse extends Image
return $this;
}
/**
* @param string $downloadUrl
* @return ImageResponse
*/
protected function setDownloadUrl(string $downloadUrl): ImageResponse {
$this->downloadUrl = $downloadUrl;
return $this;
}
/**
* TODO Are missing file attributes needed for qbank?
* @return ImageResponse
*/
public static function fromArray(array $data) {
/** @var $instance ImageResponse */
$instance = parent::fromArray($data);
$instance
->setId($data['id'])
->setId((string)$data['id'])
->setMimeType((string)$data['mimeType'])
//->setWidth((int)$data['width'])
//->setHeight((int)$data['height'])
->setFileSize((int)$data['size'])
//->setChecksum((string)$data['checksum'])
//->setPreviewUrl((string)$data['url'])
->setDownloadUrl((string)$data['url'])
->setPreviewUrl((string)$data['url'])
;
return $instance;
}
......
<?php
namespace QBNK\MarketoApi\OAuth;
use GuzzleHttp\RequestOptions;
use Sainsburys\Guzzle\Oauth2\AccessToken;
use Sainsburys\Guzzle\Oauth2\GrantType\ClientCredentials;
use Sainsburys\Guzzle\Oauth2\GrantType\GrantTypeBase;
use GuzzleHttp\Client;
class MarketoClientCredentials extends ClientCredentials
{
protected $grantType = 'client_credentials';
/* @var $client Client */
/**
* {@inheritdoc}
*/
public function getToken()
{
$body = $this->config;
$body[self::GRANT_TYPE] = $this->grantType;
unset($body[self::CONFIG_TOKEN_URL], $body[self::CONFIG_AUTH_LOCATION]);
$requestOptions = [];
if ($this->config[self::CONFIG_AUTH_LOCATION] !== RequestOptions::BODY) {
$requestOptions[RequestOptions::AUTH] = [
$this->config[self::CONFIG_CLIENT_ID],
isset($this->config[self::CONFIG_CLIENT_SECRET]) ? $this->config[self::CONFIG_CLIENT_SECRET] : '',
];
//unset($body[self::CONFIG_CLIENT_ID], $body[self::CONFIG_CLIENT_SECRET]);
}
unset($body["scope"]);
$requestOptions[RequestOptions::QUERY] = $body;
if ($additionalOptions = $this->getAdditionalOptions()) {
$requestOptions = array_merge_recursive($requestOptions, $additionalOptions);
}
var_dump( "before get");
var_dump( $this->config[self::CONFIG_TOKEN_URL], $requestOptions );
$response = $this->client->get($this->config[self::CONFIG_TOKEN_URL], $requestOptions);
var_dump($response );
$data = json_decode($response->getBody()->__toString(), true);
return new AccessToken($data['access_token'], $data['token_type'], $data);
}
}
\ No newline at end of file
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment