Git Product home page Git Product logo

commercetools-sdk-php-v2's Introduction

Commercetools

Client and Request Builder for making API requests against Commercetools.

Installation

composer require commercetools/commercetools-sdk

Usage

namespace Commercetools;

use Commercetools\Api\Client\ClientCredentialsConfig;
use Commercetools\Api\Client\Config;
use Commercetools\Client\ClientCredentials;
use Commercetools\Client\ClientFactory;

require_once __DIR__ . '/vendor/autoload.php';

/** @var string $clientId */
/** @var string $clientSecret */
$authConfig = new ClientCredentialsConfig(new ClientCredentials($clientId, $clientSecret));

$client = ClientFactory::of()->createGuzzleClient(
    new Config(),
    $authConfig
);

RequestBuilder

Detailed information of all available methods for the product API can be found here. Information for the Import API can be found here.

Examples to retrieve project information

use Commercetools\Api\Client\ApiRequestBuilder;
use GuzzleHttp\ClientInterface;

/** @var ClientInterface $client */
$builder =  new ApiRequestBuilder($client);
$request = $builder->withProjectKey('your-project-key')->get();

To avoid specifying the project key for every request built it's possible to use the ones in the Commercetools\Client namespace instead

use Commercetools\Client\ApiRequestBuilder;
use Commercetools\Client\ImportRequestBuilder;
use GuzzleHttp\ClientInterface;

/** @var ClientInterface $client */
$builder =  new ApiRequestBuilder('your-project-key', $client);
$request = $builder->categories()->get();

$importBuilder =  new ImportRequestBuilder('your-project-key', $client);
$request = $importBuilder->importSinks()->get();

Executing requests

use Commercetools\Client\ApiRequestBuilder;
use GuzzleHttp\ClientInterface;

/** @var ClientInterface $client */
$builder =  new ApiRequestBuilder('your-project-key', $client);
$request = $builder->with()->get();

// executing the request and mapping the response directly to a domain model
$project = $request->execute();

// send the request to get the response object 
$response = $request->send();
// map the response to a domain model
$project = $request->mapFromResponse($response);

// send the request asynchronously 
$promise = $request->sendAsync();
// map the response to a domain model
$project = $request->mapFromResponse($promise->wait());

// send the request using a client instance
$response = $client->send($request);
$project = $request->mapFromResponse($response);

Migration Guidelines

To migrate from the 1.x to the 2.x, there is a guideline below:

Observability

To monitor and observe the SDK, see the official documentation Observability, there is a Demo application which shows how to monitor the PHP SDK with New Relic.

Documentation

License

MIT

commercetools-sdk-php-v2's People

Contributors

ajimae avatar barbara79 avatar ct-sdks[bot] avatar evansinho avatar github-actions[bot] avatar industrian avatar jenschude avatar jherey avatar kodiakhq[bot] avatar rohitrajpimcore avatar salander85 avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

commercetools-sdk-php-v2's Issues

setCustom is missing in CustomerAddressBuilder inside importer

I am working on migrating customer data from our current shop to commercetool. I am using importer to migrate the data, but I am not able to use it to migrate customer custom address fields using importer directly without using the API.

Using importer to migrate these fileds will save sending requests using API for each customer to migrate only custom address

Add a method to retrieve the last element from a collection

Is your feature request related to a problem? Please describe.
We would like to have this primarily for handling multiple payments on a cart/order.

If a cart has multiple payments, most likely the last one in the collection is the most recent one (and usually the most relevant). Probably for this reason the merchant center will display the payments on an order in a reversed list as opposed to what I retrieve using the API playground.

It would be nice to have something similar to the native end() function for array for collections to retrieve the last element for a better DX-experience.

Describe the solution you'd like
Add an end() function to the CSequence interface, which returns the last TObject from the collection or null if it's empty.

Describe alternatives you've considered
There are alternatives, e.g. casting to array and using the native end(), looping over the iterator and only keeping the last element, ... This is really just for convenience, whenever it makes sense to deal with a collection in a way described in the problem above.

Laravel 9 compatibility

Is your feature request related to a problem? Please describe.

Cannot update to an installable set of dependencies when upgrading to Laravel 9 and any version of the SDK.

The SDK depends on cache/filesystem-adapter which in turn depends on league/flysystem v1. Laravel depends on league/flysystem v3 (Upgrade Guide for reference).

Describe the solution you'd like

Bringing one's own cache should not interfere with other optional dependencies that might not be used.

league/flysystem is a very popular, low-level package - chances of running into conflicts are high.

