Initial commit version 1.0.0

This commit is contained in:
Jérémy Munsch 2022-07-29 15:11:28 +02:00
commit ec927f66c0
No known key found for this signature in database
GPG key ID: 18361AF3BFEC0FEC
29 changed files with 4025 additions and 0 deletions

18
.editorconfig Normal file
View file

@ -0,0 +1,18 @@
root = true
[*]
charset = utf-8
end_of_line = lf
insert_final_newline = true
indent_style = space
indent_size = 4
trim_trailing_whitespace = true
[*.json]
indent_size = 4
[*.md]
trim_trailing_whitespace = false
[*.{yml,yaml}]
indent_size = 2

6
.gitignore vendored Normal file
View file

@ -0,0 +1,6 @@
workspace.code-workspace
vendor
node_modules
.phpdoc
.phive
.vscode

0
.gitkeep Normal file
View file

6
apiConfig.readonly.json Normal file
View file

@ -0,0 +1,6 @@
{
"version": "1.0.0",
"timestampTimeout": 30,
"apiRequestRatePerMinute": 256,
"servicesDBCache": 10
}

6
changelog.md Normal file
View file

@ -0,0 +1,6 @@
# Changelog
### All notable changes to `DAM CLient` will be documented in this file.
# version 1.0.0
- Initial release

42
composer.json Normal file
View file

@ -0,0 +1,42 @@
{
"name": "ldc/damclient",
"type": "library",
"description": "LDC DAM Client",
"license": "MIT",
"version": "1.0.0",
"authors": [
{
"name": "Jérémy Munsch",
"email": "jeremy.munsch@ldc.fr",
"homepage": "https://jeremydev.ovh"
}
],
"homepage": "https://github.com/kwaadpepper",
"keywords": [
"Laravel",
"DAM",
"Client",
"LDC"
],
"require": {
"ext-curl": "*",
"php": ">=7.3",
"guzzlehttp/guzzle": "^7.4",
"respect/validation": "^2.2",
"kwaadpepper/enum": "^2.0"
},
"require-dev": {
"squizlabs/php_codesniffer": "^3.5",
"slevomat/coding-standard": "^7.0"
},
"autoload": {
"psr-4": {
"LDC\\DAM\\Client\\": "src/"
}
},
"config": {
"allow-plugins": {
"dealerdirect/phpcodesniffer-composer-installer": true
}
}
}

1121
composer.lock generated Normal file

File diff suppressed because it is too large Load diff

21
license.md Normal file
View file

@ -0,0 +1,21 @@
MIT License
Copyright (c) 2022 Jérémy Munsch
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.

125
phpcs.xml Normal file
View file

