From 8fda05f38b9e0584a165272026ec83bd75c466bd Mon Sep 17 00:00:00 2001 From: vagrant Date: Wed, 20 Mar 2024 13:52:40 +0000 Subject: [PATCH 01/16] ECP-51 set up phpunit tests --- .phpcs.xml.dist | 47 ++++++++ .travis.yml | 71 ++++++++++++ bin/install-wp-tests.sh | 181 ++++++++++++++++++++++++++++++ includes/class-lengow-factory.php | 102 +++++++++++++++++ lengow.php | 13 +++ phpunit.xml.dist | 15 +++ tests/TestConnector.php | 36 ++++++ tests/TestLengowFactory.php | 59 ++++++++++ tests/bootstrap.php | 47 ++++++++ 9 files changed, 571 insertions(+) create mode 100644 .phpcs.xml.dist create mode 100644 .travis.yml create mode 100755 bin/install-wp-tests.sh create mode 100644 includes/class-lengow-factory.php create mode 100644 phpunit.xml.dist create mode 100644 tests/TestConnector.php create mode 100644 tests/TestLengowFactory.php create mode 100644 tests/bootstrap.php diff --git a/.phpcs.xml.dist b/.phpcs.xml.dist new file mode 100644 index 00000000..df58068d --- /dev/null +++ b/.phpcs.xml.dist @@ -0,0 +1,47 @@ + + + Generally-applicable sniffs for WordPress plugins. + + + . + /vendor/ + /node_modules/ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/.travis.yml b/.travis.yml new file mode 100644 index 00000000..e732d4c5 --- /dev/null +++ b/.travis.yml @@ -0,0 +1,71 @@ +sudo: false +dist: trusty + +language: php + +notifications: + email: + on_success: never + on_failure: change + +branches: + only: + - master + +cache: + directories: + - $HOME/.composer/cache + +matrix: + include: + - php: 7.4 + env: WP_VERSION=latest + - php: 7.3 + env: WP_VERSION=latest + - php: 7.2 + env: WP_VERSION=latest + - php: 7.1 + env: WP_VERSION=latest + - php: 7.0 + env: WP_VERSION=latest + - php: 5.6 + env: WP_VERSION=5.3 + - php: 5.6 + env: WP_VERSION=latest + - php: 5.6 + env: WP_VERSION=trunk + - php: 5.6 + env: WP_TRAVISCI=phpcs + +before_script: + - export PATH="$HOME/.composer/vendor/bin:$PATH" + - | + if [ -f ~/.phpenv/versions/$(phpenv version-name)/etc/conf.d/xdebug.ini ]; then + phpenv config-rm xdebug.ini + else + echo "xdebug.ini does not exist" + fi + - | + if [[ ! -z "$WP_VERSION" ]] ; then + bash bin/install-wp-tests.sh wordpress_test root '' localhost $WP_VERSION + composer global require "phpunit/phpunit=4.8.*|5.7.*" + fi + - | + if [[ "$WP_TRAVISCI" == "phpcs" ]] ; then + composer global require wp-coding-standards/wpcs + composer global require phpcompatibility/php-compatibility + composer global require phpcompatibility/phpcompatibility-paragonie + composer global require phpcompatibility/phpcompatibility-wp + phpcs --config-set installed_paths $HOME/.composer/vendor/wp-coding-standards/wpcs,$HOME/.composer/vendor/phpcompatibility/php-compatibility,$HOME/.composer/vendor/phpcompatibility/phpcompatibility-paragonie,$HOME/.composer/vendor/phpcompatibility/phpcompatibility-wp + fi + +script: + - | + if [[ ! -z "$WP_VERSION" ]] ; then + phpunit + WP_MULTISITE=1 phpunit + fi + - | + if [[ "$WP_TRAVISCI" == "phpcs" ]] ; then + phpcs + fi diff --git a/bin/install-wp-tests.sh b/bin/install-wp-tests.sh new file mode 100755 index 00000000..c6f53dc5 --- /dev/null +++ b/bin/install-wp-tests.sh @@ -0,0 +1,181 @@ +#!/usr/bin/env bash + +if [ $# -lt 3 ]; then + echo "usage: $0 [db-host] [wp-version] [skip-database-creation]" + exit 1 +fi + +DB_NAME=$1 +DB_USER=$2 +DB_PASS=$3 +DB_HOST=${4-localhost} +WP_VERSION=${5-latest} +SKIP_DB_CREATE=${6-false} + +TMPDIR=${TMPDIR-/tmp} +TMPDIR=$(echo $TMPDIR | sed -e "s/\/$//") +WP_TESTS_DIR=${WP_TESTS_DIR-$TMPDIR/wordpress-tests-lib} +WP_CORE_DIR=${WP_CORE_DIR-$TMPDIR/wordpress} + +download() { + if [ `which curl` ]; then + curl -s "$1" > "$2"; + elif [ `which wget` ]; then + wget -nv -O "$2" "$1" + fi +} + +if [[ $WP_VERSION =~ ^[0-9]+\.[0-9]+\-(beta|RC)[0-9]+$ ]]; then + WP_BRANCH=${WP_VERSION%\-*} + WP_TESTS_TAG="branches/$WP_BRANCH" + +elif [[ $WP_VERSION =~ ^[0-9]+\.[0-9]+$ ]]; then + WP_TESTS_TAG="branches/$WP_VERSION" +elif [[ $WP_VERSION =~ [0-9]+\.[0-9]+\.[0-9]+ ]]; then + if [[ $WP_VERSION =~ [0-9]+\.[0-9]+\.[0] ]]; then + # version x.x.0 means the first release of the major version, so strip off the .0 and download version x.x + WP_TESTS_TAG="tags/${WP_VERSION%??}" + else + WP_TESTS_TAG="tags/$WP_VERSION" + fi +elif [[ $WP_VERSION == 'nightly' || $WP_VERSION == 'trunk' ]]; then + WP_TESTS_TAG="trunk" +else + # http serves a single offer, whereas https serves multiple. we only want one + download http://api.wordpress.org/core/version-check/1.7/ /tmp/wp-latest.json + grep '[0-9]+\.[0-9]+(\.[0-9]+)?' /tmp/wp-latest.json + LATEST_VERSION=$(grep -o '"version":"[^"]*' /tmp/wp-latest.json | sed 's/"version":"//') + if [[ -z "$LATEST_VERSION" ]]; then + echo "Latest WordPress version could not be found" + exit 1 + fi + WP_TESTS_TAG="tags/$LATEST_VERSION" +fi +set -ex + +install_wp() { + + if [ -d $WP_CORE_DIR ]; then + return; + fi + + mkdir -p $WP_CORE_DIR + + if [[ $WP_VERSION == 'nightly' || $WP_VERSION == 'trunk' ]]; then + mkdir -p $TMPDIR/wordpress-trunk + rm -rf $TMPDIR/wordpress-trunk/* + svn export --quiet https://core.svn.wordpress.org/trunk $TMPDIR/wordpress-trunk/wordpress + mv $TMPDIR/wordpress-trunk/wordpress/* $WP_CORE_DIR + else + if [ $WP_VERSION == 'latest' ]; then + local ARCHIVE_NAME='latest' + elif [[ $WP_VERSION =~ [0-9]+\.[0-9]+ ]]; then + # https serves multiple offers, whereas http serves single. + download https://api.wordpress.org/core/version-check/1.7/ $TMPDIR/wp-latest.json + if [[ $WP_VERSION =~ [0-9]+\.[0-9]+\.[0] ]]; then + # version x.x.0 means the first release of the major version, so strip off the .0 and download version x.x + LATEST_VERSION=${WP_VERSION%??} + else + # otherwise, scan the releases and get the most up to date minor version of the major release + local VERSION_ESCAPED=`echo $WP_VERSION | sed 's/\./\\\\./g'` + LATEST_VERSION=$(grep -o '"version":"'$VERSION_ESCAPED'[^"]*' $TMPDIR/wp-latest.json | sed 's/"version":"//' | head -1) + fi + if [[ -z "$LATEST_VERSION" ]]; then + local ARCHIVE_NAME="wordpress-$WP_VERSION" + else + local ARCHIVE_NAME="wordpress-$LATEST_VERSION" + fi + else + local ARCHIVE_NAME="wordpress-$WP_VERSION" + fi + download https://wordpress.org/${ARCHIVE_NAME}.tar.gz $TMPDIR/wordpress.tar.gz + tar --strip-components=1 -zxmf $TMPDIR/wordpress.tar.gz -C $WP_CORE_DIR + fi + + download https://raw.githubusercontent.com/markoheijnen/wp-mysqli/master/db.php $WP_CORE_DIR/wp-content/db.php +} + +install_test_suite() { + # portable in-place argument for both GNU sed and Mac OSX sed + if [[ $(uname -s) == 'Darwin' ]]; then + local ioption='-i.bak' + else + local ioption='-i' + fi + + # set up testing suite if it doesn't yet exist + if [ ! -d $WP_TESTS_DIR ]; then + # set up testing suite + mkdir -p $WP_TESTS_DIR + rm -rf $WP_TESTS_DIR/{includes,data} + svn export --quiet --ignore-externals https://develop.svn.wordpress.org/${WP_TESTS_TAG}/tests/phpunit/includes/ $WP_TESTS_DIR/includes + svn export --quiet --ignore-externals https://develop.svn.wordpress.org/${WP_TESTS_TAG}/tests/phpunit/data/ $WP_TESTS_DIR/data + fi + + if [ ! -f wp-tests-config.php ]; then + download https://develop.svn.wordpress.org/${WP_TESTS_TAG}/wp-tests-config-sample.php "$WP_TESTS_DIR"/wp-tests-config.php + # remove all forward slashes in the end + WP_CORE_DIR=$(echo $WP_CORE_DIR | sed "s:/\+$::") + sed $ioption "s:dirname( __FILE__ ) . '/src/':'$WP_CORE_DIR/':" "$WP_TESTS_DIR"/wp-tests-config.php + sed $ioption "s:__DIR__ . '/src/':'$WP_CORE_DIR/':" "$WP_TESTS_DIR"/wp-tests-config.php + sed $ioption "s/youremptytestdbnamehere/$DB_NAME/" "$WP_TESTS_DIR"/wp-tests-config.php + sed $ioption "s/yourusernamehere/$DB_USER/" "$WP_TESTS_DIR"/wp-tests-config.php + sed $ioption "s/yourpasswordhere/$DB_PASS/" "$WP_TESTS_DIR"/wp-tests-config.php + sed $ioption "s|localhost|${DB_HOST}|" "$WP_TESTS_DIR"/wp-tests-config.php + fi + +} + +recreate_db() { + shopt -s nocasematch + if [[ $1 =~ ^(y|yes)$ ]] + then + mysqladmin drop $DB_NAME -f --user="$DB_USER" --password="$DB_PASS"$EXTRA + create_db + echo "Recreated the database ($DB_NAME)." + else + echo "Leaving the existing database ($DB_NAME) in place." + fi + shopt -u nocasematch +} + +create_db() { + mysqladmin create $DB_NAME --user="$DB_USER" --password="$DB_PASS"$EXTRA +} + +install_db() { + + if [ ${SKIP_DB_CREATE} = "true" ]; then + return 0 + fi + + # parse DB_HOST for port or socket references + local PARTS=(${DB_HOST//\:/ }) + local DB_HOSTNAME=${PARTS[0]}; + local DB_SOCK_OR_PORT=${PARTS[1]}; + local EXTRA="" + + if ! [ -z $DB_HOSTNAME ] ; then + if [ $(echo $DB_SOCK_OR_PORT | grep -e '^[0-9]\{1,\}$') ]; then + EXTRA=" --host=$DB_HOSTNAME --port=$DB_SOCK_OR_PORT --protocol=tcp" + elif ! [ -z $DB_SOCK_OR_PORT ] ; then + EXTRA=" --socket=$DB_SOCK_OR_PORT" + elif ! [ -z $DB_HOSTNAME ] ; then + EXTRA=" --host=$DB_HOSTNAME --protocol=tcp" + fi + fi + + # create database + if [ $(mysql --user="$DB_USER" --password="$DB_PASS"$EXTRA --execute='show databases;' | grep ^$DB_NAME$) ] + then + echo "Reinstalling will delete the existing test database ($DB_NAME)" + read -p 'Are you sure you want to proceed? [y/N]: ' DELETE_EXISTING_DB + recreate_db $DELETE_EXISTING_DB + else + create_db + fi +} + +install_wp +install_test_suite +install_db diff --git a/includes/class-lengow-factory.php b/includes/class-lengow-factory.php new file mode 100644 index 00000000..b4e1a19f --- /dev/null +++ b/includes/class-lengow-factory.php @@ -0,0 +1,102 @@ + + * @copyright 2017 Lengow SAS + */ + +declare(strict_types=1); + +class Lengow_Factory { + + + /** + * @var Lengow_Factory + */ + private static Lengow_Factory $factory; + + /** + * @var array + */ + protected array $dependencies = array(); + + /** + * @var array + */ + protected array $instances = array(); + + /** + * @return Lengow_Factory + */ + public static function instance(): Lengow_Factory { + return self::$factory ?? self::$factory = new Lengow_Factory(); + } + + private function __construct() { + } + + /** + * @param string $name + * @param mixed $concrete + * @return $this + */ + public function bind( string $name, $concrete ): self { + $this->dependencies[ $name ] = $concrete; + return $this; + } + + /** + * Make a new instance for the given dependency. + * + * @param string $name + * @return mixed + * @throws Exception if $name does not exist in the dependencies + */ + public function make( string $name ) { + if ( isset( $this->dependencies[ $name ] ) ) { + return $this->resolve( $this->dependencies[ $name ] ); + } + + throw new Exception( "Dependency {$name} not found." ); + } + + /** + * Get or create an instance for + * + * @param string $name + * @return mixed + * @throws Exception if $name does not exist in the dependencies + */ + public function get( string $name ) { + return $this->instances[ $name ] ?? $this->instances[ $name ] = $this->make( $name ); + } + + /** + * @param mixed $concrete + * @return mixed + */ + private function resolve( $concrete ) { + if ( is_callable( $concrete ) ) { + return $concrete( $this ); + } else { + return new $concrete(); + } + } +} diff --git a/lengow.php b/lengow.php index 7a71eb6d..f002bd7d 100755 --- a/lengow.php +++ b/lengow.php @@ -169,6 +169,19 @@ public function includes() { include_once 'includes/class-lengow-cron.php'; include_once 'includes/class-lengow-cron-toolbox.php'; include_once 'includes/class-lengow-cron-export.php'; + + $this->init_lengow_factory(); + } + + public function init_lengow_factory() + { + include_once 'includes/class-lengow-factory.php'; + $factory = Lengow_Factory::instance(); + $factory->bind(Lengow_Configuration::class, Lengow_Configuration::class); + $factory->bind(Lengow_Connector::class, function () use ($factory) { + list( $account_id, $access_token, $secret ) = $factory->get(Lengow_Configuration::class)::get_access_id(); + return new Lengow_Connector( $access_token, $secret ); + }); } /** diff --git a/phpunit.xml.dist b/phpunit.xml.dist new file mode 100644 index 00000000..35e23c7a --- /dev/null +++ b/phpunit.xml.dist @@ -0,0 +1,15 @@ + + + + + ./tests/ + + + diff --git a/tests/TestConnector.php b/tests/TestConnector.php new file mode 100644 index 00000000..98eb7b51 --- /dev/null +++ b/tests/TestConnector.php @@ -0,0 +1,36 @@ +getMockBuilder( 'Lengow_Connector' ) + ->onlyMethods( array( 'connect', 'make_request' ) ) + ->disableOriginalConstructor() + ->getMock(); + + $mock_connector->expects( $this->any() ) + ->method( 'connect' ) + ->willReturn( 'token' ); + + $mock_connector->expects( $this->any() ) + ->method( 'make_request' ) + ->willReturn( '{}' ); + + $result = $mock_connector->get( '/v3.0/plans' ); + + $this->assertEquals( array(), $result ); + } +} diff --git a/tests/TestLengowFactory.php b/tests/TestLengowFactory.php new file mode 100644 index 00000000..e8ac18bc --- /dev/null +++ b/tests/TestLengowFactory.php @@ -0,0 +1,59 @@ +bind('Lengow_Main', 'Lengow_Main' ); + + $main = $factory->get('Lengow_Main'); + $this->assertInstanceOf('Lengow_Main', $main); + + $main2 = $factory->get('Lengow_Main'); + $this->assertTrue($main === $main2, 'Instances should be the same'); + + $main3 = $factory->make('Lengow_Main'); + $this->assertFalse($main === $main3, 'Instances should not be the same'); + + $this->assertTrue(Lengow_Factory::instance() === $factory, 'Instances should be the same'); + } + + function test_make_instance_will_fail() { + $factory = Lengow_Factory::instance(); + $factory->bind('Lengow_Main2', 'Lengow_Main' ); + + $this->expectException(Exception::class); + $factory->get('Class_Unknown'); + + $this->expectException(Exception::class); + $factory->make('Class_Unknown'); + } + + /** + * @throws Exception + */ + function test_factory() { + $factory = Lengow_Factory::instance(); + $factory->bind('Test_Factory', function () { + return new Lengow_Main(); + } ); + + $main = $factory->get('Test_Factory'); + $this->assertInstanceOf('Lengow_Main', $main); + + $main2 = $factory->get('Test_Factory'); + $this->assertTrue($main === $main2, 'Instances should be the same'); + } +} diff --git a/tests/bootstrap.php b/tests/bootstrap.php new file mode 100644 index 00000000..060ef22e --- /dev/null +++ b/tests/bootstrap.php @@ -0,0 +1,47 @@ + Date: Mon, 15 Apr 2024 15:08:32 +0200 Subject: [PATCH 02/16] [FEAT] Sdk in wordpress --- composer.json | 18 ++++ .../admin/class-lengow-admin-connection.php | 17 +-- includes/class-lengow-configuration.php | 1 + includes/class-lengow-cron-toolbox.php | 2 +- includes/class-lengow-log.php | 4 + includes/class-sdk-listener.php | 100 ++++++++++++++++++ lengow.php | 40 +++++++ 7 files changed, 174 insertions(+), 8 deletions(-) create mode 100644 composer.json create mode 100755 includes/class-sdk-listener.php diff --git a/composer.json b/composer.json new file mode 100644 index 00000000..93d391ef --- /dev/null +++ b/composer.json @@ -0,0 +1,18 @@ +{ + "repositories": [ + { + "type": "path", + "url": "~/vhosts/lengow-sdk" + } + ], + "require": { + "lengow/php-sdk": "dev-main", + "symfony/http-client": "^5.4", + "nyholm/psr7": "^1.8" + }, + "config": { + "allow-plugins": { + "php-http/discovery": true + } + } +} diff --git a/includes/admin/class-lengow-admin-connection.php b/includes/admin/class-lengow-admin-connection.php index 2ac36632..75199f63 100644 --- a/includes/admin/class-lengow-admin-connection.php +++ b/includes/admin/class-lengow-admin-connection.php @@ -21,6 +21,8 @@ * @copyright 2017 Lengow SAS */ +use Lengow\Sdk\Client\Exception\ClientException; + if ( ! defined( 'ABSPATH' ) ) { exit; } @@ -97,20 +99,21 @@ public static function post_process() { * * @return boolean */ - private static function check_api_credentials( $access_token, $secret ) { - $access_ids_saved = false; - $account_id = Lengow_Connector::get_account_id_by_credentials( $access_token, $secret ); - if ( $account_id ) { - $access_ids_saved = Lengow_Configuration::set_access_ids( + private static function check_api_credentials( string $access_token, string $secret ): bool { + try { + $account = Lengow::sdk()->access()->getToken( $access_token, $secret ); + return Lengow_Configuration::set_access_ids( array( - Lengow_Configuration::ACCOUNT_ID => $account_id, + Lengow_Configuration::ACCOUNT_ID => $account->account_id, Lengow_Configuration::ACCESS_TOKEN => $access_token, Lengow_Configuration::SECRET => $secret, ) ); + } catch ( ClientException|Exception $e ) { + Lengow_Main::get_log_instance()->log_exception( $e ); } - return $access_ids_saved; + return false; } /** diff --git a/includes/class-lengow-configuration.php b/includes/class-lengow-configuration.php index 92ad3915..76871cfe 100755 --- a/includes/class-lengow-configuration.php +++ b/includes/class-lengow-configuration.php @@ -45,6 +45,7 @@ class Lengow_Configuration { const REPORT_MAIL_ENABLED = 'lengow_report_mail_enabled'; const REPORT_MAILS = 'lengow_report_mail_address'; const AUTHORIZATION_TOKEN = 'lengow_authorization_token'; + const AUTHORIZATION_TOKEN_EXPIRE_AT = 'authorization_token_expire_at'; const PLUGIN_DATA = 'lengow_plugin_data'; const ACCOUNT_STATUS_DATA = 'lengow_account_status'; const SHOP_TOKEN = 'lengow_shop_token'; diff --git a/includes/class-lengow-cron-toolbox.php b/includes/class-lengow-cron-toolbox.php index 7609bbce..0952e2b1 100644 --- a/includes/class-lengow-cron-toolbox.php +++ b/includes/class-lengow-cron-toolbox.php @@ -130,7 +130,7 @@ public function launch() { } if ( isset( $result[ Lengow_Toolbox::ERRORS ][ Lengow_Toolbox::ERROR_CODE ] ) ) { $error = true; - if ( $result[ Lengow_Toolbox::ERRORS ][ Lengow_Toolbox::ERROR_CODE ] === Lengow_Connector::CODE_404 ) { + if ( $result[ Lengow_Toolbox::ERRORS ][ Lengow_Toolbox::ERROR_CODE ] === 404 ) { header( 'HTTP/1.1 404 Not Found' ); } else { header( 'HTTP/1.1 403 Forbidden' ); diff --git a/includes/class-lengow-log.php b/includes/class-lengow-log.php index 8552fba9..e64305dd 100755 --- a/includes/class-lengow-log.php +++ b/includes/class-lengow-log.php @@ -90,6 +90,10 @@ public function write( $category, $message = '', $display = false, $marketplace_ $this->file->write( $log ); } + public function log_exception( Throwable $e ) { + $this->write( 'exception', $e->getMessage() . PHP_EOL . $e->getTraceAsString() ); + } + /** * Get log files. * diff --git a/includes/class-sdk-listener.php b/includes/class-sdk-listener.php new file mode 100755 index 00000000..aea1a734 --- /dev/null +++ b/includes/class-sdk-listener.php @@ -0,0 +1,100 @@ + + * @copyright 2017 Lengow SAS + * @license https://www.gnu.org/licenses/gpl-3.0 GNU General Public License + */ + +use Lengow\Sdk\Client\Listener\AfterRequestTokenInterface; +use Lengow\Sdk\Client\Listener\AfterSendRequestInterface; +use Lengow\Sdk\Client\Listener\BeforeSendRequestInterface; +use Psr\Http\Message\RequestInterface; +use Psr\Http\Message\ResponseInterface; + +if ( ! defined( 'ABSPATH' ) ) { + exit; +} + +/** + * Lengow_Sdk_Listener Class. + */ +class Lengow_Sdk_Listener implements AfterRequestTokenInterface, BeforeSendRequestInterface, AfterSendRequestInterface +{ + + /** + * @param string $token + * @param int $expireAt + * + * @return void + */ + public function afterRequestToken( string $token, int $expireAt ): void + { + Lengow_Configuration::update_value( Lengow_Configuration::AUTHORIZATION_TOKEN, $token ); + Lengow_Configuration::update_value( Lengow_Configuration::AUTHORIZATION_TOKEN_EXPIRE_AT, $expireAt ); + } + + /** + * @param ResponseInterface $response + * + * @return ResponseInterface + */ + public function afterSendRequest( ResponseInterface $response ): ResponseInterface + { + $logger = Lengow_Main::get_log_instance(); + $logger->write( + 'sdk.response', + $response->getStatusCode() . ' ' . $this->anonymize((string)$response->getBody()) + ); + + return $response; + } + + /** + * @param RequestInterface $request + * + * @return RequestInterface + */ + public function beforeSendRequest( RequestInterface $request ): RequestInterface + { + $logger = Lengow_Main::get_log_instance(); + $logger->write( + 'sdk.request', + $request->getMethod() . ' ' . $request->getUri() . ' ' . $this->anonymize((string)$request->getBody()) + ); + + return $request; + } + + /** + * Anonymize sensible data such as access keys + * + * @param string $str + * + * @return string + */ + protected function anonymize(string $str): string + { + $str = preg_replace( '/access_token=([a-z0-9]{64})/', 'access_token=***', $str ); + $str = preg_replace( '/secret=([a-z0-9]{64})/', 'secret=***', $str ); + $str = preg_replace( '/"token": "[a-z0-9-]{36}"/', '"token": "***"', $str ); + + return $str; + } +} diff --git a/lengow.php b/lengow.php index f002bd7d..b07d0378 100755 --- a/lengow.php +++ b/lengow.php @@ -39,6 +39,8 @@ */ // prevent direct access. +use Lengow\Sdk\Sdk; + if ( ! defined( 'ABSPATH' ) ) { exit; } @@ -176,9 +178,33 @@ public function includes() { public function init_lengow_factory() { include_once 'includes/class-lengow-factory.php'; + include_once 'includes/class-sdk-listener.php'; $factory = Lengow_Factory::instance(); $factory->bind(Lengow_Configuration::class, Lengow_Configuration::class); + $factory->bind( Sdk::class, function () { + $client = \Lengow\Sdk\ClientFactory::createClient( + Lengow_Configuration::get( Lengow_Configuration::ACCESS_TOKEN ), + Lengow_Configuration::get( Lengow_Configuration::SECRET ), + Lengow_Configuration::get( Lengow_Configuration::AUTHORIZATION_TOKEN ), + Lengow_Configuration::get( Lengow_Configuration::AUTHORIZATION_TOKEN_EXPIRE_AT ), + null, + null, + null, + 'preprod' === Lengow_Configuration::get_plugin_environment() + ? \Lengow\Sdk\ClientFactory::API_URL_PREPROD + : \Lengow\Sdk\ClientFactory::API_URL_PROD + ); + + $listener = new Lengow_Sdk_Listener(); + $client->addBeforeSendRequestListener($listener) + ->addAfterSendRequestListener($listener) + ->getAuthenticator() + ->addAfterRequestTokenListener($listener); + + return new Lengow\Sdk\Sdk($client); + }); $factory->bind(Lengow_Connector::class, function () use ($factory) { + // TODO replace with the SDK list( $account_id, $access_token, $secret ) = $factory->get(Lengow_Configuration::class)::get_access_id(); return new Lengow_Connector( $access_token, $secret ); }); @@ -391,6 +417,20 @@ public function remove_core_updates() { 'version_checked' => $wp_version, ); } + + /** + * @return Sdk + * @throws Exception + */ + public static function sdk(): Sdk + { + return Lengow_Factory::instance()->get( Sdk::class); + } + } + + // if WordPress does not use composer already + if (!class_exists('Lengow\Sdk\Sdk')) { + require __DIR__ . '/vendor/autoload.php'; } // start module. From 9a26a752eb01c61fab6cd5e9fa0633194e7b8ae3 Mon Sep 17 00:00:00 2001 From: Arnaud Hours Date: Tue, 16 Apr 2024 10:53:20 +0200 Subject: [PATCH 03/16] [FEAT] Sdk in wordpress --- .../admin/class-lengow-admin-connection.php | 15 +++++++--- lengow.php | 30 +++++++++++-------- 2 files changed, 28 insertions(+), 17 deletions(-) diff --git a/includes/admin/class-lengow-admin-connection.php b/includes/admin/class-lengow-admin-connection.php index 75199f63..558263e2 100644 --- a/includes/admin/class-lengow-admin-connection.php +++ b/includes/admin/class-lengow-admin-connection.php @@ -101,14 +101,21 @@ public static function post_process() { */ private static function check_api_credentials( string $access_token, string $secret ): bool { try { - $account = Lengow::sdk()->access()->getToken( $access_token, $secret ); - return Lengow_Configuration::set_access_ids( + $access = Lengow::sdk()->access()->getToken( $access_token, $secret ); + if (Lengow_Configuration::set_access_ids( array( - Lengow_Configuration::ACCOUNT_ID => $account->account_id, + Lengow_Configuration::ACCOUNT_ID => $access->account_id, Lengow_Configuration::ACCESS_TOKEN => $access_token, Lengow_Configuration::SECRET => $secret, ) - ); + )) { + Lengow_Configuration::update_value(Lengow_Configuration::AUTHORIZATION_TOKEN, $access->token); + Lengow_Configuration::update_value(Lengow_Configuration::AUTHORIZATION_TOKEN_EXPIRE_AT, time() + 3600); + + return true; + } + + return false; } catch ( ClientException|Exception $e ) { Lengow_Main::get_log_instance()->log_exception( $e ); } diff --git a/lengow.php b/lengow.php index b07d0378..91c88be3 100755 --- a/lengow.php +++ b/lengow.php @@ -182,19 +182,23 @@ public function init_lengow_factory() $factory = Lengow_Factory::instance(); $factory->bind(Lengow_Configuration::class, Lengow_Configuration::class); $factory->bind( Sdk::class, function () { - $client = \Lengow\Sdk\ClientFactory::createClient( - Lengow_Configuration::get( Lengow_Configuration::ACCESS_TOKEN ), - Lengow_Configuration::get( Lengow_Configuration::SECRET ), - Lengow_Configuration::get( Lengow_Configuration::AUTHORIZATION_TOKEN ), - Lengow_Configuration::get( Lengow_Configuration::AUTHORIZATION_TOKEN_EXPIRE_AT ), - null, - null, - null, - 'preprod' === Lengow_Configuration::get_plugin_environment() - ? \Lengow\Sdk\ClientFactory::API_URL_PREPROD - : \Lengow\Sdk\ClientFactory::API_URL_PROD - ); + $apiKey = Lengow_Configuration::get( Lengow_Configuration::ACCESS_TOKEN ); + $apiSecret = Lengow_Configuration::get( Lengow_Configuration::SECRET ); + $authToken = Lengow_Configuration::get( Lengow_Configuration::AUTHORIZATION_TOKEN ); + $expireAt = Lengow_Configuration::get( Lengow_Configuration::AUTHORIZATION_TOKEN_EXPIRE_AT ); + $factory = (new \Lengow\Sdk\ClientFactory()); + if ($apiKey && $apiSecret) { + $factory->withCredentials($apiKey, $apiSecret); + if ($authToken && $expireAt) { + $factory->withAuthorization($authToken, $expireAt); + } + } + + if ('preprod' === Lengow_Configuration::get_plugin_environment()) { + $factory->withApiUrl(\Lengow\Sdk\ClientFactory::API_URL_PREPROD); + } + $client = $factory->getClient(); $listener = new Lengow_Sdk_Listener(); $client->addBeforeSendRequestListener($listener) ->addAfterSendRequestListener($listener) @@ -424,7 +428,7 @@ public function remove_core_updates() { */ public static function sdk(): Sdk { - return Lengow_Factory::instance()->get( Sdk::class); + return Lengow_Factory::instance()->get( Sdk::class ); } } From 6b337ba0da0136ced6b7c396c2cafb8e3937f8cf Mon Sep 17 00:00:00 2001 From: Arnaud Hours Date: Thu, 18 Apr 2024 18:04:55 +0200 Subject: [PATCH 04/16] [FEAT] plugin connection with lengow sdk --- .../admin/class-lengow-admin-connection.php | 14 +++--- includes/class-lengow-configuration.php | 3 +- includes/class-lengow-sync.php | 44 +++++++++---------- includes/class-sdk-listener.php | 3 +- lengow.php | 41 ++++++++++------- 5 files changed, 56 insertions(+), 49 deletions(-) diff --git a/includes/admin/class-lengow-admin-connection.php b/includes/admin/class-lengow-admin-connection.php index 558263e2..5d6cdb36 100644 --- a/includes/admin/class-lengow-admin-connection.php +++ b/includes/admin/class-lengow-admin-connection.php @@ -132,13 +132,13 @@ private static function connect_cms() { $cms_token = Lengow_Main::get_token(); $cms_connected = Lengow_Sync::sync_catalog( true ); if ( ! $cms_connected ) { - $sync_data = wp_json_encode( Lengow_Sync::get_sync_data() ); - $result = Lengow_Connector::query_api( - Lengow_Connector::POST, - Lengow_Connector::API_CMS, - array(), - $sync_data - ); + $sync_data = Lengow_Sync::get_sync_data(); + try { + $result = Lengow::sdk( true )->cms()->post( $sync_data ); + } catch ( Exception $e ) { + Lengow_Main::get_log_instance()->log_exception( $e ); + } + if ( isset( $result->common_account ) ) { $cms_connected = true; $message_key = 'log.connection.cms_creation_success'; diff --git a/includes/class-lengow-configuration.php b/includes/class-lengow-configuration.php index 76871cfe..48d7c66c 100755 --- a/includes/class-lengow-configuration.php +++ b/includes/class-lengow-configuration.php @@ -529,7 +529,8 @@ public static function reset_access_ids() { */ public static function reset_authorization_token() { self::update_value( self::AUTHORIZATION_TOKEN, '' ); - self::update_value( self::LAST_UPDATE_AUTHORIZATION_TOKEN, '' ); + self::update_value( self::LAST_UPDATE_AUTHORIZATION_TOKEN, '' ); // TODO remove this + self::update_value( self::AUTHORIZATION_TOKEN_EXPIRE_AT, '' ); } /** diff --git a/includes/class-lengow-sync.php b/includes/class-lengow-sync.php index 84402aec..d13df79f 100755 --- a/includes/class-lengow-sync.php +++ b/includes/class-lengow-sync.php @@ -22,6 +22,8 @@ * @license https://www.gnu.org/licenses/gpl-3.0 GNU General Public License */ +use Lengow\Sdk\Client\Exception\ClientException; + if ( ! defined( 'ABSPATH' ) ) { exit; } @@ -139,11 +141,10 @@ public static function get_sync_data() { * Sync Lengow catalogs for order synchronisation. * * @param boolean $force Force cache Update - * @param boolean $log_output see log or not * * @return boolean */ - public static function sync_catalog( $force = false, $log_output = false ) { + public static function sync_catalog( $force = false) { $success = false; $setting_updated = false; if ( Lengow_Configuration::is_new_merchant() ) { @@ -157,13 +158,11 @@ public static function sync_catalog( $force = false, $log_output = false ) { return $success; } } - $result = Lengow_Connector::query_api( - Lengow_Connector::GET, - Lengow_Connector::API_CMS, - array(), - '', - $log_output - ); + try { + $result = Lengow::sdk()->cms()->list(); + } catch ( ClientException|Exception $e ) { + Lengow_Main::get_log_instance()->log_exception( $e ); + } if ( isset( $result->cms ) ) { $cms_token = Lengow_Main::get_token(); foreach ( $result->cms as $cms ) { @@ -255,11 +254,10 @@ public static function set_cms_option( $force = false, $log_output = false ) { * Get Status Account. * * @param boolean $force Force cache Update - * @param boolean $log_output see log or not * * @return array|false */ - public static function get_status_account( $force = false, $log_output = false ) { + public static function get_status_account( bool $force = false ) { if ( ! $force ) { $updated_at = Lengow_Configuration::get( Lengow_Configuration::LAST_UPDATE_ACCOUNT_STATUS_DATA ); if ( null !== $updated_at @@ -268,19 +266,19 @@ public static function get_status_account( $force = false, $log_output = false ) return json_decode( Lengow_Configuration::get( Lengow_Configuration::ACCOUNT_STATUS_DATA ), true ); } } - $result = Lengow_Connector::query_api( - Lengow_Connector::GET, - Lengow_Connector::API_PLAN, - array(), - '', - $log_output - ); - if ( isset( $result->isFreeTrial ) ) { + try { + $plans = Lengow::sdk()->plans()->plans(); + } catch ( ClientException|Exception $e ) { + Lengow_Main::get_log_instance()->log_exception($e); + return false; + } + + if ( isset( $plans->isFreeTrial ) ) { $status = array( - 'type' => $result->isFreeTrial ? 'free_trial' : '', - 'day' => (int) $result->leftDaysBeforeExpired < 0 ? 0 : (int) $result->leftDaysBeforeExpired, - 'expired' => (bool) $result->isExpired, - 'legacy' => 'v2' === $result->accountVersion, + 'type' => $plans->isFreeTrial ? 'free_trial' : '', + 'day' => $plans->leftDaysBeforeExpired < 0 ? 0 : $plans->leftDaysBeforeExpired, + 'expired' => $plans->isExpired, + 'legacy' => 'v2' === $plans->accountVersion, ); Lengow_Configuration::update_value( Lengow_Configuration::ACCOUNT_STATUS_DATA, wp_json_encode( $status ) ); Lengow_Configuration::update_value( Lengow_Configuration::LAST_UPDATE_ACCOUNT_STATUS_DATA, time() ); diff --git a/includes/class-sdk-listener.php b/includes/class-sdk-listener.php index aea1a734..faa7e07e 100755 --- a/includes/class-sdk-listener.php +++ b/includes/class-sdk-listener.php @@ -41,10 +41,11 @@ class Lengow_Sdk_Listener implements AfterRequestTokenInterface, BeforeSendReque /** * @param string $token * @param int $expireAt + * @param int $accountId * * @return void */ - public function afterRequestToken( string $token, int $expireAt ): void + public function afterRequestToken( string $token, int $expireAt, int $accountId): void { Lengow_Configuration::update_value( Lengow_Configuration::AUTHORIZATION_TOKEN, $token ); Lengow_Configuration::update_value( Lengow_Configuration::AUTHORIZATION_TOKEN_EXPIRE_AT, $expireAt ); diff --git a/lengow.php b/lengow.php index 91c88be3..2cb80508 100755 --- a/lengow.php +++ b/lengow.php @@ -182,32 +182,33 @@ public function init_lengow_factory() $factory = Lengow_Factory::instance(); $factory->bind(Lengow_Configuration::class, Lengow_Configuration::class); $factory->bind( Sdk::class, function () { - $apiKey = Lengow_Configuration::get( Lengow_Configuration::ACCESS_TOKEN ); - $apiSecret = Lengow_Configuration::get( Lengow_Configuration::SECRET ); - $authToken = Lengow_Configuration::get( Lengow_Configuration::AUTHORIZATION_TOKEN ); - $expireAt = Lengow_Configuration::get( Lengow_Configuration::AUTHORIZATION_TOKEN_EXPIRE_AT ); - $factory = (new \Lengow\Sdk\ClientFactory()); - if ($apiKey && $apiSecret) { - $factory->withCredentials($apiKey, $apiSecret); - if ($authToken && $expireAt) { - $factory->withAuthorization($authToken, $expireAt); + $api_key = Lengow_Configuration::get( Lengow_Configuration::ACCESS_TOKEN ); + $api_secret = Lengow_Configuration::get( Lengow_Configuration::SECRET ); + $auth_token = Lengow_Configuration::get( Lengow_Configuration::AUTHORIZATION_TOKEN ); + $expire_at = Lengow_Configuration::get( Lengow_Configuration::AUTHORIZATION_TOKEN_EXPIRE_AT ); + $account_id = Lengow_Configuration::get( Lengow_Configuration::ACCOUNT_ID ); + $factory = new \Lengow\Sdk\ClientFactory(); + if ( $api_key && $api_secret ) { + $factory->withCredentials( $api_key, $api_secret ); + if ( $auth_token && $expire_at && $account_id ) { + $factory->withAuthorization( $auth_token, $expire_at, $account_id ); } } - if ('preprod' === Lengow_Configuration::get_plugin_environment()) { - $factory->withApiUrl(\Lengow\Sdk\ClientFactory::API_URL_PREPROD); + if ( 'preprod' === Lengow_Configuration::get_plugin_environment() ) { + $factory->withApiUrl( \Lengow\Sdk\ClientFactory::API_URL_PREPROD ); } $client = $factory->getClient(); $listener = new Lengow_Sdk_Listener(); - $client->addBeforeSendRequestListener($listener) - ->addAfterSendRequestListener($listener) + $client->addBeforeSendRequestListener( $listener ) + ->addAfterSendRequestListener( $listener ) ->getAuthenticator() - ->addAfterRequestTokenListener($listener); + ->addAfterRequestTokenListener( $listener ); - return new Lengow\Sdk\Sdk($client); + return new Lengow\Sdk\Sdk( $client ); }); - $factory->bind(Lengow_Connector::class, function () use ($factory) { + $factory->bind(Lengow_Connector::class, function () use ( $factory ) { // TODO replace with the SDK list( $account_id, $access_token, $secret ) = $factory->get(Lengow_Configuration::class)::get_access_id(); return new Lengow_Connector( $access_token, $secret ); @@ -423,11 +424,17 @@ public function remove_core_updates() { } /** + * @param bool $reloadCredentials + * * @return Sdk * @throws Exception */ - public static function sdk(): Sdk + public static function sdk( bool $reloadCredentials = false ): Sdk { + if ( $reloadCredentials ) { + return Lengow_Factory::instance()->make( Sdk::class ); + } + return Lengow_Factory::instance()->get( Sdk::class ); } } From c068e3401e6dfd4b89568e970c8d80d51c50909e Mon Sep 17 00:00:00 2001 From: Arnaud Hours Date: Wed, 24 Apr 2024 10:53:02 +0200 Subject: [PATCH 05/16] [FEAT] plugin connection with lengow sdk --- .../admin/class-lengow-admin-connection.php | 4 +- includes/class-lengow-action.php | 54 +++++++------ includes/class-lengow-catalog.php | 36 ++++++--- includes/class-lengow-order.php | 29 ++++--- includes/class-lengow-sync.php | 76 +++++++++---------- 5 files changed, 109 insertions(+), 90 deletions(-) diff --git a/includes/admin/class-lengow-admin-connection.php b/includes/admin/class-lengow-admin-connection.php index 5d6cdb36..f63facc1 100644 --- a/includes/admin/class-lengow-admin-connection.php +++ b/includes/admin/class-lengow-admin-connection.php @@ -21,7 +21,7 @@ * @copyright 2017 Lengow SAS */ -use Lengow\Sdk\Client\Exception\ClientException; +use Lengow\Sdk\Client\Exception\HttpException; if ( ! defined( 'ABSPATH' ) ) { exit; @@ -116,7 +116,7 @@ private static function check_api_credentials( string $access_token, string $sec } return false; - } catch ( ClientException|Exception $e ) { + } catch ( HttpException|Exception $e ) { Lengow_Main::get_log_instance()->log_exception( $e ); } diff --git a/includes/class-lengow-action.php b/includes/class-lengow-action.php index 21133e30..e3999ae7 100755 --- a/includes/class-lengow-action.php +++ b/includes/class-lengow-action.php @@ -22,6 +22,8 @@ * @license https://www.gnu.org/licenses/gpl-3.0 GNU General Public License */ +use Lengow\Sdk\Client\Exception\HttpException; + if ( ! defined( 'ABSPATH' ) ) { exit; } @@ -235,14 +237,14 @@ public static function can_send_action( $params, $order_lengow ) { unset( $get_params[ $param ] ); } } - $result = Lengow_Connector::query_api( - Lengow_Connector::GET, - Lengow_Connector::API_ORDER_ACTION, - $get_params - ); - if ( isset( $result->error, $result->error->message ) ) { - throw new Lengow_Exception( $result->error->message ); + + try { + $result = Lengow::sdk()->order()->action()->list( $get_params ); + } catch ( HttpException|Exception $e ) { + Lengow_Main::get_log_instance()->log_exception( $e ); + throw new Lengow_Exception( $e->getMessage(), $e->getCode(), $e ); } + if ( isset( $result->count ) && $result->count > 0 ) { foreach ( $result->results as $row ) { $action = self::get( array( self::FIELD_ACTION_ID => (int) $row->id ) ); @@ -286,6 +288,8 @@ public static function can_send_action( $params, $order_lengow ) { */ public static function send_action( $params, $order_lengow ) { if ( ! Lengow_Configuration::debug_mode_is_active() ) { + $result = Lengow::sdk()->order()->action()->post($params); + var_dump($result); die(); $result = Lengow_Connector::query_api( Lengow_Connector::POST, Lengow_Connector::API_ORDER_ACTION, @@ -386,26 +390,26 @@ public static function check_finish_action( $log_output = false ) { $log_output ); do { - $results = Lengow_Connector::query_api( - Lengow_Connector::GET, - Lengow_Connector::API_ORDER_ACTION, - array( - Lengow_Import::ARG_UPDATED_FROM => get_date_from_gmt( - date( Lengow_Main::DATE_FULL, $date_from ), - Lengow_Main::DATE_ISO_8601 - ), - Lengow_Import::ARG_UPDATED_TO => get_date_from_gmt( - date( Lengow_Main::DATE_FULL, $date_to ), - Lengow_Main::DATE_ISO_8601 - ), - Lengow_Import::ARG_PAGE => $page, - ), - '', - $log_output - ); - if ( ! is_object( $results ) || isset( $results->error ) ) { + + try { + $results = Lengow::sdk()->order()->action()->list( + array( + Lengow_Import::ARG_UPDATED_FROM => get_date_from_gmt( + date( Lengow_Main::DATE_FULL, $date_from ), + Lengow_Main::DATE_ISO_8601 + ), + Lengow_Import::ARG_UPDATED_TO => get_date_from_gmt( + date( Lengow_Main::DATE_FULL, $date_to ), + Lengow_Main::DATE_ISO_8601 + ), + Lengow_Import::ARG_PAGE => $page, + ) + ); + } catch ( HttpException|Exception $e ) { + Lengow_Main::get_log_instance()->log_exception( $e ); break; } + // construct array actions. foreach ( $results->results as $action ) { if ( isset( $action->id ) ) { diff --git a/includes/class-lengow-catalog.php b/includes/class-lengow-catalog.php index 9fcc9b7d..2d68901f 100644 --- a/includes/class-lengow-catalog.php +++ b/includes/class-lengow-catalog.php @@ -22,6 +22,8 @@ * @license https://www.gnu.org/licenses/gpl-3.0 GNU General Public License */ +use Lengow\Sdk\Client\Exception\HttpException; + if ( ! defined( 'ABSPATH' ) ) { exit; } @@ -37,13 +39,17 @@ class Lengow_Catalog { * @return boolean */ public static function has_catalog_not_linked() { - $lengow_catalogs = Lengow_Connector::query_api( - Lengow_Connector::GET, - Lengow_Connector::API_CMS_CATALOG - ); + try { + $lengow_catalogs = Lengow::sdk()->cms()->catalog()->list(); + } catch ( HttpException|Exception $e ) { + Lengow_Main::get_log_instance()->log_exception( $e ); + return false; + } + if ( ! $lengow_catalogs ) { return false; } + foreach ( $lengow_catalogs as $catalog ) { if ( ! is_object( $catalog ) || $catalog->shop ) { continue; @@ -62,8 +68,14 @@ public static function has_catalog_not_linked() { */ public static function get_catalog_list() { $catalog_list = array(); - $lengow_catalogs = Lengow_Connector::query_api( Lengow_Connector::GET, Lengow_Connector::API_CMS_CATALOG ); - if ( ! $lengow_catalogs ) { + try { + $lengow_catalogs = Lengow::sdk()->cms()->catalog()->list(); + } catch ( HttpException|Exception $e ) { + Lengow_Main::get_log_instance()->log_exception( $e ); + return $catalog_list; + } + + if ( ! isset( $lengow_catalogs ) ) { return $catalog_list; } foreach ( $lengow_catalogs as $catalog ) { @@ -133,12 +145,12 @@ public static function link_catalogs( array $catalog_ids ) { ) ); - $result = Lengow_Connector::query_api( - Lengow_Connector::POST, - Lengow_Connector::API_CMS_MAPPING, - array(), - json_encode( $link_catalog_data ) - ); + try { + $result = Lengow::sdk()->cms()->mapping()->post( $link_catalog_data ); + } catch ( HttpException|Exception $e ) { + Lengow_Main::get_log_instance()->log_exception( $e ); + return false; + } return isset( $result->cms_token ); } diff --git a/includes/class-lengow-order.php b/includes/class-lengow-order.php index 2c9e25b7..8537d7ae 100755 --- a/includes/class-lengow-order.php +++ b/includes/class-lengow-order.php @@ -22,6 +22,8 @@ * @license https://www.gnu.org/licenses/gpl-3.0 GNU General Public License */ +use Lengow\Sdk\Client\Exception\HttpException; + if ( ! defined( 'ABSPATH' ) ) { exit; } @@ -1158,29 +1160,34 @@ public function call_action( $action ) { */ public function get_order_line_by_api() { $order_lines = array(); - $results = Lengow_Connector::query_api( - Lengow_Connector::GET, - Lengow_Connector::API_ORDER, - array( - Lengow_Import::ARG_MARKETPLACE_ORDER_ID => $this->marketplace_sku, - Lengow_Import::ARG_MARKETPLACE => $this->marketplace_name, - ) - ); - if ( ! isset( $results->count ) || 0 === (int) $results->count ) { + + try { + $results = Lengow::sdk()->order()->list( + array( + Lengow_Import::ARG_MARKETPLACE_ORDER_ID => $this->marketplace_sku, + Lengow_Import::ARG_MARKETPLACE => $this->marketplace_name + ) + ); + } catch ( HttpException|Exception $e ) { + Lengow_Main::get_log_instance()->log_exception( $e ); + } + + if ( ! isset( $results->count ) || 0 === $results->count ) { return false; } + $order_data = $results->results[0]; foreach ( $order_data->packages as $package ) { $product_lines = array(); foreach ( $package->cart as $product ) { $product_lines[] = array( - Lengow_Order_Line::FIELD_ORDER_LINE_ID => (string) $product->marketplace_order_line_id, + Lengow_Order_Line::FIELD_ORDER_LINE_ID => $product->marketplace_order_line_id, ); } if ( 0 === $this->delivery_address_id ) { return ! empty( $product_lines ) ? $product_lines : false; } - $order_lines[ (int) $package->delivery->id ] = $product_lines; + $order_lines[ $package->delivery->id ] = $product_lines; } $return = $order_lines[ $this->delivery_address_id ]; diff --git a/includes/class-lengow-sync.php b/includes/class-lengow-sync.php index d13df79f..d458650d 100755 --- a/includes/class-lengow-sync.php +++ b/includes/class-lengow-sync.php @@ -22,7 +22,7 @@ * @license https://www.gnu.org/licenses/gpl-3.0 GNU General Public License */ -use Lengow\Sdk\Client\Exception\ClientException; +use Lengow\Sdk\Client\Exception\HttpException; if ( ! defined( 'ABSPATH' ) ) { exit; @@ -160,7 +160,7 @@ public static function sync_catalog( $force = false) { } try { $result = Lengow::sdk()->cms()->list(); - } catch ( ClientException|Exception $e ) { + } catch ( HttpException|Exception $e ) { Lengow_Main::get_log_instance()->log_exception( $e ); } if ( isset( $result->cms ) ) { @@ -221,11 +221,10 @@ public static function get_option_data() { * Set CMS options. * * @param boolean $force Force cache Update - * @param boolean $log_output see log or not * * @return boolean */ - public static function set_cms_option( $force = false, $log_output = false ) { + public static function set_cms_option( $force = false ) { if ( Lengow_Configuration::is_new_merchant() || Lengow_Configuration::debug_mode_is_active() ) { return false; } @@ -237,16 +236,15 @@ public static function set_cms_option( $force = false, $log_output = false ) { return false; } } - $options = wp_json_encode( self::get_option_data() ); - Lengow_Connector::query_api( - Lengow_Connector::PUT, - Lengow_Connector::API_CMS, - array(), - $options, - $log_output - ); - Lengow_Configuration::update_value( Lengow_Configuration::LAST_UPDATE_OPTION_CMS, time() ); + $options = self::get_option_data(); + try { + Lengow::sdk()->cms()->put( $options ); + } catch ( HttpException|Exception $e ) { + Lengow_Main::get_log_instance()->log_exception( $e ); + return false; + } + Lengow_Configuration::update_value( Lengow_Configuration::LAST_UPDATE_OPTION_CMS, time() ); return true; } @@ -267,18 +265,18 @@ public static function get_status_account( bool $force = false ) { } } try { - $plans = Lengow::sdk()->plans()->plans(); - } catch ( ClientException|Exception $e ) { + $plan = Lengow::sdk()->plan()->me(); + } catch ( HttpException|Exception $e ) { Lengow_Main::get_log_instance()->log_exception($e); return false; } - if ( isset( $plans->isFreeTrial ) ) { + if ( isset( $plan->isFreeTrial ) ) { $status = array( - 'type' => $plans->isFreeTrial ? 'free_trial' : '', - 'day' => $plans->leftDaysBeforeExpired < 0 ? 0 : $plans->leftDaysBeforeExpired, - 'expired' => $plans->isExpired, - 'legacy' => 'v2' === $plans->accountVersion, + 'type' => $plan->isFreeTrial ? 'free_trial' : '', + 'day' => $plan->leftDaysBeforeExpired < 0 ? 0 : $plan->leftDaysBeforeExpired, + 'expired' => $plan->isExpired, + 'legacy' => 'v2' === $plan->accountVersion, ); Lengow_Configuration::update_value( Lengow_Configuration::ACCOUNT_STATUS_DATA, wp_json_encode( $status ) ); Lengow_Configuration::update_value( Lengow_Configuration::LAST_UPDATE_ACCOUNT_STATUS_DATA, time() ); @@ -296,11 +294,10 @@ public static function get_status_account( bool $force = false ) { * Get marketplace data. * * @param boolean $force force cache update - * @param boolean $log_output see log or not * * @return array|false */ - public static function get_marketplaces( $force = false, $log_output = false ) { + public static function get_marketplaces( $force = false ) { $file_path = Lengow_Marketplace::get_file_path(); if ( ! $force ) { $updated_at = Lengow_Configuration::get( Lengow_Configuration::LAST_UPDATE_MARKETPLACE ); @@ -317,14 +314,14 @@ public static function get_marketplaces( $force = false, $log_output = false ) { } } // recovering data with the API. - $result = Lengow_Connector::query_api( - Lengow_Connector::GET, - Lengow_Connector::API_MARKETPLACE, - array(), - '', - $log_output - ); - if ( $result && is_object( $result ) && ! isset( $result->error ) ) { + + try { + $result = (object) Lengow::sdk()->marketplace()->list(); + } catch ( HttpException|Exception $e ) { + Lengow_Main::get_log_instance()->log_exception( $e ); + } + + if ( isset( $result ) ) { // updated marketplaces.json file. try { $marketplace_file = new Lengow_File( @@ -347,7 +344,6 @@ public static function get_marketplaces( $force = false, $log_output = false ) { ), ) ), - $log_output ); } @@ -369,11 +365,10 @@ public static function get_marketplaces( $force = false, $log_output = false ) { * Get Lengow plugin data (last version and download link) * * @param boolean $force force cache update - * @param boolean $log_output see log or not * * @return array|false */ - public static function get_plugin_data( $force = false, $log_output = false ) { + public static function get_plugin_data( $force = false ) { if ( ! $force ) { $updated_at = Lengow_Configuration::get( Lengow_Configuration::LAST_UPDATE_PLUGIN_DATA ); if ( $updated_at !== null @@ -382,13 +377,14 @@ public static function get_plugin_data( $force = false, $log_output = false ) { return json_decode( Lengow_Configuration::get( Lengow_Configuration::PLUGIN_DATA ), true ); } } - $plugins = Lengow_Connector::query_api( - Lengow_Connector::GET, - Lengow_Connector::API_PLUGIN, - array(), - '', - $log_output - ); + + try { + $plugins = Lengow::sdk()->plugin()->list(); + } catch ( HttpException|Exception $e ) { + Lengow_Main::get_log_instance()->log_exception($e); + return false; + } + if ( $plugins ) { $plugin_data = false; foreach ( $plugins as $plugin ) { From 763ac2a0de878a8be6b88c55b743890734a0263a Mon Sep 17 00:00:00 2001 From: Arnaud Hours Date: Fri, 26 Apr 2024 17:07:30 +0200 Subject: [PATCH 06/16] [FEAT] plugin connection with lengow sdk --- .../admin/class-lengow-admin-connection.php | 14 +- includes/admin/views/html-admin-footer.php | 2 +- includes/class-lengow-action.php | 51 +- includes/class-lengow-configuration.php | 46 +- includes/class-lengow-connector.php | 633 ------------------ includes/class-lengow-cron-export.php | 1 - includes/class-lengow-cron-toolbox.php | 1 - includes/class-lengow-cron.php | 1 - includes/class-lengow-factory.php | 2 +- includes/class-lengow-import-order.php | 12 +- includes/class-lengow-import.php | 67 +- includes/class-lengow-order.php | 73 +- includes/class-lengow-sync.php | 6 +- includes/class-lengow-toolbox.php | 4 +- lengow.php | 6 - 15 files changed, 90 insertions(+), 829 deletions(-) delete mode 100755 includes/class-lengow-connector.php diff --git a/includes/admin/class-lengow-admin-connection.php b/includes/admin/class-lengow-admin-connection.php index f63facc1..56377ec4 100644 --- a/includes/admin/class-lengow-admin-connection.php +++ b/includes/admin/class-lengow-admin-connection.php @@ -21,6 +21,7 @@ * @copyright 2017 Lengow SAS */ +use Lengow\Sdk\Client\AuthenticatorInterface; use Lengow\Sdk\Client\Exception\HttpException; if ( ! defined( 'ABSPATH' ) ) { @@ -109,12 +110,19 @@ private static function check_api_credentials( string $access_token, string $sec Lengow_Configuration::SECRET => $secret, ) )) { - Lengow_Configuration::update_value(Lengow_Configuration::AUTHORIZATION_TOKEN, $access->token); - Lengow_Configuration::update_value(Lengow_Configuration::AUTHORIZATION_TOKEN_EXPIRE_AT, time() + 3600); + Lengow_Configuration::update_value( Lengow_Configuration::AUTHORIZATION_TOKEN, $access->token ); + Lengow_Configuration::update_value( Lengow_Configuration::AUTHORIZATION_TOKEN_EXPIRE_AT, time() + 3600 ); + Lengow::sdk()->getClient()->getAuthenticator()->setCredentials( $access_token, $secret ); + Lengow::sdk()->getClient()->getAuthenticator()->setToken( + $access->token, + time() + AuthenticatorInterface::TOKEN_LIFETIME, + $access->account_id + ); return true; } + Lengow_Main::log( 'Connector', 'Unable to save access IDs' ); return false; } catch ( HttpException|Exception $e ) { Lengow_Main::get_log_instance()->log_exception( $e ); @@ -134,7 +142,7 @@ private static function connect_cms() { if ( ! $cms_connected ) { $sync_data = Lengow_Sync::get_sync_data(); try { - $result = Lengow::sdk( true )->cms()->post( $sync_data ); + $result = Lengow::sdk()->cms()->post( $sync_data ); } catch ( Exception $e ) { Lengow_Main::get_log_instance()->log_exception( $e ); } diff --git a/includes/admin/views/html-admin-footer.php b/includes/admin/views/html-admin-footer.php index 1da19bdf..c5318b59 100755 --- a/includes/admin/views/html-admin-footer.php +++ b/includes/admin/views/html-admin-footer.php @@ -107,7 +107,7 @@ class="lgw-modalbox mod-size-medium
order()->action()->post($params); - var_dump($result); die(); - $result = Lengow_Connector::query_api( - Lengow_Connector::POST, - Lengow_Connector::API_ORDER_ACTION, - $params - ); - if ( isset( $result->id ) ) { - self::create( - array( - self::FIELD_ORDER_ID => $order_lengow->order_id, - self::FIELD_ACTION_TYPE => $params[ self::ARG_ACTION_TYPE ], - self::FIELD_ACTION_ID => $result->id, - self::FIELD_ORDER_LINE_SKU => isset( $params[ self::ARG_LINE ] ) - ? $params[ self::ARG_LINE ] - : null, - self::FIELD_PARAMETERS => wp_json_encode( $params ), - ) + try { + $result = Lengow::sdk()->order()->action()->post( $params + array( + 'account_id' => Lengow_Configuration::get( Lengow_Configuration::ACCOUNT_ID ), + ) ); + } catch ( HttpException|Exception $e ) { + Lengow_Main::get_log_instance()->log_exception( $e ); + throw new Lengow_Exception( + Lengow_Main::set_log_message( 'lengow_log.exception.action_not_created_api' ), + 0, + $e ); - } else { - if ( $result ) { - $message = Lengow_Main::set_log_message( - 'lengow_log.exception.action_not_created', - array( 'error_message' => wp_json_encode( $result ) ) - ); - } else { - // generating a generic error message when the Lengow API is unavailable. - $message = Lengow_Main::set_log_message( 'lengow_log.exception.action_not_created_api' ); - } - throw new Lengow_Exception( $message ); } + + self::create( + array( + self::FIELD_ORDER_ID => $order_lengow->order_id, + self::FIELD_ACTION_TYPE => $params[ self::ARG_ACTION_TYPE ], + self::FIELD_ACTION_ID => $result->id, + self::FIELD_ORDER_LINE_SKU => isset( $params[ self::ARG_LINE ] ) + ? $params[ self::ARG_LINE ] + : null, + self::FIELD_PARAMETERS => wp_json_encode( $params ), + ) + ); } // create log for call action. $param_list = false; diff --git a/includes/class-lengow-configuration.php b/includes/class-lengow-configuration.php index 48d7c66c..fc70623b 100755 --- a/includes/class-lengow-configuration.php +++ b/includes/class-lengow-configuration.php @@ -154,6 +154,9 @@ class Lengow_Configuration { self::LAST_UPDATE_PLUGIN_MODAL => 'last_update_plugin_modal', ); + const LENGOW_URL = 'lengow.io'; + const LENGOW_URL_PREPROD = 'lengow.net'; + /** * Get all Lengow configuration keys. * @@ -827,46 +830,13 @@ public static function check_and_log( $key, $value ) { * * @return string */ - public static function get_lengow_url() { - $url = Lengow_Connector::LENGOW_URL; - if ( self::is_production_mode() ) { - $url = str_replace( - Lengow_Connector::TEST_SUFFIX, - Lengow_Connector::LIVE_SUFFIX, - $url - ); - } else { - $url = str_replace( - Lengow_Connector::LIVE_SUFFIX, - Lengow_Connector::TEST_SUFFIX, - $url - ); - } - return $url; - } - - /** - * Returns the lengow url for API - * - * @return string - */ - public static function get_lengow_api_url() { - $url = Lengow_Connector::LENGOW_API_URL; - if ( self::is_production_mode() ) { - $url = str_replace( - Lengow_Connector::TEST_SUFFIX, - Lengow_Connector::LIVE_SUFFIX, - $url - ); - } else { - $url = str_replace( - Lengow_Connector::LIVE_SUFFIX, - Lengow_Connector::TEST_SUFFIX, - $url - ); + public static function get_lengow_url(): string { + $env = self::get_plugin_environment(); + if ( 'preprod' === $env ) { + return self::LENGOW_URL_PREPROD; } - return $url; + return self::LENGOW_URL; } /** diff --git a/includes/class-lengow-connector.php b/includes/class-lengow-connector.php deleted file mode 100755 index d09ae67e..00000000 --- a/includes/class-lengow-connector.php +++ /dev/null @@ -1,633 +0,0 @@ - - * @copyright 2017 Lengow SAS - * @license https://www.gnu.org/licenses/gpl-3.0 GNU General Public License - */ -if ( ! defined( 'ABSPATH' ) ) { - exit; -} - -/** - * Lengow_Connector Class. - */ -class Lengow_Connector { - - /** - * @var string url of Lengow solution. - */ - const LENGOW_URL = 'lengow.io'; - - - /** - * @var string url of the Lengow API. - */ - const LENGOW_API_URL = 'https://api.lengow.io'; - - /** - * @var string suffix for prod - */ - const LIVE_SUFFIX = '.io'; - - /** - * @var string suffix for pre-prod - */ - const TEST_SUFFIX = '.net'; - - - - /* Lengow API routes */ - const API_ACCESS_TOKEN = '/access/get_token'; - const API_ORDER = '/v3.0/orders'; - const API_ORDER_MOI = '/v3.0/orders/moi/'; - const API_ORDER_ACTION = '/v3.0/orders/actions/'; - const API_MARKETPLACE = '/v3.0/marketplaces'; - const API_PLAN = '/v3.0/plans'; - const API_CMS = '/v3.1/cms'; - const API_CMS_CATALOG = '/v3.1/cms/catalogs/'; - const API_CMS_MAPPING = '/v3.1/cms/mapping/'; - const API_PLUGIN = '/v3.0/plugins'; - - /* Request actions */ - const GET = 'GET'; - const POST = 'POST'; - const PUT = 'PUT'; - const PATCH = 'PATCH'; - - /* Return formats */ - const FORMAT_JSON = 'json'; - const FORMAT_STREAM = 'stream'; - - /* Http codes */ - const CODE_200 = 200; - const CODE_201 = 201; - const CODE_401 = 401; - const CODE_403 = 403; - const CODE_404 = 404; - const CODE_500 = 500; - const CODE_504 = 504; - - /** - * @var array success HTTP codes for request. - */ - private $success_codes = array( - self::CODE_200, - self::CODE_201, - ); - - /** - * @var array authorization HTTP codes for request. - */ - private $authorization_codes = array( - self::CODE_401, - self::CODE_403, - ); - - /** - * @var integer Authorization token lifetime. - */ - private $token_lifetime = 3000; - - /** - * @var array default options for curl. - */ - private $curl_opts = array( - 'connecttiemout' => 10, - 'returntransfert' => true, - 'timeout' => 10, - 'useragrent' => 'lengow-cms-woocommerce', - ); - - /** - * @var string the access token to connect. - */ - private $access_token; - - /** - * @var string the secret to connect. - */ - private $secret; - - /** - * @var string temporary token for the authorization. - */ - private $token; - - /** - * @var array lengow url for curl timeout. - */ - private $lengow_urls = array( - self::API_ORDER => 20, - self::API_ORDER_MOI => 10, - self::API_ORDER_ACTION => 15, - self::API_MARKETPLACE => 15, - self::API_PLAN => 5, - self::API_CMS => 5, - self::API_CMS_CATALOG => 10, - self::API_CMS_MAPPING => 10, - self::API_PLUGIN => 5, - ); - - /** - * @var array API requiring no arguments in the call url. - */ - private $api_without_url_args = array( - self::API_ACCESS_TOKEN, - self::API_ORDER_ACTION, - self::API_ORDER_MOI, - ); - - /** - * @var array API requiring no authorization for the call url - */ - private static $api_without_authorizations = array( - self::API_PLUGIN, - ); - - /** - * Make a new Lengow API Connector. - * - * @param string $access_token Your access token - * @param string $secret Your secret - */ - public function __construct( $access_token, $secret ) { - $this->access_token = $access_token; - $this->secret = $secret; - } - - /** - * Check API Authentication. - * - * @param boolean $log_output see log or not - * - * @return boolean - */ - public static function is_valid_auth( $log_output = false ) { - if ( ! Lengow_Toolbox::is_curl_activated() ) { - return false; - } - list( $account_id, $access_token, $secret ) = Lengow_Configuration::get_access_id(); - if ( null === $account_id ) { - return false; - } - $connector = new Lengow_Connector( $access_token, $secret ); - try { - $connector->connect( false, $log_output ); - } catch ( Lengow_Exception $e ) { - $message = Lengow_Main::decode_log_message( $e->getMessage(), Lengow_Translation::DEFAULT_ISO_CODE ); - $error = Lengow_Main::set_log_message( - 'log.connector.error_api', - array( - 'error_code' => $e->getCode(), - 'error_message' => $message, - ) - ); - Lengow_Main::log( Lengow_Log::CODE_CONNECTOR, $error, $log_output ); - - return false; - } - - return true; - } - - /** - * Get result for a query Api. - * - * @param string $type request type (GET / POST / PUT / PATCH) - * @param string $api request url - * @param array $args request params - * @param string $body body data for request - * @param boolean $log_output see log or not - * - * @return mixed - */ - public static function query_api( $type, $api, $args = array(), $body = '', $log_output = false ) { - if ( ! in_array( $type, array( self::GET, self::POST, self::PUT, self::PATCH ) ) ) { - return false; - } - try { - $authorization_required = ! in_array( $api, self::$api_without_authorizations, true ); - list( $account_id, $access_token, $secret ) = Lengow_Configuration::get_access_id(); - if ( null === $account_id && $authorization_required ) { - return false; - } - $connector = new Lengow_Connector( $access_token, $secret ); - $type = strtolower( $type ); - $args = $authorization_required ? array_merge( array( Lengow_Import::ARG_ACCOUNT_ID => $account_id ), $args ) : $args; - $results = $connector->$type( $api, $args, self::FORMAT_STREAM, $body, $log_output ); - } catch ( Lengow_Exception $e ) { - $message = Lengow_Main::decode_log_message( $e->getMessage(), Lengow_Translation::DEFAULT_ISO_CODE ); - $error = Lengow_Main::set_log_message( - 'log.connector.error_api', - array( - 'error_code' => $e->getCode(), - 'error_message' => $message, - ) - ); - Lengow_Main::log( Lengow_Log::CODE_CONNECTOR, $error, $log_output ); - - return false; - } - - // don't decode into array as we use the result as an object. - return json_decode( $results ); - } - - /** - * Get account id by credentials from Middleware. - * - * @param string $access_token access token for api - * @param string $secret secret for api - * @param boolean $log_output see log or not - * - * @return int|null - */ - public static function get_account_id_by_credentials( $access_token, $secret, $log_output = false ) { - $connector = new Lengow_Connector( $access_token, $secret ); - try { - $data = $connector->call_action( - self::API_ACCESS_TOKEN, - array( - 'access_token' => $access_token, - 'secret' => $secret, - ), - self::POST, - self::FORMAT_JSON, - '', - $log_output - ); - } catch ( Lengow_Exception $e ) { - $message = Lengow_Main::decode_log_message( $e->getMessage(), Lengow_Translation::DEFAULT_ISO_CODE ); - $error = Lengow_Main::set_log_message( - 'log.connector.error_api', - array( - 'error_code' => $e->getCode(), - 'error_message' => $message, - ) - ); - Lengow_Main::log( Lengow_Log::CODE_CONNECTOR, $error, $log_output ); - - return null; - } - - return $data['account_id'] ? (int) $data['account_id'] : null; - } - - /** - * Connection to the API. - * - * @param boolean $force Force cache Update - * @param boolean $log_output see log or not - * - * @throws Lengow_Exception - */ - public function connect( $force = false, $log_output = false ) { - $token = Lengow_Configuration::get( Lengow_Configuration::AUTHORIZATION_TOKEN ); - $updated_at = Lengow_Configuration::get( Lengow_Configuration::LAST_UPDATE_AUTHORIZATION_TOKEN ); - if ( ! $force && null !== $token && null !== $updated_at && '' !== $token && ( time() - $updated_at ) < $this->token_lifetime - ) { - $authorization_token = $token; - } else { - $authorization_token = $this->get_authorization_token( $log_output ); - Lengow_Configuration::update_value( Lengow_Configuration::AUTHORIZATION_TOKEN, $authorization_token ); - Lengow_Configuration::update_value( Lengow_Configuration::LAST_UPDATE_AUTHORIZATION_TOKEN, time() ); - } - $this->token = $authorization_token; - } - - /** - * Get API call. - * - * @param string $api Lengow method API call - * @param array $args Lengow method API parameters - * @param string $format return format of API - * @param string $body body data for request - * @param boolean $log_output see log or not - * - * @return mixed - * @throws Lengow_Exception - */ - public function get( $api, $args = array(), $format = self::FORMAT_JSON, $body = '', $log_output = false ) { - return $this->call( $api, $args, self::GET, $format, $body, $log_output ); - } - - /** - * Post API call. - * - * @param string $api Lengow method API call - * @param array $args Lengow method API parameters - * @param string $format return format of API - * @param string $body body data for request - * @param boolean $log_output see log or not - * - * @return mixed - * @throws Lengow_Exception - */ - public function post( $api, $args = array(), $format = self::FORMAT_JSON, $body = '', $log_output = false ) { - return $this->call( $api, $args, self::POST, $format, $body, $log_output ); - } - - /** - * Put API call. - * - * @param string $api Lengow method API call - * @param array $args Lengow method API parameters - * @param string $format return format of API - * @param string $body body data for request - * @param boolean $log_output see log or not - * - * @return mixed - * @throws Lengow_Exception - */ - public function put( $api, $args = array(), $format = self::FORMAT_JSON, $body = '', $log_output = false ) { - return $this->call( $api, $args, self::PUT, $format, $body, $log_output ); - } - - /** - * Patch API call. - * - * @param string $api Lengow method API call - * @param array $args Lengow method API parameters - * @param string $format return format of API - * @param string $body body data for request - * @param boolean $log_output see log or not - * - * @return mixed - * @throws Lengow_Exception - */ - public function patch( $api, $args = array(), $format = self::FORMAT_JSON, $body = '', $log_output = false ) { - return $this->call( $api, $args, self::PATCH, $format, $body, $log_output ); - } - - /** - * The API method. - * - * @param string $api Lengow method API call - * @param array $args Lengow method API parameters - * @param string $type type of request GET|POST|PUT|PATCH - * @param string $format return format of API - * @param string $body body data for request - * @param boolean $log_output see log or not - * - * @return mixed - * @throws Lengow_Exception - */ - private function call( $api, $args, $type, $format, $body, $log_output ) { - try { - if ( ! in_array( $api, self::$api_without_authorizations, true ) ) { - $this->connect( false, $log_output ); - } - $data = $this->call_action( $api, $args, $type, $format, $body, $log_output ); - } catch ( Lengow_Exception $e ) { - if ( in_array( $e->getCode(), $this->authorization_codes, true ) ) { - Lengow_Main::log( - Lengow_Log::CODE_CONNECTOR, - Lengow_Main::set_log_message( 'log.connector.retry_get_token' ), - $log_output - ); - if ( ! in_array( $api, self::$api_without_authorizations, true ) ) { - $this->connect( true, $log_output ); - } - $data = $this->call_action( $api, $args, $type, $format, $body, $log_output ); - } else { - throw new Lengow_Exception( $e->getMessage(), $e->getCode() ); - } - } - - return $data; - } - - /** - * Call API action. - * - * @param string $api Lengow method API call - * @param array $args Lengow method API parameters - * @param string $type type of request GET|POST|PUT|PATCH - * @param string $format return format of API - * @param string $body body data for request - * @param boolean $log_output see log or not - * - * @return mixed - * @throws Lengow_Exception - */ - private function call_action( $api, $args, $type, $format, $body, $log_output ) { - $result = $this->make_request( $type, $api, $args, $this->token, $body, $log_output ); - - return $this->format( $result, $format ); - } - - /** - * Get authorization token from Middleware. - * - * @param boolean $log_output see log or not - * - * @return string - * @throws Lengow_Exception - */ - private function get_authorization_token( $log_output ) { - // reset temporary token for the new authorization - $this->token = null; - $data = $this->call_action( - self::API_ACCESS_TOKEN, - array( - 'access_token' => $this->access_token, - 'secret' => $this->secret, - ), - self::POST, - self::FORMAT_JSON, - '', - $log_output - ); - // return a specific error for get_token. - if ( ! isset( $data['token'] ) ) { - throw new Lengow_Exception( - Lengow_Main::set_log_message( 'log.connector.token_not_return' ), - self::CODE_500 - ); - } - if ( '' === $data['token'] ) { - throw new Lengow_Exception( - Lengow_Main::set_log_message( 'log.connector.token_is_empty' ), - self::CODE_500 - ); - } - - return $data['token']; - } - - /** - * Make Curl request. - * - * @param string $type type of request GET|POST|PUT|PATCH - * @param string $api Lengow method API call - * @param array $args Lengow method API parameters - * @param string $token temporary authorization token - * @param string $body body data for request - * @param boolean $log_output see log or not - * - * @return bool|string - * @throws Lengow_Exception - */ - private function make_request( $type, $api, $args, $token, $body, $log_output ) { - - // get default curl options. - $opts = $this->curl_opts; - $curl_error = ''; - $curl_error_number = ''; - - // get special timeout for specific Lengow API. - if ( array_key_exists( $api, $this->lengow_urls ) ) { - $opts['timeout'] = $this->lengow_urls[ $api ]; - } - // get base url for a specific environment. - $url = Lengow_Configuration::get_lengow_api_url() . $api; - - $opts['customrequest'] = strtoupper( $type ); - - $url = parse_url( $url ); - if ( isset( $url['port'] ) ) { - $opts['port'] = $url['port']; - } - $opts['header'] = false; - $opts['verbose'] = false; - $opts['headers'] = array(); - if ( ! empty( $token ) ) { - $opts['headers']['Authorization'] = $token; - } - - // get call url with the mandatory parameters. - $opts['url'] = $url['scheme'] . '://' . $url['host'] . $url['path']; - if ( ! empty( $args ) && ( $type === self::GET || ! in_array( $api, $this->api_without_url_args, true ) ) ) { - $opts['url'] .= '?' . http_build_query( $args ); - } - if ( $type !== self::GET ) { - if ( ! empty( $body ) ) { - // sending data in json format for new APIs. - $opts['headers']['Content-Type'] = 'application/json'; - $opts['headers']['Content-Length'] = strlen( $body ); - $opts['body'] = $body; - } else { - // sending data in string format for legacy APIs. - $opts['post'] = count( $args ); - $opts['body'] = http_build_query( $args ); - } - } - Lengow_Main::log( - Lengow_Log::CODE_CONNECTOR, - Lengow_Main::set_log_message( - 'log.connector.call_api', - array( - 'call_type' => $type, - 'curl_url' => $opts['url'], - ) - ), - $log_output - ); - - if ( $type === self::GET ) { - $result = wp_remote_get( $opts['url'], $opts ); - } else { - $result = wp_remote_post( $opts['url'], $opts ); - } - - $http_code = wp_remote_retrieve_response_code( $result ); - $http_body = wp_remote_retrieve_body( $result ); - if ( $result instanceof WP_Error ) { - $curl_error = $result->get_error_message(); - $curl_error_number = $result->get_error_code(); - } - - $this->check_return_request( - $result, - (int) $http_code, - (string) $curl_error, - (string) $curl_error_number - ); - - return $http_body; - } - - /** - * Check return request and generate exception if needed. - * - * @param string|WP_Error $result Curl return call - * @param integer $http_code request http code - * @param string $curl_error Curl error - * @param string $curl_error_number Curl error number - * - * @throws Lengow_Exception - */ - private function check_return_request( $result, $http_code, $curl_error, $curl_error_number ) { - if ( false === $result ) { - // recovery of Curl errors. - if ( in_array( $curl_error_number, array( CURLE_OPERATION_TIMEDOUT ), true ) ) { - throw new Lengow_Exception( - Lengow_Main::set_log_message( 'log.connector.timeout_api' ), - self::CODE_504 - ); - } - $error = Lengow_Main::set_log_message( - 'log.connector.error_curl', - array( - 'error_code' => $curl_error_number, - 'error_message' => $curl_error, - ) - ); - throw new Lengow_Exception( $error, self::CODE_500 ); - } - - if ( ! in_array( $http_code, $this->success_codes ) ) { - - $result = $this->format( wp_remote_retrieve_body( $result ) ); - // recovery of Lengow Api errors. - - if ( $result instanceof WP_Error ) { - throw new Lengow_Exception( - (string) $result->get_error_message(), - (int) $http_code - ); - } - - throw new Lengow_Exception( - (string) Lengow_Main::set_log_message( 'log.connector.api_not_available' ), - (int) $http_code - ); - } - } - - /** - * Get data in specific format. - * - * @param mixed $data Curl response data - * @param string $format return format of API - * - * @return mixed - */ - private function format( $data, $format = self::FORMAT_JSON ) { - switch ( $format ) { - case self::FORMAT_STREAM: - return $data; - default: - case self::FORMAT_JSON: - return json_decode( $data, true ); - } - } -} diff --git a/includes/class-lengow-cron-export.php b/includes/class-lengow-cron-export.php index d7edc7c7..25112198 100644 --- a/includes/class-lengow-cron-export.php +++ b/includes/class-lengow-cron-export.php @@ -47,7 +47,6 @@ require_once 'class-lengow-address.php'; require_once 'class-lengow-catalog.php'; require_once 'class-lengow-configuration.php'; -require_once 'class-lengow-connector.php'; require_once 'class-lengow-crud.php'; require_once 'class-lengow-exception.php'; require_once 'class-lengow-export.php'; diff --git a/includes/class-lengow-cron-toolbox.php b/includes/class-lengow-cron-toolbox.php index 0952e2b1..b1df56a9 100644 --- a/includes/class-lengow-cron-toolbox.php +++ b/includes/class-lengow-cron-toolbox.php @@ -43,7 +43,6 @@ require_once 'class-lengow-address.php'; require_once 'class-lengow-catalog.php'; require_once 'class-lengow-configuration.php'; -require_once 'class-lengow-connector.php'; require_once 'class-lengow-crud.php'; require_once 'class-lengow-exception.php'; require_once 'class-lengow-export.php'; diff --git a/includes/class-lengow-cron.php b/includes/class-lengow-cron.php index 924e1373..60712acd 100644 --- a/includes/class-lengow-cron.php +++ b/includes/class-lengow-cron.php @@ -47,7 +47,6 @@ require_once 'class-lengow-address.php'; require_once 'class-lengow-catalog.php'; require_once 'class-lengow-configuration.php'; -require_once 'class-lengow-connector.php'; require_once 'class-lengow-crud.php'; require_once 'class-lengow-exception.php'; require_once 'class-lengow-export.php'; diff --git a/includes/class-lengow-factory.php b/includes/class-lengow-factory.php index b4e1a19f..67fb9ca1 100644 --- a/includes/class-lengow-factory.php +++ b/includes/class-lengow-factory.php @@ -71,7 +71,7 @@ public function bind( string $name, $concrete ): self { */ public function make( string $name ) { if ( isset( $this->dependencies[ $name ] ) ) { - return $this->resolve( $this->dependencies[ $name ] ); + return $this->instances[ $name ] = $this->resolve( $this->dependencies[ $name ] ); } throw new Exception( "Dependency {$name} not found." ); diff --git a/includes/class-lengow-import-order.php b/includes/class-lengow-import-order.php index 39a4cd43..da7282fc 100755 --- a/includes/class-lengow-import-order.php +++ b/includes/class-lengow-import-order.php @@ -1197,14 +1197,14 @@ private function create_woocommerce_order( $user, $products, $billing_address, $ $shipping = array(); foreach ( $shipping_data as $key => $field ) { - $shippingKey = str_replace( 'shipping_', '', $key ); - $shipping[ $shippingKey ] = $field; + $shippingKey = str_replace( 'shipping_', '', $key ); + $shipping[ $shippingKey ] = $field; } - $wc_order->set_address( $billing, 'billing' ); - $wc_order->set_address( $shipping, 'shipping' ); + $wc_order->set_address( $billing, 'billing' ); + $wc_order->set_address( $shipping, 'shipping' ); - $wc_order->set_customer_id( absint( $user->ID ) ); - $wc_order->save(); + $wc_order->set_customer_id( absint( $user->ID ) ); + $wc_order->save(); // load WooCommerce customer. $customer = new WC_Customer( $user->ID ); diff --git a/includes/class-lengow-import.php b/includes/class-lengow-import.php index c4c8ea68..78ea4bc5 100755 --- a/includes/class-lengow-import.php +++ b/includes/class-lengow-import.php @@ -514,11 +514,9 @@ private function setup_synchronization() { * * @return boolean */ - private function check_credentials() { - if ( Lengow_Connector::is_valid_auth( $this->log_output ) ) { - list( $this->account_id, $access_token, $secret_token ) = Lengow_Configuration::get_access_id(); - $this->connector = new Lengow_Connector( $access_token, $secret_token ); - + private function check_credentials(): bool { + list( $account_id, $access_token, $secret_token ) = Lengow_Configuration::get_access_id(); + if ( $account_id > 0 && ! empty( $access_token ) && ! empty( $secret_token ) ) { return true; } @@ -701,19 +699,12 @@ private function get_orders_from_api() { do { try { if ( $this->import_one_order ) { - $results = $this->connector->get( - Lengow_Connector::API_ORDER, - array( - self::ARG_MARKETPLACE_ORDER_ID => $this->marketplace_sku, - self::ARG_MARKETPLACE => $this->marketplace_name, - self::ARG_ACCOUNT_ID => $this->account_id, - self::ARG_PAGE => $page, - self::ARG_NO_CURRENCY_CONVERSION => $currency_conversion, - ), - Lengow_Connector::FORMAT_STREAM, - '', - $this->log_output - ); + $results = Lengow::sdk()->order()->list( array( + self::ARG_MARKETPLACE_ORDER_ID => $this->marketplace_sku, + self::ARG_MARKETPLACE => $this->marketplace_name, + self::ARG_PAGE => $page, + self::ARG_NO_CURRENCY_CONVERSION => $currency_conversion, + ) ); } else { if ( $this->created_from && $this->created_to ) { $time_params = array( @@ -738,21 +729,14 @@ private function get_orders_from_api() { ), ); } - $results = $this->connector->get( - Lengow_Connector::API_ORDER, - array_merge( - $time_params, - array( - self::ARG_CATALOG_IDS => implode( ',', $this->shop_catalog_ids ), - self::ARG_ACCOUNT_ID => $this->account_id, - self::ARG_PAGE => $page, - self::ARG_NO_CURRENCY_CONVERSION => $currency_conversion, - ) - ), - Lengow_Connector::FORMAT_STREAM, - '', - $this->log_output - ); + $results = Lengow::sdk()->order()->list( array_merge( + $time_params, + array( + self::ARG_CATALOG_IDS => implode( ',', $this->shop_catalog_ids ), + self::ARG_PAGE => $page, + self::ARG_NO_CURRENCY_CONVERSION => $currency_conversion, + ) + ) ); } } catch ( Exception $e ) { throw new Lengow_Exception( @@ -765,21 +749,12 @@ private function get_orders_from_api() { Lengow_Translation::DEFAULT_ISO_CODE ), ) - ) - ); - } - if ( null === $results ) { - throw new Lengow_Exception( - Lengow_Main::set_log_message( 'lengow_log.exception.no_connection_webservice' ) - ); - } - // don't decode into array as we use the result as an object. - $results = json_decode( $results ); - if ( ! is_object( $results ) ) { - throw new Lengow_Exception( - Lengow_Main::set_log_message( 'lengow_log.exception.no_connection_webservice' ) + ), + 0, + $e ); } + // construct array orders. foreach ( $results->results as $order ) { $orders[] = $order; diff --git a/includes/class-lengow-order.php b/includes/class-lengow-order.php index 8537d7ae..727ac124 100755 --- a/includes/class-lengow-order.php +++ b/includes/class-lengow-order.php @@ -864,49 +864,29 @@ public static function get_date_imported( $order_id ) { /** * Synchronize order with Lengow API. * - * @param Lengow_Connector|null $connector Lengow connector instance - * @param boolean $log_output see log or not - * * @return boolean */ - public function synchronize_order( $connector = null, $log_output = false ) { - list( $account_id, $access_token, $secret_token ) = Lengow_Configuration::get_access_id(); - if ( null === $connector ) { - if ( Lengow_Connector::is_valid_auth( $log_output ) ) { - $connector = new Lengow_Connector( $access_token, $secret_token ); - } else { - return false; - } - } + public function synchronize_order() { $results = self::get_all_order_id_from_lengow_orders( $this->marketplace_sku, $this->marketplace_name ); - if ( $results ) { + if ( ! empty( $results ) ) { $woocommerce_order_ids = array(); foreach ( $results as $result ) { $woocommerce_order_ids[] = $result->order_id; } // compatibility v2. if ( null !== $this->feed_id && ! Lengow_Marketplace::marketplace_exist( $this->marketplace_name ) ) { - $this->check_and_change_marketplace_name( $connector, $log_output ); + $this->check_and_change_marketplace_name(); } $body = array( - Lengow_Import::ARG_ACCOUNT_ID => $account_id, + Lengow_Import::ARG_ACCOUNT_ID => Lengow_Configuration::get( Lengow_Configuration::ACCOUNT_ID ), Lengow_Import::ARG_MARKETPLACE_ORDER_ID => $this->marketplace_sku, Lengow_Import::ARG_MARKETPLACE => $this->marketplace_name, Lengow_Import::ARG_MERCHANT_ORDER_ID => $woocommerce_order_ids, ); - $tries = self::SYNCHRONIZE_TRIES; + $tries = self::SYNCHRONIZE_TRIES; // why is this needed ? do { try { - $return = $connector->patch( - Lengow_Connector::API_ORDER_MOI, - array(), - Lengow_Connector::FORMAT_JSON, - json_encode( $body ), - $log_output - ); - return ! ( null === $return - || ( isset( $return['detail'] ) && 'Pas trouvé.' === $return['detail'] ) - || isset( $return['error'] ) ); + Lengow::sdk()->order()->moi( $body ); } catch ( Exception $e ) { --$tries; if ( $tries === 0 ) { @@ -918,7 +898,7 @@ public function synchronize_order( $connector = null, $log_output = false ) { 'error_message' => $message, ) ); - Lengow_Main::log( Lengow_Log::CODE_CONNECTOR, $error, $log_output ); + Lengow_Main::log( Lengow_Log::CODE_CONNECTOR, $error ); } } } while ( $tries > 0 ); @@ -931,32 +911,16 @@ public function synchronize_order( $connector = null, $log_output = false ) { /** * Check and change the name of the marketplace for v3 compatibility. * - * @param Lengow_Connector|null $connector Lengow connector instance - * @param boolean $log_output see log or not - * * @return boolean */ - public function check_and_change_marketplace_name( $connector = null, $log_output = false ) { - list( $account_id, $access_token, $secret_token ) = Lengow_Configuration::get_access_id(); - if ( null === $connector ) { - if ( Lengow_Connector::is_valid_auth( $log_output ) ) { - $connector = new Lengow_Connector( $access_token, $secret_token ); - } else { - return false; - } - } + public function check_and_change_marketplace_name(): bool { try { - $return = $connector->get( - Lengow_Connector::API_ORDER, + $results = Lengow::sdk()->order()->list( array( - Lengow_Import::ARG_MARKETPLACE_ORDER_ID => $this->marketplace_sku, - Lengow_Import::ARG_ACCOUNT_ID => $account_id, - ), - Lengow_Connector::FORMAT_STREAM, - '', - $log_output + Lengow_Import::ARG_MARKETPLACE_ORDER_ID => $this->marketplace_sku + ) ); - } catch ( Exception $e ) { + } catch ( HttpException|Exception $e ) { $message = Lengow_Main::decode_log_message( $e->getMessage(), Lengow_Translation::DEFAULT_ISO_CODE ); $error = Lengow_Main::set_log_message( 'log.connector.error_api', @@ -965,20 +929,13 @@ public function check_and_change_marketplace_name( $connector = null, $log_outpu 'error_message' => $message, ) ); - Lengow_Main::log( Lengow_Log::CODE_CONNECTOR, $error, $log_output ); + Lengow_Main::log( 'sdk', $error ); return false; } - if ( null === $return ) { - return false; - } - // don't decode into array as we use the result as an object. - $results = json_decode( $return ); - if ( isset( $results->error ) ) { - return false; - } + foreach ( $results->results as $order ) { - $new_marketplace_name = (string) $order->marketplace; + $new_marketplace_name = $order->marketplace; if ( $new_marketplace_name !== $this->marketplace_name ) { self::update( $this->id, array( self::FIELD_MARKETPLACE_NAME => $new_marketplace_name ) ); $this->marketplace_name = $new_marketplace_name; diff --git a/includes/class-lengow-sync.php b/includes/class-lengow-sync.php index d458650d..d70713a0 100755 --- a/includes/class-lengow-sync.php +++ b/includes/class-lengow-sync.php @@ -144,18 +144,18 @@ public static function get_sync_data() { * * @return boolean */ - public static function sync_catalog( $force = false) { + public static function sync_catalog( bool $force = false): bool { $success = false; $setting_updated = false; if ( Lengow_Configuration::is_new_merchant() ) { - return $success; + return false; } if ( ! $force ) { $updated_at = Lengow_Configuration::get( Lengow_Configuration::LAST_UPDATE_CATALOG ); if ( null !== $updated_at && ( time() - (int) $updated_at ) < self::$cache_times[ self::SYNC_CATALOG ] ) { - return $success; + return false; } } try { diff --git a/includes/class-lengow-toolbox.php b/includes/class-lengow-toolbox.php index 7ce36b29..53e3496c 100644 --- a/includes/class-lengow-toolbox.php +++ b/includes/class-lengow-toolbox.php @@ -261,7 +261,7 @@ public static function sync_orders( $params = array() ) { $result = $import->exec(); // if global error return error message and request http code. if ( isset( $result[ Lengow_Import::ERRORS ][0] ) ) { - return self::generate_error_return( Lengow_Connector::CODE_403, $result[ Lengow_Import::ERRORS ][0] ); + return self::generate_error_return( 403, $result[ Lengow_Import::ERRORS ][0] ); } unset( $result[ Lengow_Import::ERRORS ] ); @@ -288,7 +288,7 @@ public static function get_order_data( // if no reference is found, process is blocked. if ( empty( $lengow_orders ) ) { return self::generate_error_return( - Lengow_Connector::CODE_404, + 404, Lengow_Main::set_log_message( 'log.import.unable_find_order' ) ); } diff --git a/lengow.php b/lengow.php index 2cb80508..1154e99f 100755 --- a/lengow.php +++ b/lengow.php @@ -132,7 +132,6 @@ public function includes() { include_once 'includes/class-lengow-address.php'; include_once 'includes/class-lengow-catalog.php'; include_once 'includes/class-lengow-configuration.php'; - include_once 'includes/class-lengow-connector.php'; include_once 'includes/class-lengow-crud.php'; include_once 'includes/class-lengow-exception.php'; include_once 'includes/class-lengow-export.php'; @@ -208,11 +207,6 @@ public function init_lengow_factory() return new Lengow\Sdk\Sdk( $client ); }); - $factory->bind(Lengow_Connector::class, function () use ( $factory ) { - // TODO replace with the SDK - list( $account_id, $access_token, $secret ) = $factory->get(Lengow_Configuration::class)::get_access_id(); - return new Lengow_Connector( $access_token, $secret ); - }); } /** From 4f2f88f2557b922c29fd23877f16de6c4a63f566 Mon Sep 17 00:00:00 2001 From: Arnaud Hours Date: Tue, 23 Jul 2024 17:29:16 +0200 Subject: [PATCH 07/16] update API plans to restrictions --- includes/class-lengow-sync.php | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/includes/class-lengow-sync.php b/includes/class-lengow-sync.php index 0441a59d..2b753ded 100755 --- a/includes/class-lengow-sync.php +++ b/includes/class-lengow-sync.php @@ -265,18 +265,18 @@ public static function get_status_account( bool $force = false ) { } } try { - $plan = Lengow::sdk()->plan()->plans(); + $restrictions = Lengow::sdk()->restriction()->restrictions(); } catch ( HttpException|Exception $e ) { Lengow_Main::get_log_instance()->log_exception($e); return false; } - if ( isset( $plan->isFreeTrial ) ) { + if ( isset( $restrictions->isFreeTrial ) ) { $status = array( - 'type' => $plan->isFreeTrial ? 'free_trial' : '', - 'day' => $plan->leftDaysBeforeExpired < 0 ? 0 : $plan->leftDaysBeforeExpired, - 'expired' => $plan->isExpired, - 'legacy' => 'v2' === $plan->accountVersion, + 'type' => $restrictions->isFreeTrial ? 'free_trial' : '', + 'day' => $restrictions->leftDaysBeforeExpired < 0 ? 0 : $restrictions->leftDaysBeforeExpired, + 'expired' => $restrictions->isExpired, + 'legacy' => 'v2' === $restrictions->accountVersion, ); Lengow_Configuration::update_value( Lengow_Configuration::ACCOUNT_STATUS_DATA, wp_json_encode( $status ) ); Lengow_Configuration::update_value( Lengow_Configuration::LAST_UPDATE_ACCOUNT_STATUS_DATA, time() ); From e098ae62c45f9fa504c1497ae25e4821dc894276 Mon Sep 17 00:00:00 2001 From: Arnaud Hours Date: Fri, 2 Aug 2024 11:55:35 +0200 Subject: [PATCH 08/16] update api-php-sdk, phpunit tests --- composer.json | 17 ++++- .../admin/class-lengow-admin-connection.php | 8 +-- .../admin/class-lengow-admin-dashboard.php | 3 +- .../views/dashboard/html-admin-dashboard.php | 2 +- includes/admin/views/html-admin-header.php | 2 +- includes/class-lengow-action.php | 12 ++-- includes/class-lengow-catalog.php | 12 ++-- includes/class-lengow-factory.php | 16 +++-- includes/class-lengow-import.php | 4 +- includes/class-lengow-order.php | 8 +-- includes/class-lengow-sync.php | 20 +++--- includes/class-sdk-listener.php | 10 +-- lengow.php | 21 ++++-- tests/MockClientTrait.php | 66 +++++++++++++++++++ tests/TestConnector.php | 36 ---------- tests/TestLengowFactory.php | 18 ++++- tests/TestSdkListener.php | 61 +++++++++++++++++ tests/bootstrap.php | 5 ++ 18 files changed, 230 insertions(+), 91 deletions(-) create mode 100644 tests/MockClientTrait.php delete mode 100644 tests/TestConnector.php create mode 100644 tests/TestSdkListener.php diff --git a/composer.json b/composer.json index c9bee6b6..64d6acf0 100644 --- a/composer.json +++ b/composer.json @@ -8,11 +8,11 @@ "repositories": [ { "type": "path", - "url": "~/vhosts/lengow-sdk" + "url": "~/vhosts/api-php-sdk" } ], "require": { - "lengow/php-sdk": "dev-main", + "lengow/api-php-sdk": "dev-main", "symfony/http-client": "^5.4", "nyholm/psr7": "^1.8", "composer/installers": "*", @@ -20,7 +20,18 @@ }, "config": { "allow-plugins": { - "php-http/discovery": true + "php-http/discovery": true, + "composer/installers": true } + }, + "require-dev": { + "phpunit/phpunit": "^9.6", + "guzzlehttp/guzzle": "^7.8", + "php-http/mock-client": "^1.6" + }, + "autoload-dev": { + "classmap": [ + "tests/MockClientTrait.php" + ] } } diff --git a/includes/admin/class-lengow-admin-connection.php b/includes/admin/class-lengow-admin-connection.php index 56377ec4..5747f6a9 100644 --- a/includes/admin/class-lengow-admin-connection.php +++ b/includes/admin/class-lengow-admin-connection.php @@ -124,8 +124,8 @@ private static function check_api_credentials( string $access_token, string $sec Lengow_Main::log( 'Connector', 'Unable to save access IDs' ); return false; - } catch ( HttpException|Exception $e ) { - Lengow_Main::get_log_instance()->log_exception( $e ); + } catch ( HttpException $e ) { + Lengow::logger()->log_exception( $e ); } return false; @@ -143,8 +143,8 @@ private static function connect_cms() { $sync_data = Lengow_Sync::get_sync_data(); try { $result = Lengow::sdk()->cms()->post( $sync_data ); - } catch ( Exception $e ) { - Lengow_Main::get_log_instance()->log_exception( $e ); + } catch ( HttpException $e ) { + Lengow::logger()->log_exception( $e ); } if ( isset( $result->common_account ) ) { diff --git a/includes/admin/class-lengow-admin-dashboard.php b/includes/admin/class-lengow-admin-dashboard.php index 1a3a49a7..3c955050 100755 --- a/includes/admin/class-lengow-admin-dashboard.php +++ b/includes/admin/class-lengow-admin-dashboard.php @@ -36,7 +36,8 @@ class Lengow_Admin_Dashboard { public static function display() { $locale = new Lengow_Translation(); $merchant_status = Lengow_Sync::get_status_account(); - if ( 'free_trial' === $merchant_status['type'] && $merchant_status['expired'] ) { + // @TODO if $merchant_status is false ? + if ( false !== $merchant_status && 'free_trial' === $merchant_status['type'] && $merchant_status['expired'] ) { $refresh_status = admin_url( 'admin.php?action=dashboard_get_process&do_action=refresh_status' ); include_once 'views/dashboard/html-admin-status.php'; } else { diff --git a/includes/admin/views/dashboard/html-admin-dashboard.php b/includes/admin/views/dashboard/html-admin-dashboard.php index 2516842a..6eddc8db 100755 --- a/includes/admin/views/dashboard/html-admin-dashboard.php +++ b/includes/admin/views/dashboard/html-admin-dashboard.php @@ -22,7 +22,7 @@
- + t( 'menu.counter', array( 'counter' => $merchant_status['day'] ) ) ); ?> t( 'menu.upgrade_account' ) ); ?> diff --git a/includes/admin/views/html-admin-header.php b/includes/admin/views/html-admin-header.php index 5d4420d7..2633c958 100755 --- a/includes/admin/views/html-admin-header.php +++ b/includes/admin/views/html-admin-header.php @@ -53,7 +53,7 @@ class="lengow_link_tooltip" t( 'menu.jump_to_lengow' ) ); ?> - +