commit ec927f66c0a4606591f045d86012cee43875f726 Author: Jérémy Munsch Date: Fri Jul 29 15:11:28 2022 +0200 Initial commit version 1.0.0 diff --git a/.editorconfig b/.editorconfig new file mode 100644 index 0000000..0a72ec6 --- /dev/null +++ b/.editorconfig @@ -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 diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..5d77e42 --- /dev/null +++ b/.gitignore @@ -0,0 +1,6 @@ +workspace.code-workspace +vendor +node_modules +.phpdoc +.phive +.vscode \ No newline at end of file diff --git a/.gitkeep b/.gitkeep new file mode 100644 index 0000000..e69de29 diff --git a/apiConfig.readonly.json b/apiConfig.readonly.json new file mode 100644 index 0000000..33c64d3 --- /dev/null +++ b/apiConfig.readonly.json @@ -0,0 +1,6 @@ +{ + "version": "1.0.0", + "timestampTimeout": 30, + "apiRequestRatePerMinute": 256, + "servicesDBCache": 10 +} \ No newline at end of file diff --git a/changelog.md b/changelog.md new file mode 100644 index 0000000..31edb7a --- /dev/null +++ b/changelog.md @@ -0,0 +1,6 @@ +# Changelog + +### All notable changes to `DAM CLient` will be documented in this file. + +# version 1.0.0 +- Initial release diff --git a/composer.json b/composer.json new file mode 100644 index 0000000..5ac225f --- /dev/null +++ b/composer.json @@ -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 + } + } +} diff --git a/composer.lock b/composer.lock new file mode 100644 index 0000000..6c93d52 --- /dev/null +++ b/composer.lock @@ -0,0 +1,1121 @@ +{ + "_readme": [ + "This file locks the dependencies of your project to a known state", + "Read more about it at https://getcomposer.org/doc/01-basic-usage.md#installing-dependencies", + "This file is @generated automatically" + ], + "content-hash": "0cc7ad6323cfc63956eecb35780c5628", + "packages": [ + { + "name": "guzzlehttp/guzzle", + "version": "7.4.5", + "source": { + "type": "git", + "url": "https://github.com/guzzle/guzzle.git", + "reference": "1dd98b0564cb3f6bd16ce683cb755f94c10fbd82" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/guzzle/guzzle/zipball/1dd98b0564cb3f6bd16ce683cb755f94c10fbd82", + "reference": "1dd98b0564cb3f6bd16ce683cb755f94c10fbd82", + "shasum": "" + }, + "require": { + "ext-json": "*", + "guzzlehttp/promises": "^1.5", + "guzzlehttp/psr7": "^1.9 || ^2.4", + "php": "^7.2.5 || ^8.0", + "psr/http-client": "^1.0", + "symfony/deprecation-contracts": "^2.2 || ^3.0" + }, + "provide": { + "psr/http-client-implementation": "1.0" + }, + "require-dev": { + "bamarni/composer-bin-plugin": "^1.4.1", + "ext-curl": "*", + "php-http/client-integration-tests": "^3.0", + "phpunit/phpunit": "^8.5.5 || ^9.3.5", + "psr/log": "^1.1 || ^2.0 || ^3.0" + }, + "suggest": { + "ext-curl": "Required for CURL handler support", + "ext-intl": "Required for Internationalized Domain Name (IDN) support", + "psr/log": "Required for using the Log middleware" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "7.4-dev" + } + }, + "autoload": { + "files": [ + "src/functions_include.php" + ], + "psr-4": { + "GuzzleHttp\\": "src/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Graham Campbell", + "email": "hello@gjcampbell.co.uk", + "homepage": "https://github.com/GrahamCampbell" + }, + { + "name": "Michael Dowling", + "email": "mtdowling@gmail.com", + "homepage": "https://github.com/mtdowling" + }, + { + "name": "Jeremy Lindblom", + "email": "jeremeamia@gmail.com", + "homepage": "https://github.com/jeremeamia" + }, + { + "name": "George Mponos", + "email": "gmponos@gmail.com", + "homepage": "https://github.com/gmponos" + }, + { + "name": "Tobias Nyholm", + "email": "tobias.nyholm@gmail.com", + "homepage": "https://github.com/Nyholm" + }, + { + "name": "Márk Sági-Kazár", + "email": "mark.sagikazar@gmail.com", + "homepage": "https://github.com/sagikazarmark" + }, + { + "name": "Tobias Schultze", + "email": "webmaster@tubo-world.de", + "homepage": "https://github.com/Tobion" + } + ], + "description": "Guzzle is a PHP HTTP client library", + "keywords": [ + "client", + "curl", + "framework", + "http", + "http client", + "psr-18", + "psr-7", + "rest", + "web service" + ], + "support": { + "issues": "https://github.com/guzzle/guzzle/issues", + "source": "https://github.com/guzzle/guzzle/tree/7.4.5" + }, + "funding": [ + { + "url": "https://github.com/GrahamCampbell", + "type": "github" + }, + { + "url": "https://github.com/Nyholm", + "type": "github" + }, + { + "url": "https://tidelift.com/funding/github/packagist/guzzlehttp/guzzle", + "type": "tidelift" + } + ], + "time": "2022-06-20T22:16:13+00:00" + }, + { + "name": "guzzlehttp/promises", + "version": "1.5.1", + "source": { + "type": "git", + "url": "https://github.com/guzzle/promises.git", + "reference": "fe752aedc9fd8fcca3fe7ad05d419d32998a06da" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/guzzle/promises/zipball/fe752aedc9fd8fcca3fe7ad05d419d32998a06da", + "reference": "fe752aedc9fd8fcca3fe7ad05d419d32998a06da", + "shasum": "" + }, + "require": { + "php": ">=5.5" + }, + "require-dev": { + "symfony/phpunit-bridge": "^4.4 || ^5.1" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "1.5-dev" + } + }, + "autoload": { + "files": [ + "src/functions_include.php" + ], + "psr-4": { + "GuzzleHttp\\Promise\\": "src/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Graham Campbell", + "email": "hello@gjcampbell.co.uk", + "homepage": "https://github.com/GrahamCampbell" + }, + { + "name": "Michael Dowling", + "email": "mtdowling@gmail.com", + "homepage": "https://github.com/mtdowling" + }, + { + "name": "Tobias Nyholm", + "email": "tobias.nyholm@gmail.com", + "homepage": "https://github.com/Nyholm" + }, + { + "name": "Tobias Schultze", + "email": "webmaster@tubo-world.de", + "homepage": "https://github.com/Tobion" + } + ], + "description": "Guzzle promises library", + "keywords": [ + "promise" + ], + "support": { + "issues": "https://github.com/guzzle/promises/issues", + "source": "https://github.com/guzzle/promises/tree/1.5.1" + }, + "funding": [ + { + "url": "https://github.com/GrahamCampbell", + "type": "github" + }, + { + "url": "https://github.com/Nyholm", + "type": "github" + }, + { + "url": "https://tidelift.com/funding/github/packagist/guzzlehttp/promises", + "type": "tidelift" + } + ], + "time": "2021-10-22T20:56:57+00:00" + }, + { + "name": "guzzlehttp/psr7", + "version": "2.4.0", + "source": { + "type": "git", + "url": "https://github.com/guzzle/psr7.git", + "reference": "13388f00956b1503577598873fffb5ae994b5737" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/guzzle/psr7/zipball/13388f00956b1503577598873fffb5ae994b5737", + "reference": "13388f00956b1503577598873fffb5ae994b5737", + "shasum": "" + }, + "require": { + "php": "^7.2.5 || ^8.0", + "psr/http-factory": "^1.0", + "psr/http-message": "^1.0", + "ralouphie/getallheaders": "^3.0" + }, + "provide": { + "psr/http-factory-implementation": "1.0", + "psr/http-message-implementation": "1.0" + }, + "require-dev": { + "bamarni/composer-bin-plugin": "^1.4.1", + "http-interop/http-factory-tests": "^0.9", + "phpunit/phpunit": "^8.5.8 || ^9.3.10" + }, + "suggest": { + "laminas/laminas-httphandlerrunner": "Emit PSR-7 responses" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "2.4-dev" + } + }, + "autoload": { + "psr-4": { + "GuzzleHttp\\Psr7\\": "src/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Graham Campbell", + "email": "hello@gjcampbell.co.uk", + "homepage": "https://github.com/GrahamCampbell" + }, + { + "name": "Michael Dowling", + "email": "mtdowling@gmail.com", + "homepage": "https://github.com/mtdowling" + }, + { + "name": "George Mponos", + "email": "gmponos@gmail.com", + "homepage": "https://github.com/gmponos" + }, + { + "name": "Tobias Nyholm", + "email": "tobias.nyholm@gmail.com", + "homepage": "https://github.com/Nyholm" + }, + { + "name": "Márk Sági-Kazár", + "email": "mark.sagikazar@gmail.com", + "homepage": "https://github.com/sagikazarmark" + }, + { + "name": "Tobias Schultze", + "email": "webmaster@tubo-world.de", + "homepage": "https://github.com/Tobion" + }, + { + "name": "Márk Sági-Kazár", + "email": "mark.sagikazar@gmail.com", + "homepage": "https://sagikazarmark.hu" + } + ], + "description": "PSR-7 message implementation that also provides common utility methods", + "keywords": [ + "http", + "message", + "psr-7", + "request", + "response", + "stream", + "uri", + "url" + ], + "support": { + "issues": "https://github.com/guzzle/psr7/issues", + "source": "https://github.com/guzzle/psr7/tree/2.4.0" + }, + "funding": [ + { + "url": "https://github.com/GrahamCampbell", + "type": "github" + }, + { + "url": "https://github.com/Nyholm", + "type": "github" + }, + { + "url": "https://tidelift.com/funding/github/packagist/guzzlehttp/psr7", + "type": "tidelift" + } + ], + "time": "2022-06-20T21:43:11+00:00" + }, + { + "name": "kwaadpepper/enum", + "version": "2.1.4", + "source": { + "type": "git", + "url": "https://github.com/Kwaadpepper/enum.git", + "reference": "767d8c8d150c29c4f2cb462864ab07df71e92f6d" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/Kwaadpepper/enum/zipball/767d8c8d150c29c4f2cb462864ab07df71e92f6d", + "reference": "767d8c8d150c29c4f2cb462864ab07df71e92f6d", + "shasum": "" + }, + "require": { + "php": ">=7.3" + }, + "require-dev": { + "orchestra/testbench": "^5", + "phpunit/php-code-coverage": "^9.2", + "phpunit/phpunit": "~9.0", + "slevomat/coding-standard": "^7.0", + "squizlabs/php_codesniffer": "^3.5" + }, + "type": "library", + "extra": { + "laravel": { + "providers": [ + "Kwaadpepper\\Enum\\EnumServiceProvider" + ] + } + }, + "autoload": { + "psr-4": { + "Kwaadpepper\\Enum\\": "src/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Jérémy Munsch", + "email": "github@jeremydev.ovh", + "homepage": "https://jeremydev.ovh" + } + ], + "description": "Enums to use for any project", + "homepage": "https://github.com/kwaadpepper/enum", + "keywords": [ + "enum", + "laravel" + ], + "support": { + "issues": "https://github.com/Kwaadpepper/enum/issues", + "source": "https://github.com/Kwaadpepper/enum/tree/2.1.4" + }, + "time": "2022-07-28T14:19:44+00:00" + }, + { + "name": "psr/http-client", + "version": "1.0.1", + "source": { + "type": "git", + "url": "https://github.com/php-fig/http-client.git", + "reference": "2dfb5f6c5eff0e91e20e913f8c5452ed95b86621" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/php-fig/http-client/zipball/2dfb5f6c5eff0e91e20e913f8c5452ed95b86621", + "reference": "2dfb5f6c5eff0e91e20e913f8c5452ed95b86621", + "shasum": "" + }, + "require": { + "php": "^7.0 || ^8.0", + "psr/http-message": "^1.0" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "1.0.x-dev" + } + }, + "autoload": { + "psr-4": { + "Psr\\Http\\Client\\": "src/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "PHP-FIG", + "homepage": "http://www.php-fig.org/" + } + ], + "description": "Common interface for HTTP clients", + "homepage": "https://github.com/php-fig/http-client", + "keywords": [ + "http", + "http-client", + "psr", + "psr-18" + ], + "support": { + "source": "https://github.com/php-fig/http-client/tree/master" + }, + "time": "2020-06-29T06:28:15+00:00" + }, + { + "name": "psr/http-factory", + "version": "1.0.1", + "source": { + "type": "git", + "url": "https://github.com/php-fig/http-factory.git", + "reference": "12ac7fcd07e5b077433f5f2bee95b3a771bf61be" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/php-fig/http-factory/zipball/12ac7fcd07e5b077433f5f2bee95b3a771bf61be", + "reference": "12ac7fcd07e5b077433f5f2bee95b3a771bf61be", + "shasum": "" + }, + "require": { + "php": ">=7.0.0", + "psr/http-message": "^1.0" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "1.0.x-dev" + } + }, + "autoload": { + "psr-4": { + "Psr\\Http\\Message\\": "src/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "PHP-FIG", + "homepage": "http://www.php-fig.org/" + } + ], + "description": "Common interfaces for PSR-7 HTTP message factories", + "keywords": [ + "factory", + "http", + "message", + "psr", + "psr-17", + "psr-7", + "request", + "response" + ], + "support": { + "source": "https://github.com/php-fig/http-factory/tree/master" + }, + "time": "2019-04-30T12:38:16+00:00" + }, + { + "name": "psr/http-message", + "version": "1.0.1", + "source": { + "type": "git", + "url": "https://github.com/php-fig/http-message.git", + "reference": "f6561bf28d520154e4b0ec72be95418abe6d9363" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/php-fig/http-message/zipball/f6561bf28d520154e4b0ec72be95418abe6d9363", + "reference": "f6561bf28d520154e4b0ec72be95418abe6d9363", + "shasum": "" + }, + "require": { + "php": ">=5.3.0" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "1.0.x-dev" + } + }, + "autoload": { + "psr-4": { + "Psr\\Http\\Message\\": "src/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "PHP-FIG", + "homepage": "http://www.php-fig.org/" + } + ], + "description": "Common interface for HTTP messages", + "homepage": "https://github.com/php-fig/http-message", + "keywords": [ + "http", + "http-message", + "psr", + "psr-7", + "request", + "response" + ], + "support": { + "source": "https://github.com/php-fig/http-message/tree/master" + }, + "time": "2016-08-06T14:39:51+00:00" + }, + { + "name": "ralouphie/getallheaders", + "version": "3.0.3", + "source": { + "type": "git", + "url": "https://github.com/ralouphie/getallheaders.git", + "reference": "120b605dfeb996808c31b6477290a714d356e822" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/ralouphie/getallheaders/zipball/120b605dfeb996808c31b6477290a714d356e822", + "reference": "120b605dfeb996808c31b6477290a714d356e822", + "shasum": "" + }, + "require": { + "php": ">=5.6" + }, + "require-dev": { + "php-coveralls/php-coveralls": "^2.1", + "phpunit/phpunit": "^5 || ^6.5" + }, + "type": "library", + "autoload": { + "files": [ + "src/getallheaders.php" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Ralph Khattar", + "email": "ralph.khattar@gmail.com" + } + ], + "description": "A polyfill for getallheaders.", + "support": { + "issues": "https://github.com/ralouphie/getallheaders/issues", + "source": "https://github.com/ralouphie/getallheaders/tree/develop" + }, + "time": "2019-03-08T08:55:37+00:00" + }, + { + "name": "respect/stringifier", + "version": "0.2.0", + "source": { + "type": "git", + "url": "https://github.com/Respect/Stringifier.git", + "reference": "e55af3c8aeaeaa2abb5fa47a58a8e9688cc23b59" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/Respect/Stringifier/zipball/e55af3c8aeaeaa2abb5fa47a58a8e9688cc23b59", + "reference": "e55af3c8aeaeaa2abb5fa47a58a8e9688cc23b59", + "shasum": "" + }, + "require": { + "php": ">=7.1" + }, + "require-dev": { + "friendsofphp/php-cs-fixer": "^2.8", + "malukenho/docheader": "^0.1.7", + "phpunit/phpunit": "^6.4" + }, + "type": "library", + "autoload": { + "files": [ + "src/stringify.php" + ], + "psr-4": { + "Respect\\Stringifier\\": "src/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Respect/Stringifier Contributors", + "homepage": "https://github.com/Respect/Stringifier/graphs/contributors" + } + ], + "description": "Converts any value to a string", + "homepage": "http://respect.github.io/Stringifier/", + "keywords": [ + "respect", + "stringifier", + "stringify" + ], + "support": { + "issues": "https://github.com/Respect/Stringifier/issues", + "source": "https://github.com/Respect/Stringifier/tree/0.2.0" + }, + "time": "2017-12-29T19:39:25+00:00" + }, + { + "name": "respect/validation", + "version": "2.2.3", + "source": { + "type": "git", + "url": "https://github.com/Respect/Validation.git", + "reference": "4c21a7ffc9a4915673cb2c2843963919e664e627" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/Respect/Validation/zipball/4c21a7ffc9a4915673cb2c2843963919e664e627", + "reference": "4c21a7ffc9a4915673cb2c2843963919e664e627", + "shasum": "" + }, + "require": { + "php": "^7.3 || ^8.0", + "respect/stringifier": "^0.2.0", + "symfony/polyfill-mbstring": "^1.2" + }, + "require-dev": { + "egulias/email-validator": "^3.0", + "malukenho/docheader": "^0.1", + "mikey179/vfsstream": "^1.6", + "phpstan/phpstan": "^0.12", + "phpstan/phpstan-deprecation-rules": "^0.12", + "phpstan/phpstan-phpunit": "^0.12", + "phpunit/phpunit": "^9.3", + "psr/http-message": "^1.0", + "respect/coding-standard": "^3.0", + "squizlabs/php_codesniffer": "^3.5", + "symfony/validator": "^3.0||^4.0", + "zendframework/zend-validator": "^2.1" + }, + "suggest": { + "egulias/email-validator": "Strict (RFC compliant) email validation", + "ext-bcmath": "Arbitrary Precision Mathematics", + "ext-fileinfo": "File Information", + "ext-mbstring": "Multibyte String Functions", + "symfony/validator": "Use Symfony validator through Respect\\Validation", + "zendframework/zend-validator": "Use Zend Framework validator through Respect\\Validation" + }, + "type": "library", + "autoload": { + "psr-4": { + "Respect\\Validation\\": "library/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Respect/Validation Contributors", + "homepage": "https://github.com/Respect/Validation/graphs/contributors" + } + ], + "description": "The most awesome validation engine ever created for PHP", + "homepage": "http://respect.github.io/Validation/", + "keywords": [ + "respect", + "validation", + "validator" + ], + "support": { + "issues": "https://github.com/Respect/Validation/issues", + "source": "https://github.com/Respect/Validation/tree/2.2.3" + }, + "time": "2021-03-19T14:12:45+00:00" + }, + { + "name": "symfony/deprecation-contracts", + "version": "v3.1.1", + "source": { + "type": "git", + "url": "https://github.com/symfony/deprecation-contracts.git", + "reference": "07f1b9cc2ffee6aaafcf4b710fbc38ff736bd918" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/symfony/deprecation-contracts/zipball/07f1b9cc2ffee6aaafcf4b710fbc38ff736bd918", + "reference": "07f1b9cc2ffee6aaafcf4b710fbc38ff736bd918", + "shasum": "" + }, + "require": { + "php": ">=8.1" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-main": "3.1-dev" + }, + "thanks": { + "name": "symfony/contracts", + "url": "https://github.com/symfony/contracts" + } + }, + "autoload": { + "files": [ + "function.php" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Nicolas Grekas", + "email": "p@tchwork.com" + }, + { + "name": "Symfony Community", + "homepage": "https://symfony.com/contributors" + } + ], + "description": "A generic function and convention to trigger deprecation notices", + "homepage": "https://symfony.com", + "support": { + "source": "https://github.com/symfony/deprecation-contracts/tree/v3.1.1" + }, + "funding": [ + { + "url": "https://symfony.com/sponsor", + "type": "custom" + }, + { + "url": "https://github.com/fabpot", + "type": "github" + }, + { + "url": "https://tidelift.com/funding/github/packagist/symfony/symfony", + "type": "tidelift" + } + ], + "time": "2022-02-25T11:15:52+00:00" + }, + { + "name": "symfony/polyfill-mbstring", + "version": "v1.26.0", + "source": { + "type": "git", + "url": "https://github.com/symfony/polyfill-mbstring.git", + "reference": "9344f9cb97f3b19424af1a21a3b0e75b0a7d8d7e" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/symfony/polyfill-mbstring/zipball/9344f9cb97f3b19424af1a21a3b0e75b0a7d8d7e", + "reference": "9344f9cb97f3b19424af1a21a3b0e75b0a7d8d7e", + "shasum": "" + }, + "require": { + "php": ">=7.1" + }, + "provide": { + "ext-mbstring": "*" + }, + "suggest": { + "ext-mbstring": "For best performance" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-main": "1.26-dev" + }, + "thanks": { + "name": "symfony/polyfill", + "url": "https://github.com/symfony/polyfill" + } + }, + "autoload": { + "files": [ + "bootstrap.php" + ], + "psr-4": { + "Symfony\\Polyfill\\Mbstring\\": "" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Nicolas Grekas", + "email": "p@tchwork.com" + }, + { + "name": "Symfony Community", + "homepage": "https://symfony.com/contributors" + } + ], + "description": "Symfony polyfill for the Mbstring extension", + "homepage": "https://symfony.com", + "keywords": [ + "compatibility", + "mbstring", + "polyfill", + "portable", + "shim" + ], + "support": { + "source": "https://github.com/symfony/polyfill-mbstring/tree/v1.26.0" + }, + "funding": [ + { + "url": "https://symfony.com/sponsor", + "type": "custom" + }, + { + "url": "https://github.com/fabpot", + "type": "github" + }, + { + "url": "https://tidelift.com/funding/github/packagist/symfony/symfony", + "type": "tidelift" + } + ], + "time": "2022-05-24T11:49:31+00:00" + } + ], + "packages-dev": [ + { + "name": "dealerdirect/phpcodesniffer-composer-installer", + "version": "v0.7.2", + "source": { + "type": "git", + "url": "https://github.com/Dealerdirect/phpcodesniffer-composer-installer.git", + "reference": "1c968e542d8843d7cd71de3c5c9c3ff3ad71a1db" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/Dealerdirect/phpcodesniffer-composer-installer/zipball/1c968e542d8843d7cd71de3c5c9c3ff3ad71a1db", + "reference": "1c968e542d8843d7cd71de3c5c9c3ff3ad71a1db", + "shasum": "" + }, + "require": { + "composer-plugin-api": "^1.0 || ^2.0", + "php": ">=5.3", + "squizlabs/php_codesniffer": "^2.0 || ^3.1.0 || ^4.0" + }, + "require-dev": { + "composer/composer": "*", + "php-parallel-lint/php-parallel-lint": "^1.3.1", + "phpcompatibility/php-compatibility": "^9.0" + }, + "type": "composer-plugin", + "extra": { + "class": "Dealerdirect\\Composer\\Plugin\\Installers\\PHPCodeSniffer\\Plugin" + }, + "autoload": { + "psr-4": { + "Dealerdirect\\Composer\\Plugin\\Installers\\PHPCodeSniffer\\": "src/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Franck Nijhof", + "email": "franck.nijhof@dealerdirect.com", + "homepage": "http://www.frenck.nl", + "role": "Developer / IT Manager" + }, + { + "name": "Contributors", + "homepage": "https://github.com/Dealerdirect/phpcodesniffer-composer-installer/graphs/contributors" + } + ], + "description": "PHP_CodeSniffer Standards Composer Installer Plugin", + "homepage": "http://www.dealerdirect.com", + "keywords": [ + "PHPCodeSniffer", + "PHP_CodeSniffer", + "code quality", + "codesniffer", + "composer", + "installer", + "phpcbf", + "phpcs", + "plugin", + "qa", + "quality", + "standard", + "standards", + "style guide", + "stylecheck", + "tests" + ], + "support": { + "issues": "https://github.com/dealerdirect/phpcodesniffer-composer-installer/issues", + "source": "https://github.com/dealerdirect/phpcodesniffer-composer-installer" + }, + "time": "2022-02-04T12:51:07+00:00" + }, + { + "name": "phpstan/phpdoc-parser", + "version": "1.6.4", + "source": { + "type": "git", + "url": "https://github.com/phpstan/phpdoc-parser.git", + "reference": "135607f9ccc297d6923d49c2bcf309f509413215" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/phpstan/phpdoc-parser/zipball/135607f9ccc297d6923d49c2bcf309f509413215", + "reference": "135607f9ccc297d6923d49c2bcf309f509413215", + "shasum": "" + }, + "require": { + "php": "^7.2 || ^8.0" + }, + "require-dev": { + "php-parallel-lint/php-parallel-lint": "^1.2", + "phpstan/extension-installer": "^1.0", + "phpstan/phpstan": "^1.5", + "phpstan/phpstan-phpunit": "^1.1", + "phpstan/phpstan-strict-rules": "^1.0", + "phpunit/phpunit": "^9.5", + "symfony/process": "^5.2" + }, + "type": "library", + "autoload": { + "psr-4": { + "PHPStan\\PhpDocParser\\": [ + "src/" + ] + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "description": "PHPDoc parser with support for nullable, intersection and generic types", + "support": { + "issues": "https://github.com/phpstan/phpdoc-parser/issues", + "source": "https://github.com/phpstan/phpdoc-parser/tree/1.6.4" + }, + "time": "2022-06-26T13:09:08+00:00" + }, + { + "name": "slevomat/coding-standard", + "version": "7.2.1", + "source": { + "type": "git", + "url": "https://github.com/slevomat/coding-standard.git", + "reference": "aff06ae7a84e4534bf6f821dc982a93a5d477c90" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/slevomat/coding-standard/zipball/aff06ae7a84e4534bf6f821dc982a93a5d477c90", + "reference": "aff06ae7a84e4534bf6f821dc982a93a5d477c90", + "shasum": "" + }, + "require": { + "dealerdirect/phpcodesniffer-composer-installer": "^0.6.2 || ^0.7", + "php": "^7.2 || ^8.0", + "phpstan/phpdoc-parser": "^1.5.1", + "squizlabs/php_codesniffer": "^3.6.2" + }, + "require-dev": { + "phing/phing": "2.17.3", + "php-parallel-lint/php-parallel-lint": "1.3.2", + "phpstan/phpstan": "1.4.10|1.7.1", + "phpstan/phpstan-deprecation-rules": "1.0.0", + "phpstan/phpstan-phpunit": "1.0.0|1.1.1", + "phpstan/phpstan-strict-rules": "1.2.3", + "phpunit/phpunit": "7.5.20|8.5.21|9.5.20" + }, + "type": "phpcodesniffer-standard", + "extra": { + "branch-alias": { + "dev-master": "7.x-dev" + } + }, + "autoload": { + "psr-4": { + "SlevomatCodingStandard\\": "SlevomatCodingStandard" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "description": "Slevomat Coding Standard for PHP_CodeSniffer complements Consistence Coding Standard by providing sniffs with additional checks.", + "support": { + "issues": "https://github.com/slevomat/coding-standard/issues", + "source": "https://github.com/slevomat/coding-standard/tree/7.2.1" + }, + "funding": [ + { + "url": "https://github.com/kukulich", + "type": "github" + }, + { + "url": "https://tidelift.com/funding/github/packagist/slevomat/coding-standard", + "type": "tidelift" + } + ], + "time": "2022-05-25T10:58:12+00:00" + }, + { + "name": "squizlabs/php_codesniffer", + "version": "3.7.1", + "source": { + "type": "git", + "url": "https://github.com/squizlabs/PHP_CodeSniffer.git", + "reference": "1359e176e9307e906dc3d890bcc9603ff6d90619" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/squizlabs/PHP_CodeSniffer/zipball/1359e176e9307e906dc3d890bcc9603ff6d90619", + "reference": "1359e176e9307e906dc3d890bcc9603ff6d90619", + "shasum": "" + }, + "require": { + "ext-simplexml": "*", + "ext-tokenizer": "*", + "ext-xmlwriter": "*", + "php": ">=5.4.0" + }, + "require-dev": { + "phpunit/phpunit": "^4.0 || ^5.0 || ^6.0 || ^7.0" + }, + "bin": [ + "bin/phpcs", + "bin/phpcbf" + ], + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "3.x-dev" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "BSD-3-Clause" + ], + "authors": [ + { + "name": "Greg Sherwood", + "role": "lead" + } + ], + "description": "PHP_CodeSniffer tokenizes PHP, JavaScript and CSS files and detects violations of a defined set of coding standards.", + "homepage": "https://github.com/squizlabs/PHP_CodeSniffer", + "keywords": [ + "phpcs", + "standards" + ], + "support": { + "issues": "https://github.com/squizlabs/PHP_CodeSniffer/issues", + "source": "https://github.com/squizlabs/PHP_CodeSniffer", + "wiki": "https://github.com/squizlabs/PHP_CodeSniffer/wiki" + }, + "time": "2022-06-18T07:21:10+00:00" + } + ], + "aliases": [], + "minimum-stability": "stable", + "stability-flags": [], + "prefer-stable": false, + "prefer-lowest": false, + "platform": { + "ext-curl": "*", + "php": ">=7.3" + }, + "platform-dev": [], + "plugin-api-version": "2.2.0" +} diff --git a/license.md b/license.md new file mode 100644 index 0000000..49ba9b6 --- /dev/null +++ b/license.md @@ -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. diff --git a/phpcs.xml b/phpcs.xml new file mode 100644 index 0000000..80ff230 --- /dev/null +++ b/phpcs.xml @@ -0,0 +1,125 @@ + + + Created with the PHP Coding Standard Generator. http://edorian.github.com/php-coding-standard-generator/ + + + src/ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + */database/migrations/* + + + diff --git a/readme.md b/readme.md new file mode 100644 index 0000000..c801b1b --- /dev/null +++ b/readme.md @@ -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`` + + '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. diff --git a/src/DamApi.php b/src/DamApi.php new file mode 100644 index 0000000..b7f435b --- /dev/null +++ b/src/DamApi.php @@ -0,0 +1,52 @@ +call($request); + return $response->status->equals(ApiStatus::OK()); + } +} diff --git a/src/Enums/ApiError.php b/src/Enums/ApiError.php new file mode 100644 index 0000000..6d61d03 --- /dev/null +++ b/src/Enums/ApiError.php @@ -0,0 +1,93 @@ + 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' + ]; + } +} diff --git a/src/Enums/ApiStatus.php b/src/Enums/ApiStatus.php new file mode 100644 index 0000000..adc92d8 --- /dev/null +++ b/src/Enums/ApiStatus.php @@ -0,0 +1,18 @@ + 'LOG_EMERG', + 'ALERT' => 'LOG_ALERT', + 'CRIT' => 'LOG_CRIT', + 'ERR' => 'LOG_ERR', + 'WARNING' => 'LOG_WARNING', + 'NOTICE' => 'LOG_NOTICE', + 'INFO' => 'LOG_INFO', + 'DEBUG' => 'LOG_DEBUG', + ]; + } +} diff --git a/src/Enums/MediaExtension.php b/src/Enums/MediaExtension.php new file mode 100644 index 0000000..d154741 --- /dev/null +++ b/src/Enums/MediaExtension.php @@ -0,0 +1,24 @@ +$propertyName, it does not exists."); + } +} diff --git a/src/Exceptions/ApiErrorException.php b/src/Exceptions/ApiErrorException.php new file mode 100644 index 0000000..ad8c373 --- /dev/null +++ b/src/Exceptions/ApiErrorException.php @@ -0,0 +1,102 @@ +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 + } +} diff --git a/src/Exceptions/DamException.php b/src/Exceptions/DamException.php new file mode 100644 index 0000000..44a2fca --- /dev/null +++ b/src/Exceptions/DamException.php @@ -0,0 +1,10 @@ +getMessage())); + } +} diff --git a/src/Models/DamModel.php b/src/Models/DamModel.php new file mode 100644 index 0000000..ec83918 --- /dev/null +++ b/src/Models/DamModel.php @@ -0,0 +1,342 @@ + + */ +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'))); + } + } +} diff --git a/src/Models/Media.php b/src/Models/Media.php new file mode 100644 index 0000000..48ac00c --- /dev/null +++ b/src/Models/Media.php @@ -0,0 +1,274 @@ + + */ +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 + ]; + } +} diff --git a/src/Models/MediaPicture.php b/src/Models/MediaPicture.php new file mode 100644 index 0000000..e1fdc68 --- /dev/null +++ b/src/Models/MediaPicture.php @@ -0,0 +1,170 @@ + + */ +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 + ]; + } +} diff --git a/src/Transport/ApiInterface.php b/src/Transport/ApiInterface.php new file mode 100644 index 0000000..62bbfc7 --- /dev/null +++ b/src/Transport/ApiInterface.php @@ -0,0 +1,237 @@ +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 + )); + } +} diff --git a/src/Transport/Request.php b/src/Transport/Request.php new file mode 100644 index 0000000..b3fa1e5 --- /dev/null +++ b/src/Transport/Request.php @@ -0,0 +1,210 @@ +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); + } +} diff --git a/src/Transport/Response.php b/src/Transport/Response.php new file mode 100644 index 0000000..77ff7c8 --- /dev/null +++ b/src/Transport/Response.php @@ -0,0 +1,201 @@ +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()); + } + } +} diff --git a/src/Utils.php b/src/Utils.php new file mode 100644 index 0000000..5f5ddce --- /dev/null +++ b/src/Utils.php @@ -0,0 +1,694 @@ + $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); + } +} diff --git a/src/routes.json b/src/routes.json new file mode 100644 index 0000000..0c4adbf --- /dev/null +++ b/src/routes.json @@ -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" + ] + } +} \ No newline at end of file