CustomersApiV2Controller

Extends \HttpApiV2Controller

Class CustomersApiV2Controller

Contains common functionality for all the GX2 APIv2 controllers. You can use the $api instance in the child-controllers in order to gain access to request and response information. The $uri variable is an array that contains the requested resource path.

You can use a protected "__initialize" method in your child controllers for performing common operations without overriding the parent constructor method.

This class contains some private methods that define the core operations of each controller and should not be called from a child-controller (like validation, authorization, rate limiting). The only way to disable the execution of these methods is to override the controller.

category

System

package

ApiV2Controllers

Methods

AbstractApiV2Controller Constructor

__construct(\Slim\Slim $api, array $uri) 
inherited

Call this constructor from every child controller class in order to set the Slim instance and the request routes arguments to the class.

deprecated

The "__initialize" method will is deprecated and will be removed in a future version. Please use the new "init" for bootstrapping your child API controllers.

Throws
\HttpApiV2Exception

Through _validateRequest

Arguments

$api

\Slim\Slim

Slim framework instance, used for request/response manipulation.

$uri

array

This array contains all the segments of the current request, starting from the resource.

History handler for modified, changed and deleted query parameters.

_changeHistory() 
Throws
\HttpApiV2Exception

Creates a single customer and returns the reponse for this post request.

_createCustomer(string $customerJsonString) : array
Throws
\HttpApiV2Exception

If customer is already registered.

Arguments

$customerJsonString

string

Request body as json string

Response

array

Response

_createGuest

_createGuest( $customerJsonObject,  $addressBlock,  $addonValuesArray) : \Customer

Arguments

$customerJsonObject

$addressBlock

$addonValuesArray

Response

\Customer

Creates multiple customers and returns the reponse for this post request.

_createMultipleCustomers(string $customerJsonString) : array

Arguments

$customerJsonString

string

Request body as json string

Response

array

Response

_createNewAddressBlock

_createNewAddressBlock( $customerJsonObject,  $country,  $zone) : boolean

Arguments

$customerJsonObject

$country

$zone

Response

boolean

_createRegisteredCustomer

_createRegisteredCustomer( $customerJsonObject,  $addressBlock,  $addonValuesArray) : \Customer

Arguments

$customerJsonObject

$addressBlock

$addonValuesArray

Response

\Customer

Deletes a single customer and returns the response for this delete request.

_deleteCustomer(integer $customerId) : array
Throws
\HttpApiV2Exception

Thrown if customer id is not set or invalid

Arguments

$customerId

integer

ID of the customer, that should be deleted.

Response

array

JSON Response

Deletes multiple customers and returns the response for this delete request.

_deleteMultipleCustomers(array $ids) : array

Arguments

$ids

array

Response

array

Sub-Resource Customer Addresses

_getCustomerAddresses() 

This method will return all the addresses of the required customer, providing a fast way to access relations between customers and addresses.

see \CustomersApiV2Controller::get()
Throws
\HttpApiV2Exception

Get the relative URI for the mapped controller.

_getMappedControllerUri(\IntType $index, array $uri) : \the
inherited

Arguments

$index

\IntType

Contains the URI position relative to the current controller.

$uri

array

Contains the original URI

Response

\the

mapped controller URI

Checks if the response to a bulk request contains any errors.

_hasErrors(array $response) : boolean

Arguments

$response

array

The checked response

Response

boolean

Initialize pager and sorters fields.

_initializePagingAndSortingFields() 
inherited

One of the common functionaries of the APIv2 is the pagination and sorting. The fields initialized by this method are helpers to facilitate the access to sort and pagination information

Checks if the performed delete request was a bulk request.

_isBulkDeleteRequest() : boolean

Response

boolean

Checks if the performed request was a bulk request (only for POST and PUT requests).

_isBulkRequest(string $jsonString) : boolean

Arguments

$jsonString

string

The complete request body as JSON string

Response

boolean

Include links to response resources.

_linkResponse(array &$response) 
inherited

The APIv2 operates with simple resources that might be linked with other resources. This architecture promotes flexibility so that API consumers can have a simpler structure. This method will search for existing external resources and will add a link to the end of each resource.

IMPORTANT: If for some reason you need to include custom links to your resources do not use this method. Include them inside your controller method manually.

NOTICE #1: This method will only search at the first level of the resource. That means that nested ID values will not be taken into concern.

NOTICE #2: You can provide both associative (single response item) or sequential (multiple response items) arrays and this method will adjust the links accordingly.

Arguments

$response

array

Passed by reference, new links will be appended into the end of each resource.

Add location header to a specific response.

_locateResource(string $p_name, integer $p_id) 
inherited

Use this method whenever you want the "Location" header to point to an existing resource so that clients can use it to fetch that resource without having to generate the URL themselves.

Throws
\InvalidArgumentException

If the arguments contain an invalid value.

Arguments

$p_name

string

$p_id

integer

_mapAddressBlock

_mapAddressBlock( $customerJsonObject) : \AddressBlock|boolean

Arguments

$customerJsonObject

Response

\AddressBlock|boolean

Map the sub-resource to another controller.

_mapResponse(array $criteria) : boolean
inherited

