ProductsApiV2Controller
extends HttpApiV2Controller
in package
Class ProductsApiV2Controller
Provides a gateway to the ProductWriteService and ProductReadService classes, which handle the shop product resources.
Tags
Table of Contents
- DEFAULT_CONTROLLER_NAME = 'DefaultApiV2Controller'
- Default controller to be loaded when no resource was selected.
- DEFAULT_PAGE_ITEMS = 50
- Defines the default page offset for responses that return multiple items.
- DEFAULT_RATE_LIMIT = 5000
- Defines the maximum request limit for an authorized client.
- DEFAULT_RATE_RESET_PERIOD = 15
- Defines the duration of an API session in minutes.
- $languageCode : LanguageCode
- Language of the current request.
- $pager : Pager
- Pagination information.
- $productJsonSerializer : ProductJsonSerializer
- Product JSON serializer.
- $productListItemJsonSerializer : ProductListItemJsonSerializer
- Product list item JSON serializer.
- $productReadService : ProductReadService
- Product read service.
- $productWriteService : ProductWriteService
- Product write service.
- $request : Request
- $response : Response
- $sorters : array<string|int, mixed>
- Sorter information array.
- $subresource : array<string|int, mixed>
- Sub resources.
- $uri : array<string|int, mixed>
- Contains the request URI segments after the root api version segment.
- $productFieldsReadService : AdditionalProductFieldReadServiceInterface
- __construct() : mixed
- AbstractApiV2Controller Constructor
- delete() : mixed
- get() : mixed
- getBy() : mixed
- Get product using it's ID
- getByCategories() : mixed
- Get products by its categories search by categories
- getCallableResource() : mixed
- getResponse() : Response
- post() : mixed
- put() : mixed
- _deleteProduct() : mixed
- Deletes a product by its ID.
- _getAndValidateDateParam() : bool
- Read the date param and validate it's content.
- _getJsonErrorMessage() : array<string|int, mixed>
- Builds a default response body from a given Exception.
- _getMappedControllerUri() : array<string|int, mixed>
- Get the relative URI for the mapped controller.
- _hasErrors() : bool
- Checks if the response of a bulk request contains any errors.
- _initializePagingAndSortingFields() : mixed
- Initialize pager and sorters fields.
- _isBulkDeleteRequest() : bool
- Checks if the performed request was a bulk request (only for DELETE requests).
- _isBulkRequest() : bool
- Checks if the performed request was a bulk request (only for POST and PUT requests).
- _isSeachByHistory() : mixed
- _linkResponse() : mixed
- Include links to response resources.
- _locateResource() : mixed
- Add location header to a specific response.
- _mapResponse() : bool
- Map the sub-resource to another controller.
- _minimizeResponse() : mixed
- Minimize response using the $fields parameter.
- _paginateResponse() : mixed
- Paginate response using the $page and $per_page GET parameters.
- _prepareResponse() : mixed
- [PRIVATE] Prepare response headers.
- _processBulkDelete() : array<string|int, mixed>
- Performs the removal of multiple products from a list of product IDs and creates a response array.
- _processBulkInsert() : array<string|int, mixed>
- Performs the creation of multiple products from the JSON request body and creates a response array.
- _processBulkUpdate() : array<string|int, mixed>
- Performs the update of multiple products from the JSON request body and creates a response array.
- _processSingleDelete() : array<string|int, mixed>
- Performs the removal of a single product by a given product ID and creates a response array.
- _processSingleInsert() : array<string|int, mixed>
- Performs the creation of a single product from the JSON request body and creates a response array.
- _processSingleUpdate() : array<string|int, mixed>
- Performs the update of a single product by a given ID from the JSON request body and creates a response array.
- _search() : mixed
- Sub-Resource Products Search
- _searchByHistory() : mixed
- Search products by its changing history and the modified, changed and deleted query parameters.
- _searchDeletedProducts() : mixed
- _searchModifiedProducts() : mixed
- _searchResponse() : mixed
- Perform a search on the response array.
- _setJsonValue() : string
- _setPaginationHeader() : mixed
- [PRIVATE] Set header pagination links.
- _setPaginationHeaderByPage() : mixed
- [PRIVATE] Set header pagination links.
- _setRateLimitHeader() : mixed
- [PRIVATE] Handle rate limit headers.
- _sortResponse() : mixed
- Sort response array with the "sort" GET parameter.
- _validateRequest() : mixed
- [PRIVATE] Validate request before proceeding with response.
- _writeResponse() : mixed
- Write JSON encoded response data.
- addAdditionalFieldsData() : array<string|int, mixed>
- getRootUri() : string
- init() : mixed
- Initializes API Controller
Constants
DEFAULT_CONTROLLER_NAME
Default controller to be loaded when no resource was selected.
public
string
DEFAULT_CONTROLLER_NAME
= 'DefaultApiV2Controller'
DEFAULT_PAGE_ITEMS
Defines the default page offset for responses that return multiple items.
public
int
DEFAULT_PAGE_ITEMS
= 50
DEFAULT_RATE_LIMIT
Defines the maximum request limit for an authorized client.
public
int
DEFAULT_RATE_LIMIT
= 5000
DEFAULT_RATE_RESET_PERIOD
Defines the duration of an API session in minutes.
public
int
DEFAULT_RATE_RESET_PERIOD
= 15
Properties
$languageCode
Language of the current request.
protected
LanguageCode
$languageCode
$pager
Pagination information.
protected
Pager
$pager
$productJsonSerializer
Product JSON serializer.
protected
ProductJsonSerializer
$productJsonSerializer
$productListItemJsonSerializer
Product list item JSON serializer.
protected
ProductListItemJsonSerializer
$productListItemJsonSerializer
$productReadService
Product read service.
protected
ProductReadService
$productReadService
$productWriteService
Product write service.
protected
ProductWriteService
$productWriteService
$request
protected
Request
$request
$response
protected
Response
$response
$sorters
Sorter information array.
protected
array<string|int, mixed>
$sorters
= []
$subresource
Sub resources.
protected
array<string|int, mixed>
$subresource
$uri
Contains the request URI segments after the root api version segment.
protected
array<string|int, mixed>
$uri
Example: URI - api.php/v2/customers/73/addresses CODE - $this->uri[1]; // will return '73'
$productFieldsReadService
private
AdditionalProductFieldReadServiceInterface
$productFieldsReadService
Methods
__construct()
AbstractApiV2Controller Constructor
public
__construct(Request $request, Response $response, array<string|int, mixed> $uri) : mixed
Call this constructor from every child controller class in order to set the Slim instance and the request routes arguments to the class.
Parameters
- $request : Request
- $response : Response
- $uri : array<string|int, mixed>
-
This array contains all the segments of the current request, starting from the resource.
Tags
Return values
mixed —delete()
public
delete() : mixed
Tags
Return values
mixed —get()
public
get() : mixed
Tags
Return values
mixed —getBy()
Get product using it's ID
public
getBy([int $id = null ]) : mixed
Parameters
- $id : int = null
-
product ID to be searched
Tags
Return values
mixed —getByCategories()
Get products by its categories search by categories
public
getByCategories([ $category_id = null ]) : mixed
This method will search all products with a with an given category.
Parameters
Tags
Return values
mixed —getCallableResource()
public
static getCallableResource(mixed $controller, array<string|int, mixed> $mappedURI, ServerRequest $request) : mixed
Parameters
- $controller : mixed
- $mappedURI : array<string|int, mixed>
- $request : ServerRequest
Return values
mixed —getResponse()
public
getResponse() : Response
Return values
Response —post()
public
post() : mixed
Tags
Return values
mixed —put()
public
put() : mixed
Tags
Return values
mixed —_deleteProduct()
Deletes a product by its ID.
protected
_deleteProduct(IdType $id) : mixed
Parameters
- $id : IdType
-
The ID of the product that is to be deleted
Return values
mixed —_getAndValidateDateParam()
Read the date param and validate it's content.
protected
_getAndValidateDateParam(StringType $paramName) : bool
Parameters
- $paramName : StringType
-
the date param to be readed
Tags
Return values
bool —_getJsonErrorMessage()
Builds a default response body from a given Exception.
protected
_getJsonErrorMessage(Exception $exception) : array<string|int, mixed>
Parameters
- $exception : Exception
-
The Exception that is to be described
Return values
array<string|int, mixed> —The response body
_getMappedControllerUri()
Get the relative URI for the mapped controller.
protected
_getMappedControllerUri(IntType $index, array<string|int, mixed> $uri) : array<string|int, mixed>
Parameters
- $index : IntType
-
Contains the URI position relative to the current controller.
- $uri : array<string|int, mixed>
-
Contains the original URI
Return values
array<string|int, mixed> —the mapped controller URI
_hasErrors()
Checks if the response of a bulk request contains any errors.
protected
_hasErrors( $response) : bool
Parameters
Return values
bool —_initializePagingAndSortingFields()
Initialize pager and sorters fields.
protected
_initializePagingAndSortingFields() : mixed
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
Return values
mixed —_isBulkDeleteRequest()
Checks if the performed request was a bulk request (only for DELETE requests).
protected
_isBulkDeleteRequest() : bool
Return values
bool —_isBulkRequest()
Checks if the performed request was a bulk request (only for POST and PUT requests).
protected
_isBulkRequest(StringType $jsonString) : bool
Parameters
- $jsonString : StringType
-
The complete request body as JSON string
Return values
bool —_isSeachByHistory()
protected
_isSeachByHistory() : mixed
Return values
mixed —_linkResponse()
Include links to response resources.
protected
_linkResponse(array<string|int, mixed> &$response) : mixed
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.
Parameters
- $response : array<string|int, mixed>
-
Passed by reference, new links will be appended into the end of each resource.
Return values
mixed —_locateResource()
Add location header to a specific response.
protected
_locateResource(string $p_name, int $p_id) : mixed
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.
Parameters
- $p_name : string
- $p_id : int
Tags
Return values
mixed —_mapResponse()
Map the sub-resource to another controller.
protected
_mapResponse(array<string|int, mixed> $criteria) : bool
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.
Parameters
- $criteria : array<string|int, mixed>
-
An array containing the mapping criteria.
Tags
Return values
bool —Returns whether the request was eventually mapped.
_minimizeResponse()
Minimize response using the $fields parameter.
protected
_minimizeResponse(array<string|int, mixed> &$response) : mixed
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.
Parameters
- $response : array<string|int, mixed>
-
Passed by reference, it will be minified to the required fields.
Return values
mixed —_paginateResponse()
Paginate response using the $page and $per_page GET parameters.
protected
_paginateResponse(array<string|int, mixed> &$response[, int $p_totalItemCount = null ]) : mixed
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.
Parameters
- $response : array<string|int, mixed>
-
Passed by reference, it will be paginated according to the provided parameters.
- $p_totalItemCount : int = null
-
|null Optionally set the total number of resources.
Return values
mixed —_prepareResponse()
[PRIVATE] Prepare response headers.
protected
_prepareResponse() : mixed
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).
Return values
mixed —_processBulkDelete()
Performs the removal of multiple products from a list of product IDs and creates a response array.
protected
_processBulkDelete(array<string|int, mixed> $ids) : array<string|int, mixed>
Parameters
- $ids : array<string|int, mixed>
-
The IDs of the products that should be removed
Return values
array<string|int, mixed> —The response body
_processBulkInsert()
Performs the creation of multiple products from the JSON request body and creates a response array.
protected
_processBulkInsert(StringType $jsonString) : array<string|int, mixed>
Parameters
- $jsonString : StringType
-
The complete request body as JSON string
Return values
array<string|int, mixed> —The response body
_processBulkUpdate()
Performs the update of multiple products from the JSON request body and creates a response array.
protected
_processBulkUpdate(StringType $jsonString) : array<string|int, mixed>
Parameters
- $jsonString : StringType
-
The complete request body as JSON string
Return values
array<string|int, mixed> —The response body
_processSingleDelete()
Performs the removal of a single product by a given product ID and creates a response array.
protected
_processSingleDelete(IdType $productId) : array<string|int, mixed>
Parameters
- $productId : IdType
-
The ID of the product that should be deleted
Return values
array<string|int, mixed> —The response body
_processSingleInsert()
Performs the creation of a single product from the JSON request body and creates a response array.
protected
_processSingleInsert(StringType $jsonString) : array<string|int, mixed>
Parameters
- $jsonString : StringType
-
The complete request body as JSON string
Return values
array<string|int, mixed> —The response body
_processSingleUpdate()
Performs the update of a single product by a given ID from the JSON request body and creates a response array.
protected
_processSingleUpdate(StringType $jsonString, IdType $productId) : array<string|int, mixed>
Parameters
- $jsonString : StringType
-
The complete request body as JSON string
- $productId : IdType
-
The ID of the updated product
Return values
array<string|int, mixed> —The response body
_search()
Sub-Resource Products Search
protected
_search([ $searchCondition = null ]) : mixed
This method will search all products with a with an given search condition.
Parameters
Tags
Return values
mixed —_searchByHistory()
Search products by its changing history and the modified, changed and deleted query parameters.
protected
_searchByHistory() : mixed
Return values
mixed —_searchDeletedProducts()
protected
_searchDeletedProducts() : mixed
Return values
mixed —_searchModifiedProducts()
protected
_searchModifiedProducts() : mixed
Return values
mixed —_searchResponse()
Perform a search on the response array.
protected
_searchResponse(array<string|int, mixed> &$response, string $p_keyword) : mixed
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.
Parameters
- $response : array<string|int, mixed>
-
Contains the response data to be written.
- $p_keyword : string
-
The keyword to be used for the search.
Tags
Return values
mixed —_setJsonValue()
protected
_setJsonValue(string $jsonString, string $property, string $value) : string
Parameters
- $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.
Return values
string —The updated json formatted string.
_setPaginationHeader()
[PRIVATE] Set header pagination links.
protected
_setPaginationHeader(int $p_currentPage, int $p_itemsPerPage, int $p_totalItemCount) : mixed
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.
Parameters
- $p_currentPage : int
-
Current request page number.
- $p_itemsPerPage : int
-
The number of items to be returned in each page.
- $p_totalItemCount : int
-
Total number of the resource items.
Tags
Return values
mixed —_setPaginationHeaderByPage()
[PRIVATE] Set header pagination links.
protected
_setPaginationHeaderByPage([Pager $pager = null ], int $p_totalItemCount) : mixed
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.
Parameters
- $pager : Pager = null
-
Pager object with pagination information
- $p_totalItemCount : int
-
Total number of the resource items.
Tags
Return values
mixed —_setRateLimitHeader()
[PRIVATE] Handle rate limit headers.
protected
_setRateLimitHeader() : mixed
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).
Tags
Return values
mixed —_sortResponse()
Sort response array with the "sort" GET parameter.
protected
_sortResponse(array<string|int, mixed> &$response) : mixed
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
Parameters
- $response : array<string|int, mixed>
-
Passed by reference, contains an array of the multiple items that will returned as a response to the client.
Return values
mixed —_validateRequest()
[PRIVATE] Validate request before proceeding with response.
protected
_validateRequest() : mixed
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).
Tags
Return values
mixed —_writeResponse()
Write JSON encoded response data.
protected
_writeResponse(array<string|int, mixed> $response[, int $p_statusCode = 200 ]) : mixed
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.
Parameters
- $response : array<string|int, mixed>
-
Contains the response data to be written.
- $p_statusCode : int = 200
-
(optional) Provide a custom status code for the response, default 200 - Success.
Return values
mixed —addAdditionalFieldsData()
protected
addAdditionalFieldsData(array<string|int, mixed> $product) : array<string|int, mixed>
Parameters
- $product : array<string|int, mixed>
Return values
array<string|int, mixed> —getRootUri()
protected
getRootUri() : string
Return values
string —init()
Initializes API Controller
protected
init() : mixed