@ -0,0 +1,125 @@
<?xml version="1.0" encoding="UTF-8"?>
<ruleset name="DAM Laravel"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="vendor/squizlabs/php_codesniffer/phpcs.xsd">
<description>Created with the PHP Coding Standard Generator. http://edorian.github.com/php-coding-standard-generator/</description>
<arg name="colors" />
<arg name="extensions" value="php" />
<file>src/</file>
<rule ref="PSR1" />
<rule ref="PSR12" />
<rule ref="Generic.Classes.DuplicateClassName"/>
<rule ref="Generic.CodeAnalysis.EmptyStatement"/>
<rule ref="Generic.CodeAnalysis.ForLoopShouldBeWhileLoop"/>
<rule ref="Generic.CodeAnalysis.ForLoopWithTestFunctionCall"/>
<rule ref="Generic.CodeAnalysis.JumbledIncrementer"/>
<rule ref="Generic.CodeAnalysis.UnconditionalIfStatement"/>
<rule ref="Generic.CodeAnalysis.UnnecessaryFinalModifier"/>
<rule ref="Generic.CodeAnalysis.UnusedFunctionParameter"/>
<rule ref="Generic.CodeAnalysis.UselessOverridingMethod"/>
<rule ref="Generic.Commenting.Todo"/>
<rule ref="Generic.Commenting.Fixme"/>
<rule ref="Generic.ControlStructures.InlineControlStructure"/>
<rule ref="Generic.Files.ByteOrderMark"/>
<rule ref="Generic.Files.LineEndings"/>
<rule ref="Generic.Files.LineLength"/>
<rule ref="Generic.Formatting.DisallowMultipleStatements"/>
<rule ref="Generic.Formatting.MultipleStatementAlignment"/>
<rule ref="Generic.Formatting.NoSpaceAfterCast"/>
<rule ref="Generic.Functions.CallTimePassByReference"/>
<rule ref="Generic.Functions.FunctionCallArgumentSpacing"/>
<rule ref="Generic.Metrics.CyclomaticComplexity"/>
<rule ref="Generic.Metrics.NestingLevel"/>
<rule ref="Generic.NamingConventions.ConstructorName"/>
<rule ref="Generic.NamingConventions.UpperCaseConstantName"/>
<rule ref="Generic.NamingConventions.CamelCapsFunctionName"/>
<rule ref="Generic.PHP.DeprecatedFunctions"/>
<rule ref="Generic.PHP.DisallowShortOpenTag"/>
<rule ref="Generic.PHP.ForbiddenFunctions"/>
<rule ref="Generic.PHP.NoSilencedErrors"/>
<rule ref="Generic.Strings.UnnecessaryStringConcat"/>
<rule ref="Generic.WhiteSpace.DisallowTabIndent"/>
<rule ref="Generic.WhiteSpace.ScopeIndent"/>
<rule ref="MySource.PHP.EvalObjectFactory"/>
<rule ref="MySource.PHP.GetRequestData"/>
<rule ref="MySource.PHP.AjaxNullComparison"/>
<rule ref="PEAR.Classes.ClassDeclaration"/>
<rule ref="PEAR.Commenting.InlineComment"/>
<rule ref="PSR1.Classes.ClassDeclaration"/>
<rule ref="PSR1.Files.SideEffects"/>
<rule ref="PSR2.Classes.ClassDeclaration"/>
<rule ref="PSR2.Classes.PropertyDeclaration"/>
<rule ref="PSR2.ControlStructures.ElseIfDeclaration"/>
<rule ref="PSR2.ControlStructures.SwitchDeclaration"/>
<rule ref="PSR2.Files.EndFileNewline"/>
<rule ref="PSR2.Methods.MethodDeclaration"/>
<rule ref="PSR2.Namespaces.NamespaceDeclaration"/>
<rule ref="PSR2.Namespaces.UseDeclaration"/>
<rule ref="Squiz.PHP.CommentedOutCode"/>
<rule ref="Squiz.PHP.DisallowMultipleAssignments">
<exclude name="Squiz.PHP.DisallowMultipleAssignments.FoundInControlStructure" />
</rule>
<rule ref="Squiz.PHP.DisallowSizeFunctionsInLoops"/>
<rule ref="Squiz.PHP.DiscouragedFunctions">
<properties>
<property name="error" value="true"/>
</properties>
</rule>
<rule ref="Squiz.PHP.Eval"/>
<rule ref="Squiz.PHP.GlobalKeyword"/>
<rule ref="Squiz.PHP.Heredoc"/>
<rule ref="Squiz.PHP.InnerFunctions"/>
<rule ref="Squiz.PHP.LowercasePHPFunctions"/>
<rule ref="Squiz.PHP.NonExecutableCode"/>
<rule ref="Squiz.Scope.MemberVarScope"/>
<rule ref="Squiz.Scope.MethodScope"/>
<rule ref="Squiz.Scope.StaticThisUsage"/>
<rule ref="Squiz.WhiteSpace.LanguageConstructSpacing"/>
<rule ref="Squiz.WhiteSpace.LogicalOperatorSpacing"/>
<rule ref="Squiz.WhiteSpace.MemberVarSpacing">
<properties>
<property name="spacingBeforeFirst " value="false"/>
</properties>
</rule>
<rule ref="Squiz.WhiteSpace.OperatorSpacing">
<properties>
<property name="ignoreNewlines" value="true"/>
</properties>
</rule>
<rule ref="Squiz.WhiteSpace.ObjectOperatorSpacing">
<properties>
<property name="ignoreNewlines" value="true"/>
</properties>
</rule>
<rule ref="Squiz.WhiteSpace.ScopeKeywordSpacing"/>
<rule ref="Squiz.WhiteSpace.SemicolonSpacing"/>
<rule ref="Squiz.Commenting.BlockComment">
<exclude name="Squiz.Commenting.BlockComment.WrongStart" />
</rule>
<rule ref="Squiz.Commenting.ClassComment">
<exclude name="Squiz.Commenting.ClassComment.Missing" />
<exclude name="Squiz.Commenting.ClassComment.TagNotAllowed" />
</rule>
<rule ref="Squiz.Commenting.DocCommentAlignment"/>
<rule ref="Squiz.Commenting.EmptyCatchComment"/>
<rule ref="Squiz.Commenting.FunctionComment">
<exclude name="Squiz.Commenting.FunctionComment.MissingParamComment" />
</rule>
<rule ref="Squiz.Commenting.FunctionCommentThrowTag"/>
<rule ref="Squiz.Commenting.InlineComment">
<exclude name="Squiz.Commenting.InlineComment.DocBlock" />
</rule>
<rule ref="Squiz.Commenting.LongConditionClosingComment">
<exclude name="Squiz.Commenting.LongConditionClosingComment.SpacingBefore" />
</rule>
<rule ref="Squiz.Commenting.PostStatementComment"/>
<rule ref="Squiz.Commenting.VariableComment"/>
<rule ref="SlevomatCodingStandard.Namespaces.UnusedUses.UnusedUse" />
<!-- For Laravel migrations -->
<rule ref="PSR1.Classes.ClassDeclaration.MissingNamespace">
<exclude-pattern>*/database/migrations/*</exclude-pattern>
</rule>
</ruleset>

97
readme.md Normal file
View file

@ -0,0 +1,97 @@
# LDC DAM api
Api client for DAM V2
**Client version must match DAM version !!**
- [LDC DAM api](#ldc-dam-api)
- [**Installation**](#installation)
- [**Usage**](#usage)
- [**Using Laravel**](#using-laravel)
- [**Using any other project**](#using-any-other-project)
- [**Using Wordpress**](#using-wordpress)
- [**Using custom implementation and calling directly DAM**](#using-custom-implementation-and-calling-directly-dam)
- [**More information**](#more-information)
- [**Customer Informations**](#customer-informations)
- [**Change log**](#change-log)
- [**Testing**](#testing)
- [**Credits**](#credits)
- [**License**](#license)
## **Installation**
Multiple ways are possible. You may include the client directly into your project using composer. You will need to have access to this repos. If you read this it may already be the case. So using ``composer update`` or ``composer require ldc/damclient`` should be enough.
*This has few dependencies it may not interfer with your project.*
"ext-curl": "*^7.3*",
"php": ">=7.3",
"guzzlehttp/guzzle": "^7.4",
"respect/validation": "^2.2",
"kwaadpepper/enum": "^2.0"
## **Usage**
As for initialisation multiple ways are possible.
If you are in a laravel project you can map a singleton of the dam api.
### **Using Laravel**
1. Setup ``config/dam.php``
<?php
return [
'endpoint' => 'https://ldc-dam.ldc.fr',
'public' => 'YOUR_API_TOKEN',
'private' => 'YOUR_API_PASSWORD'
];
2. Make a dam singleton if needed *(optional)*
// In AppServiceProvider.php
App::singleton('DamApi', function () {
return new DamApi();
});
// You then like this.
/** @var \LDC\DAM\Client\DamApi $damApi */
$damApi = app('DamApiV2);
// Or directly use static methods.
/** @var \LDC\DAM\Client\Models\Media|null $media */
$media = Media::find('id');
### **Using any other project**
Setup once the main class *(it is already a singleton, no need to manage it)*.
Informations will be kept in memory as static meaning all instance of DamApi or any class (Media, ..) will share the same informations as credentials.
$damPublicToken = 'YOUR_API_PUBLIC_TOKEN';
$damPrivateToken = 'YOUR_API_PRIVATE_TOKEN';
// This has to hapen once. It will be kept in memory;
new DamApi('https://dam.lesidc.com', $damPublicToken, $damPrivateToken);
### **Using custom implementation and calling directly DAM**
You may implement your own call to fit your needs. If you wish to go this way please read [this](docs/src/routes.json).
## **Change log**
Please see the [changelog](changelog.md) for more information on what has changed recently.
## **Testing**
All unit test are included in the dam source code, meaning you do not have access to them. If you wish you can override any source code, write your own test, but data will still be validated on dam side.
## **Credits**
- [Jérémy Munsch](https://jeremydev.ovh)
## **License**
MIT. Please see the [license file](license.md) for more information.

52
src/DamApi.php Normal file
View file

@ -0,0 +1,52 @@
<?php
namespace LDC\DAM\Client;
use LDC\DAM\Client\Enums\ApiStatus;
use LDC\DAM\Client\Transport\ApiInterface;
/**
* This is the main class to interact with the CRM
*
* @package damclient
*/
class DamApi
{
/**
* The Api object that will handle requests and responses
*
* @var \LDC\DAM\Client\Transport\ApiInterface
*/
private static $apiInterface;
/**
* DamApi
*
* @param string|null $endpoint
* @param string|null $publicToken
* @param string|null $privateToken
*/
public function __construct(string $endpoint = null, string $publicToken = null, string $privateToken = null)
{
self::$apiInterface = self::$apiInterface ?: new ApiInterface(
$endpoint,
$publicToken,
$privateToken
);
return $this;
}
/**
* Use this the ping the crm and know its current status
*
* @return boolean
* @throws \LDC\DAM\Client\Exceptions\CrmException If an error occurs
* on server side or on getting response.
*/
public function ping(): bool
{
$request = Utils::getResquest('api.ping');
$response = self::$apiInterface->call($request);
return $response->status->equals(ApiStatus::OK());
}
}

93
src/Enums/ApiError.php Normal file
View file

@ -0,0 +1,93 @@
<?php
namespace LDC\DAM\Client\Enums;
use Kwaadpepper\Enum\BaseEnum;
/**
* This describes an API error.
*
* @method static self modelNotFound()
* The request model was not found (typically the customer)
*
* @method static self validationFailed()
* This means some data could not be validated,
* you may have to look into message to get the details
*
* @method static self apiAuthFailed()
* The authentification to the api failed. You may have to
* check into config or .env file for your service credentials
*
* @method static self authFailed()
* The authentification for this customer failed because of wrong credentials
*
* @method static self methodNotAllowed()
* This http method is not allowed
*
* @method static self wrongTimeStamp()
* The timestamp given is wrong. This would happen in case if
* a replay attack scenario. Timestamps are provided in headers
* and in the http body
*
* @method static self missingParameter()
* The request is missing some parameters
*
* @method static self throttleRequestsException()
* Too many requests have been attempted. The is a throttle security.
* Normally you should not trigger this.
* If this happens fill a ticket on https://supportweb.ldc.fr
* with some technical details
*
* @method static self authorizationException()
* You are maybe trying to access data that is out of your range.
* This should not happen normally, it is here to allow you to handle this case.
* If this happens fill a ticket on https://supportweb.ldc.fr
* with some technical details
*
* @package DAMclient
* @subpackage enums
*
* TODO: pass this as php8 enum, when support of 7 will be dropped.
*/
class ApiError extends BaseEnum
{
/**
* Valeurs des possibilités de cet énumération (value)
*
* @return array
*/
public static function values(): array
{
return [
'modelNotFound' => 101,
'validationFailed' => 102,
'authFailed' => 117,
'apiAuthFailed' => 119,
'methodNotAllowed' => 150,
'wrongTimeStamp' => 151,
'missingParameter' => 400,
'authorizationException' => 403,
'throttleRequestsException' => 429
];
}
/**
* Libellés des possibilités de cet énumération (label)
*
* @return array
*/
public static function labels(): array
{
return [
'modelNotFound' => '%s introuvable.',
'validationFailed' => 'Impossible de valider les données',
'authFailed' => 'Echec de l\'authentification du compte',
'apiAuthFailed' => 'Echec de l\'authentification client à l\'Api DAM',
'methodNotAllowed' => 'This method is not allowed for this request',
'wrongTimeStamp' => 'Your request is malformed, please check timestamp header and parameter',
'missingParameter' => 'The request is missing some parameters',
'authorizationException' => 'You are not autorized to access this',
'throttleRequestsException' => 'Throttle: too many request have been attempted, please retry later'
];
}
}

18
src/Enums/ApiStatus.php Normal file
View file

@ -0,0 +1,18 @@
<?php
namespace LDC\DAM\Client\Enums;
use Kwaadpepper\Enum\BaseEnum;
/**
* @method static self OK()
* @method static self KO()
*
* @package DAMclient
* @subpackage enums
*
* TODO: pass this as php8 enum, when support of 7 will be dropped.
*/
class ApiStatus extends BaseEnum
{
}

16
src/Enums/HttpMethods.php Normal file
View file

@ -0,0 +1,16 @@
<?php
namespace LDC\DAM\Client\Enums;
use Kwaadpepper\Enum\BaseEnum;
/**
* @ignore This is used on internal
* @method static self get()
* @method static self post()
* @method static self put()
* @method static self delete()
*/
class HttpMethods extends BaseEnum
{
}

40
src/Enums/LogLevel.php Normal file
View file

@ -0,0 +1,40 @@
<?php
namespace LDC\DAM\Client\Enums;
use Kwaadpepper\Enum\BaseEnum;
/**
* @method static self EMERG() system is unusable
* @method static self ALERT() action must be taken immediately
* @method static self CRIT() critical conditions
* @method static self ERR() critical conditions
* @method static self WARNING() critical conditions
* @method static self NOTICE() normal, but significant, condition
* @method static self INFO() informational message
* @method static self DEBUG() debug-level message
*
* @package LDCCrmClient
* @subpackage enums
*/
class LogLevel extends BaseEnum
{
/**
* Valeurs des possibilités de cet énumération (value)
*
* @return array
*/
protected static function values()
{
return [
'EMERG' => 'LOG_EMERG',
'ALERT' => 'LOG_ALERT',
'CRIT' => 'LOG_CRIT',
'ERR' => 'LOG_ERR',
'WARNING' => 'LOG_WARNING',
'NOTICE' => 'LOG_NOTICE',
'INFO' => 'LOG_INFO',
'DEBUG' => 'LOG_DEBUG',
];
}
}

View file

@ -0,0 +1,24 @@
<?php
namespace LDC\DAM\Client\Enums;
use Kwaadpepper\Enum\BaseEnum;
/**
* @method static self ai()
* @method static self gif()
* @method static self jpeg()
* @method static self jpg()
* @method static self mp4()
* @method static self mp3()
* @method static self pdf()
* @method static self png()
* @method static self psd()
* @method static self svg()
*
* @package DAMclient
* @subpackage enums
*/
class MediaExtension extends BaseEnum
{
}

View file

@ -0,0 +1,23 @@
<?php
namespace LDC\DAM\Client\Exceptions;
/**
* This is thrown when trying to set a value on an object property that does not exist.
*
* @package DAMclient
* @subpackage exceptions
*/
class AccessError extends \Error
{
/**
* AccessError
*
* @param string $objectName The object name where the property does not exist.
* @param string $propertyName The property name that does not exist.
*/
public function __construct(string $objectName, string $propertyName)
{
parent::__construct("Tried to set value in $objectName->$propertyName, it does not exists.");
}
}

View file

@ -0,0 +1,102 @@
<?php
namespace LDC\DAM\Client\Exceptions;
use LDC\DAM\Client\Enums\ApiError;
use Illuminate\Support\Facades\Log;
/**
* This would be thrown if any of the case
* referenced in \App\Enums\ApiError would
* occur within the dam
*
* On the client an ApiErrorException would
* also be throw with the ApiError corresponding to
* the situation
*
* @package DAMclient
* @subpackage exceptions
*/
class ApiErrorException extends \RuntimeException
{
/**
* Api Error
* This value makes the error more explicit.
* Handling these errors are normal as inputs or
* request may be undesired or refused by the dam.
*
* @var \LDC\DAM\Client\Enums\ApiError
*/
protected $error;
/**
* This is an explicit error message,
* ou may print this to the front or not depending
* on $error value
*
* @var string
*/
protected $message;
/**
* This is the http code returned by the dam.
* This value could be used to handle errors.
* But please take in consideration $error first
*
* @var integer
*/
protected $httpCode;
/**
* Create a new exception base on ApiError enum.
*
* @param \LDC\DAM\Client\Enums\ApiError $error
* @param integer $httpCode
* @param string $message
* @param \Throwable|null $previous
*/
public function __construct(ApiError $error, int $httpCode = 400, string $message = '', \Throwable $previous = null)
{
$this->error = $error;
$this->message = $message;
$this->httpCode = $httpCode;
parent::__construct(
strlen($this->message) ? $this->message : $error->label,
$error->value,
$previous
);
}
/**
* Get the Api Error
*
* @return \LDC\DAM\Client\Enums\ApiError
*/
public function getApiError(): ApiError
{
return $this->error;
}
/**
* Get the http code
*
* @return integer
*/
public function getStatusCode(): int
{
return $this->httpCode;
}
/**
* This is used by laravel only.
* It uses Log class to print the error.
*
* @return void
*/
public function report()
{
// @codeCoverageIgnoreStart
Log::debug(sprintf('DAM API: %s', $this->getMessage()));
// @codeCoverageIgnoreEnd
}
}

View file

@ -0,0 +1,10 @@
<?php
namespace LDC\DAM\Client\Exceptions;
/**
* Unhandled error that occus within DAM.
*/
class DamException extends \RuntimeException
{
}

View file

@ -0,0 +1,13 @@
<?php
namespace LDC\DAM\Client\Exceptions;
/**
* Used only for internal validator
*
* @package DAMclient
* @subpackage exceptions
*/
class SkipValidationException extends \RuntimeException
{
}

View file

@ -0,0 +1,27 @@
<?php
namespace LDC\DAM\Client\Exceptions;
use Illuminate\Support\Facades\Log;
/**
* This would be thrown if a data could not be validated
* on any models
*
* @package DAMclient
* @subpackage exceptions
* @codeCoverageIgnore
*/
class ValidationException extends \RuntimeException
{
/**
* This is used by laravel only.
* It uses Log class to print the error.
*
* @return void
*/
public function report()
{
Log::error(sprintf('CRM Client: %s', $this->getMessage()));
}
}

342
src/Models/DamModel.php Normal file
View file

@ -0,0 +1,342 @@
<?php
namespace LDC\DAM\Client\Models;
use LDC\DAM\Client\Enums\LogLevel;
use LDC\DAM\Client\Enums\MediaExtension;
use LDC\DAM\Client\Exceptions\AccessError;
use LDC\DAM\Client\Exceptions\ValidationException;
use LDC\DAM\Client\Transport\ApiInterface;
use LDC\DAM\Client\Utils;
/**
* @ignore
* Base Class for crm client models
*
* @category Api Models
* @package DAMclient
* @subpackage models
* @author Jérémy Munsch <jeremy.munsch@ldc.fr>
*/
abstract class DamModel implements \JsonSerializable
{
/**
* Is true if this model was not filled from crm
*
* @var boolean
*/
protected $isNew = true;
/**
* The Api object that will handle requests and responses
*
* @var \LDC\DAM\Client\Transport\ApiInterface
*/
protected static $apiInterface;
/**
* Validation rules
*
* @var array
*/
protected static $validation = [];
/**
* Model fields
*
* @var array
*/
protected $modelFields = [];
/**
* The crm fields
* that should not be visible
*
* @var array
*/
protected $invisibleFields = [];
/**
* Model updated values
*
* @var array
*/
protected $updatedValues = [];
/**
* CrmClientModel
*/
public function __construct()
{
self::setUpApiInterface();
return $this;
}
/**
* Generic accessor
*
* @param string $field
* @return mixed|null Returns null if the property was not found any way.
*/
public function __get(string $field)
{
$props = \array_diff(
$this->modelFields,
$this->invisibleFields
);
if (in_array($field, $props)) {
return Utils::getRawProperty($this, $field);
}
return null;
}
/**
* Set prop on the model.
*
* @param string $field
* @param mixed $value
* @return void
* @throws \LDC\DAM\Client\Exceptions\ValidationException If a field could not be validated.
* @throws \LDC\DAM\Client\Exceptions\AccessError If trying to set a value on a unknown property.
* @phpcs:disable Squiz.Commenting.FunctionComment.TypeHintMissing
*/
public function __set(string $field, $value): void
{
// phpcs:enable
try {
if (in_array($field, $this->modelFields)) {
$type = $this->getPropType($field);
if (!is_null($value) and !$this->checkFieldType($type, $value)) {
throw new ValidationException("Wrong type for $field");
}
$this->validateValue($field, $value);
$this->updatedValues[$field] = $value;
Utils::setRawProperty($this, $field, $value);
return;
}
// phpcs:ignore Generic.CodeAnalysis.EmptyStatement.DetectedCatch
} catch (\ReflectionException $e) {
// Do nothing.
}
throw new AccessError(\get_class($this), $field);
}
/**
* Create the Api interface
*
* @return void
*/
protected static function setUpApiInterface()
{
self::$apiInterface = self::$apiInterface ?: new ApiInterface();
}
/**
* Fill values into model using validation rules.
*
* @param array $properties
* @return void
* @throws \LDC\DAM\Client\Exceptions\ValidationException If a field could not be validated.
*/
public function fill(array $properties)
{
if (count($properties)) {
foreach ($properties as $field => $value) {
try {
$type = $this->getPropType($field);
// * Force boolean
if ($type === 'bool') {
$value = (\is_int($value) and ($value === 1 or $value === 0)) ? (bool)$value : $value;
}
// * Force DateTime
if ($type === 'DateTime') {
$value = (
\is_string($value) and
(\DateTime::createFromFormat('Y-m-d\TH:i:s.u\Z', $value) !== false)
) ? \DateTime::createFromFormat('Y-m-d\TH:i:s.u\Z', $value) : $value;
}
if (!is_null($value) and !$this->checkFieldType($type, $value)) {
throw new ValidationException("Wrong type for $field");
}
$this->validateValue($field, $value);
$this->updatedValues[$field] = $value;
Utils::setRawProperty($this, $field, $value);
} catch (AccessError | \ReflectionException $e) {
Utils::log(\sprintf(
'%s::fill : unknown property access for %s, it does not exist on object.',
\get_class($this),
$field
), LogLevel::DEBUG());
continue;
}//end try
} //end foreach
}//end if
}
/**
* Set all properties to without any validation
*
* @param array $properties
* @return void
*/
protected function fillRaw(array $properties)
{
if (count($properties)) {
foreach ($properties as $field => $value) {
try {
Utils::setRawProperty($this, $field, $value);
} catch (AccessError $e) {
Utils::log(\sprintf(
'%s::fillRaw : unknown property access for %s, it does not exist on object.',
\get_class($this),
$field
), LogLevel::DEBUG());
continue;
}
}
}
}
/**
* Validate all model properties
*
* * All properties are nullable
*
* @param array $ignore
* @return array the validated values
* @throws \LDC\DAM\Client\Exceptions\ValidationException If a field could not be validated.
*/
protected function validateAllValues(array $ignore = []): array
{
$out = [];
foreach (static::$validation as $field => $validationRules) {
if (\in_array($field, $ignore) or \is_null(Utils::getRawProperty($this, $field))) {
continue;
}
$this->validateValue($field, Utils::getRawProperty($this, $field));
$out[$field] = Utils::getRawProperty($this, $field);
}
return $out;
}
/**
* Validate a value against its rules
*
* @param string $field
* @param mixed $value
* @return boolean
* @throws \ErrorException If a field has no validation rule.
* @throws \LDC\DAM\Client\Exceptions\ValidationException If a field could not be validated.
* @phpcs:disable Squiz.Commenting.FunctionComment.TypeHintMissing
* @phpcs:ignore Squiz.Commenting.FunctionCommentThrowTag.WrongNumber
*/
protected static function validateValue(string $field, $value): bool
{
// phpcs:enable
if (!isset(static::$validation[$field])) {
throw new \ErrorException("$field has no validation rule");
}
$validator = Utils::makeValidator(
[$field => $value],
[$field => static::$validation[$field]]
);
/** @throws \LDC\DAM\Client\Exceptions\ValidationException */
$validator();
return true;
}
/**
* Check a value against its field type
*
* @param string $type
* @param mixed $value
* @return boolean Return true if $type matches $value type.
* @throws \ErrorException If type is not handled,
* handled types are boolean, string, integer, DateTime.
* @phpcs:disable Squiz.Commenting.FunctionComment.TypeHintMissing
*/
protected function checkFieldType(string $type, $value): bool
{
// phpcs:enable
/**
* Checks if the value is valid for a specific enum class
* @param string $className
* @param mixed $value
* @return boolean
*/
$checkValueIsEnum = function (string $className, $value) {
try {
$value = $className::make($value);
} finally {
return \is_object($value) and (get_class($value) === $className or
\in_array($className, \class_parents($value)));
}
};
switch ($type) {
case '\\' . MediaExtension::class:
return $checkValueIsEnum(\ltrim($type, '\\'), $value);
case 'DateTime':
return \is_object($value) and $value instanceof \DateTime;
case 'boolean':
return \is_bool(\is_int($value) ? (bool)$value : $value);
case 'array':
return \is_array($value);
case 'string':
return \is_string($value);
case 'integer':
return \is_int($value);
}
throw new \ErrorException(\sprintf("Unhandled $type for %s", \json_encode($value)));
}
/**
* Get the type of any of this class property
* from doc comment
*
* @param string $property
* @return string|null the type or null if not defined
* @throws \ErrorException If the property has no comment to read.
* @throws \ErrorException If a type for a property could ne be recognized.
* @throws \ReflectionException If the class or property does not exist.
* @phpcs:ignore Squiz.Commenting.FunctionCommentThrowTag.WrongNumber
*/
protected function getPropType(string $property)
{
$matches = [];
$propReflection = new \ReflectionProperty(static::class, $property);
$docComment = $propReflection->getDocComment();
if (!$docComment) {
throw new \ErrorException(\sprintf("%s $property has not comment to parse.", \get_class($this)));
}
preg_match_all('/@var ([\w_\x5c]+)/', $docComment, $matches);
if (
isset($matches[1][0]) and \in_array($matches[1][0], [
'string', 'integer', 'boolean', 'array', 'DateTime', '\\' . MediaExtension::class
], true)
) {
return $matches[1][0];
}
throw new \ErrorException("Unknown type for property $property");
}
/**
* Assert primaryKey is valid.
*
* @param mixed $primaryKey
* @return void
* @throws LDC\DAM\Client\Exceptions\ValidationException If a primary key is not a valid integer.
* @phpcs:disable Squiz.Commenting.FunctionComment.TypeHintMissing
*/
protected static function assertValidPrimaryKey($primaryKey): void
{
// phpcs:enable
$validator = Utils::makeValidator(
['id' => $primaryKey],
['id' => 'required|int']
);
if ($validator()) {
throw new ValidationException(implode(' ', $validator->errors()->get('id')));
}
}
}

274
src/Models/Media.php Normal file
View file

@ -0,0 +1,274 @@
<?php
namespace LDC\DAM\Client\Models;
use LDC\DAM\Client\Utils;
/**
* This class represents a media info
*
* @property integer $id The dam specific ID
* @property string $arcadia_id ID set by Arcadia
* @property string $libelle A string set by user on Dam interface
* @property string $uid The media specific file name
* @property integer $version The version number incremented by arcadia
* @property DateTime $created_at DateTime where the media was created.
* @property DateTime $updated_at DateTime where the media was updated.
*
* @example examples/CustomerExample.php
*
* @category Api Models
* @package DAMclient
* @subpackage models
* @author Jérémy Munsch <jeremy.munsch@ldc.fr>
*/
class Media extends DamModel
{
/**
* The dam specific ID
*
* Readonly
* Field Type integer
*
* @var integer
*/
private $id;
/**
* ID set by Arcadia
*
* Readonly
* Field Type integer
*
* @var integer|null
*/
private $arcadia_id = null;
/**
* A string set by user on Dam interface
*
* Min length 2
* Max length 255
* Field Type varchar
*
* @var string
*/
private $libelle = null;
/**
* The media specific file name
*
* Readonly
* Field Type string
*
* @var string
*/
private $uid;
/**
* The version number incremented by arcadia
*
* Readonly
* Field Type integer
*
* @var integer
*/
private $version;
/**
* The media thumb binary
*
* Readonly
* Field Type callable
*
* @var string|null
*/
private $base64_thumb_bin;
/**
* DateTime where the media was created.
*
* Readonly
* Field Type DateTime
*
* @var DateTime
*/
private $created_at;
/**
* DateTime where the media was updated.
*
* Readonly
* Field Type DateTime
*
* @var DateTime
*/
private $updated_at;
/**
* The fields
*
* @var array
*/
protected $modelFields = [
'id', 'arcadia_id', 'libelle', 'uid',
'version', 'created_at', 'updated_at'
];
/**
* The fields that should not be visible
*
* @var array
*/
protected $invisibleFields = [];
/**
* Validation rules
*
* @var array
*/
protected static $validation = [
'id' => 'required|int',
'arcadia_id' => 'required|nullable|int',
'libelle' => 'required|string|min:1|max:255',
'uid' => 'required|string|uuid',
'version' => 'required|int|min:1',
'base64_thumb_bin' => 'sometimes|string',
'created_at' => 'required|date',
'updated_at' => 'required|date'
];
// * PUBLIC METHODS
/**
* Get the media picture
*
* @return LDC\DAM\Client\Models\MediaPicture
* @throws \LDC\DAM\Client\Exceptions\DamException If an error occurs on server side or on getting response.
* @throws \LDC\DAM\Client\Exceptions\ApiErrorException If any error or \LDC\DAM\Client\Enums\ApiError occurs.
* @phpcs:ignore Squiz.Commenting.FunctionCommentThrowTag.WrongNumber
*/
public function getPicture(): MediaPicture
{
return MediaPicture::find($this->id);
}
/**
* Find a media using its id in the dam
*
* @param integer $id
* @return self
* @throws \LDC\DAM\Client\Exceptions\DamException If an error occurs on server side or on getting response.
* @throws \LDC\DAM\Client\Exceptions\ApiErrorException If any error or \LDC\DAM\Client\Enums\ApiError occurs.
* Possibles are : - modelNotFound, If this media id could not be found.
* @phpcs:ignore Squiz.Commenting.FunctionCommentThrowTag.WrongNumber
*/
public static function find(int $id): self
{
static::setUpApiInterface();
$request = Utils::getResquest('api.media.show', [
'apiMedia' => $id
]);
$media = null;
$response = static::$apiInterface->call($request);
$media = new self();
$media->fill($response->data);
Utils::setRawProperty($media, 'isNew', false);
return $media;
}
/**
* Find a media using the arcadia id.
*
* @param integer $arcadiaId
* @return self|null
* @throws \LDC\DAM\Client\Exceptions\CrmException If an error occurs on server side or on getting response.
* @throws \LDC\DAM\Client\Exceptions\ApiErrorException If any error or \LDC\DAM\Client\Enums\ApiError occurs.
* Possibles are : - modelNotFound, If this media arcadia id could not be found.
*/
public static function findWithArcadiaId(int $arcadiaId): ?self
{
static::setUpApiInterface();
$request = Utils::getResquest('api.media.showByArcadiaId', [
'apiMediaArcadiaId' => $arcadiaId
]);
$media = null;
$response = static::$apiInterface->call($request);
$media = new self();
$media->fill($response->data);
Utils::setRawProperty($media, 'isNew', false);
return $media;
}
/**
* Get all media associated with an article
* as paginated result (15 by call)
*
* @param integer $noArt The arcadia article id.
* @param integer $page The page to retrieve.
* @return array<\LDC\DAM\Client\Models\Media>
* @throws \LDC\DAM\Client\Exceptions\CrmException If an error occurs on server side or on getting response.
* @throws \LDC\DAM\Client\Exceptions\ApiErrorException If any error or \LDC\DAM\Client\Enums\ApiError occurs.
* Possibles are : - modelNotFound, If this media arcadia id could not be found.
*/
public static function allWithArcadiaArticleId(int $noArt, int $page = 1): array
{
static::setUpApiInterface();
$request = Utils::getResquest('api.articles.media.index', [
'apiNoArticle' => $noArt,
'page' => $page
]);
$media = null;
$response = static::$apiInterface->call($request);
$out = [];
foreach ($response->data as $mediaArray) {
$media = new self();
$media->fill($mediaArray);
Utils::setRawProperty($media, 'isNew', false);
$out[] = $media;
}
return $out;
}
/**
* Check if this media model has thumb
*
* @return boolean
*/
public function hasThumb(): bool
{
return !\is_null($this->base64_thumb_bin);
}
/**
* Get the media thumb binary string
*
* @return string|false
*/
public function decodeThumbPicture()
{
if (!$this->hasThumb()) {
return false;
}
return \base64_decode($this->base64_thumb_bin);
}
/**
* Serialize this object to an array
*
* @return array
*/
public function jsonSerialize()
{
return [
'id' => $this->id,
'arcadia_id' => $this->arcadia_id,
'libelle' => $this->libelle,
'uid' => $this->uid,
'version' => $this->version,
'created_at' => $this->created_at,
'updated_at' => $this->updated_at
];
}
}

170
src/Models/MediaPicture.php Normal file
View file

@ -0,0 +1,170 @@
<?php
namespace LDC\DAM\Client\Models;
use LDC\DAM\Client\Enums\MediaExtension;
use LDC\DAM\Client\Utils;
/**
* This class represents a media info
*
* @property string $base64_bin The media bin base64 encoded
* @property string $uid The media specific file name
* @property \LDC\DAM\Client\Enums\MediaExtension $extension The media extension
*
* @example examples/CustomerExample.php
*
* @category Api Models
* @package DAMclient
* @subpackage models
* @author Jérémy Munsch <jeremy.munsch@ldc.fr>
*/
class MediaPicture extends DamModel
{
/**
* The media binary
*
* Readonly
* Field Type string
*
* @var string
*/
private $base64_bin;
/**
* The media specific file name
*
* Readonly
* Field Type string
*
* @var string
*/
private $uid;
/**
* The media extension
*
* Readonly
* Field Type unsigned tinyInt
*
* @var \LDC\DAM\Client\Enums\MediaExtension
*/
private $extension;
/**
* The fields
*
* @var array
*/
protected $modelFields = [
'base64_bin', 'uid', 'extension'
];
/**
* The fields that should not be visible
*
* @var array
*/
protected $invisibleFields = [];
/**
* Validation rules
*
* @var array
*/
protected static $validation = [
'base64_bin' => 'required|string',
'uid' => 'required|uuid',
'extension' => ['required']
];
// * PUBLIC METHODS
/**
* Generic accessor
*
* @param string $field
* @return mixed|null Returns null if the property was not found any way.
*/
public function __get(string $field)
{
$props = \array_diff(
$this->modelFields,
$this->invisibleFields
);
if (in_array($field, $props)) {
if ($field === 'extension' and !\is_object($this->{$field})) {
return MediaExtension::make($this->{$field});
}
}
return parent::__get($field);
}
/**
* Set prop on the model.
*
* @param string $field
* @param mixed $value
* @return void
* @throws \LDC\DAM\Client\Exceptions\ValidationException If a field could not be validated.
* @throws \LDC\DAM\Client\Exceptions\AccessError If trying to set a value on a unknown property.
* @phpcs:disable Squiz.Commenting.FunctionComment.TypeHintMissing
*/
public function __set(string $field, $value): void
{
// phpcs:enable
if ($field === 'extension') {
$value = (\is_object($value) and
get_class($value) === MediaExtension::class) ? $value->value : $value;
}
parent::__set($field, $value);
}
/**
* Find a media picture using its id in the dam
*
* @param integer $id
* @return self
* @throws \LDC\DAM\Client\Exceptions\DamException If an error occurs on server side or on getting response.
* @throws \LDC\DAM\Client\Exceptions\ApiErrorException If any error or \LDC\DAM\Client\Enums\ApiError occurs.
* Possibles are : - modelNotFound, If this media id could not be found.
* @phpcs:ignore Squiz.Commenting.FunctionCommentThrowTag.WrongNumber
*/
public static function find(int $id): self
{
static::setUpApiInterface();
$request = Utils::getResquest('api.media.picture', [
'apiMedia' => $id
]);
$mediaPicture = null;
$response = static::$apiInterface->call($request);
$mediaPicture = new self();
$mediaPicture->fill($response->data);
Utils::setRawProperty($mediaPicture, 'isNew', false);
return $mediaPicture;
}
/**
* Get the picture binary string
*
* @return string|false
*/
public function decodePicture()
{
return \base64_decode($this->base64_bin);
}
/**
* Serialize this object to an array
*
* @return array
*/
public function jsonSerialize()
{
return [
'base64_bin' => $this->base64_bin,
'uid' => $this->uid,
'extension' => $this->extension->value
];
}
}

View file

@ -0,0 +1,237 @@
<?php
namespace LDC\DAM\Client\Transport;
use LDC\DAM\Client\Enums\ApiStatus;
use LDC\DAM\Client\Exceptions\ApiErrorException;
use LDC\DAM\Client\Exceptions\DamException;
use LDC\DAM\Client\Utils;
/**
* @ignore
*
* This class contains static api credentials
* It handles a request to get a response
*
* @package DAMclient
* @subpackage transport
*/
class ApiInterface
{
/**
* The api endpoint url
* This is the DAM FQDN
*
* @var string
*/
protected static $endpoint;
/**
* The public token
*
* @var string
*/
protected static $publicToken;
/**
* The private token
*
* @var string
*/
protected static $privateToken;
/**
* HTTP AUTH string
*
* @var string
*/
protected static $authentification = null;
/**
* ApiInterface
*
* @param string|null $endpoint The dam endpoint.
* @param string|null $publicToken The dam service public token.
* @param string|null $privateToken The dam service private token.
*
* @throws \LDC\DAM\Client\Exceptions\DamException If dam.public, dam.private or
* dam.endpoint is missing on .env file or in laravel config.
*/
public function __construct(string $endpoint = null, string $publicToken = null, string $privateToken = null)
{
self::$endpoint = self::$endpoint ?: $endpoint;
self::$publicToken = self::$publicToken ?: $publicToken;
self::$privateToken = self::$privateToken ?: $privateToken;
static::$publicToken = static::$publicToken ?: Utils::getConfig('dam.public');
static::$privateToken = static::$privateToken ?: Utils::getConfig('dam.private');
static::$endpoint = static::$endpoint ?: Utils::getConfig('dam.endpoint');
if (!self::$publicToken or !self::$privateToken or !self::$endpoint) {
throw new DamException(
'Either config or .env file need to have the token var set (dam.public, dam.private, dam.endpoint)'
);
}
// Handle HTTP Auth .
if (\strpos(self::$endpoint, '@')) {
$vars = \parse_url(self::$endpoint);
self::$authentification = \base64_encode($vars['user'] . ':' . $vars['pass']);
}
}
/**
* Make a dam http call to get a reponse
*
* @param \LDC\DAM\Client\Transport\Request $request
* @return \LDC\DAM\Client\Transport\Response
* @throws \LDC\DAM\Client\Exceptions\DamException If an error occurs on server side or on getting response.
* @throws \LDC\DAM\Client\Exceptions\ApiErrorException If any error or \LDC\DAM\Client\Enums\ApiError occurs.
*/
public function call(Request $request): Response
{
$response = $this->processRequest($request);
// * Handle response Status.
if ($response->status->equals(ApiStatus::KO())) {
if (\is_int($response->apiError)) {
throw new DamException($response->message, $response->apiError);
} else {
throw new ApiErrorException($response->apiError, $response->httpCode, $response->message);
}
}
return $response;
}
/**
* Process request
*
* @param Request $request
* @return \LDC\DAM\Client\Transport\Response
*/
private function processRequest(Request $request): Response
{
$this->setCredentials($request);
$this->setHeaders($request);
$this->setTimestamp($request);
$request->setEndpoint(self::$endpoint);
$request->addData([
'signature' => $this->calulateSignature($request)
]);
/** @var \Psr\Http\Message\ResponseInterface $response */
$response = $request->call();
$status = in_array($response->getStatusCode(), [200, 201]) ?
ApiStatus::OK() : ApiStatus::KO();
return new Response($status, $response);
}
/**
* Add spécific headers to he request
*
* @param \LDC\DAM\Client\Transport\Request $request
* @return void
*/
private function setHeaders(Request &$request): void
{
$headers = [
'User-Agent' => sprintf('LDC DAM client version %s', Utils::getPackageInfo()['version']),
'Accept' => 'application/json',
'Content-Type' => 'application/json'
];
$request->addHeaders($headers);
}
/**
* Inject bearer credentials into the request
*
* @param \LDC\DAM\Client\Transport\Request $request
* @return void
*/
protected function setCredentials(Request $request)
{
if (self::$authentification) {
$request->addHeaders([
'Authorization' => implode(',', [
sprintf('Basic %s', self::$authentification)
])
]);
}
$request->addData(['bearer_token' => self::$publicToken]);
}
/**
* Add a timestamp (UTC) to the request
*
* @param Request $request
* @return void
*/
protected function setTimestamp(Request $request): void
{
$request->addData([
// ! UTC date time.
'timestamp' => \gmdate('Y-m-d H:i:s')
]);
}
/**
* Calculates request signature
*
* @param Request $request
* @return string
* @throws \LDC\DAM\Client\Exceptions\DamException In case of failure.
*/
protected function calulateSignature(Request $request): string
{
$uri = \parse_url(sprintf('%s/%s', self::$endpoint, $request->uri));
$method = \strtolower($request->method->value);
$parameters = $request->data;
$signature = [
'uri' => sprintf(
'%s://%s%s',
// Assume https if non provided, security first.
$uri['scheme'] ?? 'https',
$uri['host'],
$uri['path'] ?? '',
),
'method' => $method
];
$flattenRequestArray = function (array $array) use (&$flattenRequestArray) {
$out = [];
foreach ($array as $key => $value) {
if (is_array($value)) {
$subArray = $flattenRequestArray($value);
foreach ($subArray as $subKey => $subValue) {
$out["$key.$subKey"] = $subValue;
}
continue;
}
$out[$key] = $value;
}
return $out;
};
$parameters = $flattenRequestArray($parameters);
// ! Natural sort by keys.
if (!uksort($parameters, "strnatcmp")) {
throw new DamException('Natural sorting the request parameters failed.');
}
$parameters = \array_map(function ($key, $value) {
return sprintf('%s=%s', \rawurlencode($key), \rawurlencode($value));
}, \array_keys($parameters), $parameters);
$signature[] = \implode('&', $parameters);
return base64_encode(hash_hmac(
'sha256',
\implode('\n', $signature),
self::$privateToken,
true
));
}
}

210
src/Transport/Request.php Normal file
View file

@ -0,0 +1,210 @@
<?php
namespace LDC\DAM\Client\Transport;
use GuzzleHttp\Client;
use GuzzleHttp\Psr7\Request as Psr7Request;
use GuzzleHttp\Psr7\Utils as Psr7Utils;
use GuzzleHttp\RequestOptions;
use GuzzleHttp\Utils as GuzzleHttpUtils;
use LDC\DAM\Client\Enums\HttpMethods;
use LDC\DAM\Client\Utils;
use Psr\Http\Message\ResponseInterface;
/**
* The LDC DAM request
* Contains the http method, the requested url and data to pass
*
* @property \LDC\DAM\Client\Enums\HttpMethods $method readonly method
* @property string $uri readonly uri
* @property array $headers headers
* @property array $data readonly data
*
* @package DAMclient
* @subpackage transport
*/
class Request
{
/**
* GuzzleHttp client
*
* @var \GuzzleHttp\Client
*/
private $client;
/**
* The http method
*
* @var \LDC\DAM\Client\Enums\HttpMethods
*/
protected $method;
/**
* The http url
*
* @var string
*/
protected $uri;
/**
* Data to pass to the http headers
*
* @var array
*/
protected $headers = [];
/**
* Data to pass to the http body
*
* @var array
*/
protected $data = [];
/**
* Guzzle request
*
* @var callable the returns \GuzzleHttp\Psr7\Request
*/
private $request;
/**
* The Api endpoint
*
* @var string
*/
private $endpoint;
/**
* Request
*
* @param \LDC\DAM\Client\Enums\HttpMethods $method
* @param string $uri
* @param array $headers
* @param array $data
*/
public function __construct(
HttpMethods $method,
string $uri,
array $headers = [],
array $data = []
) {
$this->hidden = function () {
return [];
};
$this->method = $method;
$this->uri = $uri;
$this->data = $data;
$this->headers = $headers;
$this->client = new Client([
RequestOptions::HEADERS => [
'User-Agent' => sprintf(
'LDC DAM Client v%s',
Utils::getPackageInfo()['version']
)
]
]);
}
/**
* Generic accessor
*
* @param string $field
* @return mixed|null
*/
public function __get(string $field)
{
if (\in_array($field, ['method', 'uri', 'data'])) {
return $this->{$field};
}
return null;
}
/**
* make the guzzle request
*
* @return void
*/
private function makeRequest(): void
{
$this->request = function () {
$uri = $this->uri;
// * If query merge query and data, set data to empty.
if ($this->method->equals(HttpMethods::get())) {
// * Merge query in url with Data
$q = \parse_url($uri, \PHP_URL_QUERY) ?? '';
$q = \strpos($q, '&') !== false ? explode('&', $q) : [];
$query = [];
foreach ($q as $qParam) {
$qParam = explode('=', $qParam, 2);
$query[$qParam[0]] = $qParam[1];
}
// * Remove query part.
$uri = strtok($uri, '?');
// * Append build query
$uri = sprintf("%s?%s", $uri, http_build_query(array_merge($query, $this->data)));
$this->data = [];
}
$request = new Psr7Request(
\strtoupper($this->method),
sprintf('%s/%s', $this->endpoint, $uri),
$this->headers
);
$request = Psr7Utils::modifyRequest($request, [
'body' => GuzzleHttpUtils::jsonEncode($this->data)
]);
return $request;
};
}
/**
* Set the api endpoint to the request
*
* @param string $endpoint
* @return void
*/
public function setEndpoint(string $endpoint): void
{
$this->endpoint = $endpoint;
}
/**
* Make the Http request
*
* @return ResponseInterface
*/
public function call(): ResponseInterface
{
$this->makeRequest();
/** @var \GuzzleHttp\Psr7\Request */
$request = ($this->request)();
return $this->client->send($request, [
// ! Do not throw HTTP Exceptions.
'http_errors' => false,
'allow_redirects' => false
]);
}
/**
* Add headers to the request
*
* @param array $headers
* @return void
*/
public function addHeaders(array $headers)
{
$this->headers = \array_merge($this->headers, $headers);
}
/**
* Add data to the request
*
* @param array $data
* @return void
*/
public function addData(array $data)
{
$this->data = \array_merge($this->data, $data);
}
}

201
src/Transport/Response.php Normal file
View file

@ -0,0 +1,201 @@
<?php
namespace LDC\DAM\Client\Transport;
use LDC\DAM\Client\Enums\ApiError;
use LDC\DAM\Client\Enums\ApiStatus;
use LDC\DAM\Client\Enums\LogLevel;
use LDC\DAM\Client\Exceptions\DamException;
use LDC\DAM\Client\Utils;
use Psr\Http\Message\ResponseInterface;
use RecursiveArrayIterator;
use RecursiveIteratorIterator;
/**
* @property \LDC\DAM\Client\Enums\ApiStatus $status The response api status
* @property \LDC\DAM\Client\Enums\ApiError|int $apiError The api error status it there is any
* @property int $httpCode The http response code
* @property string $message The api message
* @property array $headers The http reponse headers
* @property array $body The http response body, this is parsed json
* @property ?array $data The reponse data
*
* @package DAMclient
* @subpackage transport
*/
class Response
{
/**
* The response status
*
* @var \LDC\DAM\Client\Enums\ApiStatus
*/
private $status;
/**
* The api error
*
* @var \LDC\DAM\Client\Enums\ApiError
*/
private $apiError;
/**
* The response http code
*
* @var integer
*/
private $httpCode = 0;
/**
* The response headers
*
* @var string
*/
private $headers;
/**
* The response body
*
* @var string
*/
private $body;
/**
* The interface message
*
* @var string
*/
private $message;
/**
* PSR response
*
* @var \Psr\Http\Message\ResponseInterface
*/
private $response;
/**
* Response
*
* @param \LDC\DAM\Client\Enums\ApiStatus $status
* @param \Psr\Http\Message\ResponseInterface $response
* @throws \LDC\DAM\Client\Exceptions\DamException If HTTP response body in not JSON.
*/
public function __construct(ApiStatus $status, ResponseInterface $response)
{
$this->response = $response;
$this->status = $status;
$this->httpCode = $response->getStatusCode();
$this->headers = $response->getHeaders();
/** @var \GuzzleHttp\Psr7\Stream */
$this->body = $response->getBody();
if (!in_array($response->getStatusCode(), [200, 201])) {
$this->message = $response->getReasonPhrase();
}
// * Body should be json data.
if (($decodedJson = $this->tryDecodeJson($this->body->getContents())) === false) {
if (Utils::getConfig('app.env') === 'testing') {
dump((string)$this->body);
}
throw new DamException('The Api should have returned JSON data');
}
$this->body = $decodedJson;
// * If Api Error.
if ($this->status->equals(ApiStatus::KO())) {
// * If DAM Exception or Any Exception.
if ($this->httpCode === 500) {
$this->apiError = $this->body['data']['code'];
} else {
// * From here it should be an ApiErrorException.
$this->apiError = ApiError::make($this->body['data']['code']);
$this->message = $this->body['data']['message'];
if ($this->apiError->equals(ApiError::validationFailed())) {
$errors = new RecursiveIteratorIterator(
new RecursiveArrayIterator($this->body['data']['errors'])
);
foreach ($errors as $error) {
$this->message = "$this->message $error";
}
}
}
}
$this->checkVersion($this->body['version']);
return $this;
}
/**
* Generic accessor
*
* @param string $field
* @return mixed|null
*/
public function __get(string $field)
{
if (
\in_array($field, [
'status', 'httpCode', 'headers',
'body', 'message', 'response', 'apiError'
])
) {
return $this->{$field};
}
if ($field === 'data' and isset($this->body[$field])) {
return $this->body[$field];
}
return null;
}
/**
* Try to decode json and return false if it is
* not a valid json
*
* @param string $string
* @return array|false Returns an associative data array or false if failed to parse.
*/
private function tryDecodeJson(string $string)
{
/** @var array|null */
$data = json_decode($string, true);
return (json_last_error() == JSON_ERROR_NONE) ? $data : false;
}
/**
* This checks if the DAM version is way far beyond the client version.
* If a minor version mismatch is detected we will log this as a warning.
* If a major version mismatch is detected we will throw a DamException as
* there shall be an incompatibility with the response.
*
* The goal here is to force clients to be up to date.
* A major version change means breaking change.
*
* @param string $version
* @return void
* @throws \LDC\DAM\Client\Exceptions\DamException If a major version mismatch is detected.
*/
private function checkVersion(string $version)
{
$packageInfo = Utils::getPackageInfo();
$ApackageInfo = explode('.', $packageInfo['version']);
$Aversion = \explode('.', $version);
if ($ApackageInfo[0] != $Aversion[0]) {
throw new DamException(sprintf(
'Incompatible major versions between DAM server %s and client %s',
$version,
$packageInfo['version']
));
}
if ($ApackageInfo[1] != $Aversion[1]) {
$message = sprintf(
'Minor version mismatch between DAM server %s and client %s, this could lead to errors',
$version,
$packageInfo['version']
);
Utils::log($message, LogLevel::WARNING());
}
}
}

694
src/Utils.php Normal file
View file

@ -0,0 +1,694 @@
<?php
namespace LDC\DAM\Client;
use LDC\DAM\Client\Enums\HttpMethods;
use LDC\DAM\Client\Enums\LogLevel;
use LDC\DAM\Client\Exceptions\AccessError;
use LDC\DAM\Client\Exceptions\SkipValidationException;
use LDC\DAM\Client\Exceptions\ValidationException;
use LDC\DAM\Client\Transport\Request;
use Respect\Validation\Validator;
/**
* This is the LDCDAM utility class
*
* @category Utility
* @uses \LDC\DAM\Client\Enums\HttpMethods
* @uses \LDC\DAM\Client\Transport\Request
*
* @package damclient
* @subpackage utilities
*/
class Utils
{
/**
* Package infos
*
* @var array
*/
private static $packageInfos;
/**
* Loaded translations
*
* @var array
*/
private static $translations = [];
/**
* Create a new Validator instance.
*
* @param array $data
* @param array $rules
* @return closure
* @throws \ErrorException If an unknown validation rule is used.
*/
public static function makeValidator(
array $data,
array $rules
): object {
foreach ($rules as $attribute => $attrRules) {
$validators = [];
if (\is_string($attrRules)) {
$attrRules = \explode('|', $attrRules);
}
foreach ($attrRules as $rule) {
$validators[] = self::makeValidatorFromRule($rule, $data, $attribute);
} //end foreach
} //end foreach
return function () use ($validators) {
foreach ($validators as $validator) {
try {
if (!$validator['validate']()) {
throw new ValidationException($validator['error']);
}
} catch (SkipValidationException $e) {
break;
}
}
};
}
/**
* Generate a validator
*
* @param mixed $rule
* @param array $data
* @param string $attribute
* @return array
* @throws \ErrorException If a rule is unknown.
*/
private static function makeValidatorFromRule(
mixed $rule,
array $data,
string $attribute
): array {
$rParams = [];
$closure = null;
if (\is_callable($rule) and !is_string($rule)) {
/** @var \Closure $closure */
$closure = $rule;
$rule = '#closure#';
} elseif (\strpos($rule, ':') !== false) {
$rParams = \explode(':', $rule, 2);
$rule = \array_shift($rParams);
}
switch (true) {
case in_array($rule, [
'nullable', 'sometimes',
'int', 'bool', 'uuid', 'string',
'date', 'email', 'array',
'mixedCase', 'containDigit', 'containSymbol',
]):
return self::{sprintf('validation%s', \ucfirst($rule))}(
$attribute,
$data[$attribute] ?? null
);
case in_array($rule, ['min', 'max']):
return self::{sprintf('validation%s', \ucfirst($rule))}(
$attribute,
$data[$attribute],
$rParams
);
case in_array($rule, ['required', 'sometimes']):
return self::{sprintf('validation%s', \ucfirst($rule))}(
$attribute,
$data,
);
case $rule === 'date_format':
return self::validationDateFormat($attribute, $data[$attribute], $rParams);
case $rule === '#closure#':
/** @var \Closure $rule */
return self::validationClosure($attribute, $data[$attribute], $closure);
default:
throw new \ErrorException("Unknown validation rule $rule " . implode(': ', $rParams));
} //end switch
}
// * VALIDATION RULES
/**
* Make Required validator
*
* @param string $attribute
* @param array $data
* @return array
*/
private static function validationRequired(string $attribute, array $data): array
{
return [
'type' => 'required',
'error' => sprintf(
'%s est obligatoire',
self::translate($attribute)
),
'validate' => function () use ($attribute, $data) {
return isset($data[$attribute]);
}
];
}
/**
* Make Nullable validator
*
* @param string $attribute
* @param mixed $value
* @return array
*/
private static function validationNullable(string $attribute, mixed $value): array
{
return [
'type' => 'nullable',
'error' => sprintf(
'%s peut être égale à nul',
self::translate($attribute)
),
'validate' => function () use ($value) {
if (is_null($value)) {
throw new SkipValidationException();
}
return true;
}
];
}
/**
* Make Sometimes validator
*
* @param string $attribute
* @param mixed $data
* @return array
*/
private static function validationSometimes(string $attribute, mixed $data): array
{
return [
'type' => 'sometimes',
'error' => sprintf(
'%s est falcutatif',
self::translate($attribute)
),
'validate' => function () use ($data) {
if (empty($data)) {
throw new SkipValidationException();
}
return true;
}
];
}
/**
* Make Int validator
*
* @param string $attribute
* @param mixed $value
* @return array
*/
private static function validationInt(string $attribute, mixed $value): array
{
return [
'type' => 'int',
'error' => sprintf(
'%s doit être un entier',
self::translate($attribute)
),
'validate' => function () use ($value) {
return \is_int($value);
}
];
}
/**
* Make String validator
*
* @param string $attribute
* @param mixed $value
* @return array
*/
private static function validationString(string $attribute, mixed $value): array
{
return [
'type' => 'string',
'error' => sprintf(
'%s doit être une chaine de charactères',
self::translate($attribute)
),
'validate' => function () use ($value) {
return \is_string($value);
}
];
}
/**
* Make Bool validator
*
* @param string $attribute
* @param mixed $value
* @return array
*/
private static function validationBool(string $attribute, mixed $value): array
{
return [
'type' => 'bool',
'error' => sprintf(
'%s doit être un booléen',
self::translate($attribute)
),
'validate' => function () use ($value) {
return \is_bool($value) or $value === 1 or $value === 0;
}
];
}
/**
* Make Min validator
*
* @param string $attribute
* @param mixed $value
* @param array $params
* @return array
*/
private static function validationMin(string $attribute, mixed $value, array $params): array
{
return [
'type' => 'min',
'error' => sprintf(
'%s doit avoir au moins %s caratères, ou être plus grand que %s si c\'est un nombre',
self::translate($attribute),
$params[0],
$params[0]
),
'validate' => function () use ($value, $params) {
if (\is_string($value)) {
return \strlen($value) >= (int)$params[0];
}
if (\is_int($value)) {
return $value >= (int)$params[0];
}
return false;
}
];
}
/**
* Make Max validator
*
* @param string $attribute
* @param mixed $value
* @param array $params
* @return array
*/
private static function validationMax(string $attribute, mixed $value, array $params): array
{
return [
'type' => 'max',
'error' => sprintf(
'%s doit avoir au moins %s caratères, ou être plus grand que %s si c\'est un nombre',
self::translate($attribute),
$params[0],
$params[0]
),
'validate' => function () use ($value, $params) {
if (\is_string($value)) {
return \strlen($value) <= (int)$params[0];
}
if (\is_int($value)) {
return $value <= (int)$params[0];
}
return false;
}
];
}
/**
* Make Uuid validator
*
* @param string $attribute
* @param mixed $value
* @return array
*/
private static function validationUuid(string $attribute, mixed $value): array
{
return [
'type' => 'uuid',
'error' => sprintf(
'%s doit être un uuid valide',
self::translate($attribute)
),
'validate' => function () use ($value) {
return Validator::uuid()->validate($value);
}
];
}
/**
* Make MixedCase validator
*
* @param string $attribute
* @param mixed $value
* @return array
*/
private static function validationMixedCase(string $attribute, mixed $value): array
{
return [
'type' => 'mixedCase',
'error' => sprintf(
'%s doit contenir des lettre minuscules et majuscules',
self::translate($attribute)
),
'validate' => function () use ($value) {
return \preg_match('/[a-z]/', $value) and \preg_match('/[A-Z]/', $value);
}
];
}
/**
* Make ContainDigit validator
*
* @param string $attribute
* @param mixed $value
* @return array
*/
private static function validationContainDigit(string $attribute, mixed $value): array
{
return [
'type' => 'containDigit',
'error' => sprintf(
'%s doit contenir au moins un chiffre',
self::translate($attribute)
),
'validate' => function () use ($value) {
return \preg_match('/[0-9]/', $value);
}
];
}
/**
* Make ContainSymbol validator
*
* @param string $attribute
* @param mixed $value
* @return array
*/
private static function validationContainSymbol(string $attribute, mixed $value): array
{
return [
'type' => 'containSymbol',
'error' => sprintf(
'%s doit contenir au moins un caractère spécial comme une virgule par exemple',
self::translate($attribute)
),
'validate' => function () use ($value) {
return \preg_match('/[^a-zA-Z0-9]/', $value);
}
];
}
/**
* Make Date validator
*
* @param string $attribute
* @param mixed $value
* @return array
*/
private static function validationDate(string $attribute, mixed $value): array
{
return [
'type' => 'date',
'error' => sprintf('%s doit être une date valide', self::translate($attribute)),
'validate' => function () use ($value) {
return Validator::dateTime()->validate($value);
}
];
}
/**
* Make DateFormat validator
*
* @param string $attribute
* @param mixed $value
* @param array $params
* @return array
*/
private static function validationDateFormat(string $attribute, mixed $value, array $params): array
{
return [
'type' => 'date_format',
'error' => sprintf('%s doit être une date au format %s', self::translate($attribute), $params[0]),
'validate' => function () use ($value, $params) {
return Validator::dateTime($params[0])->validate($value);
}
];
}
/**
* Make Email validator
*
* @param string $attribute
* @param mixed $value
* @return array
*/
private static function validationEmail(string $attribute, mixed $value): array
{
return [
'type' => 'email',
'error' => sprintf('%s doit être un email valide', self::translate($attribute)),
'validate' => function () use ($value) {
return Validator::email()->validate($value);
}
];
}
/**
* Make Array validator
*
* @param string $attribute
* @param mixed $value
* @return array
*/
private static function validationArray(string $attribute, mixed $value): array
{
return [
'type' => 'array',
'error' => sprintf('%s doit être un tableau valide', self::translate($attribute)),
'validate' => function () use ($value) {
return Validator::arrayType()->validate($value);
}
];
}
/**
* Make Closure validator
*
* @param string $attribute
* @param mixed $value
* @param \Closure $closure
* @return array
*/
private static function validationClosure(string $attribute, mixed $value, \Closure $closure): array
{
return [
'type' => 'closure',
'error' => sprintf('%s doit être validé', self::translate($attribute)),
'validate' => function () use ($attribute, $value, $closure) {
$closure($attribute, $value, function ($message) {
throw new ValidationException($message);
});
return true;
}
];
}
// * END VALIDATION RULES
/**
* This is only used for unit tests.
* Get config
*
* @param string $key
* @param string $default
* @return string|null
*/
public static function getConfig(string $key, string $default = null): ?string
{
$value = null;
if (function_exists('config')) {
$value = \config($key, $default);
}
return $value;
}
/**
* Generate a Request from the route name
*
* @param string $routeName
* @param array $query Params to pass on to the route.
* @param array $data Http body params.
* @return \LDC\DAM\Client\Transport\Request
* @throws \ErrorException If the requested route is unknown.
* @throws \ErrorException If a required parameter is missing.
*/
public static function getResquest(string $routeName, array $query = [], array $data = []): Request
{
// Convert bool to integer.
$query = \array_map(function ($v) {
return is_bool($v) ? (int)$v : $v;
}, $query);
$data = \array_map(function ($v) {
return is_bool($v) ? (int)$v : $v;
}, $data);
$routes = \json_decode(\file_get_contents(__DIR__ . '/routes.json'), true);
if (!isset($routes[$routeName])) {
throw new \ErrorException("Unknown route $routeName from the dam");
}
$route = $routes[$routeName];
$matches = [];
$matchedIndex = [];
\preg_match_all('/{([\w-]*)}/', $route['uri'], $matches);
if (\count($matches[0])) {
foreach ($matches[0] as $k => $match) {
if (!isset($query[$matches[1][$k]])) {
throw new \ErrorException(sprintf('Missing required parameter %s', $matches[1][$k]));
}
$route['uri'] = str_replace($match, $query[$matches[1][$k]], $route['uri']);
$matchedIndex[$matches[1][$k]] = $query[$matches[1][$k]];
}
}
foreach ($matchedIndex as $key => $value) {
unset($query[$key]);
}
if (count($query)) {
$route['uri'] = sprintf('%s?%s', $route['uri'], \http_build_query($query));
}
return new Request(HttpMethods::make($route['methods'][0]), $route['uri'], [], $data);
}
/**
* Get composer.json infos
*
* @return array
*/
public static function getPackageInfo(): array
{
if (!static::$packageInfos) {
static::$packageInfos = \json_decode(\file_get_contents(__DIR__ . '/../composer.json'), true);
}
return static::$packageInfos;
}
/**
* Translation a string using php file lang
*
* @param string $key
* @param string $lang
* @return string
*/
public static function translate(string $key, string $lang = 'fr'): string
{
try {
if (!array_key_exists($lang, self::$translations)) {
self::$translations = require __DIR__ . "/../resources/lang/$lang.php";
}
} finally {
if (!isset(self::$translations['validation'][$key])) {
return $key;
} else {
return self::$translations['validation'][$key];
}
}
}
/**
* Write log using syslog
* It also write log using \Illuminate\Support\Facades\Log
* if it is present
*
* @param string $message The message is prefixed with "LDC DAM:" .
* @param \LDC\DAM\Client\Enums\LogLevel $level The log level to apply.
* @return void
*/
public static function log(string $message, LogLevel $level)
{
$message = "LDC DAM: $message";
if (\class_exists('\Illuminate\Support\Facades\Log')) {
switch ($level) {
case LogLevel::EMERG():
\Illuminate\Support\Facades\Log::emergency($message);
break;
case LogLevel::ALERT():
\Illuminate\Support\Facades\Log::alert($message);
break;
case LogLevel::CRIT():
\Illuminate\Support\Facades\Log::critical($message);
break;
case LogLevel::ERR():
\Illuminate\Support\Facades\Log::error($message);
break;
case LogLevel::WARNING():
\Illuminate\Support\Facades\Log::warning($message);
break;
case LogLevel::NOTICE():
\Illuminate\Support\Facades\Log::notice($message);
break;
case LogLevel::INFO():
\Illuminate\Support\Facades\Log::info($message);
break;
case LogLevel::DEBUG():
\Illuminate\Support\Facades\Log::debug($message);
break;
} //end switch
\Illuminate\Support\Facades\Log::warning($message);
} //end if
\syslog(\constant($level), $message);
}
/**
* Set a property without any validation.
*
* ! Warning : this can change any property of the object, use with caution.
*
* @param object $object The object to inspect.
* @param string $property The object property to assign to.
* @param mixed $value The value to insert.
* @return void
* @throws LDC\DAM\Client\Exceptions\AccessError If trying to set a value on a unknown property.
*/
public static function setRawProperty(object $object, string $property, mixed $value): void
{
if (is_object($value) and in_array(BaseEnum::class, class_parents($value))) {
$value = $value->value;
}
$objectName = \get_class($object);
$refClass = new \ReflectionClass($objectName);
try {
$refProp = $refClass->getProperty($property);
} catch (\ReflectionException $e) {
throw new AccessError($objectName, $property);
}
$refProp->setAccessible(true);
$refProp->setValue($object, $value);
}
/**
* Get a property of an object.
*
* ! Warning : this will return any property of the object, use with caution.
*
* @param object $object The object to inspect.
* @param string $property The object property to inspect.
* @return mixed|null Returns null if the property was not found any way.
*/
public static function getRawProperty(object $object, string $property)
{
$refClass = new \ReflectionClass(\get_class($object));
try {
$refProp = $refClass->getProperty($property);
} catch (\ReflectionException $e) {
return null;
}
$refProp->setAccessible(true);
return $refProp->getValue($object);
}
}

37
src/routes.json Normal file
View file

@ -0,0 +1,37 @@
{
"api.ping": {
"uri": "api/ping",
"methods": [
"GET",
"HEAD"
]
},
"api.media.show": {
"uri": "api/media/{apiMedia}",
"methods": [
"GET",
"HEAD"
]
},
"api.media.showByArcadiaId": {
"uri": "api/media/{apiMediaArcadiaId}/byArcadiaId",
"methods": [
"GET",
"HEAD"
]
},
"api.articles.media.index": {
"uri": "api/article/{apiNoArticle}/media",
"methods": [
"GET",
"HEAD"
]
},
"api.media.picture": {
"uri": "api/media/{apiMedia}/picture",
"methods": [
"GET",
"HEAD"
]
}
}