Some API resources contain many subresources which makes the creation of a single controller class complicated and hard to maintain. This method will forward the request to a another controller by checking the provided criteria.

Example:

$criteria = array( 'items' => 'OrdersItemsAttributesApiV2Controller', 'totals' => 'OrdersTotalsApiV2Controller' );

Notice: Each controller should map a direct subresource and not deeper ones. This way every API controller is responsible to map its direct subresources.

Throws
\HttpApiV2Exception

If the subresource is not supported by the API.

Arguments

$criteria

array

An array containing the mapping criteria.

Response

boolean

Returns whether the request was eventually mapped.

Minimize response using the $fields parameter.

_minimizeResponse(array &$response) 
inherited

APIv2 supports the GET "fields" parameter which enables the client to select the exact fields to be included in the response. It does not support nested fields, only first-level.

You can provide both associative (single response item) or sequential (multiple response items) arrays and this method will adjust the links accordingly.

Arguments

$response

array

Passed by reference, it will be minified to the required fields.

Paginate response using the $page and $per_page GET parameters.

_paginateResponse(array &$response, integer $p_totalItemCount = null) 
inherited

One of the common functionalities of the APIv2 is the pagination and this can be easily achieved by this function which will update the response with the records that need to be returned. This method will automatically set the pagination headers in the response so that client apps can easily navigate through results.

Arguments

$response

array

Passed by reference, it will be paginated according to the provided parameters.

$p_totalItemCount

integer

|null Optionally set the total number of resources.

[PRIVATE] Prepare response headers.

_prepareResponse() 
inherited

This method will prepare default attributes of the API responses. Further response settings must be set explicitly from each controller method separately.

Not available to child-controllers (private method).

Perform a search on the response array.

_searchResponse(array &$response, string $p_keyword) 
inherited

Normally the best way to filter the results is through the corresponding service but some times there is not specific method for searching the requested resource or subresource. When this is the case use this method to filter the results of the response before returning them back to the client.

Throws
\InvalidArgumentException

If search keyword parameter is not a string.

Arguments

$response

array

Contains the response data to be written.

$p_keyword

string

The keyword to be used for the search.

_setJsonValue

_setJsonValue(string $jsonString, string $property, string $value) : string
inherited

Arguments

$jsonString

string

The json formatted string which should be updated.

$property

string

The name or key of the property which should be updated.

$value

string

The new value which should be set.

Response

string

The updated json formatted string.

[PRIVATE] Set header pagination links.

_setPaginationHeader(integer $p_currentPage, integer $p_itemsPerPage, integer $p_totalItemCount) 
inherited

Useful for GET responses that return multiple items to the client. The client can use the links to navigate through the records without having to construct them on its own.

link

http://www.w3.org/wiki/LinkHeader

Throws
\HttpApiV2Exception

If one of the parameters are invalid.

Arguments

$p_currentPage

integer

Current request page number.

$p_itemsPerPage

integer

The number of items to be returned in each page.

$p_totalItemCount

integer

Total number of the resource items.

[PRIVATE] Set header pagination links.

_setPaginationHeaderByPage(\Pager $pager = null, integer $p_totalItemCount) 
inherited

Useful for GET responses that return multiple items to the client. The client can use the links to navigate through the records without having to construct them on its own.

link

http://www.w3.org/wiki/LinkHeader

Throws
\HttpApiV2Exception

If one of the parameters are invalid.

Arguments

$pager

\Pager

Pager object with pagination information

$p_totalItemCount

integer

Total number of the resource items.

[PRIVATE] Handle rate limit headers.

_setRateLimitHeader() 
inherited

There is a cache file that will store each user session and provide a security mechanism that will protect the shop from DOS attacks or service overuse. Each session will use the hashed "Authorization header" to identify the client. When the limit is reached a "HTTP/1.1 429 Too Many Requests" will be returned.

Headers: X-Rate-Limit-Limit >> Max number of requests allowed. X-Rate-Limit-Remaining >> Number of requests remaining. X-Rate-Limit-Reset >> UTC epoch seconds until the limit is reset.

Important: This method will be executed in every API call and it might slow the response time due to filesystem operations. If the difference is significant then it should be optimized.

Not available to child-controllers (private method).

Throws
\HttpApiV2Exception

If request limit exceed - 429 Too Many Requests

Sort response array with the "sort" GET parameter.

_sortResponse(array &$response) 
inherited

This method supports nested sort values, so by providing a "+address.street" value to the "sort" GET parameter the records will be sort by street value in ascending order. Method supports sorting up to 5 fields.

Important #1: This method has some advantages and disadvantages over the classic database sort mechanism. First it does not need mapping between the API fields and the database fields. Second it does not depend on external system code to sort the response items, so if for example a domain-service does not support sorting the result can still be sorted before sent to the client. The disadvantages are that it will only support a predefined number of fields and this is a trade-off because the method should not use the "eval" function, which will introduce security risks. Furthermore it might be a bit slower than the database sorting.

Important #2: This method is using PHP's array_multisort which by default will sort strings in a case sensitive manner. That means that strings starting with a capital letter will come before strings starting with a lowercase letter. http://php.net/manual/en/function.array-multisort.php