As a PSR 6 compliant cache instance may be passed into the SDK (which we do - we inject Laravel's cache) I'd suggest making the installation of cache/filesystem-adapter optional.
The reasoning being that the use of an internal fallback is optional by default thus the dependency itself should be optional as well.

  • Make cache/filesystem-adapter "just" a suggested package in a new major version
  • Check for its existence before instantiation
  • Throw an exception when no cache was given nor an expected adapter installed
  • Additionally point out that requirement in the installation docs/readme.

๐Ÿ’ก Mostly future proof but will require additional dependencies after installation (or injecting another cache instance as is supported now already). Very much the desirable outcome in my opinion (unless there's a much simpler yet robust solution to this, obviously).

Describe alternatives you've considered

Wait for cache/filesystem-adapter PR to be merged (which will add league/flysystem v3 support), then update the SDK's dependency on cache/filesystem-adapter accordingly.

๐Ÿ’ก Not as future proof, might break again, but will work out of the box without any additional dependencies after installation (or providing another cache instance, again). The easy way out, no estimated time of arrival.

Additional Information

php-cache/cache:

Back in 2016, this was the first library supporting PSR-6. We created Symfony bundles and made many great libraries in the PHP-cache organization. This was a few years ago and the library is not activly maintained. Starting a new project one should consider using the more performant and activly supported Symfony Cache.

Steps to reproduce

composer create-project laravel/laravel laravel-commercetools
cd laravel-commercetools
composer require commercetools/commercetools-sdk  -W
Your requirements could not be resolved to an installable set of packages.

  Problem 1
    - cache/filesystem-adapter[1.1.0, ..., 1.2.0] require league/flysystem ^1.0 -> found league/flysystem[1.0.0-alpha1, ..., 1.x-dev] but these were not loaded, likely because it conflicts with another require.
    - commercetools/commercetools-sdk 4.4.0 requires cache/filesystem-adapter ^1.1.0 -> satisfiable by cache/filesystem-adapter[1.1.0, 1.1.x-dev, 1.2.0].
    - Root composer.json requires commercetools/commercetools-sdk ^4.4 -> satisfiable by commercetools/commercetools-sdk[4.4.0].

Support current versions of psr/log

Hey. This project depends on psr/log:^1.0. In our Symfony based project we're currently using psr/log:^2.0 and consequently we get version conflicts when trying to install this package with Composer.

We could downgrade to psr/log:^1.0 but this is not our preferred option. Would it be possible to change the version requirements of this library to the following like it already has been done for psr/cache etc?

"psr/log": "^1.0 || ^2.0 || ^3.0",

The different versions only aim at different PHP versions so this should not be an issue.

Thank you!

Not able to set empty values for category description

Describe the bug
ร'm trying to overwrite the localized description field of a category, using empty values but this is not working.

To Reproduce

  • create a category;
  • set the category description for a particular locale (e.g. en-GB);
  • try to overwrite the category description with an empty value using the SDK.

Expected behavior
The operation should overwrite correctly the description.

Screenshots/Code snippet

$version = 12;
$categoryCode = 'my-category';
$actionsCollection = CategoryUpdateActionCollection::of();
$action = CategorySetDescriptionActionBuilder::of()
            ->withDescription(LocalizedStringBuilder::fromArray([])->build())
            ->build();
$actionsCollection->add($action);
$categoryUpdate = CategoryUpdateBuilder::of()
            ->withVersion($version)
            ->withActions($actionsCollection)
            ->build();

// Correctly configure the $api object...
$api->categories()
            ->withKey($categoryCode)
            ->post($categoryUpdate)
            ->withExpand(['parent'])
            ->execute();

This code will generate the given request body:

{
	"version": 12,
	"actions": [
		{
			"action": "setDescription",
			"description": []
		}
	]
}

The response that it will get is:

{
	"statusCode": 400,
	"message": "Request body does not contain valid JSON.",
	"errors": [
		{
			"code": "InvalidJsonInput",
			"message": "Request body does not contain valid JSON.",
			"detailedErrorMessage": "actions -> description: JSON object expected."
		}
	]
}

If I change the request body to:

{
	"version": 12,
	"actions": [
		{
			"action": "setDescription",
			"description": {}
		}
	]
}

the response will be ok.

Stack information (please complete the following information):

  • PHP: 8.1
  • SDK: 6.0.1

Additional context
Note that I've found the same issue for other fields as well: meta description and meta title (they are both localizable).

PHP SDK ME Endpoint support

Implement the functionalities of the me endpoint in the PHP SDK

Acceptance Criteria

  • Study how its done in .NET SDK.
  • Implement ME endpoint in PHP SDK v2.
  • Implement demo by reusing as much as possible from the .NET demo app.
  • keep the demo app consistent in UX

Scope of implementation

  • ME endpoints can be used server-side
  • Re-authentication using refresh tokens
  • Anonymous checkout possible
  • Switching from anonymous to password flow
  • Simplify overall authentication process

PHP SDK V2 - Generated Documentation Content

Auto generate documentation around PHP SDK V2 to improve UX and reduce support questions with the help of Doxygen framework.

Accptance Criteria

Reference:

introduce builder inheritance

The Model Builders are atm independent. For discriminating classes it would be helpful to have a inheritance structure.

  • Introduce the builder pattern for PHP.

Add Integration test - category model

Adding Integration tests in Autogenerated PHP SDK:

  • Category model

Acceptance Criteria:

  • Test the query Request is completed
  • Test update request is completed
  • Test create/delete request is completed
  • Try to come up with estimation idea for upcoming integration tests. => average 1 week and half for each Model

Missing helper methods

I currently have the task of migrating from the old commercetools-php-sdk to the new commercetools-sdk-php-v2 in a project.
I'm not sure if some methods have been deliberately removed or are simply missing in the new SDK.

As example for ProductProjection in the old SDK there was a method called getVariantBySku($sku) to easily retrieve a ProductVariant by sku ( https://github.com/commercetools/commercetools-php-sdk/blob/f111ca0cbfc16370c1916f45863eb5bd72eb0c76/src/Core/Model/Product/ProductProjection.php#L122 ).

In the new SDK such method is missing and even a workaround to implement such method by using getVariants method is tricky because ProductProjectionCollection does not have such method like getBy like the old SDK had but instead a method valueByKey inherited from MapperSequence which is final protected (

final protected function valueByKey(string $field, string $key)
) and not public.

TypeError caused by mapper() in MapperSequence

Describe the bug
Calling current() on an empty collection object causes a TypeError similar to this one:

TypeError: Commercetools\Api\Models\Common\BaseResourceCollection::Commercetools\Api\Models\Common\{closure}(): Argument #1 ($index) must be of type int, null given

This is caused when implementing the abstract function Commercetools\Base\MapperSequence::mapper with a non-nullable type. I have not checked all implementations, but so far it seems like pretty much all of them are affected.

To Reproduce
See failing test in #42

Expected behavior
Calling current() on an empty list should return null and not throw any type error.

Stack information (please complete the following information):

  • PHP: 8.0.8
  • SDK: 2.3.0

unable get type of message

Describe the bug
When I read the messages from the messages endpoint, I get a list of messages but cant differentiate them, because getType always returns null although the MessageModel has the correct value in self::FIELD_TYPE.

To Reproduce

$messages = $this->apiRoot
    ->messages()
    ->get()
    ->execute();

/** @var MessageModel $message */
foreach ($messages->getResults() as $message) {
    dump($message->getType());
}

Expected behavior
I expect that getType returns the type of the message.

Screenshots/Code snippet
see steps to reproduce

Stack information (please complete the following information):

  • PHP: [8.1]
  • SDK: [v6.0.1]

Additional context
none

WithExpand not working

Describe the bug
If i get a order and want it to expand, no error is showing and no expansion is coming uo

To Reproduce
$commercetoolsOrder = $this->apiRoot
->orders()
->get()
->withExpand('PaymentInfo')
->execute();

Expected behavior
FROM normal tax it should be expand within tax to obj. My example in Screenshot ist with PaymentInfo. But you can do it with Customers too
{
"id": "",
"version": 4,
"productType": {
"typeId": "product-type",
"id": ""
},
...
"taxCategory": {
"typeId": "tax-category",
"id": ""
},
...
}
{
"id": "",
"version": 4,
"productType": {
"typeId": "product-type",
"id": ""
"obj": {
"id": "",
"version": 4,
"name": "Example Product Type",
"description": "example Product Type to showcase Reference Expansion",
"classifier": "Complex",
"attributes": [
....
],
},
...
"taxCategory": {
"typeId": "tax-category",
"id": ""
"obj": {
"id": "",
"version": 2,
"name": "Standard tax category",
"rates": [
{
"name": "5% US",
"amount": 0.05,
"includedInPrice": false,
"country": "US",
"id": "zJJ5KIGH"
},
{
"name": "19% MwSt",
"amount": 0.19,
"includedInPrice": true,
"country": "DE",
"id": "893f_nXJ"
}
],
...
}
Screenshots/Code snippet
image

Stack information (please complete the following information):

  • PHP: 7.4
  • commercetools/php-sdk : 2.16

Additional context
Add any other context about the problem here.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.