Example: // will sort ascending by customer ID and descending by customer company api.php/v2/customers?sort=+id,-address.company

Arguments

$response

array

Passed by reference, contains an array of the multiple items that will returned as a response to the client.

Updates a single user and returns the response for this put request.

_updateCustomer(string $customerJsonString, integer $customerId) : array
Throws
\HttpApiV2Exception

If customer does not exists.

Arguments

$customerJsonString

string

Request body as string.

$customerId

integer

Id of the customer that should be updated.

Response

array

Updates multiple customers and returns the response for this put request.

_updateMultipleCustomer( $customerJsonString) : array

Arguments

$customerJsonString

Request body as json.

Response

array

[PRIVATE] Validate request before proceeding with response.

_validateRequest() 
inherited

This method will validate the request headers, user authentication and other parameters before the controller proceeds with the response.

Not available to child-controllers (private method).

Throws
\HttpApiV2Exception

If validation fails - 415 Unsupported media type.

Write JSON encoded response data.

_writeResponse(array $response, integer $p_statusCode = 200) 
inherited

Use this method to write a JSON encoded, pretty printed and unescaped response to the client consumer. It is very important that the API provides pretty printed responses because it is easier for users to debug and develop.

IMPORTANT: PHP v5.3 does not support the JSON_PRETTY_PRINT and JSON_UNESCAPED_SLASHES so this method will check for their existance and then use them if possible.

Arguments

$response

array

Contains the response data to be written.

$p_statusCode

integer

(optional) Provide a custom status code for the response, default 200 - Success.

delete

delete() 
api
apiVersion

2.1.0

apiName

DeleteCustomer

apiGroup

Customers

apiDescription

Remove a customer record from the system. This method will always return success even if the customer does not exist (due to internal CustomerWriteService architecture decisions, which strive to avoid unnecessary failures). An example script to demonstrate how to delete a customer is located under ./docs/REST/samples/customer-service/remove_account.php in the git clone.

get

get() 
api
apiVersion

2.3.0

apiName

GetCustomer

apiGroup

Customers

apiDescription

Get multiple or a single customer record through the GET method. This resource supports the following GET parameters as described in the first section of documentation: sorting minimization, search, pagination and links. Additionally you can filter customers by providing the GET parameter "type=guest" or "type=registree". Sort and pagination GET parameters do not apply when a single customer record is selected (e.g. api.php/v2/customers/84). An example script to demonstrate how to fetch customer data is located under ./docs/REST/samples/customer-service/get_admin_data.php in the git clone

getCallableResource

getCallableResource( $controller, array $mappedURI, \Slim\Slim $api) 
inherited static

Arguments

$controller

$mappedURI

array

$api

\Slim\Slim

Initializes API Controller

init() 

post

post() 
api
apiVersion

2.3.0

apiName

CreateCustomer

apiGroup

Customers

apiDescription

This method enables the creation of a new customer (whether registree or a guest). Additionally the user can provide new address information or just set the id of an existing one. Check the examples bellow. An example script to demonstrate the creation of a new customer is located under ./docs/REST/samples/customer-service/create_account.php in the git clone, another one to demonstrate the creation of a guest customer is located under ./docs/REST/samples/customer-service/create_guest_account.php.

put

put() 
api
apiVersion

2.3.0

apiName

UpdateCustomer

apiGroup

Customers

apiDescription

This method will update the information of an existing customer record. You will need to provide all the customer information with the request (except from password and customer id). Also note that you only have to include the "addressId" property. An example script to demonstrate how to update the admin accounts telephone number is located under ./docs/REST/samples/customer-service/update_admin_telephone.php in the git clone.

Constants

Defines the default page offset for responses that return multiple items.

DEFAULT_PAGE_ITEMS
inherited
var

Default controller to be loaded when no resource was selected.

DEFAULT_CONTROLLER_NAME
inherited
var

Defines the maximum request limit for an authorized client.

DEFAULT_RATE_LIMIT
inherited
var

Defines the duration of an API session in minutes.

DEFAULT_RATE_RESET_PERIOD
inherited
var

Properties

customerWriteService

customerWriteService : \CustomerWriteService
var

Type(s)

\CustomerWriteService

customerReadService

customerReadService : \CustomerReadService
var

Type(s)

\CustomerReadService

countryService

countryService : \CountryService
var

Type(s)

\CountryService

addressService

addressService : \AddressBookSErvice
var

Type(s)

\AddressBookSErvice

customerJsonSerializer

customerJsonSerializer : \CustomerJsonSerializer

addressJsonSerializer

addressJsonSerializer : \AddressJsonSerializer

Sorter information array.

sorters : array
inherited
var

Type(s)

array

Pagination information.

pager : \Pager
inherited
var

pager

Type(s)

\Pager

Slim Framework instance is used to manipulate the request or response data.

api : \Slim\Slim
inherited
var

Type(s)

\Slim\Slim

Contains the request URI segments after the root api version segment.

uri : array
inherited

Example: URI - api.php/v2/customers/73/addresses CODE - $this->uri[1]; // will return '73'

var

Type(s)

array