first commit

This commit is contained in:
2024-10-28 22:14:22 +01:00
commit b65352c452
40581 changed files with 5712079 additions and 0 deletions

View File

@@ -0,0 +1,16 @@
drwxr-xr-x 15 30094 users 16 Oct 6 10:16 .
drwxr-xr-x 10 30094 users 21 Oct 6 10:16 ..
drwxr-xr-x 2 30094 users 7 Oct 6 10:16 Api
drwxr-xr-x 2 30094 users 3 Oct 6 10:16 Builder
drwxr-xr-x 2 30094 users 3 Oct 6 10:16 Config
drwxr-xr-x 2 30094 users 4 Oct 6 10:16 Controller
drwxr-xr-x 2 30094 users 5 Oct 6 10:16 DTO
drwxr-xr-x 2 30094 users 6 Oct 6 10:16 Decorator
drwxr-xr-x 2 30094 users 11 Oct 6 10:16 Exception
drwxr-xr-x 2 30094 users 5 Oct 6 10:16 Factory
drwxr-xr-x 2 30094 users 6 Oct 6 10:16 Formatter
drwxr-xr-x 2 30094 users 5 Oct 6 10:16 Module
drwxr-xr-x 2 30094 users 11 Oct 6 10:16 Provider
drwxr-xr-x 2 30094 users 25 Oct 6 10:16 Repository
drwxr-xr-x 2 30094 users 8 Oct 6 10:16 Service
-rw-r--r-- 1 30094 users 1273 Oct 14 2021 index.php

View File

@@ -0,0 +1,7 @@
drwxr-xr-x 2 30094 users 7 Oct 6 10:16 .
drwxr-xr-x 15 30094 users 16 Oct 6 10:16 ..
-rw-r--r-- 1 30094 users 3655 Oct 14 2021 EventBusProxyClient.php
-rw-r--r-- 1 30094 users 1601 Oct 14 2021 EventBusSyncClient.php
-rw-r--r-- 1 30094 users 4369 Oct 14 2021 GenericClient.php
-rw-r--r-- 1 30094 users 2213 Oct 14 2021 ResponseApiHandler.php
-rw-r--r-- 1 30094 users 1083 Oct 14 2021 index.php

View File

@@ -0,0 +1,154 @@
<?php
/**
* 2007-2020 PrestaShop and Contributors
*
* NOTICE OF LICENSE
*
* This source file is subject to the Academic Free License 3.0 (AFL-3.0)
* that is bundled with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* https://opensource.org/licenses/AFL-3.0
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@prestashop.com so we can send you a copy immediately.
*
* @author PrestaShop SA <contact@prestashop.com>
* @copyright 2007-2020 PrestaShop SA and Contributors
* @license https://opensource.org/licenses/AFL-3.0 Academic Free License 3.0 (AFL-3.0)
* International Registered Trademark & Property of PrestaShop SA
*/
namespace PrestaShop\Module\PsEventbus\Api;
use Link;
use PrestaShop\Module\PsEventbus\Api\Post\MultipartBody;
use PrestaShop\Module\PsEventbus\Api\Post\PostFileApi;
use PrestaShop\Module\PsEventbus\Config\Config;
use Prestashop\ModuleLibGuzzleAdapter\ClientFactory;
use PrestaShop\PsAccountsInstaller\Installer\Exception\ModuleNotInstalledException;
use PrestaShop\PsAccountsInstaller\Installer\Exception\ModuleVersionException;
use PrestaShop\PsAccountsInstaller\Installer\Facade\PsAccounts;
use Ps_eventbus;
/**
* Construct the client used to make call to Segment API
*/
class EventBusProxyClient extends GenericClient
{
/**
* @var string
*/
private $baseUrl;
/**
* @var Ps_eventbus
*/
private $module;
/**
* @param Link $link
* @param PsAccounts $psAccounts
* @param string $baseUrl
* @param Ps_eventbus $module
*
* @throws ModuleNotInstalledException
* @throws ModuleVersionException
* @throws \Exception
*/
public function __construct(Link $link, PsAccounts $psAccounts, $baseUrl, $module)
{
$this->module = $module;
$this->baseUrl = $baseUrl;
$this->setLink($link);
$token = $psAccounts->getPsAccountsService()->getOrRefreshToken();
$options = [
'base_uri' => $this->baseUrl,
'timeout' => 60,
'http_errors' => $this->catchExceptions,
'headers' => ['authorization' => "Bearer $token"],
];
$client = (new ClientFactory())->getClient($options);
parent::__construct($client, $options);
}
/**
* @param string $jobId
* @param string $data
* @param int $scriptStartTime
* @param bool $isFull
*
* @return array
*/
public function upload(string $jobId, string $data, int $scriptStartTime, bool $isFull = false)
{
$timeout = Config::PROXY_TIMEOUT - (time() - $scriptStartTime);
$route = $this->baseUrl . "/upload/$jobId";
$this->setRoute($route);
$file = new PostFileApi('file', $data, 'file');
$multipartBody = new MultipartBody([], [$file], 'ps_eventbus_boundary');
$response = $this->post([
'headers' => [
'Content-Type' => 'multipart/form-data; boundary=ps_eventbus_boundary',
'ps-eventbus-version' => $this->module->version,
'full' => $isFull ? '1' : '0',
'Content-Length' => $file->getContent()->getSize(),
'timeout' => $timeout,
],
'body' => $multipartBody->getContents(),
]);
if (is_array($response)) {
$response['upload_url'] = $route;
}
return $response;
}
/**
* @param string $jobId
* @param string $compressedData
* @param int $scriptStartTime
*
* @return array
*/
public function uploadDelete(string $jobId, string $compressedData, int $scriptStartTime)
{
$timeout = Config::PROXY_TIMEOUT - (time() - $scriptStartTime);
$route = $this->baseUrl . "/delete/$jobId";
$this->setRoute($route);
$file = new PostFileApi(
'file',
$compressedData,
'file'
);
$multipartBody = new MultipartBody([], [$file], 'ps_eventbus_boundary');
$response = $this->post([
'headers' => [
'Content-Type' => 'multipart/form-data; boundary=ps_eventbus_boundary',
'ps-eventbus-version' => $this->module->version,
'Content-Length' => $file->getContent()->getSize(),
'timeout' => $timeout,
],
'body' => $multipartBody->getContents(),
]);
if (is_array($response)) {
$response['upload_url'] = $route;
}
return $response;
}
}

View File

@@ -0,0 +1,61 @@
<?php
namespace PrestaShop\Module\PsEventbus\Api;
use Link;
use PrestaShop\Module\PsEventbus\Exception\EnvVarException;
use Prestashop\ModuleLibGuzzleAdapter\ClientFactory;
use PrestaShop\PsAccountsInstaller\Installer\Facade\PsAccounts;
class EventBusSyncClient extends GenericClient
{
/**
* @var string
*/
private $baseUrl;
/**
* EventBusSyncClient constructor.
*
* @param Link $link
* @param PsAccounts $psAccounts
* @param string $baseUrl
*
* @throws \PrestaShop\PsAccountsInstaller\Installer\Exception\ModuleNotInstalledException
* @throws \PrestaShop\PsAccountsInstaller\Installer\Exception\ModuleVersionException
* @throws \Exception
*/
public function __construct(Link $link, PsAccounts $psAccounts, $baseUrl)
{
$this->baseUrl = $baseUrl;
$this->setLink($link);
$token = $psAccounts->getPsAccountsService()->getOrRefreshToken();
$options = [
'base_uri' => $this->baseUrl,
'timeout' => 60,
'http_errors' => $this->catchExceptions,
'headers' => [
'authorization' => "Bearer $token",
'Accept' => 'application/json',
],
];
$client = (new ClientFactory())->getClient($options);
parent::__construct($client, $options);
}
/**
* @param string $jobId
*
* @return array|bool
*
* @throws EnvVarException
*/
public function validateJobId($jobId)
{
$this->setRoute($this->baseUrl . "/job/$jobId");
return $this->get();
}
}

View File

@@ -0,0 +1,300 @@
<?php
namespace PrestaShop\Module\PsEventbus\Api;
use GuzzleHttp\Psr7\Request;
use Psr\Http\Client\ClientExceptionInterface;
use Psr\Http\Client\ClientInterface;
use Psr\Http\Message\RequestInterface;
abstract class GenericClient
{
/**
* If set to false, you will not be able to catch the error
* guzzle will show a different error message.
*
* @var bool
*/
protected $catchExceptions = false;
/**
* Guzzle Client.
*
* @var ClientInterface
*/
protected $client;
/**
* Class Link in order to generate module link.
*
* @var \Link
*/
protected $link;
/**
* Api route.
*
* @var string
*/
protected $route;
/**
* Set how long guzzle will wait a response before end it up.
*
* @var int
*/
protected $timeout = 10;
/**
* @var array
*/
public $options;
/**
* @var array
*/
public $headers;
/**
* @param ClientInterface $client
* @param array $options
*/
public function __construct(ClientInterface $client, array $options)
{
$this->setClient($client);
$this->setOptions($options);
$this->setHeaders($options['headers']);
}
/**
* @return array
*/
public function getOptions(): array
{
return $this->options;
}
/**
* @param array $options
*
* @return GenericClient
*/
public function setOptions(array $options): GenericClient
{
$this->options = $options;
return $this;
}
/**
* @return array
*/
public function getHeaders(): array
{
return $this->headers;
}
/**
* @param array $headers
*
* @return GenericClient
*/
public function setHeaders(array $headers): GenericClient
{
$this->headers = $headers;
return $this;
}
/**
* @param array $headers
*
* @return GenericClient
*/
public function mergeHeader(array $headers)
{
return $this->setHeaders(array_merge($this->getHeaders(), $headers));
}
/**
* Getter for client.
*
* @return ClientInterface
*/
protected function getClient()
{
return $this->client;
}
/**
* Getter for exceptions mode.
*
* @return bool
*/
protected function getExceptionsMode()
{
return $this->catchExceptions;
}
/**
* Getter for Link.
*
* @return \Link
*/
protected function getLink()
{
return $this->link;
}
/**
* Getter for route.
*
* @return string
*/
protected function getRoute()
{
return $this->route;
}
/**
* Getter for timeout.
*
* @return int
*/
protected function getTimeout()
{
return $this->timeout;
}
/**
* Wrapper of method post from guzzle client.
*
* @param array $options payload
*
* @return array return response or false if no response
*/
protected function post(array $options = [])
{
$this->mergeHeader($options['headers']);
$request = new Request('POST', $this->getRoute(), $this->getHeaders(), $options['body']);
return $this->sendRequest($request);
}
/**
* Wrapper of method patch from guzzle client.
*
* @param array $options payload
*
* @return array return response or false if no response
*/
protected function patch(array $options = [])
{
$this->mergeHeader($options['headers']);
$request = new Request('PATCH', $this->getRoute(), $this->getHeaders(), $options['body']);
return $this->sendRequest($request);
}
/**
* Wrapper of method delete from guzzle client.
*
* @param array $options payload
*
* @return array return response array
*/
protected function delete(array $options = [])
{
$this->mergeHeader($options['headers']);
$request = new Request('DELETE', $this->getRoute(), $this->getHeaders(), $options['body']);
return $this->sendRequest($request);
}
/**
* Wrapper of method post from guzzle client.
*
* @return array return response or false if no response
*
* @throws ClientExceptionInterface
*/
protected function get()
{
$request = new Request('GET', $this->getRoute(), $this->getHeaders());
return $this->sendRequest($request);
}
/**
* Wrapper of method sendRequest from guzzle client.
*
* @param RequestInterface $request
*
* @return array
*
* @throws ClientExceptionInterface
*/
public function sendRequest(RequestInterface $request)
{
$response = $this->getClient()->sendRequest($request);
$responseHandler = new ResponseApiHandler();
$response = $responseHandler->handleResponse($response);
return $response;
}
/**
* Setter for client.
*
* @return void
*/
protected function setClient(ClientInterface $client)
{
$this->client = $client;
}
/**
* Setter for exceptions mode.
*
* @param bool $bool
*
* @return void
*/
protected function setExceptionsMode($bool)
{
$this->catchExceptions = $bool;
}
/**
* Setter for link.
*
* @return void
*/
protected function setLink(\Link $link)
{
$this->link = $link;
}
/**
* Setter for route.
*
* @param string $route
*
* @return void
*/
protected function setRoute($route)
{
$this->route = $route;
}
/**
* Setter for timeout.
*
* @param int $timeout
*
* @return void
*/
protected function setTimeout($timeout)
{
$this->timeout = $timeout;
}
}

View File

@@ -0,0 +1,123 @@
<?php
namespace PrestaShop\Module\PsEventbus\Api\Post;
use GuzzleHttp\Psr7\AppendStream;
use GuzzleHttp\Psr7\StreamDecoratorTrait;
use Psr\Http\Message\StreamInterface;
/**
* Stream that when read returns bytes for a streaming multipart/form-data body
*/
class MultipartBody implements StreamInterface
{
use StreamDecoratorTrait;
/** @var string */
private $boundary;
/**
* @param array $fields associative array of field names to values where
* each value is a string or array of strings
* @param array $files Associative array of PostFileInterface objects
* @param string $boundary You can optionally provide a specific boundary
*
* @throws \InvalidArgumentException
*/
public function __construct(
array $fields = [],
array $files = [],
$boundary = null
) {
$this->boundary = $boundary ?: uniqid();
$this->stream = $this->createStream($fields, $files);
}
/**
* Get the boundary
*
* @return string
*/
public function getBoundary()
{
return $this->boundary;
}
public function isWritable()
{
return false;
}
/**
* Get the string needed to transfer a POST field
*
* @param string $name
* @param string $value
*
* @return string
*/
private function getFieldString($name, $value)
{
return sprintf(
"--%s\r\nContent-Disposition: form-data; name=\"%s\"\r\n\r\n%s\r\n",
$this->boundary,
$name,
$value
);
}
/**
* Get the headers needed before transferring the content of a POST file
*
* @param PostFileInterface $file
*
* @return string
*/
private function getFileHeaders(PostFileInterface $file)
{
$headers = '';
foreach ($file->getHeaders() as $key => $value) {
$headers .= "{$key}: {$value}\r\n";
}
return "--{$this->boundary}\r\n" . trim($headers) . "\r\n\r\n";
}
/**
* Create the aggregate stream that will be used to upload the POST data
*
* @param array $fields
* @param array $files
*
* @return AppendStream
*/
protected function createStream(array $fields, array $files)
{
$stream = new AppendStream();
foreach ($fields as $name => $fieldValues) {
foreach ((array) $fieldValues as $value) {
$stream->addStream(
Stream::factory($this->getFieldString($name, $value))
);
}
}
foreach ($files as $file) {
if (!$file instanceof PostFileInterface) {
throw new \InvalidArgumentException('All POST fields must implement PostFieldInterface');
}
$stream->addStream(
Stream::factory($this->getFileHeaders($file))
);
$stream->addStream($file->getContent());
$stream->addStream(Stream::factory("\r\n"));
}
// Add the trailing boundary with CRLF
$stream->addStream(Stream::factory("--{$this->boundary}--\r\n"));
return $stream;
}
}

View File

@@ -0,0 +1,146 @@
<?php
namespace PrestaShop\Module\PsEventbus\Api\Post;
use Psr\Http\Message\StreamInterface;
/**
* Post file upload
*/
class PostFileApi implements PostFileInterface
{
/** @var string */
private $name;
/** @var string|null */
private $filename;
/** @var StreamInterface|MultipartBody|mixed */
private $content;
/** @var array */
private $headers = [];
/**
* @param string $name Name of the form field
* @param StreamInterface|MultipartBody|string $content Data to send
* @param string|null $filename Filename content-disposition attribute
* @param array $headers Array of headers to set on the file (can override any default headers)
*
* @throws \RuntimeException when filename is not passed or can't be determined
*/
public function __construct(
$name,
$content,
$filename = null,
array $headers = []
) {
$this->headers = $headers;
$this->name = $name;
$this->prepareContent($content);
$this->prepareFilename($filename);
$this->prepareDefaultHeaders();
}
public function getName()
{
return $this->name;
}
/**
* @return string|null
*/
public function getFilename()
{
return $this->filename;
}
public function getContent()
{
return $this->content;
}
public function getHeaders()
{
return $this->headers;
}
/**
* Prepares the contents of a POST file.
*
* @param StreamInterface|MultipartBody|string $content Content of the POST file
*
* @return void
*/
private function prepareContent($content)
{
$this->content = $content;
if (!($this->content instanceof StreamInterface)) {
$this->content = Stream::factory($this->content);
} elseif ($this->content instanceof MultipartBody) {
if (!$this->hasHeader('Content-Disposition')) {
$disposition = 'form-data; name="' . $this->name . '"';
$this->headers['Content-Disposition'] = $disposition;
}
if (!$this->hasHeader('Content-Type')) {
$this->headers['Content-Type'] = sprintf(
'multipart/form-data; boundary=%s',
$this->content->getBoundary()
);
}
}
}
/**
* Applies a file name to the POST file based on various checks.
*
* @param string|null $filename Filename to apply (or null to guess)
*
* @return void
*/
private function prepareFilename($filename)
{
$this->filename = $filename;
if (!$this->filename) {
$this->filename = $this->content->getMetadata('uri');
}
if (!$this->filename || substr($this->filename, 0, 6) === 'php://') {
$this->filename = $this->name;
}
}
/**
* Applies default Content-Disposition and Content-Type headers if needed.
*
* @return void
*/
private function prepareDefaultHeaders()
{
// Set a default content-disposition header if one was no provided
if (!$this->hasHeader('Content-Disposition')) {
$this->headers['Content-Disposition'] = sprintf(
'form-data; name="%s"; filename="%s"',
$this->name,
basename(is_null($this->filename) ? '' : $this->filename)
);
}
// Set a default Content-Type if one was not supplied
if (!$this->hasHeader('Content-Type')) {
$this->headers['Content-Type'] = 'text/plain';
}
}
/**
* Check if a specific header exists on the POST file by name.
*
* @param string $name Case-insensitive header to check
*
* @return bool
*/
private function hasHeader($name)
{
return isset(array_change_key_case($this->headers)[strtolower($name)]);
}
}

View File

@@ -0,0 +1,42 @@
<?php
namespace PrestaShop\Module\PsEventbus\Api\Post;
use Psr\Http\Message\StreamInterface;
/**
* Post file upload interface
*/
interface PostFileInterface
{
/**
* Get the name of the form field
*
* @return string
*/
public function getName();
/**
* Get the full path to the file
*
* @return string
*/
public function getFilename();
/**
* Get the content
*
* @return StreamInterface
*/
public function getContent();
/**
* Gets all POST file headers.
*
* The keys represent the header name as it will be sent over the wire, and
* each value is a string.
*
* @return array Returns an associative array of the file's headers
*/
public function getHeaders();
}

View File

@@ -0,0 +1,309 @@
<?php
namespace PrestaShop\Module\PsEventbus\Api\Post;
use GuzzleHttp\Psr7\PumpStream;
use InvalidArgumentException;
use Iterator;
use Psr\Http\Message\StreamInterface;
/**
* PHP stream implementation
*/
class Stream implements StreamInterface
{
/** @var resource */
private $stream;
/** @var int|mixed */
private $size;
/** @var bool */
private $seekable;
/** @var bool */
private $writable;
/** @var bool */
private $readable;
/** @var string */
private $uri;
/** @var array */
private $customMetadata;
/** @var array Hash of readable and writable stream types */
private static $readWriteHash = [
'read' => [
'r' => true, 'w+' => true, 'r+' => true, 'x+' => true, 'c+' => true,
'rb' => true, 'w+b' => true, 'r+b' => true, 'x+b' => true,
'c+b' => true, 'rt' => true, 'w+t' => true, 'r+t' => true,
'x+t' => true, 'c+t' => true, 'a+' => true,
],
'write' => [
'w' => true, 'w+' => true, 'rw' => true, 'r+' => true, 'x+' => true,
'c+' => true, 'wb' => true, 'w+b' => true, 'r+b' => true,
'x+b' => true, 'c+b' => true, 'w+t' => true, 'r+t' => true,
'x+t' => true, 'c+t' => true, 'a' => true, 'a+' => true,
],
];
/**
* Create a new stream based on the input type.
*
* This factory accepts the same associative array of options as described
* in the constructor.
*
* @param resource|string|StreamInterface|Iterator $resource Entity body data
* @param array $options Additional options
*
* @return \GuzzleHttp\Psr7\Stream|PumpStream|Stream|StreamInterface
*
* @throws InvalidArgumentException if the $resource arg is not valid
*/
public static function factory($resource = '', array $options = [])
{
if (is_string($resource)) {
$stream = fopen('php://temp', 'r+');
if ($resource !== '' && is_resource($stream)) {
fwrite($stream, $resource);
fseek($stream, 0);
return new self($stream, $options);
}
}
if (is_resource($resource)) {
return new self($resource, $options);
}
if ($resource instanceof StreamInterface) {
return $resource;
}
if (is_object($resource) && method_exists($resource, '__toString')) {
return self::factory((string) $resource, $options);
}
if (is_callable($resource)) {
return new PumpStream($resource, $options);
}
if ($resource instanceof Iterator) {
return new PumpStream(function () use ($resource) {
if (!$resource->valid()) {
return false;
}
/** @var string|false|null $result */
$result = $resource->current();
$resource->next();
return $result;
}, $options);
}
throw new InvalidArgumentException('Invalid resource type: ' . gettype($resource));
}
/**
* This constructor accepts an associative array of options.
*
* - size: (int) If a read stream would otherwise have an indeterminate
* size, but the size is known due to foreknownledge, then you can
* provide that size, in bytes.
* - metadata: (array) Any additional metadata to return when the metadata
* of the stream is accessed.
*
* @param resource $stream Stream resource to wrap
* @param array $options Associative array of options
*
* @throws \InvalidArgumentException if the stream is not a stream resource
*/
public function __construct($stream, $options = [])
{
if (!is_resource($stream)) {
throw new \InvalidArgumentException('Stream must be a resource');
}
if (isset($options['size'])) {
$this->size = $options['size'];
}
$this->customMetadata = $options['metadata'] ?? [];
$this->attach($stream);
}
/**
* Closes the stream when the destructed
*/
public function __destruct()
{
$this->close();
}
public function __toString()
{
$this->seek(0);
return (string) stream_get_contents($this->stream);
}
/**
* @return false|string
*/
public function getContents()
{
return stream_get_contents($this->stream);
}
public function close()
{
if (is_resource($this->stream)) {
fclose($this->stream);
}
$this->detach();
}
public function detach()
{
$result = $this->stream;
$this->size = $this->stream = null;
$this->readable = $this->writable = $this->seekable = false;
$this->uri = '';
return $result;
}
/**
* @param resource $stream
*
* @return void
*/
public function attach($stream)
{
$this->stream = $stream;
$meta = stream_get_meta_data($this->stream);
$this->seekable = $meta['seekable'];
$this->readable = isset(self::$readWriteHash['read'][$meta['mode']]);
$this->writable = isset(self::$readWriteHash['write'][$meta['mode']]);
/** @var string $uri */
$uri = $this->getMetadata('uri');
$this->uri = $uri;
}
/**
* @return int|mixed|null
*/
public function getSize()
{
if ($this->size !== null) {
return $this->size;
}
// Clear the stat cache if the stream has a URI
if ($this->uri) {
clearstatcache(true, $this->uri);
}
$stats = fstat($this->stream);
if (
/* @phpstan-ignore-next-line */
isset($stats['size'])
) {
$this->size = $stats['size'];
return $this->size;
}
return null;
}
public function isReadable()
{
return $this->readable;
}
public function isWritable()
{
return $this->writable;
}
public function isSeekable()
{
return $this->seekable;
}
public function eof()
{
return feof($this->stream);
}
/**
* @return false|int
*/
public function tell()
{
return ftell($this->stream);
}
/**
* @param int|mixed $size
*
* @return $this
*/
public function setSize($size)
{
$this->size = $size;
return $this;
}
/**
* @param int $offset
* @param int $whence
*
* @return bool
*/
public function seek($offset, $whence = SEEK_SET)
{
return $this->seekable && fseek($this->stream, $offset, $whence) === 0;
}
/**
* @param int<0, max> $length
*
* @return false|string
*/
public function read($length)
{
return $this->readable ? fread($this->stream, $length) : false;
}
/**
* @param string $string
*
* @return false|int
*/
public function write($string)
{
// We can't know the size after writing anything
$this->size = null;
return $this->writable ? fwrite($this->stream, $string) : false;
}
public function getMetadata($key = null)
{
if (!$key) {
return $this->customMetadata + stream_get_meta_data($this->stream);
} elseif (isset($this->customMetadata[$key])) {
return $this->customMetadata[$key];
}
$meta = stream_get_meta_data($this->stream);
return isset($meta[$key]) ? $meta[$key] : null;
}
public function rewind(): void
{
$this->seek(0);
}
}

View File

@@ -0,0 +1,71 @@
<?php
/**
* 2007-2020 PrestaShop.
*
* NOTICE OF LICENSE
*
* This source file is subject to the Academic Free License (AFL 3.0)
* that is bundled with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://opensource.org/licenses/afl-3.0.php
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@prestashop.com so we can send you a copy immediately.
*
* DISCLAIMER
*
* Do not edit or add to this file if you wish to upgrade PrestaShop to newer
* versions in the future. If you wish to customize PrestaShop for your
* needs please refer to http://www.prestashop.com for more information.
*
* @author PrestaShop SA <contact@prestashop.com>
* @copyright 2007-2020 PrestaShop SA
* @license http://opensource.org/licenses/afl-3.0.php Academic Free License (AFL 3.0)
* International Registered Trademark & Property of PrestaShop SA
*/
namespace PrestaShop\Module\PsEventbus\Api;
use Psr\Http\Message\ResponseInterface;
/**
* Handle api response.
*/
class ResponseApiHandler
{
/**
* Format api response.
*
* @return array
*/
public function handleResponse(ResponseInterface $response)
{
/** @var array $responseContents */
$responseContents = json_decode($response->getBody()->getContents(), true);
return [
'status' => $this->responseIsSuccessful($responseContents, $response->getStatusCode()),
'httpCode' => $response->getStatusCode(),
'body' => $responseContents,
];
}
/**
* Check if the response is successful or not (response code 200 to 299).
*
* @param array $responseContents
* @param int $httpStatusCode
*
* @return bool
*/
private function responseIsSuccessful($responseContents, $httpStatusCode)
{
// Directly return true, no need to check the body for a 204 status code
// 204 status code is only send by /payments/order/update
if (204 === $httpStatusCode) {
return true;
}
return '2' === substr((string) $httpStatusCode, 0, 1) && null !== $responseContents;
}
}

View File

@@ -0,0 +1,28 @@
<?php
/**
* 2007-2020 PrestaShop and Contributors
*
* NOTICE OF LICENSE
*
* This source file is subject to the Academic Free License 3.0 (AFL-3.0)
* that is bundled with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* https://opensource.org/licenses/AFL-3.0
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@prestashop.com so we can send you a copy immediately.
*
* @author PrestaShop SA <contact@prestashop.com>
* @copyright 2007-2020 PrestaShop SA and Contributors
* @license https://opensource.org/licenses/AFL-3.0 Academic Free License 3.0 (AFL-3.0)
* International Registered Trademark & Property of PrestaShop SA
*/
header('Expires: Mon, 26 Jul 1997 05:00:00 GMT');
header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT');
header('Cache-Control: no-store, no-cache, must-revalidate');
header('Cache-Control: post-check=0, pre-check=0', false);
header('Pragma: no-cache');
header('Location: ../');
exit;

View File

@@ -0,0 +1,3 @@
drwxr-xr-x 2 30094 users 3 Oct 6 10:16 .
drwxr-xr-x 15 30094 users 16 Oct 6 10:16 ..
-rw-r--r-- 1 30094 users 8558 Oct 14 2021 CarrierBuilder.php

View File

@@ -0,0 +1,256 @@
<?php
namespace PrestaShop\Module\PsEventbus\Builder;
use Carrier;
use Currency;
use Language;
use PrestaShop\Module\PsEventbus\DTO\Carrier as EventBusCarrier;
use PrestaShop\Module\PsEventbus\DTO\CarrierDetail;
use PrestaShop\Module\PsEventbus\DTO\CarrierTax;
use PrestaShop\Module\PsEventbus\Repository\CarrierRepository;
use PrestaShop\Module\PsEventbus\Repository\ConfigurationRepository;
use PrestaShop\Module\PsEventbus\Repository\CountryRepository;
use PrestaShop\Module\PsEventbus\Repository\StateRepository;
use PrestaShop\Module\PsEventbus\Repository\TaxRepository;
use RangePrice;
use RangeWeight;
class CarrierBuilder
{
/**
* @var CarrierRepository
*/
private $carrierRepository;
/**
* @var CountryRepository
*/
private $countryRepository;
/**
* @var StateRepository
*/
private $stateRepository;
/**
* @var TaxRepository
*/
private $taxRepository;
/**
* @var ConfigurationRepository
*/
private $configurationRepository;
public function __construct(
CarrierRepository $carrierRepository,
CountryRepository $countryRepository,
StateRepository $stateRepository,
TaxRepository $taxRepository,
ConfigurationRepository $configurationRepository
) {
$this->carrierRepository = $carrierRepository;
$this->countryRepository = $countryRepository;
$this->stateRepository = $stateRepository;
$this->taxRepository = $taxRepository;
$this->configurationRepository = $configurationRepository;
}
/**
* @param array $carriers
* @param Language $lang
* @param Currency $currency
* @param string $weightUnit
*
* @return array
*
* @throws \PrestaShopDatabaseException
* @throws \PrestaShopException
*/
public function buildCarriers(array $carriers, Language $lang, Currency $currency, $weightUnit)
{
$eventBusCarriers = [];
foreach ($carriers as $carrier) {
$eventBusCarriers[] = $this->buildCarrier(
new Carrier($carrier['id_carrier'], $lang->id),
$currency->iso_code,
$weightUnit,
$carrier['update_date']
);
}
$formattedCarriers = [];
/** @var EventBusCarrier $eventBusCarrier */
foreach ($eventBusCarriers as $eventBusCarrier) {
/** @var array $eventBusCarrierSerialized */
$eventBusCarrierSerialized = $eventBusCarrier->jsonSerialize();
$formattedCarriers = array_merge($formattedCarriers, $eventBusCarrierSerialized);
}
return $formattedCarriers;
}
/**
* @param Carrier $carrier
* @param string $currencyIsoCode
* @param string $weightUnit
* @param string $updateDate
*
* @return EventBusCarrier
*
* @throws \PrestaShopDatabaseException
* @throws \PrestaShopException
*/
public function buildCarrier(Carrier $carrier, $currencyIsoCode, $weightUnit, $updateDate)
{
$eventBusCarrier = new EventBusCarrier();
$freeShippingStartsAtPrice = (float) $this->configurationRepository->get('PS_SHIPPING_FREE_PRICE');
$freeShippingStartsAtWeight = (float) $this->configurationRepository->get('PS_SHIPPING_FREE_WEIGHT');
$eventBusCarrier->setFreeShippingStartsAtPrice($freeShippingStartsAtPrice);
$eventBusCarrier->setFreeShippingStartsAtWeight($freeShippingStartsAtWeight);
$eventBusCarrier->setShippingHandling($this->getShippingHandlePrice((bool) $carrier->shipping_handling));
$eventBusCarrier
->setIdCarrier((int) $carrier->id)
->setIdReference((int) $carrier->id_reference)
->setName($carrier->name)
->setTaxesRatesGroupId((int) $carrier->getIdTaxRulesGroup())
->setUrl($carrier->url)
->setActive($carrier->active)
->setDeleted($carrier->deleted)
->setDisableCarrierWhenOutOfRange((bool) $carrier->range_behavior)
->setIsModule($carrier->is_module)
->setIsFree($carrier->is_free)
->setShippingExternal($carrier->shipping_external)
->setNeedRange($carrier->need_range)
->setExternalModuleName($carrier->external_module_name)
->setMaxWidth($carrier->max_width)
->setMaxHeight($carrier->max_height)
->setMaxDepth($carrier->max_depth)
->setMaxWeight($carrier->max_weight)
->setGrade($carrier->grade)
->setDelay($carrier->delay)
->setCurrency($currencyIsoCode)
->setWeightUnit($weightUnit)
->setUpdateAt($updateDate);
$deliveryPriceByRanges = $this->carrierRepository->getDeliveryPriceByRange($carrier);
if (!$deliveryPriceByRanges) {
return $eventBusCarrier;
}
$carrierDetails = [];
$carrierTaxes = [];
foreach ($deliveryPriceByRanges as $deliveryPriceByRange) {
$range = $this->carrierRepository->getCarrierRange($deliveryPriceByRange);
if (!$range) {
continue;
}
foreach ($deliveryPriceByRange['zones'] as $zone) {
$carrierDetail = $this->buildCarrierDetails($carrier, $range, $zone);
if ($carrierDetail) {
$carrierDetails[] = $carrierDetail;
}
/** @var int $rangeId */
$rangeId = $range->id;
$carrierTax = $this->buildCarrierTaxes($carrier, $zone['id_zone'], $rangeId);
if ($carrierTax) {
$carrierTaxes[] = $carrierTax;
}
}
}
$eventBusCarrier->setCarrierDetails($carrierDetails);
$eventBusCarrier->setCarrierTaxes($carrierTaxes);
return $eventBusCarrier;
}
/**
* @param Carrier $carrier
* @param RangeWeight|RangePrice $range
* @param array $zone
*
* @return false|CarrierDetail
*
* @throws \PrestaShopDatabaseException
*/
private function buildCarrierDetails(Carrier $carrier, $range, array $zone)
{
/** @var int $rangeId */
$rangeId = $range->id;
$carrierDetail = new CarrierDetail();
$carrierDetail->setShippingMethod($carrier->getRangeTable());
$carrierDetail->setCarrierDetailId($rangeId);
$carrierDetail->setDelimiter1($range->delimiter1);
$carrierDetail->setDelimiter2($range->delimiter2);
$carrierDetail->setPrice($zone['price']);
$carrierDetail->setCarrierReference($carrier->id_reference);
$carrierDetail->setZoneId($zone['id_zone']);
$carrierDetail->setRangeId($rangeId);
/** @var array $countryIsoCodes */
$countryIsoCodes = $this->countryRepository->getCountyIsoCodesByZoneId($zone['id_zone']);
if (!$countryIsoCodes) {
return false;
}
$carrierDetail->setCountryIsoCodes($countryIsoCodes);
/** @var array $stateIsoCodes */
$stateIsoCodes = $this->stateRepository->getStateIsoCodesByZoneId($zone['id_zone']);
$carrierDetail->setStateIsoCodes($stateIsoCodes);
return $carrierDetail;
}
/**
* @param Carrier $carrier
* @param int $zoneId
* @param int $rangeId
*
* @return CarrierTax|null
*
* @throws \PrestaShopDatabaseException
*/
private function buildCarrierTaxes(Carrier $carrier, $zoneId, $rangeId)
{
$taxRulesGroupId = (int) $carrier->getIdTaxRulesGroup();
/** @var array $carrierTaxesByZone */
$carrierTaxesByZone = $this->taxRepository->getCarrierTaxesByZone($zoneId, $taxRulesGroupId);
if (!$carrierTaxesByZone[0]['country_iso_code']) {
return null;
}
$carrierTaxesByZone = $carrierTaxesByZone[0];
$carrierTax = new CarrierTax();
$carrierTax->setCarrierReference($carrier->id_reference);
$carrierTax->setRangeId($rangeId);
$carrierTax->setTaxRulesGroupId($taxRulesGroupId);
$carrierTax->setZoneId($zoneId);
$carrierTax->setCountryIsoCode($carrierTaxesByZone['country_iso_code']);
$carrierTax->setStateIsoCodes($carrierTaxesByZone['state_iso_code']);
$carrierTax->setTaxRate($carrierTaxesByZone['rate']);
return $carrierTax;
}
/**
* @param bool $shippingHandling
*
* @return float
*/
private function getShippingHandlePrice($shippingHandling)
{
if ($shippingHandling) {
return (float) $this->configurationRepository->get('PS_SHIPPING_HANDLING');
}
return 0.0;
}
}

View File

@@ -0,0 +1,3 @@
drwxr-xr-x 2 30094 users 3 Oct 6 10:16 .
drwxr-xr-x 15 30094 users 16 Oct 6 10:16 ..
-rw-r--r-- 1 30094 users 1065 Oct 14 2021 Config.php

View File

@@ -0,0 +1,45 @@
<?php
namespace PrestaShop\Module\PsEventbus\Config;
class Config
{
public const PROXY_TIMEOUT = 30;
public const REFRESH_TOKEN_ERROR_CODE = 452;
public const ENV_MISCONFIGURED_ERROR_CODE = 453;
public const DATABASE_QUERY_ERROR_CODE = 454;
public const DATABASE_INSERT_ERROR_CODE = 455;
public const PS_FACEBOOK_NOT_INSTALLED = 456;
public const INVALID_URL_QUERY = 458;
public const INVALID_PS_ACCOUNTS_VERSION = 459;
public const PS_ACCOUNTS_NOT_INSTALLED = 460;
public const HTTP_STATUS_MESSAGES = [
self::REFRESH_TOKEN_ERROR_CODE => 'Cannot refresh token',
self::ENV_MISCONFIGURED_ERROR_CODE => 'Environment misconfigured',
self::DATABASE_QUERY_ERROR_CODE => 'Database syntax error',
self::DATABASE_INSERT_ERROR_CODE => 'Failed to write to database',
self::PS_FACEBOOK_NOT_INSTALLED => 'Cannot sync Taxonomies without Facebook module',
self::INVALID_URL_QUERY => 'Invalid URL query',
self::INVALID_PS_ACCOUNTS_VERSION => 'Invalid PsAccounts version',
self::PS_ACCOUNTS_NOT_INSTALLED => 'PsAccounts not installed',
];
public const COLLECTION_CARRIERS = 'carriers';
public const COLLECTION_CARTS = 'carts';
public const COLLECTION_CART_PRODUCTS = 'cart_products';
public const COLLECTION_CATEGORIES = 'categories';
public const COLLECTION_SPECIFIC_PRICES = 'specific_prices';
public const COLLECTION_CUSTOM_PRODUCT_CARRIERS = 'custom_product_carriers';
public const COLLECTION_TAXONOMIES = 'taxonomies';
public const COLLECTION_MODULES = 'modules';
public const COLLECTION_ORDERS = 'orders';
public const COLLECTION_ORDER_DETAILS = 'order_details';
public const COLLECTION_ORDER_STATUS_HISTORY = 'order_status_history';
public const COLLECTION_PRODUCTS = 'products';
public const COLLECTION_PRODUCT_ATTRIBUTES = 'attributes';
public const COLLECTION_DELETED = 'deleted';
public const COLLECTION_SHOPS = 'shops';
public const COLLECTION_THEMES = 'themes';
public const COLLECTION_BUNDLES = 'bundles';
}

View File

@@ -0,0 +1,42 @@
<?php
/**
* Copyright since 2007 PrestaShop SA and Contributors
* PrestaShop is an International Registered Trademark & Property of PrestaShop SA
*
* NOTICE OF LICENSE
*
* This source file is subject to the Academic Free License version 3.0
* that is bundled with this package in the file LICENSE.md.
* It is also available through the world-wide-web at this URL:
* https://opensource.org/licenses/AFL-3.0
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@prestashop.com so we can send you a copy immediately.
*
* @author PrestaShop SA and Contributors <contact@prestashop.com>
* @copyright Since 2007 PrestaShop SA and Contributors
* @license https://opensource.org/licenses/AFL-3.0 Academic Free License version 3.0
*/
namespace PrestaShop\Module\PsEventbus\Config;
/**
* This class allows to retrieve config data that can be overwritten by a .env file.
* Otherwise it returns by default from the Config class.
*/
class Env
{
/**
* @param string $key
*
* @return string
*/
public function get($key)
{
if (!empty($_ENV[$key])) {
return $_ENV[$key];
}
return constant(Config::class . '::' . $key);
}
}

View File

@@ -0,0 +1,34 @@
<?php
/**
* 2007-2020 PrestaShop.
*
* NOTICE OF LICENSE
*
* This source file is subject to the Academic Free License (AFL 3.0)
* that is bundled with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://opensource.org/licenses/afl-3.0.php
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@prestashop.com so we can send you a copy immediately.
*
* DISCLAIMER
*
* Do not edit or add to this file if you wish to upgrade PrestaShop to newer
* versions in the future. If you wish to customize PrestaShop for your
* needs please refer to http://www.prestashop.com for more information.
*
* @author PrestaShop SA <contact@prestashop.com>
* @copyright 2007-2020 PrestaShop SA
* @license http://opensource.org/licenses/afl-3.0.php Academic Free License (AFL 3.0)
* International Registered Trademark & Property of PrestaShop SA
*/
header('Expires: Mon, 26 Jul 1997 05:00:00 GMT');
header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT');
header('Cache-Control: no-store, no-cache, must-revalidate');
header('Cache-Control: post-check=0, pre-check=0', false);
header('Pragma: no-cache');
header('Location: ../');
exit;

View File

@@ -0,0 +1,4 @@
drwxr-xr-x 2 30094 users 4 Oct 6 10:16 .
drwxr-xr-x 15 30094 users 16 Oct 6 10:16 ..
-rw-r--r-- 1 30094 users 10118 Oct 14 2021 AbstractApiController.php
-rw-r--r-- 1 30094 users 1083 Oct 14 2021 index.php

View File

@@ -0,0 +1,340 @@
<?php
namespace PrestaShop\Module\PsEventbus\Controller;
use DateTime;
use Exception;
use ModuleFrontController;
use PrestaShop\AccountsAuth\Service\PsAccountsService;
use PrestaShop\Module\PsEventbus\Config\Config;
use PrestaShop\Module\PsEventbus\Exception\EnvVarException;
use PrestaShop\Module\PsEventbus\Exception\FirebaseException;
use PrestaShop\Module\PsEventbus\Exception\QueryParamsException;
use PrestaShop\Module\PsEventbus\Handler\ErrorHandler\ErrorHandler;
use PrestaShop\Module\PsEventbus\Provider\PaginatedApiDataProviderInterface;
use PrestaShop\Module\PsEventbus\Repository\EventbusSyncRepository;
use PrestaShop\Module\PsEventbus\Repository\IncrementalSyncRepository;
use PrestaShop\Module\PsEventbus\Repository\LanguageRepository;
use PrestaShop\Module\PsEventbus\Service\ApiAuthorizationService;
use PrestaShop\Module\PsEventbus\Service\ProxyService;
use PrestaShop\Module\PsEventbus\Service\SynchronizationService;
use PrestaShop\PsAccountsInstaller\Installer\Exception\ModuleNotInstalledException;
use PrestaShop\PsAccountsInstaller\Installer\Exception\ModuleVersionException;
use PrestaShop\PsAccountsInstaller\Installer\Facade\PsAccounts;
use PrestaShopDatabaseException;
use PrestaShopException;
use Ps_eventbus;
use Tools;
abstract class AbstractApiController extends ModuleFrontController
{
/**
* Endpoint name
*
* @var string
*/
public $type = '';
/**
* Timestamp when script started
*
* @var int
*/
public $startTime;
/**
* @var ApiAuthorizationService
*/
protected $authorizationService;
/**
* @var ProxyService
*/
protected $proxyService;
/**
* @var EventbusSyncRepository
*/
protected $eventbusSyncRepository;
/**
* @var LanguageRepository
*/
private $languageRepository;
/**
* @var PsAccountsService
*/
private $psAccountsService;
/**
* @var IncrementalSyncRepository
*/
protected $incrementalSyncRepository;
/**
* @var SynchronizationService
*/
private $synchronizationService;
/**
* @var Ps_eventbus
*/
public $module;
/**
* @var bool
*/
public $psAccountsInstalled = true;
/**
* @var ErrorHandler
*/
public $errorHandler;
public function __construct()
{
parent::__construct();
$this->ajax = true;
$this->content_only = true;
$this->controller_type = 'module';
$this->errorHandler = $this->module->getService(ErrorHandler::class);
try {
$this->psAccountsService = $this->module->getService(PsAccounts::class)->getPsAccountsService();
$this->proxyService = $this->module->getService(ProxyService::class);
$this->authorizationService = $this->module->getService(ApiAuthorizationService::class);
$this->synchronizationService = $this->module->getService(SynchronizationService::class);
} catch (ModuleVersionException $exception) {
$this->errorHandler->handle($exception);
$this->exitWithExceptionMessage($exception);
}
$this->eventbusSyncRepository = $this->module->getService(EventbusSyncRepository::class);
$this->languageRepository = $this->module->getService(LanguageRepository::class);
$this->incrementalSyncRepository = $this->module->getService(IncrementalSyncRepository::class);
}
/**
* @return void
*/
public function init()
{
$this->startTime = time();
try {
$this->authorize();
} catch (PrestaShopDatabaseException $exception) {
$this->errorHandler->handle($exception);
$this->exitWithExceptionMessage($exception);
} catch (EnvVarException $exception) {
$this->errorHandler->handle($exception);
$this->exitWithExceptionMessage($exception);
} catch (FirebaseException $exception) {
$this->errorHandler->handle($exception);
$this->exitWithExceptionMessage($exception);
}
}
/**
* @return void
*
* @throws PrestaShopDatabaseException|EnvVarException|FirebaseException
*/
private function authorize()
{
/** @var string $jobId */
$jobId = Tools::getValue('job_id', 'empty_job_id');
$authorizationResponse = $this->authorizationService->authorizeCall($jobId);
if (is_array($authorizationResponse)) {
$this->exitWithResponse($authorizationResponse);
} elseif (!$authorizationResponse) {
throw new PrestaShopDatabaseException('Failed saving job id to database');
}
try {
$token = $this->psAccountsService->getOrRefreshToken();
} catch (Exception $exception) {
throw new FirebaseException($exception->getMessage());
}
if (!$token) {
throw new FirebaseException('Invalid token');
}
}
/**
* @param PaginatedApiDataProviderInterface $dataProvider
*
* @return array
*/
protected function handleDataSync(PaginatedApiDataProviderInterface $dataProvider)
{
/** @var string $jobId */
$jobId = Tools::getValue('job_id');
/** @var string $langIso */
$langIso = Tools::getValue('lang_iso', $this->languageRepository->getDefaultLanguageIsoCode());
/** @var int $limit */
$limit = Tools::getValue('limit', 50);
if ($limit < 0) {
$this->exitWithExceptionMessage(new QueryParamsException('Invalid URL Parameters', Config::INVALID_URL_QUERY));
}
/** @var bool $initFullSync */
$initFullSync = Tools::getValue('full', 0) == 1;
$dateNow = (new DateTime())->format(DateTime::ATOM);
$offset = 0;
$incrementalSync = false;
$response = [];
try {
$typeSync = $this->eventbusSyncRepository->findTypeSync($this->type, $langIso);
if ($typeSync !== false && is_array($typeSync)) {
$offset = (int) $typeSync['offset'];
if ((int) $typeSync['full_sync_finished'] === 1 && !$initFullSync) {
$incrementalSync = true;
} elseif ($initFullSync) {
$offset = 0;
$this->eventbusSyncRepository->updateTypeSync(
$this->type,
$offset,
$dateNow,
false,
$langIso
);
}
} else {
$this->eventbusSyncRepository->insertTypeSync($this->type, $offset, $dateNow, $langIso);
}
if ($incrementalSync) {
$response = $this->synchronizationService->handleIncrementalSync(
$dataProvider,
$this->type,
$jobId,
$limit,
$langIso,
$this->startTime,
$initFullSync
);
} else {
$response = $this->synchronizationService->handleFullSync(
$dataProvider,
$this->type,
$jobId,
$langIso,
$offset,
$limit,
$dateNow,
$this->startTime,
$initFullSync
);
}
return array_merge(
[
'job_id' => $jobId,
'object_type' => $this->type,
],
$response
);
} catch (PrestaShopDatabaseException $exception) {
$this->errorHandler->handle($exception);
$this->exitWithExceptionMessage($exception);
} catch (EnvVarException $exception) {
$this->errorHandler->handle($exception);
$this->exitWithExceptionMessage($exception);
} catch (FirebaseException $exception) {
$this->errorHandler->handle($exception);
$this->exitWithExceptionMessage($exception);
} catch (Exception $exception) {
$this->errorHandler->handle($exception);
$this->exitWithExceptionMessage($exception);
}
return $response;
}
/**
* @param array|null $value
* @param string|null $controller
* @param string|null $method
*
* @return void
*
* @throws PrestaShopException
*/
public function ajaxDie($value = null, $controller = null, $method = null)
{
parent::ajaxDie(json_encode($value) ?: null, $controller, $method);
}
/**
* @param array $response
*
* @return void
*/
protected function exitWithResponse(array $response)
{
$httpCode = isset($response['httpCode']) ? (int) $response['httpCode'] : 200;
$this->dieWithResponse($response, $httpCode);
}
/**
* @param Exception $exception
*
* @return void
*/
protected function exitWithExceptionMessage(Exception $exception)
{
$code = $exception->getCode() == 0 ? 500 : $exception->getCode();
if ($exception instanceof PrestaShopDatabaseException) {
$code = Config::DATABASE_QUERY_ERROR_CODE;
} elseif ($exception instanceof EnvVarException) {
$code = Config::ENV_MISCONFIGURED_ERROR_CODE;
} elseif ($exception instanceof FirebaseException) {
$code = Config::REFRESH_TOKEN_ERROR_CODE;
} elseif ($exception instanceof QueryParamsException) {
$code = Config::INVALID_URL_QUERY;
} elseif ($exception instanceof ModuleVersionException) {
$code = Config::INVALID_PS_ACCOUNTS_VERSION;
} elseif ($exception instanceof ModuleNotInstalledException) {
$code = Config::PS_ACCOUNTS_NOT_INSTALLED;
}
$response = [
'object_type' => $this->type,
'status' => false,
'httpCode' => $code,
'message' => $exception->getMessage(),
];
$this->dieWithResponse($response, (int) $code);
}
/**
* @param array $response
* @param int $code
*
* @return void
*/
private function dieWithResponse(array $response, $code)
{
$httpStatusText = "HTTP/1.1 $code";
if (array_key_exists((int) $code, Config::HTTP_STATUS_MESSAGES)) {
$httpStatusText .= ' ' . Config::HTTP_STATUS_MESSAGES[(int) $code];
} elseif (isset($response['body']['statusText'])) {
$httpStatusText .= ' ' . $response['body']['statusText'];
}
$response['httpCode'] = (int) $code;
header('Cache-Control: no-store, no-cache, must-revalidate, post-check=0, pre-check=0');
header('Content-Type: application/json;charset=utf-8');
header($httpStatusText);
echo json_encode($response, JSON_UNESCAPED_SLASHES);
exit;
}
}

View File

@@ -0,0 +1,28 @@
<?php
/**
* 2007-2020 PrestaShop and Contributors
*
* NOTICE OF LICENSE
*
* This source file is subject to the Academic Free License 3.0 (AFL-3.0)
* that is bundled with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* https://opensource.org/licenses/AFL-3.0
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@prestashop.com so we can send you a copy immediately.
*
* @author PrestaShop SA <contact@prestashop.com>
* @copyright 2007-2020 PrestaShop SA and Contributors
* @license https://opensource.org/licenses/AFL-3.0 Academic Free License 3.0 (AFL-3.0)
* International Registered Trademark & Property of PrestaShop SA
*/
header('Expires: Mon, 26 Jul 1997 05:00:00 GMT');
header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT');
header('Cache-Control: no-store, no-cache, must-revalidate');
header('Cache-Control: post-check=0, pre-check=0', false);
header('Pragma: no-cache');
header('Location: ../');
exit;

View File

@@ -0,0 +1,5 @@
drwxr-xr-x 2 30094 users 5 Oct 6 10:16 .
drwxr-xr-x 15 30094 users 16 Oct 6 10:16 ..
-rw-r--r-- 1 30094 users 13063 Oct 14 2021 Carrier.php
-rw-r--r-- 1 30094 users 5550 Oct 14 2021 CarrierDetail.php
-rw-r--r-- 1 30094 users 3508 Oct 14 2021 CarrierTax.php

View File

@@ -0,0 +1,745 @@
<?php
namespace PrestaShop\Module\PsEventbus\DTO;
use JsonSerializable;
class Carrier implements JsonSerializable
{
/**
* @var string
*/
private $collection = 'carriers';
/**
* @var int
*/
private $idCarrier;
/**
* @var int
*/
private $idReference;
/**
* @var int
*/
private $taxesRatesGroupId;
/**
* @var string
*/
private $name;
/**
* @var string
*/
private $url;
/**
* @var bool
*/
private $active;
/**
* @var bool
*/
private $deleted;
/**
* @var float
*/
private $shippingHandling = 0;
/**
* @var float
*/
private $freeShippingStartsAtPrice;
/**
* @var float
*/
private $freeShippingStartsAtWeight;
/**
* @var bool
*/
private $disableCarrierWhenOutOfRange;
/**
* @var bool
*/
private $isModule;
/**
* @var bool
*/
private $isFree;
/**
* @var bool
*/
private $shippingExternal;
/**
* @var bool
*/
private $needRange;
/**
* @var string
*/
private $externalModuleName;
/**
* @var float
*/
private $maxWidth;
/**
* @var float
*/
private $maxHeight;
/**
* @var float
*/
private $maxDepth;
/**
* @var float
*/
private $maxWeight;
/**
* @var int
*/
private $grade;
/**
* @var string
*/
private $delay;
/**
* @var string
*/
private $currency;
/**
* @var string
*/
private $weightUnit;
/**
* @var CarrierDetail[]
*/
private $carrierDetails = [];
/**
* @var CarrierTax[]
*/
private $carrierTaxes = [];
/**
* @var string
*/
private $updateAt;
/**
* @return string
*/
public function getCollection()
{
return $this->collection;
}
/**
* @return int
*/
public function getIdCarrier()
{
return $this->idCarrier;
}
/**
* @param int $idCarrier
*
* @return Carrier
*/
public function setIdCarrier($idCarrier)
{
$this->idCarrier = $idCarrier;
return $this;
}
/**
* @return int
*/
public function getIdReference()
{
return $this->idReference;
}
/**
* @param int $idReference
*
* @return Carrier
*/
public function setIdReference($idReference)
{
$this->idReference = $idReference;
return $this;
}
/**
* @return int
*/
public function getTaxesRatesGroupId()
{
return $this->taxesRatesGroupId;
}
/**
* @param int $taxesRatesGroupId
*
* @return Carrier
*/
public function setTaxesRatesGroupId($taxesRatesGroupId)
{
$this->taxesRatesGroupId = $taxesRatesGroupId;
return $this;
}
/**
* @return string
*/
public function getName()
{
return $this->name;
}
/**
* @param string $name
*
* @return Carrier
*/
public function setName($name)
{
$this->name = $name;
return $this;
}
/**
* @return string
*/
public function getUrl()
{
return $this->url;
}
/**
* @param string $url
*
* @return Carrier
*/
public function setUrl($url)
{
$this->url = $url;
return $this;
}
/**
* @return bool
*/
public function isActive()
{
return $this->active;
}
/**
* @param bool $active
*
* @return Carrier
*/
public function setActive($active)
{
$this->active = $active;
return $this;
}
/**
* @return bool
*/
public function isDeleted()
{
return $this->deleted;
}
/**
* @param bool $deleted
*
* @return Carrier
*/
public function setDeleted($deleted)
{
$this->deleted = $deleted;
return $this;
}
/**
* @return float
*/
public function getShippingHandling()
{
return $this->shippingHandling;
}
/**
* @param float $shippingHandling
*
* @return Carrier
*/
public function setShippingHandling($shippingHandling)
{
$this->shippingHandling = $shippingHandling;
return $this;
}
/**
* @return float
*/
public function getFreeShippingStartsAtPrice()
{
return $this->freeShippingStartsAtPrice;
}
/**
* @param float $freeShippingStartsAtPrice
*
* @return Carrier
*/
public function setFreeShippingStartsAtPrice($freeShippingStartsAtPrice)
{
$this->freeShippingStartsAtPrice = $freeShippingStartsAtPrice;
return $this;
}
/**
* @return float
*/
public function getFreeShippingStartsAtWeight()
{
return $this->freeShippingStartsAtWeight;
}
/**
* @param float $freeShippingStartsAtWeight
*
* @return Carrier
*/
public function setFreeShippingStartsAtWeight($freeShippingStartsAtWeight)
{
$this->freeShippingStartsAtWeight = $freeShippingStartsAtWeight;
return $this;
}
/**
* @return bool
*/
public function isDisableCarrierWhenOutOfRange()
{
return $this->disableCarrierWhenOutOfRange;
}
/**
* @param bool $disableCarrierWhenOutOfRange
*
* @return Carrier
*/
public function setDisableCarrierWhenOutOfRange($disableCarrierWhenOutOfRange)
{
$this->disableCarrierWhenOutOfRange = $disableCarrierWhenOutOfRange;
return $this;
}
/**
* @return bool
*/
public function isModule()
{
return $this->isModule;
}
/**
* @param bool $isModule
*
* @return Carrier
*/
public function setIsModule($isModule)
{
$this->isModule = $isModule;
return $this;
}
/**
* @return bool
*/
public function isFree()
{
return $this->isFree;
}
/**
* @param bool $isFree
*
* @return Carrier
*/
public function setIsFree($isFree)
{
$this->isFree = $isFree;
return $this;
}
/**
* @return bool
*/
public function isShippingExternal()
{
return $this->shippingExternal;
}
/**
* @param bool $shippingExternal
*
* @return Carrier
*/
public function setShippingExternal($shippingExternal)
{
$this->shippingExternal = $shippingExternal;
return $this;
}
/**
* @return bool
*/
public function isNeedRange()
{
return $this->needRange;
}
/**
* @param bool $needRange
*
* @return Carrier
*/
public function setNeedRange($needRange)
{
$this->needRange = $needRange;
return $this;
}
/**
* @return string
*/
public function getExternalModuleName()
{
return $this->externalModuleName;
}
/**
* @param string $externalModuleName
*
* @return Carrier
*/
public function setExternalModuleName($externalModuleName)
{
$this->externalModuleName = $externalModuleName;
return $this;
}
/**
* @return float
*/
public function getMaxWidth()
{
return $this->maxWidth;
}
/**
* @param float $maxWidth
*
* @return Carrier
*/
public function setMaxWidth($maxWidth)
{
$this->maxWidth = $maxWidth;
return $this;
}
/**
* @return float
*/
public function getMaxHeight()
{
return $this->maxHeight;
}
/**
* @param float $maxHeight
*
* @return Carrier
*/
public function setMaxHeight($maxHeight)
{
$this->maxHeight = $maxHeight;
return $this;
}
/**
* @return float
*/
public function getMaxDepth()
{
return $this->maxDepth;
}
/**
* @param float $maxDepth
*
* @return Carrier
*/
public function setMaxDepth($maxDepth)
{
$this->maxDepth = $maxDepth;
return $this;
}
/**
* @return float
*/
public function getMaxWeight()
{
return $this->maxWeight;
}
/**
* @param float $maxWeight
*
* @return Carrier
*/
public function setMaxWeight($maxWeight)
{
$this->maxWeight = $maxWeight;
return $this;
}
/**
* @return int
*/
public function getGrade()
{
return $this->grade;
}
/**
* @param int $grade
*
* @return Carrier
*/
public function setGrade($grade)
{
$this->grade = $grade;
return $this;
}
/**
* @return string
*/
public function getDelay()
{
return $this->delay;
}
/**
* @param string $delay
*
* @return Carrier
*/
public function setDelay($delay)
{
$this->delay = $delay;
return $this;
}
/**
* @return string
*/
public function getCurrency()
{
return $this->currency;
}
/**
* @param string $currency
*
* @return Carrier
*/
public function setCurrency($currency)
{
$this->currency = $currency;
return $this;
}
/**
* @return string
*/
public function getWeightUnit()
{
return $this->weightUnit;
}
/**
* @param string $weightUnit
*
* @return Carrier
*/
public function setWeightUnit($weightUnit)
{
$this->weightUnit = $weightUnit;
return $this;
}
/**
* @return CarrierDetail[]
*/
public function getCarrierDetails()
{
return $this->carrierDetails;
}
/**
* @param CarrierDetail[] $carrierDetails
*
* @return Carrier
*/
public function setCarrierDetails($carrierDetails)
{
$this->carrierDetails = $carrierDetails;
return $this;
}
/**
* @return CarrierTax[]
*/
public function getCarrierTaxes()
{
return $this->carrierTaxes;
}
/**
* @param CarrierTax[] $carrierTaxes
*
* @return Carrier
*/
public function setCarrierTaxes($carrierTaxes)
{
$this->carrierTaxes = $carrierTaxes;
return $this;
}
/**
* @return string
*/
public function getUpdateAt()
{
return $this->updateAt;
}
/**
* @param string $updateAt
*
* @return Carrier
*/
public function setUpdateAt($updateAt)
{
$this->updateAt = $updateAt;
return $this;
}
public function jsonSerialize()
{
$return = [];
$return[] = [
'collection' => $this->getCollection(),
'id' => (string) $this->getIdReference(),
'properties' => [
'id_carrier' => (string) $this->getIdCarrier(),
'id_reference' => (string) $this->getIdReference(),
'name' => (string) $this->getName(),
'carrier_taxes_rates_group_id' => (string) $this->getTaxesRatesGroupId(),
'url' => (string) $this->getUrl(),
'active' => (bool) $this->isActive(),
'deleted' => (bool) $this->isDeleted(),
'shipping_handling' => (float) $this->getShippingHandling(),
'free_shipping_starts_at_price' => (float) $this->getFreeShippingStartsAtPrice(),
'free_shipping_starts_at_weight' => (float) $this->getFreeShippingStartsAtWeight(),
'disable_carrier_when_out_of_range' => (bool) $this->isDisableCarrierWhenOutOfRange(),
'is_module' => (bool) $this->isModule(),
'is_free' => (bool) $this->isFree(),
'shipping_external' => (bool) $this->isShippingExternal(),
'need_range' => (bool) $this->isNeedRange(),
'external_module_name' => (string) $this->getExternalModuleName(),
'max_width' => (float) $this->getMaxWidth(),
'max_height' => (float) $this->getMaxHeight(),
'max_depth' => (float) $this->getMaxDepth(),
'max_weight' => (float) $this->getMaxWeight(),
'grade' => (int) $this->getGrade(),
'delay' => (string) $this->getDelay(),
'currency' => (string) $this->getCurrency(),
'weight_unit' => (string) $this->getWeightUnit(),
'updated_at' => (string) $this->getUpdateAt(),
],
];
$carrierDetails = [];
foreach ($this->getCarrierDetails() as $carrierDetail) {
$carrierDetails[] = $carrierDetail->jsonSerialize();
}
$carrierTaxRates = [];
foreach ($this->getCarrierTaxes() as $carrierTax) {
$carrierTaxRates[] = $carrierTax->jsonSerialize();
}
return array_merge($return, $carrierDetails, $carrierTaxRates);
}
}

View File

@@ -0,0 +1,294 @@
<?php
namespace PrestaShop\Module\PsEventbus\DTO;
use JsonSerializable;
class CarrierDetail implements JsonSerializable
{
/**
* @var string
*/
private $collection = 'carrier_details';
/**
* @var string|bool
*/
private $shippingMethod;
/**
* @var int
*/
private $carrierReference;
/**
* @var int
*/
private $CarrierDetailId;
/**
* @var int
*/
private $zoneId;
/**
* @var int
*/
private $rangeId;
/**
* @var float
*/
private $delimiter1;
/**
* @var float
*/
private $delimiter2;
/**
* @var array
*/
private $countryIsoCodes;
/**
* @var array
*/
private $stateIsoCodes;
/**
* @var float
*/
private $price;
/**
* @return string
*/
public function getCollection()
{
return $this->collection;
}
/**
* @return string|bool
*/
public function getShippingMethod()
{
return $this->shippingMethod;
}
/**
* @param bool|string $shippingMethod
*
* @return CarrierDetail
*/
public function setShippingMethod($shippingMethod)
{
$this->shippingMethod = $shippingMethod;
return $this;
}
/**
* @return int
*/
public function getCarrierReference()
{
return $this->carrierReference;
}
/**
* @param int $carrierReference
*
* @return CarrierDetail
*/
public function setCarrierReference($carrierReference)
{
$this->carrierReference = $carrierReference;
return $this;
}
/**
* @return int
*/
public function getCarrierDetailId()
{
return $this->CarrierDetailId;
}
/**
* @param int $CarrierDetailId
*
* @return CarrierDetail
*/
public function setCarrierDetailId($CarrierDetailId)
{
$this->CarrierDetailId = $CarrierDetailId;
return $this;
}
/**
* @return int
*/
public function getZoneId()
{
return $this->zoneId;
}
/**
* @param int $zoneId
*
* @return CarrierDetail
*/
public function setZoneId($zoneId)
{
$this->zoneId = $zoneId;
return $this;
}
/**
* @return int
*/
public function getRangeId()
{
return $this->rangeId;
}
/**
* @param int $rangeId
*
* @return CarrierDetail
*/
public function setRangeId($rangeId)
{
$this->rangeId = $rangeId;
return $this;
}
/**
* @return float
*/
public function getDelimiter1()
{
return $this->delimiter1;
}
/**
* @param float $delimiter1
*
* @return CarrierDetail
*/
public function setDelimiter1($delimiter1)
{
$this->delimiter1 = $delimiter1;
return $this;
}
/**
* @return float
*/
public function getDelimiter2()
{
return $this->delimiter2;
}
/**
* @param float $delimiter2
*
* @return CarrierDetail
*/
public function setDelimiter2($delimiter2)
{
$this->delimiter2 = $delimiter2;
return $this;
}
/**
* @return array
*/
public function getCountryIsoCodes()
{
return $this->countryIsoCodes;
}
/**
* @param array $countryIsoCodes
*
* @return CarrierDetail
*/
public function setCountryIsoCodes($countryIsoCodes)
{
$this->countryIsoCodes = $countryIsoCodes;
return $this;
}
/**
* @return array
*/
public function getStateIsoCodes()
{
return $this->stateIsoCodes;
}
/**
* @param array $stateIsoCodes
*
* @return CarrierDetail
*/
public function setStateIsoCodes($stateIsoCodes)
{
$this->stateIsoCodes = $stateIsoCodes;
return $this;
}
/**
* @return float
*/
public function getPrice()
{
return $this->price;
}
/**
* @param float $price
*
* @return CarrierDetail
*/
public function setPrice($price)
{
$this->price = $price;
return $this;
}
public function jsonSerialize()
{
$countryIds = implode(',', $this->getCountryIsoCodes());
$stateIds = implode(',', $this->getStateIsoCodes());
return [
'collection' => $this->getCollection(),
'id' => $this->getCarrierReference() . '-' . $this->getZoneId() . '-' . $this->getShippingMethod() . '-' . $this->getRangeId(),
'properties' => [
'id_reference' => (string) $this->getCarrierReference(),
'id_zone' => (string) $this->getZoneId(),
'id_range' => (string) $this->getRangeId(),
'id_carrier_detail' => (string) $this->getCarrierDetailId(),
'shipping_method' => (string) $this->getShippingMethod(),
'delimiter1' => (float) $this->getDelimiter1(),
'delimiter2' => (float) $this->getDelimiter2(),
'country_ids' => (string) $countryIds,
'state_ids' => (string) $stateIds,
'price' => (float) $this->getPrice(),
],
];
}
}

View File

@@ -0,0 +1,210 @@
<?php
namespace PrestaShop\Module\PsEventbus\DTO;
use JsonSerializable;
class CarrierTax implements JsonSerializable
{
/**
* @var string
*/
private $collection = 'carrier_taxes';
/**
* @var int
*/
private $carrierReference;
/**
* @var int
*/
private $rangeId;
/**
* @var int
*/
private $taxRulesGroupId;
/**
* @var int
*/
private $zoneId;
/**
* @var string
*/
private $countryIsoCode;
/**
* @var string
*/
private $stateIsoCodes;
/**
* @var float
*/
private $taxRate;
/**
* @return string
*/
public function getCollection()
{
return $this->collection;
}
/**
* @return int
*/
public function getCarrierReference()
{
return $this->carrierReference;
}
/**
* @param int $carrierReference
*
* @return CarrierTax
*/
public function setCarrierReference($carrierReference)
{
$this->carrierReference = $carrierReference;
return $this;
}
public function getRangeId(): int
{
return $this->rangeId;
}
/**
* @param int $rangeId
*
* @return CarrierTax
*/
public function setRangeId(int $rangeId): CarrierTax
{
$this->rangeId = $rangeId;
return $this;
}
/**
* @return int
*/
public function getTaxRulesGroupId()
{
return $this->taxRulesGroupId;
}
/**
* @param int $taxRulesGroupId
*
* @return CarrierTax
*/
public function setTaxRulesGroupId($taxRulesGroupId)
{
$this->taxRulesGroupId = $taxRulesGroupId;
return $this;
}
/**
* @return int
*/
public function getZoneId()
{
return $this->zoneId;
}
/**
* @param int $zoneId
*
* @return CarrierTax
*/
public function setZoneId($zoneId)
{
$this->zoneId = $zoneId;
return $this;
}
/**
* @return string
*/
public function getCountryIsoCode()
{
return $this->countryIsoCode;
}
/**
* @param string $countryIsoCode
*
* @return CarrierTax
*/
public function setCountryIsoCode($countryIsoCode)
{
$this->countryIsoCode = $countryIsoCode;
return $this;
}
/**
* @return string
*/
public function getStateIsoCodes()
{
return $this->stateIsoCodes;
}
/**
* @param string $stateIsoCodes
*
* @return CarrierTax
*/
public function setStateIsoCodes($stateIsoCodes)
{
$this->stateIsoCodes = $stateIsoCodes;
return $this;
}
/**
* @return float
*/
public function getTaxRate()
{
return $this->taxRate;
}
/**
* @param float $taxRate
*
* @return CarrierTax
*/
public function setTaxRate($taxRate)
{
$this->taxRate = $taxRate;
return $this;
}
public function jsonSerialize()
{
return [
'collection' => $this->getCollection(),
'id' => $this->getCarrierReference() . '-' . $this->getZoneId() . '-' . $this->getRangeId(),
'properties' => [
'id_reference' => (string) $this->getCarrierReference(),
'id_zone' => (string) $this->getZoneId(),
'id_range' => (string) $this->getRangeId(),
'id_carrier_tax' => (string) $this->getTaxRulesGroupId(),
'country_id' => (string) $this->getCountryIsoCode(),
'state_ids' => (string) $this->getStateIsoCodes(),
'tax_rate' => (float) $this->getTaxRate(),
],
];
}
}

View File

@@ -0,0 +1,6 @@
drwxr-xr-x 2 30094 users 6 Oct 6 10:16 .
drwxr-xr-x 15 30094 users 16 Oct 6 10:16 ..
-rw-r--r-- 1 30094 users 870 Oct 14 2021 CategoryDecorator.php
-rw-r--r-- 1 30094 users 1017 Oct 14 2021 PayloadDecorator.php
-rw-r--r-- 1 30094 users 9499 Oct 14 2021 ProductDecorator.php
-rw-r--r-- 1 30094 users 1273 Oct 14 2021 index.php

View File

@@ -0,0 +1,40 @@
<?php
namespace PrestaShop\Module\PsEventbus\Decorator;
class CategoryDecorator
{
/**
* @param array $categories
*
* @return void
*/
public function decorateCategories(array &$categories)
{
foreach ($categories as &$category) {
$this->castPropertyValues($category);
$this->formatDescription($category);
}
}
/**
* @param array $category
*
* @return void
*/
private function castPropertyValues(array &$category)
{
$category['id_category'] = (int) $category['id_category'];
$category['id_parent'] = (int) $category['id_parent'];
}
/**
* @param array $category
*
* @return void
*/
private function formatDescription(array &$category)
{
$category['description'] = md5($category['description']);
}
}

View File

@@ -0,0 +1,121 @@
<?php
namespace PrestaShop\Module\PsEventbus\Decorator;
use Context;
use PrestaShop\Module\PsEventbus\Service\SpecificPriceService;
class CustomPriceDecorator
{
/**
* @var Context
*/
private $context;
/**
* @var SpecificPriceService
*/
private $priceService;
public function __construct(
Context $context,
SpecificPriceService $priceService
) {
$this->context = $context;
$this->priceService = $priceService;
}
public function decorateSpecificPrices(array &$specificPrices): void
{
foreach ($specificPrices as &$specificPrice) {
$this->addTotalPrice($specificPrice);
$this->setShopId($specificPrice);
$this->castPropertyValues($specificPrice);
}
}
private function addTotalPrice(array &$specificPrice): void
{
$this->context->country = new \Country($specificPrice['id_country']);
$this->context->currency = new \Currency($specificPrice['id_currency']);
$specificPrice['price_tax_included'] = $this->priceService->getSpecificProductPrice(
$specificPrice['id_product'],
$specificPrice['id_product_attribute'],
$specificPrice['id_specific_price'],
true,
false,
$this->context
);
$specificPrice['price_tax_excluded'] = $this->priceService->getSpecificProductPrice(
$specificPrice['id_product'],
$specificPrice['id_product_attribute'],
$specificPrice['id_specific_price'],
false,
false,
$this->context
);
$specificPrice['sale_price_tax_incl'] = $this->priceService->getSpecificProductPrice(
$specificPrice['id_product'],
$specificPrice['id_product_attribute'],
$specificPrice['id_specific_price'],
true,
true,
$this->context
);
$specificPrice['sale_price_tax_excl'] = $this->priceService->getSpecificProductPrice(
$specificPrice['id_product'],
$specificPrice['id_product_attribute'],
$specificPrice['id_specific_price'],
false,
true,
$this->context
);
}
private function castPropertyValues(array &$specificPrice): void
{
$specificPrice['id_specific_price'] = (int) $specificPrice['id_specific_price'];
$specificPrice['id_product'] = (int) $specificPrice['id_product'];
$specificPrice['id_shop'] = (int) $specificPrice['id_shop'];
$specificPrice['id_group'] = (int) $specificPrice['id_group'];
$specificPrice['id_shop_group'] = (int) $specificPrice['id_shop_group'];
$specificPrice['id_product_attribute'] = (int) $specificPrice['id_product_attribute'];
$specificPrice['price'] = (float) $specificPrice['price'];
$specificPrice['from_quantity'] = (int) $specificPrice['from_quantity'];
$specificPrice['reduction'] = (float) $specificPrice['reduction'];
$specificPrice['reduction_tax'] = (int) $specificPrice['reduction_tax'];
$specificPrice['id_currency'] = (int) $specificPrice['id_currency'];
$specificPrice['id_country'] = (int) $specificPrice['id_country'];
$specificPrice['id_customer'] = (int) $specificPrice['id_customer'];
$specificPrice['currency'] = $specificPrice['currency'] ?: 'ALL';
$specificPrice['country'] = $specificPrice['country'] ?: 'ALL';
$specificPrice['price_tax_included'] = (float) $specificPrice['price_tax_included'];
$specificPrice['price_tax_excluded'] = (float) $specificPrice['price_tax_excluded'];
$specificPrice['sale_price_tax_incl'] = (float) $specificPrice['sale_price_tax_incl'];
$specificPrice['sale_price_tax_excl'] = (float) $specificPrice['sale_price_tax_excl'];
if ($specificPrice['from'] === '0000-00-00 00:00:00') {
unset($specificPrice['from']);
}
if ($specificPrice['to'] === '0000-00-00 00:00:00') {
unset($specificPrice['to']);
}
if ($specificPrice['reduction_type'] === 'percentage') {
$specificPrice['discount_percentage'] = $specificPrice['reduction'] * 100;
$specificPrice['discount_value_tax_incl'] = 0.0;
$specificPrice['discount_value_tax_excl'] = 0.0;
} else {
$specificPrice['discount_percentage'] = 0;
$specificPrice['discount_value_tax_incl'] = $specificPrice['price_tax_included'] - $specificPrice['sale_price_tax_incl'];
$specificPrice['discount_value_tax_excl'] = $specificPrice['price_tax_excluded'] - $specificPrice['sale_price_tax_excl'];
}
}
private function setShopId(array &$specificPrice): void
{
if ($specificPrice['id_shop']) {
$specificPrice['id_shop'] = $this->context->shop->id;
}
}
}

View File

@@ -0,0 +1,48 @@
<?php
namespace PrestaShop\Module\PsEventbus\Decorator;
use PrestaShop\Module\PsEventbus\Formatter\DateFormatter;
class PayloadDecorator
{
/**
* @var DateFormatter
*/
private $dateFormatter;
public function __construct(DateFormatter $dateFormatter)
{
$this->dateFormatter = $dateFormatter;
}
/**
* @param array $payload
*
* @return void
*/
public function convertDateFormat(array &$payload)
{
foreach ($payload as &$payloadItem) {
if (isset($payloadItem['properties']['created_at'])) {
$payloadItem['properties']['created_at'] =
$this->dateFormatter->convertToIso8061($payloadItem['properties']['created_at']);
}
if (isset($payloadItem['properties']['updated_at'])) {
$payloadItem['properties']['updated_at'] =
$this->dateFormatter->convertToIso8061($payloadItem['properties']['updated_at']);
}
if (isset($payloadItem['properties']['from'])) {
$payloadItem['properties']['from'] =
$this->dateFormatter->convertToIso8061($payloadItem['properties']['from']);
}
if (isset($payloadItem['properties']['to'])) {
$payloadItem['properties']['to'] =
$this->dateFormatter->convertToIso8061($payloadItem['properties']['to']);
}
}
}
}

View File

@@ -0,0 +1,354 @@
<?php
namespace PrestaShop\Module\PsEventbus\Decorator;
use Context;
use PrestaShop\Module\PsEventbus\Config\Config;
use PrestaShop\Module\PsEventbus\Formatter\ArrayFormatter;
use PrestaShop\Module\PsEventbus\Repository\BundleRepository;
use PrestaShop\Module\PsEventbus\Repository\CategoryRepository;
use PrestaShop\Module\PsEventbus\Repository\LanguageRepository;
use PrestaShop\Module\PsEventbus\Repository\ProductRepository;
use PrestaShopException;
class ProductDecorator
{
/**
* @var Context
*/
private $context;
/**
* @var LanguageRepository
*/
private $languageRepository;
/**
* @var ProductRepository
*/
private $productRepository;
/**
* @var CategoryRepository
*/
private $categoryRepository;
/**
* @var ArrayFormatter
*/
private $arrayFormatter;
/**
* @var BundleRepository
*/
private $bundleRepository;
public function __construct(
Context $context,
LanguageRepository $languageRepository,
ProductRepository $productRepository,
CategoryRepository $categoryRepository,
ArrayFormatter $arrayFormatter,
BundleRepository $bundleRepository
) {
$this->context = $context;
$this->languageRepository = $languageRepository;
$this->productRepository = $productRepository;
$this->categoryRepository = $categoryRepository;
$this->arrayFormatter = $arrayFormatter;
$this->bundleRepository = $bundleRepository;
}
/**
* @param array $products
* @param string $langIso
* @param int $langId
*
* @throws \PrestaShopDatabaseException
*
* @return void
*/
public function decorateProducts(array &$products, $langIso, $langId)
{
$this->addFeatureValues($products, $langId);
$this->addAttributeValues($products, $langId);
$this->addImages($products);
foreach ($products as &$product) {
$this->addLanguageIsoCode($product, $langIso);
$this->addUniqueId($product);
$this->addAttributeId($product);
$this->addLink($product);
$this->addProductPrices($product);
$this->formatDescriptions($product);
$this->addCategoryTree($product);
$this->castPropertyValues($product);
}
}
/**
* @param array $products
*
* @return array
*/
public function getBundles(array $products)
{
$bundles = [];
foreach ($products as $product) {
if ($product['is_bundle']) {
$bundles = array_merge($bundles, $this->getBundleCollection($product));
}
}
return $bundles;
}
/**
* @param array $product
*
* @return void
*/
private function addLink(array &$product)
{
try {
$product['link'] = $this->context->link->getProductLink(
$product,
null,
null,
null,
$this->languageRepository->getLanguageIdByIsoCode($product['iso_code']),
$this->context->shop->id,
$product['id_attribute']
);
} catch (PrestaShopException $e) {
$product['link'] = '';
}
}
/**
* @param array $product
*
* @return void
*/
private function addProductPrices(array &$product)
{
$product['price_tax_excl'] = (float) $product['price_tax_excl'];
$product['price_tax_incl'] =
(float) $this->productRepository->getPriceTaxIncluded($product['id_product'], $product['id_attribute']);
$product['sale_price_tax_excl'] =
(float) $this->productRepository->getSalePriceTaxExcluded($product['id_product'], $product['id_attribute']);
$product['sale_price_tax_incl'] =
(float) $this->productRepository->getSalePriceTaxIncluded($product['id_product'], $product['id_attribute']);
$product['tax'] = $product['price_tax_incl'] - $product['price_tax_excl'];
$product['sale_tax'] = $product['sale_price_tax_incl'] - $product['sale_price_tax_excl'];
}
private function getBundleCollection(array $product): array
{
$bundleProducts = $this->bundleRepository->getBundleProducts($product['id_product']);
$uniqueProductId = $product['unique_product_id'];
return array_map(function ($bundleProduct) use ($uniqueProductId) {
return [
'id' => $bundleProduct['id_bundle'],
'collection' => Config::COLLECTION_BUNDLES,
'properties' => [
'id_bundle' => $bundleProduct['id_bundle'],
'id_product' => $bundleProduct['id_product'],
'id_product_attribute' => $bundleProduct['id_product_attribute'],
'unique_product_id' => $uniqueProductId,
'quantity' => $bundleProduct['quantity'],
],
];
}, $bundleProducts);
}
/**
* @param array $product
*
* @return void
*/
private function formatDescriptions(array &$product)
{
$product['description'] = base64_encode($product['description']);
$product['description_short'] = base64_encode($product['description_short']);
}
/**
* @param array $product
*
* @return void
*/
private function addCategoryTree(array &$product)
{
/** @var int $shopId */
$shopId = $this->context->shop->id;
$categoryPaths = $this->categoryRepository->getCategoryPaths(
$product['id_category_default'],
$this->languageRepository->getLanguageIdByIsoCode($product['iso_code']),
$shopId
);
$product['category_path'] = $categoryPaths['category_path'];
$product['category_id_path'] = $categoryPaths['category_id_path'];
}
/**
* @param array $product
*
* @return void
*/
private function castPropertyValues(array &$product)
{
$product['id_product'] = (int) $product['id_product'];
$product['id_attribute'] = (int) $product['id_attribute'];
$product['id_category_default'] = (int) $product['id_category_default'];
$product['quantity'] = (int) $product['quantity'];
$product['weight'] = (float) $product['weight'];
$product['active'] = $product['active'] == '1';
$product['manufacturer'] = (string) $product['manufacturer'];
$product['default_category'] = (string) $product['default_category'];
$product['isbn'] = isset($product['isbn']) ? (string) $product['isbn'] : '';
$product['mpn'] = isset($product['mpn']) ? (string) $product['mpn'] : '';
$product['ean'] = (string) $product['ean'];
$product['upc'] = (string) $product['upc'];
$product['is_default_attribute'] = $product['id_attribute'] === 0 ? true : $product['is_default_attribute'] == 1;
$product['available_for_order'] = $product['available_for_order'] == '1';
$product['available_date'] = (string) $product['available_date'];
$product['is_bundle'] = $product['is_bundle'] == '1';
$product['is_virtual'] = $product['is_virtual'] == '1';
if ($product['unit_price_ratio'] == 0) {
unset($product['unit_price_ratio']);
unset($product['unity']);
} else {
$product['unit_price_ratio'] = (float) $product['unit_price_ratio'];
$product['unity'] = (string) $product['unity'];
$product['price_per_unit'] = (float) ($product['price_tax_excl'] / $product['unit_price_ratio']);
}
}
/**
* @param array $product
*
* @return void
*/
private function addUniqueId(array &$product)
{
$product['unique_product_id'] = "{$product['id_product']}-{$product['id_attribute']}-{$product['iso_code']}";
}
/**
* @param array $product
*
* @return void
*/
private function addAttributeId(array &$product)
{
$product['id_product_attribute'] = "{$product['id_product']}-{$product['id_attribute']}";
}
/**
* @param array $product
* @param string $langiso
*
* @return void
*/
private function addLanguageIsoCode(&$product, $langiso)
{
$product['iso_code'] = $langiso;
}
/**
* @param array $products
* @param int $langId
*
* @throws \PrestaShopDatabaseException
*
* @return void
*/
private function addFeatureValues(array &$products, $langId)
{
$productIds = $this->arrayFormatter->formatValueArray($products, 'id_product', true);
$features = $this->productRepository->getProductFeatures($productIds, $langId);
foreach ($products as &$product) {
$product['features'] = isset($features[$product['id_product']]) ? $features[$product['id_product']] : '';
}
}
/**
* @param array $products
* @param int $langId
*
* @throws \PrestaShopDatabaseException
*
* @return void
*/
private function addAttributeValues(array &$products, $langId)
{
$attributeIds = $this->arrayFormatter->formatValueArray($products, 'id_attribute', true);
$attributes = $this->productRepository->getProductAttributeValues($attributeIds, $langId);
foreach ($products as &$product) {
$product['attributes'] = isset($attributes[$product['id_attribute']]) ? $attributes[$product['id_attribute']] : '';
}
}
/**
* @param array $products
*
* @throws \PrestaShopDatabaseException
*
* @return void
*/
private function addImages(array &$products)
{
$productIds = $this->arrayFormatter->formatValueArray($products, 'id_product', true);
$attributeIds = $this->arrayFormatter->formatValueArray($products, 'id_attribute', true);
$images = $this->productRepository->getProductImages($productIds);
$attributeImages = $this->productRepository->getAttributeImages($attributeIds);
foreach ($products as &$product) {
$coverImageId = '0';
$productImages = array_filter($images, function ($image) use ($product) {
return $image['id_product'] === $product['id_product'];
});
foreach ($productImages as $productImage) {
if ($productImage['cover'] == 1) {
$coverImageId = $productImage['id_image'];
break;
}
}
// Product is without attributes -> get product images
if ($product['id_attribute'] == 0) {
$productImageIds = $this->arrayFormatter->formatValueArray($productImages, 'id_image');
} else {
$productAttributeImages = array_filter($attributeImages, function ($image) use ($product) {
return $image['id_product_attribute'] === $product['id_attribute'];
});
// If combination has some pictures -> the first one is the cover
if (count($productAttributeImages)) {
$productImageIds = $this->arrayFormatter->formatValueArray($productAttributeImages, 'id_image');
$coverImageId = reset($productImageIds);
}
// Fallback on cover & images of the product when no pictures are chosen
else {
$productImageIds = $this->arrayFormatter->formatValueArray($productImages, 'id_image');
}
}
$productImageIds = array_diff($productImageIds, [$coverImageId]);
$product['images'] = $this->arrayFormatter->arrayToString(
array_map(function ($imageId) use ($product) {
return $this->context->link->getImageLink($product['link_rewrite'], (string) $imageId);
}, $productImageIds)
);
$product['cover'] = $coverImageId == '0' ?
'' :
$this->context->link->getImageLink($product['link_rewrite'], (string) $coverImageId);
}
}
}

View File

@@ -0,0 +1,34 @@
<?php
/**
* 2007-2020 PrestaShop.
*
* NOTICE OF LICENSE
*
* This source file is subject to the Academic Free License (AFL 3.0)
* that is bundled with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://opensource.org/licenses/afl-3.0.php
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@prestashop.com so we can send you a copy immediately.
*
* DISCLAIMER
*
* Do not edit or add to this file if you wish to upgrade PrestaShop to newer
* versions in the future. If you wish to customize PrestaShop for your
* needs please refer to http://www.prestashop.com for more information.
*
* @author PrestaShop SA <contact@prestashop.com>
* @copyright 2007-2020 PrestaShop SA
* @license http://opensource.org/licenses/afl-3.0.php Academic Free License (AFL 3.0)
* International Registered Trademark & Property of PrestaShop SA
*/
header('Expires: Mon, 26 Jul 1997 05:00:00 GMT');
header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT');
header('Cache-Control: no-store, no-cache, must-revalidate');
header('Cache-Control: post-check=0, pre-check=0', false);
header('Pragma: no-cache');
header('Location: ../');
exit;

View File

@@ -0,0 +1,11 @@
drwxr-xr-x 2 30094 users 11 Oct 6 10:16 .
drwxr-xr-x 15 30094 users 16 Oct 6 10:16 ..
-rw-r--r-- 1 30094 users 882 Oct 14 2021 ApiException.php
-rw-r--r-- 1 30094 users 885 Oct 14 2021 EnvVarException.php
-rw-r--r-- 1 30094 users 887 Oct 14 2021 FirebaseException.php
-rw-r--r-- 1 30094 users 883 Oct 14 2021 HmacException.php
-rw-r--r-- 1 30094 users 905 Oct 14 2021 PsAccountsRsaSignDataEmptyException.php
-rw-r--r-- 1 30094 users 890 Oct 14 2021 QueryParamsException.php
-rw-r--r-- 1 30094 users 109 Oct 14 2021 UnauthorizedException.php
-rw-r--r-- 1 30094 users 886 Oct 14 2021 WebhookException.php
-rw-r--r-- 1 30094 users 1083 Oct 14 2021 index.php

View File

@@ -0,0 +1,25 @@
<?php
/**
* 2007-2020 PrestaShop and Contributors
*
* NOTICE OF LICENSE
*
* This source file is subject to the Academic Free License 3.0 (AFL-3.0)
* that is bundled with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* https://opensource.org/licenses/AFL-3.0
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@prestashop.com so we can send you a copy immediately.
*
* @author PrestaShop SA <contact@prestashop.com>
* @copyright 2007-2020 PrestaShop SA and Contributors
* @license https://opensource.org/licenses/AFL-3.0 Academic Free License 3.0 (AFL-3.0)
* International Registered Trademark & Property of PrestaShop SA
*/
namespace PrestaShop\Module\PsEventbus\Exception;
class ApiException extends \Exception
{
}

View File

@@ -0,0 +1,25 @@
<?php
/**
* 2007-2020 PrestaShop and Contributors
*
* NOTICE OF LICENSE
*
* This source file is subject to the Academic Free License 3.0 (AFL-3.0)
* that is bundled with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* https://opensource.org/licenses/AFL-3.0
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@prestashop.com so we can send you a copy immediately.
*
* @author PrestaShop SA <contact@prestashop.com>
* @copyright 2007-2020 PrestaShop SA and Contributors
* @license https://opensource.org/licenses/AFL-3.0 Academic Free License 3.0 (AFL-3.0)
* International Registered Trademark & Property of PrestaShop SA
*/
namespace PrestaShop\Module\PsEventbus\Exception;
class EnvVarException extends \Exception
{
}

View File

@@ -0,0 +1,25 @@
<?php
/**
* 2007-2020 PrestaShop and Contributors
*
* NOTICE OF LICENSE
*
* This source file is subject to the Academic Free License 3.0 (AFL-3.0)
* that is bundled with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* https://opensource.org/licenses/AFL-3.0
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@prestashop.com so we can send you a copy immediately.
*
* @author PrestaShop SA <contact@prestashop.com>
* @copyright 2007-2020 PrestaShop SA and Contributors
* @license https://opensource.org/licenses/AFL-3.0 Academic Free License 3.0 (AFL-3.0)
* International Registered Trademark & Property of PrestaShop SA
*/
namespace PrestaShop\Module\PsEventbus\Exception;
class FirebaseException extends \Exception
{
}

View File

@@ -0,0 +1,25 @@
<?php
/**
* 2007-2020 PrestaShop and Contributors
*
* NOTICE OF LICENSE
*
* This source file is subject to the Academic Free License 3.0 (AFL-3.0)
* that is bundled with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* https://opensource.org/licenses/AFL-3.0
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@prestashop.com so we can send you a copy immediately.
*
* @author PrestaShop SA <contact@prestashop.com>
* @copyright 2007-2020 PrestaShop SA and Contributors
* @license https://opensource.org/licenses/AFL-3.0 Academic Free License 3.0 (AFL-3.0)
* International Registered Trademark & Property of PrestaShop SA
*/
namespace PrestaShop\Module\PsEventbus\Exception;
class HmacException extends \Exception
{
}

View File

@@ -0,0 +1,25 @@
<?php
/**
* 2007-2020 PrestaShop and Contributors
*
* NOTICE OF LICENSE
*
* This source file is subject to the Academic Free License 3.0 (AFL-3.0)
* that is bundled with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* https://opensource.org/licenses/AFL-3.0
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@prestashop.com so we can send you a copy immediately.
*
* @author PrestaShop SA <contact@prestashop.com>
* @copyright 2007-2020 PrestaShop SA and Contributors
* @license https://opensource.org/licenses/AFL-3.0 Academic Free License 3.0 (AFL-3.0)
* International Registered Trademark & Property of PrestaShop SA
*/
namespace PrestaShop\Module\PsEventbus\Exception;
class PsAccountsRsaSignDataEmptyException extends \Exception
{
}

View File

@@ -0,0 +1,25 @@
<?php
/**
* 2007-2020 PrestaShop and Contributors
*
* NOTICE OF LICENSE
*
* This source file is subject to the Academic Free License 3.0 (AFL-3.0)
* that is bundled with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* https://opensource.org/licenses/AFL-3.0
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@prestashop.com so we can send you a copy immediately.
*
* @author PrestaShop SA <contact@prestashop.com>
* @copyright 2007-2020 PrestaShop SA and Contributors
* @license https://opensource.org/licenses/AFL-3.0 Academic Free License 3.0 (AFL-3.0)
* International Registered Trademark & Property of PrestaShop SA
*/
namespace PrestaShop\Module\PsEventbus\Exception;
class QueryParamsException extends \Exception
{
}

View File

@@ -0,0 +1,7 @@
<?php
namespace PrestaShop\Module\PsEventbus\Exception;
class UnauthorizedException extends \Exception
{
}

View File

@@ -0,0 +1,25 @@
<?php
/**
* 2007-2020 PrestaShop and Contributors
*
* NOTICE OF LICENSE
*
* This source file is subject to the Academic Free License 3.0 (AFL-3.0)
* that is bundled with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* https://opensource.org/licenses/AFL-3.0
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@prestashop.com so we can send you a copy immediately.
*
* @author PrestaShop SA <contact@prestashop.com>
* @copyright 2007-2020 PrestaShop SA and Contributors
* @license https://opensource.org/licenses/AFL-3.0 Academic Free License 3.0 (AFL-3.0)
* International Registered Trademark & Property of PrestaShop SA
*/
namespace PrestaShop\Module\PsEventbus\Exception;
class WebhookException extends \Exception
{
}

View File

@@ -0,0 +1,28 @@
<?php
/**
* 2007-2020 PrestaShop and Contributors
*
* NOTICE OF LICENSE
*
* This source file is subject to the Academic Free License 3.0 (AFL-3.0)
* that is bundled with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* https://opensource.org/licenses/AFL-3.0
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@prestashop.com so we can send you a copy immediately.
*
* @author PrestaShop SA <contact@prestashop.com>
* @copyright 2007-2020 PrestaShop SA and Contributors
* @license https://opensource.org/licenses/AFL-3.0 Academic Free License 3.0 (AFL-3.0)
* International Registered Trademark & Property of PrestaShop SA
*/
header('Expires: Mon, 26 Jul 1997 05:00:00 GMT');
header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT');
header('Cache-Control: no-store, no-cache, must-revalidate');
header('Cache-Control: post-check=0, pre-check=0', false);
header('Pragma: no-cache');
header('Location: ../');
exit;

View File

@@ -0,0 +1,5 @@
drwxr-xr-x 2 30094 users 5 Oct 6 10:16 .
drwxr-xr-x 15 30094 users 16 Oct 6 10:16 ..
-rw-r--r-- 1 30094 users 879 Oct 14 2021 ContextFactory.php
-rw-r--r-- 1 30094 users 211 Oct 14 2021 Link.php
-rw-r--r-- 1 30094 users 1083 Oct 14 2021 index.php

View File

@@ -0,0 +1,72 @@
<?php
namespace PrestaShop\Module\PsEventbus\Factory;
use Context;
class ContextFactory
{
/**
* @return Context|null
*/
public static function getContext()
{
return Context::getContext();
}
/**
* @return \Language|\PrestaShopBundle\Install\Language
*/
public static function getLanguage()
{
return Context::getContext()->language;
}
/**
* @return \Currency|null
*/
public static function getCurrency()
{
return Context::getContext()->currency;
}
/**
* @return \Smarty
*/
public static function getSmarty()
{
return Context::getContext()->smarty;
}
/**
* @return \Shop
*/
public static function getShop()
{
return Context::getContext()->shop;
}
/**
* @return \AdminController|\FrontController
*/
public static function getController()
{
return Context::getContext()->controller;
}
/**
* @return \Cookie
*/
public static function getCookie()
{
return Context::getContext()->cookie;
}
/**
* @return \Link
*/
public static function getLink()
{
return Context::getContext()->link;
}
}

View File

@@ -0,0 +1,16 @@
<?php
namespace PrestaShop\Module\PsEventbus\Factory;
use Context;
class Link
{
/**
* @return \Link
*/
public static function get()
{
return Context::getContext()->link;
}
}

View File

@@ -0,0 +1,28 @@
<?php
/**
* 2007-2020 PrestaShop and Contributors
*
* NOTICE OF LICENSE
*
* This source file is subject to the Academic Free License 3.0 (AFL-3.0)
* that is bundled with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* https://opensource.org/licenses/AFL-3.0
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@prestashop.com so we can send you a copy immediately.
*
* @author PrestaShop SA <contact@prestashop.com>
* @copyright 2007-2020 PrestaShop SA and Contributors
* @license https://opensource.org/licenses/AFL-3.0 Academic Free License 3.0 (AFL-3.0)
* International Registered Trademark & Property of PrestaShop SA
*/
header('Expires: Mon, 26 Jul 1997 05:00:00 GMT');
header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT');
header('Cache-Control: no-store, no-cache, must-revalidate');
header('Cache-Control: post-check=0, pre-check=0', false);
header('Pragma: no-cache');
header('Location: ../');
exit;

View File

@@ -0,0 +1,6 @@
drwxr-xr-x 2 30094 users 6 Oct 6 10:16 .
drwxr-xr-x 15 30094 users 16 Oct 6 10:16 ..
-rw-r--r-- 1 30094 users 1193 Oct 14 2021 ArrayFormatter.php
-rw-r--r-- 1 30094 users 392 Oct 14 2021 DateFormatter.php
-rw-r--r-- 1 30094 users 401 Oct 14 2021 JsonFormatter.php
-rw-r--r-- 1 30094 users 1083 Oct 14 2021 index.php

View File

@@ -0,0 +1,59 @@
<?php
namespace PrestaShop\Module\PsEventbus\Formatter;
class ArrayFormatter
{
/**
* @param array $data
* @param string $separator
*
* @return string
*/
public function arrayToString(array $data, $separator = ';')
{
return implode($separator, $data);
}
/**
* @param array $data
* @param string|int $key
* @param bool $unique
*
* @return array
*/
public function formatValueArray(array $data, $key, $unique = false)
{
$result = array_map(function ($dataItem) use ($key) {
return $dataItem[$key];
}, $data);
if ($unique) {
return $this->unique($result);
}
return $result;
}
/**
* @param array $data
*
* @return array
*/
private function unique(array $data)
{
return array_unique($data);
}
/**
* @param array $data
* @param string|int $key
* @param string $separator
*
* @return string
*/
public function formatValueString(array $data, $key, $separator = ';')
{
return implode($separator, $this->formatValueArray($data, $key));
}
}

View File

@@ -0,0 +1,23 @@
<?php
namespace PrestaShop\Module\PsEventbus\Formatter;
use DateTime;
use Exception;
class DateFormatter
{
/**
* @param string $date
*
* @return string
*/
public function convertToIso8061($date)
{
try {
return (new DateTime($date))->format(DateTime::ISO8601);
} catch (Exception $e) {
return $date;
}
}
}

View File

@@ -0,0 +1,22 @@
<?php
namespace PrestaShop\Module\PsEventbus\Formatter;
class JsonFormatter
{
/**
* @param array $data
*
* @return string
*/
public function formatNewlineJsonString($data)
{
$jsonArray = array_map(function ($dataItem) {
return json_encode($dataItem, JSON_UNESCAPED_SLASHES);
}, $data);
$json = implode("\r\n", $jsonArray);
return str_replace('\\u0000', '', $json);
}
}

View File

@@ -0,0 +1,28 @@
<?php
/**
* 2007-2020 PrestaShop and Contributors
*
* NOTICE OF LICENSE
*
* This source file is subject to the Academic Free License 3.0 (AFL-3.0)
* that is bundled with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* https://opensource.org/licenses/AFL-3.0
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@prestashop.com so we can send you a copy immediately.
*
* @author PrestaShop SA <contact@prestashop.com>
* @copyright 2007-2020 PrestaShop SA and Contributors
* @license https://opensource.org/licenses/AFL-3.0 Academic Free License 3.0 (AFL-3.0)
* International Registered Trademark & Property of PrestaShop SA
*/
header('Expires: Mon, 26 Jul 1997 05:00:00 GMT');
header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT');
header('Cache-Control: no-store, no-cache, must-revalidate');
header('Cache-Control: post-check=0, pre-check=0', false);
header('Pragma: no-cache');
header('Location: ../');
exit;

View File

@@ -0,0 +1,94 @@
<?php
/**
* Copyright since 2007 PrestaShop SA and Contributors
* PrestaShop is an International Registered Trademark & Property of PrestaShop SA
*
* NOTICE OF LICENSE
*
* This source file is subject to the Academic Free License version 3.0
* that is bundled with this package in the file LICENSE.md.
* It is also available through the world-wide-web at this URL:
* https://opensource.org/licenses/AFL-3.0
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@prestashop.com so we can send you a copy immediately.
*
* @author PrestaShop SA and Contributors <contact@prestashop.com>
* @copyright Since 2007 PrestaShop SA and Contributors
* @license https://opensource.org/licenses/AFL-3.0 Academic Free License version 3.0
*/
namespace PrestaShop\Module\PsEventbus\Handler\ErrorHandler;
use Configuration;
use Exception;
use Module;
use PrestaShop\PsAccountsInstaller\Installer\Facade\PsAccounts;
use Raven_Client;
/**
* Handle Error.
*/
class ErrorHandler implements ErrorHandlerInterface
{
/**
* @var ?Raven_Client
*/
protected $client;
public function __construct(Module $module, PsAccounts $accountsService, string $sentryDsn, string $sentryEnv)
{
$psAccounts = Module::getInstanceByName('ps_accounts');
try {
$this->client = new Raven_Client(
$sentryDsn,
[
'level' => 'warning',
'tags' => [
'shop_id' => $accountsService->getPsAccountsService()->getShopUuid(),
'ps_eventbus_version' => $module->version,
'ps_accounts_version' => $psAccounts ? $psAccounts->version : false,
'php_version' => phpversion(),
'prestashop_version' => _PS_VERSION_,
'ps_eventbus_is_enabled' => Module::isEnabled($module->name),
'ps_eventbus_is_installed' => Module::isInstalled($module->name),
'env' => $sentryEnv,
],
]
);
/** @var string $configurationPsShopEmail */
$configurationPsShopEmail = Configuration::get('PS_SHOP_EMAIL');
$this->client->set_user_data($accountsService->getPsAccountsService()->getShopUuid(), $configurationPsShopEmail);
} catch (Exception $e) {
}
}
/**
* @param Exception $error
* @param mixed $code
* @param bool|null $throw
* @param array|null $data
*
* @return void
*
* @throws Exception
*/
public function handle($error, $code = null, $throw = true, $data = null)
{
if (!$this->client) {
return;
}
$this->client->captureException($error, $data);
if (is_int($code) && true === $throw) {
http_response_code($code);
throw $error;
}
}
/**
* @return void
*/
private function __clone()
{
}
}

View File

@@ -0,0 +1,18 @@
<?php
namespace PrestaShop\Module\PsEventbus\Handler\ErrorHandler;
use Exception;
interface ErrorHandlerInterface
{
/**
* @param Exception $error
* @param mixed $code
* @param bool|null $throw
* @param array|null $data
*
* @return void
*/
public function handle($error, $code = null, $throw = true, $data = null);
}

View File

@@ -0,0 +1,34 @@
<?php
/**
* 2007-2020 PrestaShop.
*
* NOTICE OF LICENSE
*
* This source file is subject to the Academic Free License (AFL 3.0)
* that is bundled with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://opensource.org/licenses/afl-3.0.php
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@prestashop.com so we can send you a copy immediately.
*
* DISCLAIMER
*
* Do not edit or add to this file if you wish to upgrade PrestaShop to newer
* versions in the future. If you wish to customize PrestaShop for your
* needs please refer to http://www.prestashop.com for more information.
*
* @author PrestaShop SA <contact@prestashop.com>
* @copyright 2007-2020 PrestaShop SA
* @license http://opensource.org/licenses/afl-3.0.php Academic Free License (AFL 3.0)
* International Registered Trademark & Property of PrestaShop SA
*/
header('Expires: Mon, 26 Jul 1997 05:00:00 GMT');
header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT');
header('Cache-Control: no-store, no-cache, must-revalidate');
header('Cache-Control: post-check=0, pre-check=0', false);
header('Pragma: no-cache');
header('Location: ../');
exit;

View File

@@ -0,0 +1,5 @@
drwxr-xr-x 2 30094 users 5 Oct 6 10:16 .
drwxr-xr-x 15 30094 users 16 Oct 6 10:16 ..
-rw-r--r-- 1 30094 users 3659 Oct 14 2021 Install.php
-rw-r--r-- 1 30094 users 2388 Oct 14 2021 Uninstall.php
-rw-r--r-- 1 30094 users 1084 Oct 14 2021 index.php

View File

@@ -0,0 +1,143 @@
<?php
/**
* 2007-2020 PrestaShop and Contributors.
*
* NOTICE OF LICENSE
*
* This source file is subject to the Academic Free License 3.0 (AFL-3.0)
* that is bundled with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* https://opensource.org/licenses/AFL-3.0
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@prestashop.com so we can send you a copy immediately.
*
* @author PrestaShop SA <contact@prestashop.com>
* @copyright 2007-2020 PrestaShop SA and Contributors
* @license https://opensource.org/licenses/AFL-3.0 Academic Free License 3.0 (AFL-3.0)
* International Registered Trademark & Property of PrestaShop SA
*/
namespace PrestaShop\Module\PsEventbus\Module;
use Tools;
class Install
{
public const PARENT_TAB_NAME = -1;
public const TAB_ACTIVE = 0;
/**
* @var \Ps_eventbus
*/
private $module;
/**
* @var \Db
*/
private $db;
public function __construct(\Ps_eventbus $module, \Db $db)
{
$this->module = $module;
$this->db = $db;
}
/**
* installInMenu.
*
* @return bool
*/
public function installInMenu()
{
foreach ($this->module->adminControllers as $controllerName) {
$tabId = (int) \Tab::getIdFromClassName($controllerName);
if (!$tabId) {
$tabId = null;
}
$tab = new \Tab($tabId);
$tab->active = (bool) self::TAB_ACTIVE;
$tab->class_name = $controllerName;
$tab->name = [];
foreach (\Language::getLanguages(true) as $lang) {
if (is_array($lang)) {
$tab->name[$lang['id_lang']] = $this->module->displayName;
}
}
$tab->id_parent = (int) \Tab::getIdFromClassName((string) self::PARENT_TAB_NAME);
$tab->module = $this->module->name;
$tab->save();
}
return true;
}
/**
* Installs database tables
*
* @return bool
*/
public function installDatabaseTables()
{
$dbInstallFile = "{$this->module->getLocalPath()}/sql/install.sql";
if (!file_exists($dbInstallFile)) {
return false;
}
$sql = Tools::file_get_contents($dbInstallFile);
if (empty($sql) || !is_string($sql)) {
return false;
}
$sql = str_replace(['PREFIX_', 'ENGINE_TYPE'], [_DB_PREFIX_, _MYSQL_ENGINE_], $sql);
$sql = preg_split("/;\s*[\r\n]+/", trim($sql));
if (!empty($sql)) {
foreach ($sql as $query) {
if (!$this->db->execute($query)) {
return false;
}
}
}
$this->copyDataFromPsAccounts();
return true;
}
/**
* @return void
*/
private function copyDataFromPsAccounts()
{
$dbInstallFile = "{$this->module->getLocalPath()}/sql/migrate.sql";
if (!file_exists($dbInstallFile)) {
return;
}
$sql = Tools::file_get_contents($dbInstallFile);
if (empty($sql) || !is_string($sql)) {
return;
}
$sql = str_replace(['PREFIX_', 'ENGINE_TYPE'], [_DB_PREFIX_, _MYSQL_ENGINE_], $sql);
$sql = preg_split("/;\s*[\r\n]+/", trim($sql));
if (!empty($sql)) {
foreach ($sql as $query) {
try {
$this->db->execute($query);
} catch (\Exception $exception) {
}
}
}
}
}

View File

@@ -0,0 +1,95 @@
<?php
/**
* 2007-2020 PrestaShop and Contributors.
*
* NOTICE OF LICENSE
*
* This source file is subject to the Academic Free License 3.0 (AFL-3.0)
* that is bundled with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* https://opensource.org/licenses/AFL-3.0
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@prestashop.com so we can send you a copy immediately.
*
* @author PrestaShop SA <contact@prestashop.com>
* @copyright 2007-2020 PrestaShop SA and Contributors
* @license https://opensource.org/licenses/AFL-3.0 Academic Free License 3.0 (AFL-3.0)
* International Registered Trademark & Property of PrestaShop SA
*/
namespace PrestaShop\Module\PsEventbus\Module;
use Tools;
class Uninstall
{
/**
* @var \Ps_eventbus
*/
private $module;
/**
* @var \Db
*/
private $db;
public function __construct(\Ps_eventbus $module, \Db $db)
{
$this->module = $module;
$this->db = $db;
}
/**
* uninstallMenu.
*
* @return bool
*/
public function uninstallMenu()
{
// foreach( ['configure', 'hmac', 'ajax'] as $aliasController){
foreach ($this->module->adminControllers as $controllerName) {
$tabId = (int) \Tab::getIdFromClassName($controllerName);
if (!$tabId) {
return true;
}
$tab = new \Tab($tabId);
return $tab->delete();
}
return true;
}
/**
* @return bool
*/
public function uninstallDatabaseTables()
{
$dbUninstallFile = "{$this->module->getLocalPath()}/sql/uninstall.sql";
if (!file_exists($dbUninstallFile)) {
return false;
}
$sql = Tools::file_get_contents($dbUninstallFile);
if (empty($sql) || !is_string($sql)) {
return false;
}
$sql = str_replace(['PREFIX_', 'ENGINE_TYPE'], [_DB_PREFIX_, _MYSQL_ENGINE_], $sql);
$sql = preg_split("/;\s*[\r\n]+/", trim($sql));
if (!empty($sql)) {
foreach ($sql as $query) {
if (!$this->db->execute($query)) {
return false;
}
}
}
return true;
}
}

View File

@@ -0,0 +1,28 @@
<?php
/**
* 2007-2020 PrestaShop and Contributors.
*
* NOTICE OF LICENSE
*
* This source file is subject to the Academic Free License 3.0 (AFL-3.0)
* that is bundled with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* https://opensource.org/licenses/AFL-3.0
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@prestashop.com so we can send you a copy immediately.
*
* @author PrestaShop SA <contact@prestashop.com>
* @copyright 2007-2020 PrestaShop SA and Contributors
* @license https://opensource.org/licenses/AFL-3.0 Academic Free License 3.0 (AFL-3.0)
* International Registered Trademark & Property of PrestaShop SA
*/
header('Expires: Mon, 26 Jul 1997 05:00:00 GMT');
header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT');
header('Cache-Control: no-store, no-cache, must-revalidate');
header('Cache-Control: post-check=0, pre-check=0', false);
header('Pragma: no-cache');
header('Location: ../');
exit;

View File

@@ -0,0 +1,11 @@
drwxr-xr-x 2 30094 users 11 Oct 6 10:16 .
drwxr-xr-x 15 30094 users 16 Oct 6 10:16 ..
-rw-r--r-- 1 30094 users 2737 Oct 14 2021 CarrierDataProvider.php
-rw-r--r-- 1 30094 users 4589 Oct 14 2021 CartDataProvider.php
-rw-r--r-- 1 30094 users 2691 Oct 14 2021 CategoryDataProvider.php
-rw-r--r-- 1 30094 users 1550 Oct 14 2021 GoogleTaxonomyDataProvider.php
-rw-r--r-- 1 30094 users 1582 Oct 14 2021 ModuleDataProvider.php
-rw-r--r-- 1 30094 users 6422 Oct 14 2021 OrderDataProvider.php
-rw-r--r-- 1 30094 users 853 Oct 14 2021 PaginatedApiDataProviderInterface.php
-rw-r--r-- 1 30094 users 3139 Oct 14 2021 ProductDataProvider.php
-rw-r--r-- 1 30094 users 1273 Oct 14 2021 index.php

View File

@@ -0,0 +1,120 @@
<?php
namespace PrestaShop\Module\PsEventbus\Provider;
use Currency;
use Language;
use PrestaShop\Module\PsEventbus\Builder\CarrierBuilder;
use PrestaShop\Module\PsEventbus\Config\Config;
use PrestaShop\Module\PsEventbus\DTO\Carrier as EventBusCarrier;
use PrestaShop\Module\PsEventbus\Repository\CarrierRepository;
use PrestaShop\Module\PsEventbus\Repository\ConfigurationRepository;
use PrestaShop\Module\PsEventbus\Repository\LanguageRepository;
class CarrierDataProvider implements PaginatedApiDataProviderInterface
{
/**
* @var ConfigurationRepository
*/
private $configurationRepository;
/**
* @var CarrierBuilder
*/
private $carrierBuilder;
/**
* @var CarrierRepository
*/
private $carrierRepository;
/**
* @var LanguageRepository
*/
private $languageRepository;
public function __construct(
ConfigurationRepository $configurationRepository,
CarrierBuilder $carrierBuilder,
CarrierRepository $carrierRepository,
LanguageRepository $languageRepository
) {
$this->configurationRepository = $configurationRepository;
$this->carrierBuilder = $carrierBuilder;
$this->carrierRepository = $carrierRepository;
$this->languageRepository = $languageRepository;
}
/**
* @param int $offset
* @param int $limit
* @param string $langIso
*
* @return array
*
* @throws \PrestaShopDatabaseException
*/
public function getFormattedData($offset, $limit, $langIso)
{
$language = new Language();
$currency = new Currency();
/** @var array $carriers */
$carriers = $this->carrierRepository->getAllCarrierProperties($offset, $limit, $language->id);
/** @var string $configurationPsWeightUnit */
$configurationPsWeightUnit = $this->configurationRepository->get('PS_WEIGHT_UNIT');
/** @var EventBusCarrier[] $eventBusCarriers */
$eventBusCarriers = $this->carrierBuilder->buildCarriers(
$carriers,
$language,
$currency,
$configurationPsWeightUnit
);
return $eventBusCarriers;
}
public function getFormattedDataIncremental($limit, $langIso, $objectIds)
{
/** @var array $shippingIncremental */
$shippingIncremental = $this->carrierRepository->getShippingIncremental(Config::COLLECTION_CARRIERS, $langIso);
if (!$shippingIncremental) {
return [];
}
$language = new Language();
$currency = new Currency();
$carrierIds = array_column($shippingIncremental, 'id_object');
/** @var array $carriers */
$carriers = $this->carrierRepository->getCarrierProperties($carrierIds, $language->id);
/** @var string $configurationPsWeightUnit */
$configurationPsWeightUnit = $this->configurationRepository->get('PS_WEIGHT_UNIT');
/** @var EventBusCarrier[] $eventBusCarriers */
$eventBusCarriers = $this->carrierBuilder->buildCarriers(
$carriers,
$language,
$currency,
$configurationPsWeightUnit
);
return $eventBusCarriers;
}
/**
* @param int $offset
* @param string $langIso
*
* @return int
*
* @throws \PrestaShopDatabaseException
*/
public function getRemainingObjectsCount($offset, $langIso)
{
$langId = $this->languageRepository->getLanguageIdByIsoCode($langIso);
return (int) $this->carrierRepository->getRemainingCarriersCount($offset, $langId);
}
}

View File

@@ -0,0 +1,159 @@
<?php
namespace PrestaShop\Module\PsEventbus\Provider;
use PrestaShop\Module\PsEventbus\Config\Config;
use PrestaShop\Module\PsEventbus\Repository\CartProductRepository;
use PrestaShop\Module\PsEventbus\Repository\CartRepository;
class CartDataProvider implements PaginatedApiDataProviderInterface
{
/**
* @var CartRepository
*/
private $cartRepository;
/**
* @var CartProductRepository
*/
private $cartProductRepository;
/**
* @param CartRepository $cartRepository
* @param CartProductRepository $cartProductRepository
*/
public function __construct(
CartRepository $cartRepository,
CartProductRepository $cartProductRepository
) {
$this->cartRepository = $cartRepository;
$this->cartProductRepository = $cartProductRepository;
}
public function getFormattedData($offset, $limit, $langIso)
{
$carts = $this->cartRepository->getCarts($offset, $limit);
if (!is_array($carts)) {
return [];
}
$cartProducts = $this->getCartProducts($carts);
$this->castCartValues($carts);
$carts = array_map(function ($cart) {
return [
'id' => $cart['id_cart'],
'collection' => Config::COLLECTION_CARTS,
'properties' => $cart,
];
}, $carts);
return array_merge($carts, $cartProducts);
}
/**
* @param int $offset
* @param string $langIso
*
* @return int
*/
public function getRemainingObjectsCount($offset, $langIso)
{
return (int) $this->cartRepository->getRemainingCartsCount($offset);
}
/**
* @param array $carts
*
* @return void
*/
private function castCartValues(array &$carts)
{
foreach ($carts as &$cart) {
$cart['id_cart'] = (string) $cart['id_cart'];
}
}
/**
* @param array $cartProducts
*
* @return void
*/
private function castCartProductValues(array &$cartProducts)
{
foreach ($cartProducts as &$cartProduct) {
$cartProduct['id_cart_product'] = (string) "{$cartProduct['id_cart']}-{$cartProduct['id_product']}-{$cartProduct['id_product_attribute']}";
$cartProduct['id_cart'] = (string) $cartProduct['id_cart'];
$cartProduct['id_product'] = (string) $cartProduct['id_product'];
$cartProduct['id_product_attribute'] = (string) $cartProduct['id_product_attribute'];
$cartProduct['quantity'] = (int) $cartProduct['quantity'];
}
}
/**
* @param int $limit
* @param string $langIso
* @param array $objectIds
*
* @return array
*
* @throws \PrestaShopDatabaseException
*/
public function getFormattedDataIncremental($limit, $langIso, $objectIds)
{
$carts = $this->cartRepository->getCartsIncremental($limit, $objectIds);
if (!is_array($carts) || empty($carts)) {
return [];
}
$cartProducts = $this->getCartProducts($carts);
$this->castCartValues($carts);
$carts = array_map(function ($cart) {
return [
'id' => $cart['id_cart'],
'collection' => Config::COLLECTION_CARTS,
'properties' => $cart,
];
}, $carts);
return array_merge($carts, $cartProducts);
}
/**
* @param array $carts
*
* @return array
*
* @throws \PrestaShopDatabaseException
*/
private function getCartProducts(array $carts)
{
$cartIds = array_map(function ($cart) {
return (string) $cart['id_cart'];
}, $carts);
$cartProducts = $this->cartProductRepository->getCartProducts($cartIds);
if (!is_array($cartProducts) || empty($cartProducts)) {
return [];
}
$this->castCartProductValues($cartProducts);
if (is_array($cartProducts)) {
return array_map(function ($cartProduct) {
return [
'id' => "{$cartProduct['id_cart']}-{$cartProduct['id_product']}-{$cartProduct['id_product_attribute']}",
'collection' => Config::COLLECTION_CART_PRODUCTS,
'properties' => $cartProduct,
];
}, $cartProducts);
}
return [];
}
}

View File

@@ -0,0 +1,92 @@
<?php
namespace PrestaShop\Module\PsEventbus\Provider;
use PrestaShop\Module\PsEventbus\Config\Config;
use PrestaShop\Module\PsEventbus\Decorator\CategoryDecorator;
use PrestaShop\Module\PsEventbus\Repository\CategoryRepository;
class CategoryDataProvider implements PaginatedApiDataProviderInterface
{
/**
* @var CategoryRepository
*/
private $categoryRepository;
/**
* @var CategoryDecorator
*/
private $categoryDecorator;
public function __construct(CategoryRepository $categoryRepository, CategoryDecorator $categoryDecorator)
{
$this->categoryRepository = $categoryRepository;
$this->categoryDecorator = $categoryDecorator;
}
/**
* @param int $offset
* @param int $limit
* @param string $langIso
*
* @return array
*
* @throws \PrestaShopDatabaseException
*/
public function getFormattedData($offset, $limit, $langIso)
{
$categories = $this->categoryRepository->getCategories($offset, $limit, $langIso);
if (!is_array($categories)) {
return [];
}
$this->categoryDecorator->decorateCategories($categories);
return array_map(function ($category) {
return [
'id' => "{$category['id_category']}-{$category['iso_code']}",
'collection' => Config::COLLECTION_CATEGORIES,
'properties' => $category,
];
}, $categories);
}
/**
* @param int $offset
* @param string $langIso
*
* @return int
*/
public function getRemainingObjectsCount($offset, $langIso)
{
return (int) $this->categoryRepository->getRemainingCategoriesCount($offset, $langIso);
}
/**
* @param int $limit
* @param string $langIso
* @param array $objectIds
*
* @return array
*
* @throws \PrestaShopDatabaseException
*/
public function getFormattedDataIncremental($limit, $langIso, $objectIds)
{
$categories = $this->categoryRepository->getCategoriesIncremental($limit, $langIso, $objectIds);
if (!is_array($categories)) {
return [];
}
$this->categoryDecorator->decorateCategories($categories);
return array_map(function ($category) {
return [
'id' => "{$category['id_category']}-{$category['iso_code']}",
'collection' => Config::COLLECTION_CATEGORIES,
'properties' => $category,
];
}, $categories);
}
}

View File

@@ -0,0 +1,92 @@
<?php
namespace PrestaShop\Module\PsEventbus\Provider;
use PrestaShop\Module\PsEventbus\Config\Config;
use PrestaShop\Module\PsEventbus\Decorator\CustomPriceDecorator;
use PrestaShop\Module\PsEventbus\Repository\CustomPriceRepository;
class CustomPriceDataProvider implements PaginatedApiDataProviderInterface
{
/**
* @var CustomPriceRepository
*/
private $customPriceRepository;
/**
* @var CustomPriceDecorator
*/
private $customPriceDecorator;
public function __construct(
CustomPriceRepository $customPriceRepository,
CustomPriceDecorator $customPriceDecorator
) {
$this->customPriceRepository = $customPriceRepository;
$this->customPriceDecorator = $customPriceDecorator;
}
/**
* @param int $offset
* @param int $limit
* @param string $langIso
*
* @return array
*
* @throws \PrestaShopDatabaseException
*/
public function getFormattedData($offset, $limit, $langIso)
{
$specificPrices = $this->customPriceRepository->getSpecificPrices($offset, $limit);
$this->customPriceDecorator->decorateSpecificPrices($specificPrices);
return array_map(function ($specificPrice) {
return [
'id' => $specificPrice['id_specific_price'],
'collection' => Config::COLLECTION_SPECIFIC_PRICES,
'properties' => $specificPrice,
];
}, $specificPrices);
}
/**
* @param int $offset
* @param string $langIso
*
* @return int
*
* @throws \PrestaShopDatabaseException
*/
public function getRemainingObjectsCount($offset, $langIso)
{
return (int) $this->customPriceRepository->getRemainingSpecificPricesCount($offset);
}
/**
* @param int $limit
* @param string $langIso
* @param array $objectIds
*
* @return array
*
* @throws \PrestaShopDatabaseException
*/
public function getFormattedDataIncremental($limit, $langIso, $objectIds)
{
$specificPrices = $this->customPriceRepository->getSpecificPricesIncremental($limit, $objectIds);
if (!empty($specificPrices)) {
$this->customPriceDecorator->decorateSpecificPrices($specificPrices);
} else {
return [];
}
return array_map(function ($specificPrice) {
return [
'id' => $specificPrice['id_specific_price'],
'collection' => Config::COLLECTION_SPECIFIC_PRICES,
'properties' => $specificPrice,
];
}, $specificPrices);
}
}

View File

@@ -0,0 +1,71 @@
<?php
namespace PrestaShop\Module\PsEventbus\Provider;
use PrestaShop\Module\PsEventbus\Config\Config;
use PrestaShop\Module\PsEventbus\Repository\ProductCarrierRepository;
class CustomProductCarrierDataProvider implements PaginatedApiDataProviderInterface
{
/**
* @var ProductCarrierRepository
*/
private $productCarrierRepository;
public function __construct(
ProductCarrierRepository $productCarrierRepository
) {
$this->productCarrierRepository = $productCarrierRepository;
}
/**
* @param int $offset
* @param int $limit
* @param string $langIso
*
* @return array
*
* @throws \PrestaShopDatabaseException
*/
public function getFormattedData($offset, $limit, $langIso)
{
$productCarriers = $this->productCarrierRepository->getProductCarriers($offset, $limit);
$productCarriers = array_map(function ($productCarrier) {
return [
'id' => $productCarrier['id_product'] . '-' . $productCarrier['id_carrier_reference'],
'collection' => Config::COLLECTION_CUSTOM_PRODUCT_CARRIERS,
'properties' => $productCarrier,
];
}, $productCarriers);
return $productCarriers;
}
public function getFormattedDataIncremental($limit, $langIso, $objectIds)
{
/** @var array $productCarrierIncremental */
$productCarrierIncremental = $this->productCarrierRepository->getProductCarrierIncremental(Config::COLLECTION_CUSTOM_PRODUCT_CARRIERS, $langIso);
if (!$productCarrierIncremental) {
return [];
}
$productIds = array_column($productCarrierIncremental, 'id_object');
/** @var array $productCarriers */
$productCarriers = $this->productCarrierRepository->getProductCarriersProperties($productIds);
return array_map(function ($productCarrier) {
return [
'id' => "{$productCarrier['id_product']}-{$productCarrier['id_carrier_reference']}",
'collection' => Config::COLLECTION_CUSTOM_PRODUCT_CARRIERS,
'properties' => $productCarrier,
];
}, $productCarriers);
}
public function getRemainingObjectsCount($offset, $langIso)
{
return (int) $this->productCarrierRepository->getRemainingProductCarriersCount($offset);
}
}

View File

@@ -0,0 +1,60 @@
<?php
namespace PrestaShop\Module\PsEventbus\Provider;
use Context;
use PrestaShop\Module\PsEventbus\Config\Config;
use PrestaShop\Module\PsEventbus\Repository\GoogleTaxonomyRepository;
class GoogleTaxonomyDataProvider implements PaginatedApiDataProviderInterface
{
/**
* @var GoogleTaxonomyRepository
*/
private $googleTaxonomyRepository;
/**
* @var Context
*/
private $context;
public function __construct(GoogleTaxonomyRepository $googleTaxonomyRepository, Context $context)
{
$this->googleTaxonomyRepository = $googleTaxonomyRepository;
$this->context = $context;
}
public function getFormattedData($offset, $limit, $langIso)
{
/** @var int $shopId */
$shopId = $this->context->shop->id;
$data = $this->googleTaxonomyRepository->getTaxonomyCategories($offset, $limit, $shopId);
if (!is_array($data)) {
return [];
}
return array_map(function ($googleTaxonomy) {
$uniqueId = "{$googleTaxonomy['id_category']}-{$googleTaxonomy['id_category']}";
$googleTaxonomy['taxonomy_id'] = $uniqueId;
return [
'id' => $uniqueId,
'collection' => Config::COLLECTION_TAXONOMIES,
'properties' => $googleTaxonomy,
];
}, $data);
}
public function getRemainingObjectsCount($offset, $langIso)
{
/** @var int $shopId */
$shopId = $this->context->shop->id;
return (int) $this->googleTaxonomyRepository->getRemainingTaxonomyRepositories($offset, $shopId);
}
public function getFormattedDataIncremental($limit, $langIso, $objectIds)
{
return [];
}
}

View File

@@ -0,0 +1,71 @@
<?php
namespace PrestaShop\Module\PsEventbus\Provider;
use PrestaShop\Module\PsEventbus\Config\Config;
use PrestaShop\Module\PsEventbus\Repository\ModuleRepository;
use PrestaShop\Module\PsEventbus\Repository\ShopRepository;
class ModuleDataProvider implements PaginatedApiDataProviderInterface
{
/**
* @var ModuleRepository
*/
private $moduleRepository;
/**
* @var string
*/
private $createdAt;
public function __construct(ModuleRepository $moduleRepository, ShopRepository $shopRepository)
{
$this->moduleRepository = $moduleRepository;
$this->createdAt = $shopRepository->getCreatedAt();
}
/**
* @param int $offset
* @param int $limit
* @param string $langIso
*
* @return array
*/
public function getFormattedData($offset, $limit, $langIso)
{
$modules = $this->moduleRepository->getModules($offset, $limit);
if (!is_array($modules)) {
return [];
}
return array_map(function ($module) {
$moduleId = (string) $module['module_id'];
$module['active'] = $module['active'] == '1';
$module['created_at'] = $module['created_at'] ?: $this->createdAt;
$module['updated_at'] = $module['updated_at'] ?: $this->createdAt;
return [
'id' => $moduleId,
'collection' => Config::COLLECTION_MODULES,
'properties' => $module,
];
}, $modules);
}
/**
* @param int $offset
* @param string $langIso
*
* @return int
*/
public function getRemainingObjectsCount($offset, $langIso)
{
return (int) $this->moduleRepository->getRemainingModules($offset);
}
public function getFormattedDataIncremental($limit, $langIso, $objectIds)
{
return [];
}
}

View File

@@ -0,0 +1,327 @@
<?php
namespace PrestaShop\Module\PsEventbus\Provider;
use Context;
use Language;
use PrestaShop\Module\PsEventbus\Config\Config;
use PrestaShop\Module\PsEventbus\Formatter\ArrayFormatter;
use PrestaShop\Module\PsEventbus\Repository\OrderDetailsRepository;
use PrestaShop\Module\PsEventbus\Repository\OrderHistoryRepository;
use PrestaShop\Module\PsEventbus\Repository\OrderRepository;
use PrestaShopDatabaseException;
class OrderDataProvider implements PaginatedApiDataProviderInterface
{
/**
* @var OrderRepository
*/
private $orderRepository;
/**
* @var Context
*/
private $context;
/**
* @var ArrayFormatter
*/
private $arrayFormatter;
/**
* @var OrderDetailsRepository
*/
private $orderDetailsRepository;
/**
* @var OrderHistoryRepository
*/
private $orderHistoryRepository;
public function __construct(
Context $context,
OrderRepository $orderRepository,
OrderDetailsRepository $orderDetailsRepository,
ArrayFormatter $arrayFormatter,
OrderHistoryRepository $orderHistoryRepository
) {
$this->orderRepository = $orderRepository;
$this->context = $context;
$this->arrayFormatter = $arrayFormatter;
$this->orderDetailsRepository = $orderDetailsRepository;
$this->orderHistoryRepository = $orderHistoryRepository;
}
/**
* @param int $offset
* @param int $limit
* @param string $langIso
*
* @return array
*
* @throws PrestaShopDatabaseException
*/
public function getFormattedData($offset, $limit, $langIso)
{
/** @var int $shopId */
$shopId = $this->context->shop->id;
$orders = $this->orderRepository->getOrders($offset, $limit, $shopId);
if (empty($orders)) {
return [];
}
$langId = (int) Language::getIdByIso($langIso);
$this->castOrderValues($orders, $langId);
$orderDetails = $this->getOrderDetails($orders, $shopId);
$orderStatuses = $this->getOrderStatuses($orders, $langId);
$orders = array_map(function ($order) {
return [
'id' => $order['id_order'],
'collection' => Config::COLLECTION_ORDERS,
'properties' => $order,
];
}, $orders);
return array_merge($orders, $orderDetails, $orderStatuses);
}
/**
* @param int $offset
* @param string $langIso
*
* @return int
*/
public function getRemainingObjectsCount($offset, $langIso)
{
/** @var int $shopId */
$shopId = $this->context->shop->id;
return (int) $this->orderRepository->getRemainingOrderCount($offset, $shopId);
}
/**
* @param int $limit
* @param string $langIso
*
* @return array
*
* @throws PrestaShopDatabaseException
*/
public function getFormattedDataIncremental($limit, $langIso, $objectIds)
{
/** @var int $shopId */
$shopId = $this->context->shop->id;
$orders = $this->orderRepository->getOrdersIncremental($limit, $shopId, $objectIds);
if (!is_array($orders) || empty($orders)) {
return [];
}
$orderDetails = $this->getOrderDetails($orders, $shopId);
$this->castOrderValues($orders, (int) Language::getIdByIso($langIso));
$orders = array_map(function ($order) {
return [
'id' => $order['id_order'],
'collection' => Config::COLLECTION_ORDERS,
'properties' => $order,
];
}, $orders);
return array_merge($orders, $orderDetails);
}
/**
* @param array $orders
* @param int $shopId
*
* @return array
*
* @throws PrestaShopDatabaseException
*/
private function getOrderDetails(array $orders, $shopId)
{
if (empty($orders)) {
return [];
}
$orderIds = $this->arrayFormatter->formatValueArray($orders, 'id_order');
$orderDetails = $this->orderDetailsRepository->getOrderDetails($orderIds, $shopId);
if (!is_array($orderDetails) || empty($orderDetails)) {
return [];
}
$this->castOrderDetailValues($orderDetails);
$orderDetails = array_map(function ($orderDetail) {
return [
'id' => $orderDetail['id_order_detail'],
'collection' => Config::COLLECTION_ORDER_DETAILS,
'properties' => $orderDetail,
];
}, $orderDetails);
return $orderDetails;
}
/**
* @param array $orders
* @param int $langId
*
* @return array|array[]
*
* @throws PrestaShopDatabaseException
*/
private function getOrderStatuses(array $orders, $langId)
{
if (empty($orders)) {
return [];
}
$orderIds = $this->arrayFormatter->formatValueArray($orders, 'id_order');
$orderHistoryStatuses = $this->orderHistoryRepository->getOrderHistoryStatuses($orderIds, $langId);
$orderHistoryStatuses = $this->castOrderStatuses($orderHistoryStatuses);
return array_map(function ($orderHistoryStatus) {
return [
'id' => $orderHistoryStatus['id_order_history'],
'collection' => Config::COLLECTION_ORDER_STATUS_HISTORY,
'properties' => $orderHistoryStatus,
];
}, $orderHistoryStatuses);
}
/**
* @param array $orders
* @param int $langId
*
* @return void
*
* @throws PrestaShopDatabaseException
*/
private function castOrderValues(array &$orders, int $langId)
{
foreach ($orders as &$order) {
$order['id_order'] = (int) $order['id_order'];
$order['id_customer'] = (int) $order['id_customer'];
$order['current_state'] = (int) $order['current_state'];
$order['conversion_rate'] = (float) $order['conversion_rate'];
$order['total_paid_tax_incl'] = (float) $order['total_paid_tax_incl'];
$order['total_paid_tax_excl'] = (float) $order['total_paid_tax_excl'];
$order['refund'] = (float) $order['refund'];
$order['refund_tax_excl'] = (float) $order['refund_tax_excl'];
$order['new_customer'] = $order['new_customer'] == 1;
$order['is_paid'] = $this->castIsPaidValue($orders, $order, $langId);
$order['shipping_cost'] = (float) $order['shipping_cost'];
$order['total_paid_tax'] = $order['total_paid_tax_incl'] - $order['total_paid_tax_excl'];
$order['id_carrier'] = (int) $order['id_carrier'];
$this->castAddressIsoCodes($order);
unset($order['address_iso']);
}
}
/**
* @param array $orders
* @param array $order
* @param int $langId
*
* @return bool
*
* @throws PrestaShopDatabaseException
*/
private function castIsPaidValue(array $orders, array $order, int $langId)
{
$isPaid = $dateAdd = 0;
$orderIds = $this->arrayFormatter->formatValueArray($orders, 'id_order');
/** @var array $orderHistoryStatuses */
$orderHistoryStatuses = $this->orderHistoryRepository->getOrderHistoryStatuses($orderIds, $langId);
foreach ($orderHistoryStatuses as &$orderHistoryStatus) {
if ($order['id_order'] == $orderHistoryStatus['id_order'] && $dateAdd < $orderHistoryStatus['date_add']) {
$isPaid = (bool) $orderHistoryStatus['paid'];
$dateAdd = $orderHistoryStatus['date_add'];
}
}
return (bool) $isPaid;
}
/**
* @param array $orderDetails
*
* @return void
*/
private function castOrderDetailValues(array &$orderDetails)
{
foreach ($orderDetails as &$orderDetail) {
$orderDetail['id_order_detail'] = (int) $orderDetail['id_order_detail'];
$orderDetail['id_order'] = (int) $orderDetail['id_order'];
$orderDetail['product_id'] = (int) $orderDetail['product_id'];
$orderDetail['product_attribute_id'] = (int) $orderDetail['product_attribute_id'];
$orderDetail['product_quantity'] = (int) $orderDetail['product_quantity'];
$orderDetail['unit_price_tax_incl'] = (float) $orderDetail['unit_price_tax_incl'];
$orderDetail['unit_price_tax_excl'] = (float) $orderDetail['unit_price_tax_excl'];
$orderDetail['refund'] = (float) $orderDetail['refund'] > 0 ? -1 * (float) $orderDetail['refund'] : 0;
$orderDetail['refund_tax_excl'] = (float) $orderDetail['refund_tax_excl'] > 0 ? -1 * (float) $orderDetail['refund_tax_excl'] : 0;
$orderDetail['category'] = (int) $orderDetail['category'];
$orderDetail['unique_product_id'] = "{$orderDetail['product_id']}-{$orderDetail['product_attribute_id']}-{$orderDetail['iso_code']}";
$orderDetail['conversion_rate'] = (float) $orderDetail['conversion_rate'];
}
}
private function castOrderStatuses(array &$orderStatuses): array
{
$castedOrderStatuses = [];
foreach ($orderStatuses as $orderStatus) {
$castedOrderStatus = [];
$castedOrderStatus['id_order_state'] = (int) $orderStatus['id_order_state'];
$castedOrderStatus['id_order'] = (int) $orderStatus['id_order'];
$castedOrderStatus['id_order_history'] = (int) $orderStatus['id_order_history'];
$castedOrderStatus['name'] = (string) $orderStatus['name'];
$castedOrderStatus['template'] = (string) $orderStatus['template'];
$castedOrderStatus['date_add'] = (string) $orderStatus['date_add'];
$castedOrderStatus['is_validated'] = (bool) $orderStatus['logable'];
$castedOrderStatus['is_delivered'] = (bool) $orderStatus['delivery'];
$castedOrderStatus['is_shipped'] = (bool) $orderStatus['shipped'];
$castedOrderStatus['is_paid'] = (bool) $orderStatus['paid'];
$castedOrderStatus['is_deleted'] = (bool) $orderStatus['deleted'];
$castedOrderStatuses[] = $castedOrderStatus;
}
return $castedOrderStatuses;
}
/**
* @param array $orderDetail
*
* @return void
*/
private function castAddressIsoCodes(&$orderDetail)
{
if (!$orderDetail['address_iso']) {
$orderDetail['invoice_country_code'] = null;
$orderDetail['delivery_country_code'] = null;
return;
}
$addressAndIsoCodes = explode(',', $orderDetail['address_iso']);
if (count($addressAndIsoCodes) === 1) {
$addressAndIsoCode = explode(':', $addressAndIsoCodes[0]);
$orderDetail['invoice_country_code'] = $addressAndIsoCode[1];
$orderDetail['delivery_country_code'] = $addressAndIsoCode[1];
return;
}
foreach ($addressAndIsoCodes as $addressAndIsoCodeString) {
$addressAndIsoCode = explode(':', $addressAndIsoCodeString);
if ($addressAndIsoCode[0] === 'delivery') {
$orderDetail['delivery_country_code'] = $addressAndIsoCode[1];
} elseif ($addressAndIsoCode[0] === 'invoice') {
$orderDetail['invoice_country_code'] = $addressAndIsoCode[1];
}
}
}
}

View File

@@ -0,0 +1,40 @@
<?php
namespace PrestaShop\Module\PsEventbus\Provider;
use PrestaShopDatabaseException;
interface PaginatedApiDataProviderInterface
{
/**
* @param int $offset
* @param int $limit
* @param string $langIso
*
* @return array
*
* @throws PrestaShopDatabaseException
*/
public function getFormattedData($offset, $limit, $langIso);
/**
* @param int $offset
* @param string $langIso
*
* @return int
*
* @throws PrestaShopDatabaseException
*/
public function getRemainingObjectsCount($offset, $langIso);
/**
* @param int $limit
* @param string $langIso
* @param array $objectIds
*
* @return array
*
* @throws PrestaShopDatabaseException
*/
public function getFormattedDataIncremental($limit, $langIso, $objectIds);
}

View File

@@ -0,0 +1,117 @@
<?php
namespace PrestaShop\Module\PsEventbus\Provider;
use PrestaShop\Module\PsEventbus\Config\Config;
use PrestaShop\Module\PsEventbus\Decorator\ProductDecorator;
use PrestaShop\Module\PsEventbus\Repository\LanguageRepository;
use PrestaShop\Module\PsEventbus\Repository\ProductRepository;
class ProductDataProvider implements PaginatedApiDataProviderInterface
{
/**
* @var ProductRepository
*/
private $productRepository;
/**
* @var ProductDecorator
*/
private $productDecorator;
/**
* @var LanguageRepository
*/
private $languageRepository;
public function __construct(
ProductRepository $productRepository,
ProductDecorator $productDecorator,
LanguageRepository $languageRepository
) {
$this->productRepository = $productRepository;
$this->productDecorator = $productDecorator;
$this->languageRepository = $languageRepository;
}
/**
* @param int $offset
* @param int $limit
* @param string $langIso
*
* @return array
*
* @throws \PrestaShopDatabaseException
*/
public function getFormattedData($offset, $limit, $langIso)
{
$langId = $this->languageRepository->getLanguageIdByIsoCode($langIso);
$products = $this->productRepository->getProducts($offset, $limit, $langId);
if (!$products) {
return [];
}
$this->productDecorator->decorateProducts($products, $langIso, $langId);
$bundles = $this->productDecorator->getBundles($products);
$products = array_map(function ($product) {
return [
'id' => $product['unique_product_id'],
'collection' => Config::COLLECTION_PRODUCTS,
'properties' => $product,
];
}, $products);
return array_merge($products, $bundles);
}
/**
* @param int $offset
* @param string $langIso
*
* @return int
*
* @throws \PrestaShopDatabaseException
*/
public function getRemainingObjectsCount($offset, $langIso)
{
$langId = $this->languageRepository->getLanguageIdByIsoCode($langIso);
return (int) $this->productRepository->getRemainingProductsCount($offset, $langId);
}
/**
* @param int $limit
* @param string $langIso
* @param array $objectIds
*
* @return array
*
* @throws \PrestaShopDatabaseException
*/
public function getFormattedDataIncremental($limit, $langIso, $objectIds)
{
$langId = $this->languageRepository->getLanguageIdByIsoCode($langIso);
$products = $this->productRepository->getProductsIncremental($limit, $langId, $objectIds);
if (!empty($products)) {
$this->productDecorator->decorateProducts($products, $langIso, $langId);
} else {
return [];
}
$orderDetails = $this->productDecorator->getBundles($products);
$products = array_map(function ($product) {
return [
'id' => $product['unique_product_id'],
'collection' => Config::COLLECTION_PRODUCTS,
'properties' => $product,
];
}, $products);
return array_merge($products, $orderDetails);
}
}

View File

@@ -0,0 +1,34 @@
<?php
/**
* 2007-2020 PrestaShop.
*
* NOTICE OF LICENSE
*
* This source file is subject to the Academic Free License (AFL 3.0)
* that is bundled with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://opensource.org/licenses/afl-3.0.php
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@prestashop.com so we can send you a copy immediately.
*
* DISCLAIMER
*
* Do not edit or add to this file if you wish to upgrade PrestaShop to newer
* versions in the future. If you wish to customize PrestaShop for your
* needs please refer to http://www.prestashop.com for more information.
*
* @author PrestaShop SA <contact@prestashop.com>
* @copyright 2007-2020 PrestaShop SA
* @license http://opensource.org/licenses/afl-3.0.php Academic Free License (AFL 3.0)
* International Registered Trademark & Property of PrestaShop SA
*/
header('Expires: Mon, 26 Jul 1997 05:00:00 GMT');
header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT');
header('Cache-Control: no-store, no-cache, must-revalidate');
header('Cache-Control: post-check=0, pre-check=0', false);
header('Pragma: no-cache');
header('Location: ../');
exit;

View File

@@ -0,0 +1,25 @@
drwxr-xr-x 2 30094 users 25 Oct 6 10:16 .
drwxr-xr-x 15 30094 users 16 Oct 6 10:16 ..
-rw-r--r-- 1 30094 users 4252 Oct 14 2021 CarrierRepository.php
-rw-r--r-- 1 30094 users 1203 Oct 14 2021 CartProductRepository.php
-rw-r--r-- 1 30094 users 2150 Oct 14 2021 CartRepository.php
-rw-r--r-- 1 30094 users 5883 Oct 14 2021 CategoryRepository.php
-rw-r--r-- 1 30094 users 366 Oct 14 2021 ConfigurationRepository.php
-rw-r--r-- 1 30094 users 1829 Oct 14 2021 CountryRepository.php
-rw-r--r-- 1 30094 users 586 Oct 14 2021 CurrencyRepository.php
-rw-r--r-- 1 30094 users 2140 Oct 14 2021 DeletedObjectsRepository.php
-rw-r--r-- 1 30094 users 3990 Oct 14 2021 EventbusSyncRepository.php
-rw-r--r-- 1 30094 users 1385 Oct 14 2021 GoogleTaxonomyRepository.php
-rw-r--r-- 1 30094 users 1865 Oct 14 2021 ImageRepository.php
-rw-r--r-- 1 30094 users 3609 Oct 14 2021 IncrementalSyncRepository.php
-rw-r--r-- 1 30094 users 988 Oct 14 2021 LanguageRepository.php
-rw-r--r-- 1 30094 users 1236 Oct 14 2021 ModuleRepository.php
-rw-r--r-- 1 30094 users 2019 Oct 14 2021 OrderDetailsRepository.php
-rw-r--r-- 1 30094 users 3095 Oct 14 2021 OrderRepository.php
-rw-r--r-- 1 30094 users 10185 Oct 14 2021 ProductRepository.php
-rw-r--r-- 1 30094 users 5535 Oct 14 2021 ServerInformationRepository.php
-rw-r--r-- 1 30094 users 647 Oct 14 2021 ShopRepository.php
-rw-r--r-- 1 30094 users 1655 Oct 14 2021 StateRepository.php
-rw-r--r-- 1 30094 users 2468 Oct 14 2021 TaxRepository.php
-rw-r--r-- 1 30094 users 2943 Oct 14 2021 ThemeRepository.php
-rw-r--r-- 1 30094 users 1083 Oct 14 2021 index.php

View File

@@ -0,0 +1,66 @@
<?php
namespace PrestaShop\Module\PsEventbus\Repository;
use Db;
use DbQuery;
use PrestaShopDatabaseException;
class BundleRepository
{
/**
* @var Db
*/
private $db;
public function __construct(Db $db)
{
$this->db = $db;
}
/**
* @param int $productPackId
*
* @return DbQuery
*/
private function getBaseQuery($productPackId)
{
$query = new DbQuery();
$query->from('pack', 'pac')
->innerJoin('product', 'p', 'p.id_product = pac.id_product_item');
$query->where('pac.id_product_pack = ' . (int) $productPackId);
return $query;
}
/**
* @param int $productPackId
*
* @return array
*
* @throws PrestaShopDatabaseException
*/
public function getBundleProducts($productPackId)
{
$query = $this->getBaseQuery($productPackId);
$this->addSelectParameters($query);
$result = $this->db->executeS($query);
return is_array($result) ? $result : [];
}
/**
* @param DbQuery $query
*
* @return void
*/
private function addSelectParameters(DbQuery $query)
{
$query->select('pac.id_product_pack as id_bundle, pac.id_product_attribute_item as id_product_attribute');
$query->select('p.id_product, pac.quantity');
}
}

View File

@@ -0,0 +1,213 @@
<?php
namespace PrestaShop\Module\PsEventbus\Repository;
use Carrier;
use Context;
use Db;
use DbQuery;
use PrestaShop\Module\PsEventbus\Config\Config;
use PrestaShopDatabaseException;
use RangePrice;
use RangeWeight;
class CarrierRepository
{
/**
* @var Db
*/
private $db;
/**
* @var Context
*/
private $context;
public function __construct(Db $db, Context $context)
{
$this->db = $db;
$this->context = $context;
}
/**
* @param Carrier $carrierObj
*
* @return array|false
*/
public function getDeliveryPriceByRange(Carrier $carrierObj)
{
$rangeTable = $carrierObj->getRangeTable();
switch ($rangeTable) {
case 'range_weight':
return $this->getCarrierByWeightRange($carrierObj, 'range_weight');
case 'range_price':
return $this->getCarrierByPriceRange($carrierObj, 'range_price');
default:
return false;
}
}
/**
* @param Carrier $carrierObj
* @param string $rangeTable
*
* @return array
*/
private function getCarrierByPriceRange(
Carrier $carrierObj,
$rangeTable
) {
$deliveryPriceByRange = Carrier::getDeliveryPriceByRanges($rangeTable, (int) $carrierObj->id);
$filteredRanges = [];
foreach ($deliveryPriceByRange as $range) {
$filteredRanges[$range['id_range_price']]['id_range_price'] = $range['id_range_price'];
$filteredRanges[$range['id_range_price']]['id_carrier'] = $range['id_carrier'];
$filteredRanges[$range['id_range_price']]['zones'][$range['id_zone']]['id_zone'] = $range['id_zone'];
$filteredRanges[$range['id_range_price']]['zones'][$range['id_zone']]['price'] = $range['price'];
}
return $filteredRanges;
}
/**
* @param Carrier $carrierObj
* @param string $rangeTable
*
* @return array
*/
private function getCarrierByWeightRange(
Carrier $carrierObj,
$rangeTable
) {
$deliveryPriceByRange = Carrier::getDeliveryPriceByRanges($rangeTable, (int) $carrierObj->id);
$filteredRanges = [];
foreach ($deliveryPriceByRange as $range) {
$filteredRanges[$range['id_range_weight']]['id_range_weight'] = $range['id_range_weight'];
$filteredRanges[$range['id_range_weight']]['id_carrier'] = $range['id_carrier'];
$filteredRanges[$range['id_range_weight']]['zones'][$range['id_zone']]['id_zone'] = $range['id_zone'];
$filteredRanges[$range['id_range_weight']]['zones'][$range['id_zone']]['price'] = $range['price'];
}
return $filteredRanges;
}
/**
* @param string $type
* @param string $langIso
*
* @return array|bool|\mysqli_result|\PDOStatement|resource|null
*
* @throws \PrestaShopDatabaseException
*/
public function getShippingIncremental($type, $langIso)
{
$query = new DbQuery();
$query->from(IncrementalSyncRepository::INCREMENTAL_SYNC_TABLE, 'aic');
$query->leftJoin(EventbusSyncRepository::TYPE_SYNC_TABLE_NAME, 'ts', 'ts.type = aic.type');
$query->where('aic.type = "' . (string) $type . '"');
$query->where('ts.id_shop = ' . (string) $this->context->shop->id);
$query->where('ts.lang_iso = "' . (string) $langIso . '"');
return $this->db->executeS($query);
}
/**
* @param array $deliveryPriceByRange
*
* @return false|RangeWeight|RangePrice
*
* @throws \PrestaShopDatabaseException
* @throws \PrestaShopException
*/
public function getCarrierRange(array $deliveryPriceByRange)
{
if (isset($deliveryPriceByRange['id_range_weight'])) {
return new RangeWeight($deliveryPriceByRange['id_range_weight']);
}
if (isset($deliveryPriceByRange['id_range_price'])) {
return new RangePrice($deliveryPriceByRange['id_range_price']);
}
return false;
}
/**
* @param int[] $carrierIds
* @param int $langId
*
* @return array|bool|\mysqli_result|\PDOStatement|resource|null
*
* @throws PrestaShopDatabaseException
*/
public function getCarrierProperties($carrierIds, $langId)
{
if (!$carrierIds) {
return [];
}
$query = new DbQuery();
$query->from('carrier', 'c');
$query->select('c.*, cl.delay, eis.created_at as update_date');
$query->leftJoin('carrier_lang', 'cl', 'cl.id_carrier = c.id_carrier AND cl.id_lang = ' . (int) $langId);
$query->leftJoin('carrier_shop', 'cs', 'cs.id_carrier = c.id_carrier');
$query->leftJoin(
'eventbus_incremental_sync',
'eis',
'eis.id_object = c.id_carrier AND eis.type = "' . Config::COLLECTION_CARRIERS . '" AND eis.id_shop = cs.id_shop AND eis.lang_iso = cl.id_lang'
);
$query->where('c.id_carrier IN (' . implode(',', array_map('intval', $carrierIds)) . ')');
$query->where('cs.id_shop = ' . (int) $this->context->shop->id);
$query->where('c.deleted = 0');
return $this->db->executeS($query);
}
/**
* @param int $offset
* @param int $limit
* @param int $langId
*
* @return array|bool|\mysqli_result|\PDOStatement|resource|null
*
* @throws PrestaShopDatabaseException
*/
public function getAllCarrierProperties($offset, $limit, $langId)
{
$query = new DbQuery();
$query->from('carrier', 'c');
$query->select('c.id_carrier, IFNULL(eis.created_at, CURRENT_DATE()) as update_date');
$query->leftJoin('carrier_lang', 'cl', 'cl.id_carrier = c.id_carrier AND cl.id_lang = ' . (int) $langId);
$query->leftJoin('carrier_shop', 'cs', 'cs.id_carrier = c.id_carrier');
$query->leftJoin(
'eventbus_incremental_sync',
'eis',
'eis.id_object = c.id_carrier AND eis.type = "' . Config::COLLECTION_CARRIERS . '" AND eis.id_shop = cs.id_shop AND eis.lang_iso = cl.id_lang'
);
$query->where('cs.id_shop = ' . (int) $this->context->shop->id);
$query->where('c.deleted = 0');
$query->orderBy('c.id_carrier');
$query->limit($limit, $offset);
return $this->db->executeS($query);
}
/**
* @param int $offset
* @param int $langId
*
* @return int
*
* @throws PrestaShopDatabaseException
*/
public function getRemainingCarriersCount($offset, $langId)
{
$carriers = $this->getAllCarrierProperties($offset, 1, $langId);
if (!is_array($carriers) || empty($carriers)) {
return 0;
}
return count($carriers);
}
}

View File

@@ -0,0 +1,58 @@
<?php
namespace PrestaShop\Module\PsEventbus\Repository;
use Context;
use Db;
use DbQuery;
class CartProductRepository
{
/**
* @var Db
*/
private $db;
/**
* @var Context
*/
private $context;
public function __construct(Db $db, Context $context)
{
$this->db = $db;
$this->context = $context;
}
/**
* @return DbQuery
*/
public function getBaseQuery()
{
$query = new DbQuery();
$query->from('cart_product', 'cp')
->where('cp.id_shop = ' . (int) $this->context->shop->id);
return $query;
}
/**
* @param array $cartIds
*
* @return array|bool|\mysqli_result|\PDOStatement|resource|null
*
* @throws \PrestaShopDatabaseException
*/
public function getCartProducts(array $cartIds)
{
$query = $this->getBaseQuery();
$query->select('cp.id_cart, cp.id_product, cp.id_product_attribute, cp.quantity, cp.date_add as created_at');
if (!empty($cartIds)) {
$query->where('cp.id_cart IN (' . implode(',', array_map('intval', $cartIds)) . ')');
}
return $this->db->executeS($query);
}
}

View File

@@ -0,0 +1,106 @@
<?php
namespace PrestaShop\Module\PsEventbus\Repository;
use Context;
use Db;
use DbQuery;
use mysqli_result;
use PDOStatement;
use PrestaShopDatabaseException;
class CartRepository
{
/**
* @var Db
*/
private $db;
/**
* @var Context
*/
private $context;
public function __construct(Db $db, Context $context)
{
$this->db = $db;
$this->context = $context;
}
/**
* @return DbQuery
*/
private function getBaseQuery()
{
$query = new DbQuery();
$query->from('cart', 'c')
->where('c.id_shop = ' . (int) $this->context->shop->id);
return $query;
}
/**
* @param int $offset
* @param int $limit
*
* @return array|bool|mysqli_result|PDOStatement|resource|null
*
* @throws PrestaShopDatabaseException
*/
public function getCarts($offset, $limit)
{
$query = $this->getBaseQuery();
$this->addSelectParameters($query);
$query->limit($limit, $offset);
return $this->db->executeS($query);
}
/**
* @param int $offset
*
* @return int
*/
public function getRemainingCartsCount($offset)
{
$query = $this->getBaseQuery();
$query->select('(COUNT(c.id_cart) - ' . (int) $offset . ') as count');
return (int) $this->db->getValue($query);
}
/**
* @param int $limit
* @param array $cartIds
*
* @return array
*
* @throws PrestaShopDatabaseException
*/
public function getCartsIncremental($limit, $cartIds)
{
$query = $this->getBaseQuery();
$this->addSelectParameters($query);
$query->where('c.id_cart IN(' . implode(',', array_map('intval', $cartIds)) . ')')
->limit($limit);
$result = $this->db->executeS($query);
return is_array($result) ? $result : [];
}
/**
* @param DbQuery $query
*
* @return void
*/
private function addSelectParameters(DbQuery $query)
{
$query->select('c.id_cart, date_add as created_at, date_upd as updated_at');
}
}

View File

@@ -0,0 +1,220 @@
<?php
namespace PrestaShop\Module\PsEventbus\Repository;
use Context;
use Db;
use DbQuery;
use mysqli_result;
use PDOStatement;
use PrestaShopDatabaseException;
class CategoryRepository
{
/**
* @var Db
*/
private $db;
/**
* @var array
*/
private $categoryLangCache;
/**
* @var Context
*/
private $context;
public function __construct(Db $db, Context $context)
{
$this->db = $db;
$this->context = $context;
}
/**
* @param int $shopId
* @param string $langIso
*
* @return DbQuery
*/
public function getBaseQuery($shopId, $langIso)
{
$query = new DbQuery();
$query->from('category_shop', 'cs')
->innerJoin('category', 'c', 'cs.id_category = c.id_category')
->leftJoin('category_lang', 'cl', 'cl.id_category = cs.id_category')
->leftJoin('lang', 'l', 'l.id_lang = cl.id_lang')
->where('cs.id_shop = ' . (int) $shopId)
->where('cl.id_shop = cs.id_shop')
->where('l.iso_code = "' . pSQL($langIso) . '"');
return $query;
}
/**
* @param int $topCategoryId
* @param int $langId
* @param int $shopId
*
* @return array
*/
public function getCategoryPaths($topCategoryId, $langId, $shopId)
{
if ((int) $topCategoryId === 0) {
return [
'category_path' => '',
'category_id_path' => '',
];
}
$categories = [];
try {
$categoriesWithParentsInfo = $this->getCategoriesWithParentInfo($langId, $shopId);
} catch (PrestaShopDatabaseException $e) {
return [
'category_path' => '',
'category_id_path' => '',
];
}
$this->buildCategoryPaths($categoriesWithParentsInfo, $topCategoryId, $categories);
$categories = array_reverse($categories);
return [
'category_path' => implode(' > ', array_map(function ($category) {
return $category['name'];
}, $categories)),
'category_id_path' => implode(' > ', array_map(function ($category) {
return $category['id_category'];
}, $categories)),
];
}
/**
* @param array $categoriesWithParentsInfo
* @param int $currentCategoryId
* @param array $categories
*
* @return void
*/
private function buildCategoryPaths($categoriesWithParentsInfo, $currentCategoryId, &$categories)
{
foreach ($categoriesWithParentsInfo as $category) {
if ($category['id_category'] == $currentCategoryId) {
$categories[] = $category;
$this->buildCategoryPaths($categoriesWithParentsInfo, $category['id_parent'], $categories);
}
}
}
/**
* @param int $langId
* @param int $shopId
*
* @return array
*
* @throws PrestaShopDatabaseException
*/
public function getCategoriesWithParentInfo($langId, $shopId)
{
if (!isset($this->categoryLangCache[$langId])) {
$query = new DbQuery();
$query->select('c.id_category, cl.name, c.id_parent')
->from('category', 'c')
->leftJoin(
'category_lang',
'cl',
'cl.id_category = c.id_category AND cl.id_shop = ' . (int) $shopId
)
->where('cl.id_lang = ' . (int) $langId)
->orderBy('cl.id_category');
$result = $this->db->executeS($query);
if (is_array($result)) {
$this->categoryLangCache[$langId] = $result;
} else {
throw new PrestaShopDatabaseException('No categories found');
}
}
return $this->categoryLangCache[$langId];
}
/**
* @param int $offset
* @param int $limit
* @param string $langIso
*
* @return array|bool|mysqli_result|PDOStatement|resource|null
*
* @throws PrestaShopDatabaseException
*/
public function getCategories($offset, $limit, $langIso)
{
/** @var int $shopId */
$shopId = $this->context->shop->id;
$query = $this->getBaseQuery($shopId, $langIso);
$this->addSelectParameters($query);
$query->limit($limit, $offset);
return $this->db->executeS($query);
}
/**
* @param int $offset
* @param string $langIso
*
* @return int
*/
public function getRemainingCategoriesCount($offset, $langIso)
{
/** @var int $shopId */
$shopId = $this->context->shop->id;
$query = $this->getBaseQuery($shopId, $langIso)
->select('(COUNT(cs.id_category) - ' . (int) $offset . ') as count');
return (int) $this->db->getValue($query);
}
/**
* @param int $limit
* @param string $langIso
* @param array $categoryIds
*
* @return array|bool|mysqli_result|PDOStatement|resource|null
*
* @throws PrestaShopDatabaseException
*/
public function getCategoriesIncremental($limit, $langIso, $categoryIds)
{
/** @var int $shopId */
$shopId = $this->context->shop->id;
$query = $this->getBaseQuery($shopId, $langIso);
$this->addSelectParameters($query);
$query->where('c.id_category IN(' . implode(',', array_map('intval', $categoryIds)) . ')')
->limit($limit);
return $this->db->executeS($query);
}
/**
* @param DbQuery $query
*
* @return void
*/
private function addSelectParameters(DbQuery $query)
{
$query->select('CONCAT(cs.id_category, "-", l.iso_code) as unique_category_id, cs.id_category,
c.id_parent, cl.name, cl.description, cl.link_rewrite, cl.meta_title, cl.meta_keywords, cl.meta_description,
l.iso_code, c.date_add as created_at, c.date_upd as updated_at');
}
}

View File

@@ -0,0 +1,20 @@
<?php
namespace PrestaShop\Module\PsEventbus\Repository;
use Configuration;
class ConfigurationRepository
{
/**
* We wrap Configuration::get function in here to be able to mock static functions
*
* @param string $key
*
* @return bool|string
*/
public function get($key)
{
return Configuration::get($key);
}
}

View File

@@ -0,0 +1,82 @@
<?php
namespace PrestaShop\Module\PsEventbus\Repository;
use Context;
use Db;
use DbQuery;
use mysqli_result;
use PDOStatement;
use PrestaShopDatabaseException;
class CountryRepository
{
/**
* @var Db
*/
private $db;
/**
* @var Context
*/
private $context;
/**
* @var array
*/
private $countryIsoCodeCache = [];
public function __construct(Db $db, Context $context)
{
$this->db = $db;
$this->context = $context;
}
/**
* @return DbQuery
*/
private function getBaseQuery()
{
$query = new DbQuery();
$query->from('country', 'c')
->innerJoin('country_shop', 'cs', 'cs.id_country = c.id_country')
->innerJoin('country_lang', 'cl', 'cl.id_country = c.id_country')
->where('cs.id_shop = ' . (int) $this->context->shop->id)
->where('cl.id_lang = ' . (int) $this->context->language->id);
return $query;
}
/**
* @param int $zoneId
* @param bool $active
*
* @return array|bool|mysqli_result|PDOStatement|resource|null
*
* @throws PrestaShopDatabaseException
*/
public function getCountyIsoCodesByZoneId($zoneId, $active = true)
{
$cacheKey = $zoneId . '-' . (int) $active;
if (!isset($this->countryIsoCodeCache[$cacheKey])) {
$query = $this->getBaseQuery();
$query->select('iso_code');
$query->where('id_zone = ' . (int) $zoneId);
$query->where('active = ' . (bool) $active);
$isoCodes = [];
$result = $this->db->executeS($query);
if (is_array($result)) {
foreach ($result as $country) {
$isoCodes[] = $country['iso_code'];
}
}
$this->countryIsoCodeCache[$cacheKey] = $isoCodes;
}
return $this->countryIsoCodeCache[$cacheKey];
}
}

View File

@@ -0,0 +1,30 @@
<?php
namespace PrestaShop\Module\PsEventbus\Repository;
use Currency;
class CurrencyRepository
{
/**
* @return array
*/
public function getCurrenciesIsoCodes()
{
$currencies = Currency::getCurrencies();
return array_map(function ($currency) {
return $currency['iso_code'];
}, $currencies);
}
/**
* @return string
*/
public function getDefaultCurrencyIsoCode()
{
$currency = Currency::getDefaultCurrency();
return $currency instanceof Currency ? $currency->iso_code : '';
}
}

View File

@@ -0,0 +1,133 @@
<?php
namespace PrestaShop\Module\PsEventbus\Repository;
use Context;
use Db;
use DbQuery;
use Employee;
use PrestaShopDatabaseException;
class CustomPriceRepository
{
/**
* @var Context
*/
private $context;
/**
* @var Db
*/
private $db;
public function __construct(Db $db, Context $context)
{
$this->db = $db;
$this->context = $context;
if (!$this->context->employee instanceof Employee) {
if (($employees = Employee::getEmployees()) !== false) {
$this->context->employee = new Employee($employees[0]['id_employee']);
}
}
}
/**
* @param int $shopId
*
* @return DbQuery
*/
private function getBaseQuery($shopId)
{
$query = new DbQuery();
$query->from('specific_price', 'sp')
->leftJoin('country', 'c', 'c.id_country = sp.id_country')
->leftJoin('currency', 'cur', 'cur.id_currency = sp.id_currency')
;
$query->where('sp.id_shop = 0 OR sp.id_shop = ' . (int) $shopId);
return $query;
}
/**
* @param int $offset
* @param int $limit
*
* @return array
*
* @throws PrestaShopDatabaseException
*/
public function getSpecificPrices($offset, $limit)
{
/** @var int $shopId */
$shopId = $this->context->shop->id;
$query = $this->getBaseQuery($shopId);
$this->addSelectParameters($query);
$query->limit($limit, $offset);
$result = $this->db->executeS($query);
return is_array($result) ? $result : [];
}
/**
* @param int $offset
*
* @return int
*
* @throws PrestaShopDatabaseException
*/
public function getRemainingSpecificPricesCount($offset)
{
/** @var int $shopId */
$shopId = $this->context->shop->id;
$query = $this->getBaseQuery($shopId);
$query->select('(COUNT(sp.id_specific_price) - ' . (int) $offset . ') as count');
return (int) $this->db->getValue($query);
}
/**
* @param DbQuery $query
*
* @return void
*/
private function addSelectParameters(DbQuery $query)
{
$query->select('sp.id_specific_price, sp.id_product, sp.id_shop, sp.id_shop_group, sp.id_currency,
sp.id_country, sp.id_group, sp.id_customer, sp.id_product_attribute, sp.price, sp.from_quantity,
sp.reduction, sp.reduction_tax, sp.from, sp.to, sp.reduction_type
');
$query->select('c.iso_code as country');
$query->select('cur.iso_code as currency');
}
/**
* @param int $limit
* @param array $specificPriceIds
*
* @return array
*
* @throws PrestaShopDatabaseException
*/
public function getSpecificPricesIncremental($limit, $specificPriceIds)
{
/** @var int $shopId */
$shopId = $this->context->shop->id;
$query = $this->getBaseQuery($shopId);
$this->addSelectParameters($query);
$query->where('sp.id_specific_price IN(' . implode(',', array_map('intval', $specificPriceIds)) . ')')
->limit($limit);
$result = $this->db->executeS($query);
return is_array($result) ? $result : [];
}
}

View File

@@ -0,0 +1,96 @@
<?php
namespace PrestaShop\Module\PsEventbus\Repository;
use Db;
use DbQuery;
use PrestaShop\Module\PsEventbus\Handler\ErrorHandler\ErrorHandlerInterface;
class DeletedObjectsRepository
{
public const DELETED_OBJECTS_TABLE = 'eventbus_deleted_objects';
/**
* @var Db
*/
private $db;
/**
* @var ErrorHandlerInterface
*/
private $errorHandler;
public function __construct(Db $db, ErrorHandlerInterface $errorHandler)
{
$this->db = $db;
$this->errorHandler = $errorHandler;
}
/**
* @param int $shopId
*
* @return array
*
* @throws \PrestaShopDatabaseException
*/
public function getDeletedObjectsGrouped($shopId)
{
$query = new DbQuery();
$query->select('type, GROUP_CONCAT(id_object SEPARATOR ";") as ids')
->from(self::DELETED_OBJECTS_TABLE)
->where('id_shop = ' . (int) $shopId)
->groupBy('type');
$result = $this->db->executeS($query);
return is_array($result) ? $result : [];
}
/**
* @param int $objectId
* @param string $objectType
* @param string $date
* @param int $shopId
*
* @return bool
*/
public function insertDeletedObject($objectId, $objectType, $date, $shopId)
{
try {
return $this->db->insert(
self::DELETED_OBJECTS_TABLE,
[
'id_shop' => $shopId,
'id_object' => $objectId,
'type' => $objectType,
'created_at' => $date,
],
false,
true,
Db::ON_DUPLICATE_KEY
);
} catch (\PrestaShopDatabaseException $e) {
$this->errorHandler->handle($e);
return false;
}
}
/**
* @param string $type
* @param array $objectIds
* @param int $shopId
*
* @return bool
*/
public function removeDeletedObjects($type, $objectIds, $shopId)
{
return $this->db->delete(
self::DELETED_OBJECTS_TABLE,
'type = "' . pSQL($type) . '"
AND id_shop = ' . $shopId . '
AND id_object IN(' . implode(',', $objectIds) . ')'
);
}
}

View File

@@ -0,0 +1,136 @@
<?php
namespace PrestaShop\Module\PsEventbus\Repository;
use Context;
use Db;
use DbQuery;
use PrestaShop\Module\PsEventbus\Config\Config;
use PrestaShopDatabaseException;
class EventbusSyncRepository
{
public const TYPE_SYNC_TABLE_NAME = 'eventbus_type_sync';
public const JOB_TABLE_NAME = 'eventbus_job';
/**
* @var Db
*/
private $db;
/**
* @var Context
*/
private $context;
public function __construct(Db $db, Context $context)
{
$this->db = $db;
$this->context = $context;
}
/**
* @param string $type
* @param int $offset
* @param string $lastSyncDate
* @param string $langIso
*
* @return bool
*
* @throws \PrestaShopDatabaseException
*/
public function insertTypeSync($type, $offset, $lastSyncDate, $langIso = null)
{
$result = $this->db->insert(
self::TYPE_SYNC_TABLE_NAME,
[
'id_shop' => (int) $this->context->shop->id,
'type' => pSQL((string) $type),
'offset' => (int) $offset,
'last_sync_date' => pSQL((string) $lastSyncDate),
'lang_iso' => pSQL((string) $langIso),
]
);
if (!$result) {
throw new PrestaShopDatabaseException('Failed to insert type sync', Config::DATABASE_INSERT_ERROR_CODE);
}
return $result;
}
/**
* @param string $jobId
* @param string $date
*
* @return bool
*
* @throws \PrestaShopDatabaseException
*/
public function insertJob($jobId, $date)
{
return $this->db->insert(
self::JOB_TABLE_NAME,
[
'job_id' => pSQL($jobId),
'created_at' => pSQL($date),
]
);
}
/**
* @param string $jobId
*
* @return array|bool|false|object|null
*/
public function findJobById($jobId)
{
$query = new DbQuery();
$query->select('*')
->from(self::JOB_TABLE_NAME)
->where('job_id = "' . pSQL($jobId) . '"');
return $this->db->getRow($query);
}
/**
* @param string $type
* @param string $langIso
*
* @return array|bool|object|null
*/
public function findTypeSync($type, $langIso = null)
{
$query = new DbQuery();
$query->select('*')
->from(self::TYPE_SYNC_TABLE_NAME)
->where('type = "' . pSQL($type) . '"')
->where('lang_iso = "' . pSQL((string) $langIso) . '"')
->where('id_shop = ' . (int) $this->context->shop->id);
return $this->db->getRow($query);
}
/**
* @param string $type
* @param int $offset
* @param string $date
* @param bool $fullSyncFinished
* @param string $langIso
*
* @return bool
*/
public function updateTypeSync($type, $offset, $date, $fullSyncFinished, $langIso = null)
{
return $this->db->update(
self::TYPE_SYNC_TABLE_NAME,
[
'offset' => (int) $offset,
'full_sync_finished' => (int) $fullSyncFinished,
'last_sync_date' => pSQL($date),
],
'type = "' . pSQL($type) . '"
AND lang_iso = "' . pSQL((string) $langIso) . '"
AND id_shop = ' . $this->context->shop->id
);
}
}

View File

@@ -0,0 +1,68 @@
<?php
namespace PrestaShop\Module\PsEventbus\Repository;
use Db;
use DbQuery;
class GoogleTaxonomyRepository
{
/**
* @var Db
*/
private $db;
public function __construct(Db $db)
{
$this->db = $db;
}
/**
* @param int $shopId
*
* @return DbQuery
*/
public function getBaseQuery($shopId)
{
$query = new DbQuery();
$query->from('fb_category_match', 'cm')
->where('cm.id_shop = ' . (int) $shopId);
return $query;
}
/**
* @param int $offset
* @param int $limit
* @param int $shopId
*
* @return array|bool|\mysqli_result|\PDOStatement|resource|null
*
* @throws \PrestaShopDatabaseException
*/
public function getTaxonomyCategories($offset, $limit, $shopId)
{
$query = $this->getBaseQuery($shopId);
$query->select('cm.id_category, cm.google_category_id')
->limit($limit, $offset);
return $this->db->executeS($query);
}
/**
* @param int $offset
* @param int $shopId
*
* @return int
*/
public function getRemainingTaxonomyRepositories($offset, $shopId)
{
$query = $this->getBaseQuery($shopId);
$query->select('(COUNT(cm.id_category) - ' . (int) $offset . ') as count');
return (int) $this->db->getValue($query);
}
}

View File

@@ -0,0 +1,74 @@
<?php
namespace PrestaShop\Module\PsEventbus\Repository;
use Db;
use DbQuery;
class ImageRepository
{
/**
* @var Db
*/
private $db;
public function __construct(Db $db)
{
$this->db = $db;
}
/**
* @param int $productId
* @param int $shopId
*
* @return false|string|null
*/
public function getProductCoverImage($productId, $shopId)
{
$query = new DbQuery();
$query->select('imgs.id_image')
->from('image_shop', 'imgs')
->where('imgs.cover = 1')
->where('imgs.id_shop = ' . (int) $shopId)
->where('imgs.id_product = ' . (int) $productId);
return $this->db->getValue($query);
}
/**
* @param int $productId
* @param int $attributeId
* @param int $shopId
* @param bool $includeCover
*
* @return array|bool|\mysqli_result|\PDOStatement|resource|null
*
* @throws \PrestaShopDatabaseException
*/
public function getProductImages($productId, $attributeId, $shopId, $includeCover = false)
{
$query = new DbQuery();
$query->select('imgs.id_image')
->from('image_shop', 'imgs')
->leftJoin('image', 'img', 'imgs.id_image = img.id_image')
->where('imgs.id_shop = ' . (int) $shopId)
->where('imgs.id_product = ' . (int) $productId)
->orderBy('img.position ASC');
if ((int) $attributeId !== 0) {
$query->innerJoin(
'product_attribute_image',
'pai',
'imgs.id_image = pai.id_image AND pai.id_product_attribute = ' . (int) $attributeId
);
}
if (!$includeCover) {
$query->where('(imgs.cover IS NULL OR imgs.cover = 0)');
}
return $this->db->executeS($query);
}
}

View File

@@ -0,0 +1,152 @@
<?php
namespace PrestaShop\Module\PsEventbus\Repository;
use Context;
use Db;
use DbQuery;
use PrestaShop\Module\PsEventbus\Handler\ErrorHandler\ErrorHandlerInterface;
use PrestaShopDatabaseException;
class IncrementalSyncRepository
{
public const INCREMENTAL_SYNC_TABLE = 'eventbus_incremental_sync';
/**
* @var Db
*/
private $db;
/**
* @var Context
*/
private $context;
/**
* @var ErrorHandlerInterface
*/
private $errorHandler;
public function __construct(Db $db, Context $context, ErrorHandlerInterface $errorHandler)
{
$this->db = $db;
$this->context = $context;
$this->errorHandler = $errorHandler;
}
/**
* @param int $objectId
* @param string $objectType
* @param string $date
* @param int $shopId
* @param string $langIso
*
* @return bool
*/
public function insertIncrementalObject($objectId, $objectType, $date, $shopId, $langIso)
{
try {
return $this->db->insert(
self::INCREMENTAL_SYNC_TABLE,
[
'id_shop' => $shopId,
'id_object' => $objectId,
'type' => $objectType,
'created_at' => $date,
'lang_iso' => $langIso,
],
false,
true,
Db::ON_DUPLICATE_KEY
);
} catch (PrestaShopDatabaseException $e) {
$this->errorHandler->handle(
new PrestaShopDatabaseException('Failed to insert incremental object', $e->getCode(), $e)
);
return false;
}
}
/**
* @param string $type
* @param array $objectIds
* @param string $langIso
*
* @return bool
*/
public function removeIncrementalSyncObjects($type, $objectIds, $langIso)
{
return $this->db->delete(
self::INCREMENTAL_SYNC_TABLE,
'type = "' . pSQL($type) . '"
AND id_shop = ' . $this->context->shop->id . '
AND id_object IN(' . implode(',', array_map('intval', $objectIds)) . ')
AND lang_iso = "' . pSQL($langIso) . '"'
);
}
/**
* @param string $type
* @param string $langIso
* @param int $limit
*
* @return array
*
* @throws PrestaShopDatabaseException
*/
public function getIncrementalSyncObjectIds($type, $langIso, $limit)
{
$query = new DbQuery();
$query->select('id_object')
->from(self::INCREMENTAL_SYNC_TABLE)
->where('lang_iso = "' . pSQL($langIso) . '"')
->where('id_shop = "' . $this->context->shop->id . '"')
->where('type = "' . pSQL($type) . '"')
->limit($limit);
$result = $this->db->executeS($query);
if (is_array($result) && !empty($result)) {
return array_map(function ($object) {
return $object['id_object'];
}, $result);
}
return [];
}
/**
* @param string $type
* @param string $langIso
*
* @return int
*/
public function getRemainingIncrementalObjects($type, $langIso)
{
$query = new DbQuery();
$query->select('COUNT(id_object) as count')
->from(self::INCREMENTAL_SYNC_TABLE)
->where('lang_iso = "' . pSQL($langIso) . '"')
->where('id_shop = "' . $this->context->shop->id . '"')
->where('type = "' . pSQL($type) . '"');
return (int) $this->db->getValue($query);
}
/**
* @param string $type
* @param int $objectId
*
* @return bool
*/
public function removeIncrementalSyncObject($type, $objectId)
{
return $this->db->delete(
self::INCREMENTAL_SYNC_TABLE,
'type = "' . pSQL($type) . '"
AND id_shop = ' . $this->context->shop->id . '
AND id_object = ' . (int) $objectId
);
}
}

View File

@@ -0,0 +1,54 @@
<?php
namespace PrestaShop\Module\PsEventbus\Repository;
use Configuration;
use Language;
class LanguageRepository
{
/**
* @return array
*/
public function getLanguagesIsoCodes()
{
/** @var array $languages */
$languages = Language::getLanguages();
return array_map(function ($language) {
return $language['iso_code'];
}, $languages);
}
/**
* @return string
*/
public function getDefaultLanguageIsoCode()
{
$language = Language::getLanguage((int) Configuration::get('PS_LANG_DEFAULT'));
if (is_array($language)) {
return $language['iso_code'];
}
return '';
}
/**
* @param string $isoCode
*
* @return int
*/
public function getLanguageIdByIsoCode($isoCode)
{
return (int) Language::getIdByIso($isoCode);
}
/**
* @return array
*/
public function getLanguages()
{
return Language::getLanguages();
}
}

View File

@@ -0,0 +1,64 @@
<?php
namespace PrestaShop\Module\PsEventbus\Repository;
use Db;
use DbQuery;
class ModuleRepository
{
public const MODULE_TABLE = 'module';
public const MODULE_TABLE_HISTORY = 'module_history';
/**
* @var Db
*/
private $db;
public function __construct(Db $db)
{
$this->db = $db;
}
/**
* @return DbQuery
*/
public function getBaseQuery()
{
return (new DbQuery())
->from(self::MODULE_TABLE, 'm')
->leftJoin(self::MODULE_TABLE_HISTORY, 'h', 'm.id_module = h.id_module');
}
/**
* @param int $offset
* @param int $limit
*
* @return array|bool|false|\mysqli_result|\PDOStatement|resource|null
*
* @throws \PrestaShopDatabaseException
*/
public function getModules($offset, $limit)
{
$query = $this->getBaseQuery();
$query->select('m.id_module as module_id, name, version as module_version, active, date_add as created_at, date_upd as updated_at')
->limit($limit, $offset);
return $this->db->executeS($query);
}
/**
* @param int $offset
*
* @return int
*/
public function getRemainingModules($offset)
{
$query = $this->getBaseQuery();
$query->select('(COUNT(m.id_module) - ' . (int) $offset . ') as count');
return (int) $this->db->getValue($query);
}
}

View File

@@ -0,0 +1,71 @@
<?php
namespace PrestaShop\Module\PsEventbus\Repository;
use Context;
use Db;
use DbQuery;
class OrderDetailsRepository
{
public const TABLE_NAME = 'order_detail';
/**
* @var Db
*/
private $db;
/**
* @var Context
*/
private $context;
public function __construct(Db $db, Context $context)
{
$this->context = $context;
$this->db = $db;
}
/**
* @return DbQuery
*/
public function getBaseQuery()
{
$query = new DbQuery();
$query->from(self::TABLE_NAME, 'od')
->where('od.id_shop = ' . (int) $this->context->shop->id);
return $query;
}
/**
* @param array $orderIds
* @param int $shopId
*
* @return array|bool|\mysqli_result|\PDOStatement|resource|null
*
* @throws \PrestaShopDatabaseException
*/
public function getOrderDetails(array $orderIds, $shopId)
{
if (!$orderIds) {
return [];
}
$query = $this->getBaseQuery();
$query->select('od.id_order_detail, od.id_order, od.product_id, od.product_attribute_id,
od.product_quantity, od.unit_price_tax_incl, od.unit_price_tax_excl, SUM(osd.total_price_tax_incl) as refund,
SUM(osd.total_price_tax_excl) as refund_tax_excl, c.iso_code as currency, ps.id_category_default as category,
l.iso_code, o.conversion_rate as conversion_rate, o.date_add as created_at, o.date_upd as updated_at')
->leftJoin('order_slip_detail', 'osd', 'od.id_order_detail = osd.id_order_detail')
->leftJoin('product_shop', 'ps', 'od.product_id = ps.id_product AND ps.id_shop = ' . (int) $shopId)
->innerJoin('orders', 'o', 'od.id_order = o.id_order')
->leftJoin('currency', 'c', 'c.id_currency = o.id_currency')
->leftJoin('lang', 'l', 'o.id_lang = l.id_lang')
->where('od.id_order IN (' . implode(',', array_map('intval', $orderIds)) . ')')
->groupBy('od.id_order_detail');
return $this->db->executeS($query);
}
}

View File

@@ -0,0 +1,59 @@
<?php
namespace PrestaShop\Module\PsEventbus\Repository;
use Db;
use DbQuery;
class OrderHistoryRepository
{
public const TABLE_NAME = 'order_history';
/**
* @var Db
*/
private $db;
public function __construct(Db $db)
{
$this->db = $db;
}
/**
* @return DbQuery
*/
public function getBaseQuery()
{
$query = new DbQuery();
$query->from(self::TABLE_NAME, 'oh');
return $query;
}
/**
* @param array $orderIds
* @param int $langId
*
* @return array|bool|\mysqli_result|\PDOStatement|resource|null
*
* @throws \PrestaShopDatabaseException
*/
public function getOrderHistoryStatuses(array $orderIds, $langId)
{
if (!$orderIds) {
return [];
}
$query = $this->getBaseQuery();
$query->select('oh.id_order_state, osl.name, osl.template, oh.date_add, oh.id_order, oh.id_order_history')
->select('os.logable, os.delivery, os.shipped, os.paid, os.deleted')
->innerJoin('order_state', 'os', 'os.id_order_state = oh.id_order_State')
->innerJoin('order_state_lang', 'osl', 'osl.id_order_state = os.id_order_State AND osl.id_lang = ' . (int) $langId)
->where('oh.id_order IN (' . implode(',', array_map('intval', $orderIds)) . ')')
;
return $this->db->executeS($query);
}
}

View File

@@ -0,0 +1,129 @@
<?php
namespace PrestaShop\Module\PsEventbus\Repository;
use Db;
use DbQuery;
use PrestaShopDatabaseException;
class OrderRepository
{
public const ORDERS_TABLE = 'orders';
/**
* @var Db
*/
private $db;
public function __construct(Db $db)
{
$this->db = $db;
}
/**
* @param int $shopId
*
* @return DbQuery
*/
public function getBaseQuery($shopId)
{
$query = new DbQuery();
$query->from(self::ORDERS_TABLE, 'o')
->leftJoin('currency', 'c', 'o.id_currency = c.id_currency')
->leftJoin('order_slip', 'os', 'o.id_order = os.id_order')
->leftJoin('address', 'ad', 'ad.id_address = o.id_address_delivery')
->leftJoin('address', 'ai', 'ai.id_address = o.id_address_invoice')
->leftJoin('country', 'cntd', 'cntd.id_country = ad.id_country')
->leftJoin('country', 'cnti', 'cnti.id_country = ai.id_country')
->leftJoin('order_state_lang', 'osl', 'o.current_state = osl.id_order_state')
->leftJoin('order_state', 'ost', 'o.current_state = ost.id_order_state')
->where('o.id_shop = ' . (int) $shopId)
->groupBy('o.id_order');
return $query;
}
/**
* @param int $offset
* @param int $limit
* @param int $shopId
*
* @return array|bool|\mysqli_result|\PDOStatement|resource|null
*
* @throws PrestaShopDatabaseException
*/
public function getOrders($offset, $limit, $shopId)
{
$query = $this->getBaseQuery($shopId);
$this->addSelectParameters($query);
$query->limit((int) $limit, (int) $offset);
return $this->db->executeS($query);
}
/**
* @param int $offset
* @param int $shopId
*
* @return int
*/
public function getRemainingOrderCount($offset, $shopId)
{
$query = new DbQuery();
$query->select('(COUNT(o.id_order) - ' . (int) $offset . ') as count')
->from(self::ORDERS_TABLE, 'o')
->where('o.id_shop = ' . (int) $shopId);
return (int) $this->db->getValue($query);
}
/**
* @param int $limit
* @param int $shopId
* @param array $orderIds
*
* @return array
*
* @throws PrestaShopDatabaseException
*/
public function getOrdersIncremental($limit, $shopId, $orderIds)
{
$query = $this->getBaseQuery($shopId);
$this->addSelectParameters($query);
$query->where('o.id_order IN(' . implode(',', array_map('intval', $orderIds)) . ')')
->limit($limit);
$result = $this->db->executeS($query);
return is_array($result) ? $result : [];
}
/**
* @param DbQuery $query
*
* @return void
*/
private function addSelectParameters(DbQuery $query)
{
$query->select('o.id_order, o.reference, o.id_customer, o.id_cart, o.current_state,
o.conversion_rate, o.total_paid_tax_excl, o.total_paid_tax_incl,
IF((SELECT so.id_order FROM `' . _DB_PREFIX_ . 'orders` so WHERE so.id_customer = o.id_customer AND so.id_order < o.id_order LIMIT 1) > 0, 0, 1) as new_customer,
c.iso_code as currency, SUM(os.total_products_tax_incl + os.total_shipping_tax_incl) as refund,
SUM(os.total_products_tax_excl + os.total_shipping_tax_excl) as refund_tax_excl, o.module as payment_module,
o.payment as payment_mode, o.total_paid_real, o.total_shipping as shipping_cost, o.date_add as created_at,
o.date_upd as updated_at, o.id_carrier,
o.payment as payment_name,
CONCAT(CONCAT("delivery", ":", cntd.iso_code), ",", CONCAT("invoice", ":", cnti.iso_code)) as address_iso,
o.valid as is_validated,
ost.paid as is_paid,
ost.shipped as is_shipped,
osl.name as status_label,
o.module as payment_name'
);
}
}

View File

@@ -0,0 +1,135 @@
<?php
namespace PrestaShop\Module\PsEventbus\Repository;
use Context;
use Db;
use DbQuery;
use PrestaShop\Module\PsEventbus\Formatter\ArrayFormatter;
use PrestaShopDatabaseException;
class ProductCarrierRepository
{
/**
* @var Db
*/
private $db;
/**
* @var Context
*/
private $context;
/**
* @var ArrayFormatter
*/
private $arrayFormatter;
public function __construct(Db $db, Context $context, ArrayFormatter $arrayFormatter)
{
$this->db = $db;
$this->context = $context;
$this->arrayFormatter = $arrayFormatter;
}
/**
* @return DbQuery
*/
private function getBaseQuery()
{
$query = new DbQuery();
$query->from('product_carrier', 'pc');
$query->where('pc.id_shop = ' . (int) $this->context->shop->id);
return $query;
}
/**
* @param int $offset
* @param int $limit
*
* @return array
*
* @throws PrestaShopDatabaseException
*/
public function getProductCarriers($offset, $limit)
{
$query = $this->getBaseQuery();
$this->addSelectParameters($query);
$query->limit($limit, $offset);
$result = $this->db->executeS($query);
return is_array($result) ? $result : [];
}
/**
* @param int $offset
*
* @return int
*
* @throws PrestaShopDatabaseException
*/
public function getRemainingProductCarriersCount($offset)
{
$productCarriers = $this->getProductCarriers($offset, 1);
if (!is_array($productCarriers) || empty($productCarriers)) {
return 0;
}
return count($productCarriers);
}
/**
* @param string $type
* @param string $langIso
*
* @return array|bool|\mysqli_result|\PDOStatement|resource|null
*
* @throws \PrestaShopDatabaseException
*/
public function getProductCarrierIncremental($type, $langIso)
{
$query = new DbQuery();
$query->from(IncrementalSyncRepository::INCREMENTAL_SYNC_TABLE, 'aic');
$query->leftJoin(EventbusSyncRepository::TYPE_SYNC_TABLE_NAME, 'ts', 'ts.type = aic.type');
$query->where('aic.type = "' . (string) $type . '"');
$query->where('ts.id_shop = ' . (string) $this->context->shop->id);
$query->where('ts.lang_iso = "' . (string) $langIso . '"');
return $this->db->executeS($query);
}
/**
* @param array $productIds
*
* @return array|bool|\mysqli_result|\PDOStatement|resource|null
*
* @throws PrestaShopDatabaseException
*/
public function getProductCarriersProperties(array $productIds)
{
if (!$productIds) {
return [];
}
$query = new DbQuery();
$query->select('pc.*')
->from('product_carrier', 'pc')
->where('pc.id_product IN (' . $this->arrayFormatter->arrayToString($productIds, ',') . ')');
return $this->db->executeS($query);
}
/**
* @param DbQuery $query
*
* @return void
*/
private function addSelectParameters(DbQuery $query)
{
$query->select('pc.id_carrier_reference, pc.id_product');
}
}

View File

@@ -0,0 +1,329 @@
<?php
namespace PrestaShop\Module\PsEventbus\Repository;
use Context;
use Db;
use DbQuery;
use Employee;
use PrestaShop\Module\PsEventbus\Formatter\ArrayFormatter;
use PrestaShopDatabaseException;
use Product;
use Shop;
class ProductRepository
{
/**
* @var Context
*/
private $context;
/**
* @var Db
*/
private $db;
/**
* @var ArrayFormatter
*/
private $arrayFormatter;
public function __construct(Db $db, Context $context, ArrayFormatter $arrayFormatter)
{
$this->db = $db;
$this->context = $context;
if (!$this->context->employee instanceof Employee) {
if (($employees = Employee::getEmployees()) !== false) {
$this->context->employee = new Employee($employees[0]['id_employee']);
}
}
$this->arrayFormatter = $arrayFormatter;
}
/**
* @param Shop $shop
* @param int $langId
*
* @return DbQuery
*/
private function getBaseQuery(Shop $shop, $langId)
{
$query = new DbQuery();
$query->from('product', 'p')
->innerJoin('product_shop', 'ps', 'ps.id_product = p.id_product AND ps.id_shop = ' . (int) $shop->id)
->innerJoin('product_lang', 'pl', 'pl.id_product = ps.id_product AND pl.id_shop = ps.id_shop AND pl.id_lang = ' . (int) $langId)
->leftJoin('product_attribute_shop', 'pas', 'pas.id_product = p.id_product AND pas.id_shop = ps.id_shop')
->leftJoin('product_attribute', 'pa', 'pas.id_product_attribute = pa.id_product_attribute')
->leftJoin('category_lang', 'cl', 'ps.id_category_default = cl.id_category AND ps.id_shop = cl.id_shop AND cl.id_lang = ' . (int) $langId)
->leftJoin('manufacturer', 'm', 'p.id_manufacturer = m.id_manufacturer');
if ($shop->getGroup()->share_stock) {
$query->leftJoin('stock_available', 'sa', 'sa.id_product = p.id_product AND
sa.id_product_attribute = IFNULL(pas.id_product_attribute, 0) AND sa.id_shop_group = ' . (int) $shop->id_shop_group);
} else {
$query->leftJoin('stock_available', 'sa', 'sa.id_product = p.id_product AND
sa.id_product_attribute = IFNULL(pas.id_product_attribute, 0) AND sa.id_shop = ps.id_shop');
}
return $query;
}
/**
* @param int $offset
* @param int $limit
* @param int $langId
*
* @return array
*
* @throws PrestaShopDatabaseException
*/
public function getProducts($offset, $limit, $langId)
{
$query = $this->getBaseQuery($this->context->shop, $langId);
$this->addSelectParameters($query);
$query->limit($limit, $offset);
$result = $this->db->executeS($query);
return is_array($result) ? $result : [];
}
/**
* @param int $offset
* @param int $langId
*
* @return int
*
* @throws PrestaShopDatabaseException
*/
public function getRemainingProductsCount($offset, $langId)
{
$products = $this->getProducts($offset, 1, $langId);
if (!is_array($products) || empty($products)) {
return 0;
}
return count($products);
}
/**
* @param array $attributeIds
* @param int $langId
*
* @return array
*
* @throws PrestaShopDatabaseException
*/
public function getProductAttributeValues(array $attributeIds, $langId)
{
if (!$attributeIds) {
return [];
}
$query = new DbQuery();
$query->select('pas.id_product_attribute, agl.name as name, al.name as value')
->from('product_attribute_shop', 'pas')
->leftJoin('product_attribute_combination', 'pac', 'pac.id_product_attribute = pas.id_product_attribute')
->leftJoin('attribute', 'a', 'a.id_attribute = pac.id_attribute')
->leftJoin('attribute_group_lang', 'agl', 'agl.id_attribute_group = a.id_attribute_group AND agl.id_lang = ' . (int) $langId)
->leftJoin('attribute_lang', 'al', 'al.id_attribute = pac.id_attribute AND al.id_lang = agl.id_lang')
->where('pas.id_product_attribute IN (' . $this->arrayFormatter->arrayToString($attributeIds, ',') . ') AND pas.id_shop = ' . (int) $this->context->shop->id);
$attributes = $this->db->executeS($query);
if (is_array($attributes)) {
$resultArray = [];
foreach ($attributes as $attribute) {
$resultArray[$attribute['id_product_attribute']][$attribute['name']] = $attribute['value'];
}
return $resultArray;
}
return [];
}
/**
* @param array $productIds
* @param int $langId
*
* @return array
*
* @throws PrestaShopDatabaseException
*/
public function getProductFeatures(array $productIds, $langId)
{
if (!$productIds) {
return [];
}
$query = new DbQuery();
$query->select('fp.id_product, fl.name, fvl.value')
->from('feature_product', 'fp')
->leftJoin('feature_lang', 'fl', 'fl.id_feature = fp.id_feature AND fl.id_lang = ' . (int) $langId)
->leftJoin('feature_value_lang', 'fvl', 'fvl.id_feature_value = fp.id_feature_value AND fvl.id_lang = fl.id_lang')
->where('fp.id_product IN (' . $this->arrayFormatter->arrayToString($productIds, ',') . ')');
$features = $this->db->executeS($query);
if (is_array($features)) {
$resultArray = [];
foreach ($features as $feature) {
$resultArray[$feature['id_product']][$feature['name']] = $feature['value'];
}
return $resultArray;
}
return [];
}
/**
* @param array $productIds
*
* @return array
*
* @throws PrestaShopDatabaseException
*/
public function getProductImages(array $productIds)
{
if (!$productIds) {
return [];
}
$query = new DbQuery();
$query->select('imgs.id_product, imgs.id_image, IFNULL(imgs.cover, 0) as cover')
->from('image_shop', 'imgs')
->where('imgs.id_shop = ' . (int) $this->context->shop->id . ' AND imgs.id_product IN (' . $this->arrayFormatter->arrayToString($productIds, ',') . ')');
$result = $this->db->executeS($query);
return is_array($result) ? $result : [];
}
/**
* @param array $attributeIds
*
* @return array
*
* @throws PrestaShopDatabaseException
*/
public function getAttributeImages(array $attributeIds)
{
if (!$attributeIds) {
return [];
}
$query = new DbQuery();
$query->select('id_product_attribute, id_image')
->from('product_attribute_image', 'pai')
->where('pai.id_product_attribute IN (' . $this->arrayFormatter->arrayToString($attributeIds, ',') . ')');
$result = $this->db->executeS($query);
return is_array($result) ? $result : [];
}
/**
* @param int $productId
* @param int $attributeId
*
* @return float
*/
public function getPriceTaxExcluded($productId, $attributeId)
{
return Product::getPriceStatic($productId, false, $attributeId, 6, null, false, false);
}
/**
* @param int $productId
* @param int $attributeId
*
* @return float
*/
public function getPriceTaxIncluded($productId, $attributeId)
{
return Product::getPriceStatic($productId, true, $attributeId, 6, null, false, false);
}
/**
* @param int $productId
* @param int $attributeId
*
* @return float
*/
public function getSalePriceTaxExcluded($productId, $attributeId)
{
return Product::getPriceStatic($productId, false, $attributeId, 6);
}
/**
* @param int $productId
* @param int $attributeId
*
* @return float
*/
public function getSalePriceTaxIncluded($productId, $attributeId)
{
return Product::getPriceStatic($productId, true, $attributeId, 6);
}
/**
* @param int $limit
* @param int $langId
* @param array $productIds
*
* @return array
*
* @throws PrestaShopDatabaseException
*/
public function getProductsIncremental($limit, $langId, $productIds)
{
$query = $this->getBaseQuery($this->context->shop, $langId);
$this->addSelectParameters($query);
$query->where('p.id_product IN(' . implode(',', array_map('intval', $productIds)) . ')')
->limit($limit);
$result = $this->db->executeS($query);
return is_array($result) ? $result : [];
}
/**
* @param DbQuery $query
*
* @return void
*/
private function addSelectParameters(DbQuery $query)
{
$query->select('p.id_product, IFNULL(pas.id_product_attribute, 0) as id_attribute, pas.default_on as is_default_attribute,
pl.name, pl.description, pl.description_short, pl.link_rewrite, cl.name as default_category,
ps.id_category_default, IFNULL(NULLIF(pa.reference, ""), p.reference) as reference, IFNULL(NULLIF(pa.upc, ""), p.upc) as upc,
IFNULL(NULLIF(pa.ean13, ""), p.ean13) as ean, ps.condition, ps.visibility, ps.active, sa.quantity, m.name as manufacturer,
(p.weight + IFNULL(pas.weight, 0)) as weight, (ps.price + IFNULL(pas.price, 0)) as price_tax_excl,
p.date_add as created_at, p.date_upd as updated_at,
p.available_for_order, p.available_date, p.cache_is_pack as is_bundle, p.is_virtual,
p.unity, p.unit_price_ratio
');
if (property_exists(new Product(), 'mpn')) {
$query->select('p.mpn');
}
$query->select('p.width, p.height, p.depth, p.additional_delivery_times, p.additional_shipping_cost');
$query->select('pl.delivery_in_stock, pl.delivery_out_stock');
if (version_compare(_PS_VERSION_, '1.7', '>=')) {
$query->select('IFNULL(NULLIF(pa.isbn, ""), p.isbn) as isbn');
}
}
}

View File

@@ -0,0 +1,200 @@
<?php
namespace PrestaShop\Module\PsEventbus\Repository;
use Context;
use Db;
use DbQuery;
use Exception;
use Language;
use PrestaShop\AccountsAuth\Service\PsAccountsService;
use PrestaShop\Module\PsAccounts\Api\Client\AccountsClient;
use PrestaShop\Module\PsEventbus\Config\Config;
use PrestaShop\Module\PsEventbus\Handler\ErrorHandler\ErrorHandlerInterface;
use PrestaShop\PsAccountsInstaller\Installer\Facade\PsAccounts;
use PrestaShopDatabaseException;
use Ps_accounts;
use Ps_eventbus;
class ServerInformationRepository
{
/**
* @var CurrencyRepository
*/
private $currencyRepository;
/**
* @var LanguageRepository
*/
private $languageRepository;
/**
* @var ConfigurationRepository
*/
private $configurationRepository;
/**
* @var Context
*/
private $context;
/**
* @var Db
*/
private $db;
/**
* @var ShopRepository
*/
private $shopRepository;
/**
* @var PsAccountsService
*/
private $psAccountsService;
/**
* @var array
*/
private $configuration;
/**
* @var string
*/
private $createdAt;
/**
* @var ErrorHandlerInterface
*/
private $errorHandler;
public function __construct(
Context $context,
Db $db,
CurrencyRepository $currencyRepository,
LanguageRepository $languageRepository,
ConfigurationRepository $configurationRepository,
ShopRepository $shopRepository,
PsAccounts $psAccounts,
ErrorHandlerInterface $errorHandler,
array $configuration
) {
$this->currencyRepository = $currencyRepository;
$this->languageRepository = $languageRepository;
$this->configurationRepository = $configurationRepository;
$this->shopRepository = $shopRepository;
$this->context = $context;
$this->db = $db;
$this->psAccountsService = $psAccounts->getPsAccountsService();
$this->configuration = $configuration;
$this->createdAt = $this->shopRepository->getCreatedAt();
$this->errorHandler = $errorHandler;
}
/**
* @param string $langIso
*
* @return array[]
*
* @throws \PrestaShopException
*/
public function getServerInformation($langIso = '')
{
$langId = !empty($langIso) ? (int) Language::getIdByIso($langIso) : null;
return [
[
'id' => '1',
'collection' => Config::COLLECTION_SHOPS,
'properties' => [
'created_at' => $this->createdAt,
'cms_version' => _PS_VERSION_,
'url_is_simplified' => $this->configurationRepository->get('PS_REWRITING_SETTINGS') == '1',
'cart_is_persistent' => $this->configurationRepository->get('PS_CART_FOLLOWING') == '1',
'default_language' => $this->languageRepository->getDefaultLanguageIsoCode(),
'languages' => implode(';', $this->languageRepository->getLanguagesIsoCodes()),
'default_currency' => $this->currencyRepository->getDefaultCurrencyIsoCode(),
'currencies' => implode(';', $this->currencyRepository->getCurrenciesIsoCodes()),
'weight_unit' => $this->configurationRepository->get('PS_WEIGHT_UNIT'),
'distance_unit' => $this->configurationRepository->get('PS_BASE_DISTANCE_UNIT'),
'volume_unit' => $this->configurationRepository->get('PS_VOLUME_UNIT'),
'dimension_unit' => $this->configurationRepository->get('PS_DIMENSION_UNIT'),
'timezone' => $this->configurationRepository->get('PS_TIMEZONE'),
'is_order_return_enabled' => $this->configurationRepository->get('PS_ORDER_RETURN') == '1',
'order_return_nb_days' => (int) $this->configurationRepository->get('PS_ORDER_RETURN_NB_DAYS'),
'php_version' => phpversion(),
'http_server' => isset($_SERVER['SERVER_SOFTWARE']) ? $_SERVER['SERVER_SOFTWARE'] : '',
'url' => $this->context->link->getPageLink('index', null, $langId),
'ssl' => $this->configurationRepository->get('PS_SSL_ENABLED') == '1',
'multi_shop_count' => $this->shopRepository->getMultiShopCount(),
'country_code' => $this->shopRepository->getShopCountryCode(),
],
],
];
}
/**
* @return array
*/
public function getHealthCheckData()
{
$tokenValid = false;
$tokenIsSet = true;
$allTablesInstalled = true;
try {
$token = $this->psAccountsService->getOrRefreshToken();
if (!$token) {
$tokenIsSet = false;
} else {
$accountsClient = $this->getAccountsClient();
/** @phpstan-ignore-next-line */
$response = $accountsClient->verifyToken($token);
if ($response && true === $response['status']) {
$tokenValid = true;
}
}
} catch (Exception $e) {
$this->errorHandler->handle($e);
$tokenIsSet = false;
}
foreach (Ps_eventbus::REQUIRED_TABLES as $requiredTable) {
$query = new DbQuery();
$query->select('*')
->from($requiredTable)
->limit(1);
try {
$this->db->executeS($query);
} catch (PrestaShopDatabaseException $e) {
$allTablesInstalled = false;
break;
}
}
if (defined('PHP_VERSION') && defined('PHP_EXTRA_VERSION')) {
$phpVersion = str_replace(PHP_EXTRA_VERSION, '', PHP_VERSION);
} else {
$phpVersion = (string) explode('-', (string) phpversion())[0];
}
return [
'prestashop_version' => _PS_VERSION_,
'ps_eventbus_version' => Ps_eventbus::VERSION,
'ps_accounts_version' => defined('Ps_accounts::VERSION') ? Ps_accounts::VERSION : false, /* @phpstan-ignore-line */
'php_version' => $phpVersion,
'ps_account' => $tokenIsSet,
'is_valid_jwt' => $tokenValid,
'ps_eventbus' => $allTablesInstalled,
'env' => [
'EVENT_BUS_PROXY_API_URL' => isset($this->configuration['EVENT_BUS_PROXY_API_URL']) ? $this->configuration['EVENT_BUS_PROXY_API_URL'] : null,
'EVENT_BUS_SYNC_API_URL' => isset($this->configuration['EVENT_BUS_SYNC_API_URL']) ? $this->configuration['EVENT_BUS_SYNC_API_URL'] : null,
],
];
}
/**
* @return mixed
*/
private function getAccountsClient()
{
$module = \Module::getInstanceByName('ps_accounts');
/* @phpstan-ignore-next-line */
return $module->getService(AccountsClient::class);
}
}

View File

@@ -0,0 +1,63 @@
<?php
namespace PrestaShop\Module\PsEventbus\Repository;
use Db;
use DbQuery;
class ShopRepository
{
/**
* @var Db
*/
private $db;
public function __construct(Db $db)
{
$this->db = $db;
}
/**
* @return int
*/
public function getMultiShopCount()
{
$query = new DbQuery();
$query->select('COUNT(id_shop)')
->from('shop')
->where('active = 1 and deleted = 0');
return (int) $this->db->getValue($query);
}
/**
* @return string
*/
public function getCreatedAt()
{
$query = new DbQuery();
$query->select('date_add as created_at')
->from('configuration')
->where('name = "PS_INSTALL_VERSION"');
return (string) $this->db->getValue($query);
}
/**
* Gives back the first iso_code registered, which correspond to the default country of this shop
*
* @return string
*/
public function getShopCountryCode()
{
$query = new DbQuery();
$query->select('iso_code')
->from('country')
->where('active = 1');
return (string) $this->db->getValue($query);
}
}

View File

@@ -0,0 +1,74 @@
<?php
namespace PrestaShop\Module\PsEventbus\Repository;
use Db;
use DbQuery;
use mysqli_result;
use PDOStatement;
use PrestaShopDatabaseException;
class StateRepository
{
/**
* @var Db
*/
private $db;
/**
* @var array
*/
private $stateIsoCodeCache = [];
public function __construct(Db $db)
{
$this->db = $db;
}
/**
* @return DbQuery
*/
private function getBaseQuery()
{
$query = new DbQuery();
$query->from('state', 's');
return $query;
}
/**
* @param int $zoneId
* @param bool $active
*
* @return array|bool|mysqli_result|PDOStatement|resource|null
*
* @throws PrestaShopDatabaseException
*/
public function getStateIsoCodesByZoneId($zoneId, $active = true)
{
$cacheKey = $zoneId . '-' . (int) $active;
if (!isset($this->stateIsoCodeCache[$cacheKey])) {
$query = $this->getBaseQuery();
$query->select('s.iso_code');
$query->innerJoin('country', 'c', 'c.id_country = s.id_country');
$query->where('s.id_zone = ' . (int) $zoneId);
$query->where('s.active = ' . (bool) $active);
$query->where('c.active = ' . (bool) $active);
$isoCodes = [];
$result = $this->db->executeS($query);
if (is_array($result)) {
foreach ($result as $state) {
$isoCodes[] = $state['iso_code'];
}
}
$this->stateIsoCodeCache[$cacheKey] = $isoCodes;
}
return $this->stateIsoCodeCache[$cacheKey];
}
}

View File

@@ -0,0 +1,84 @@
<?php
namespace PrestaShop\Module\PsEventbus\Repository;
use Context;
use Db;
use DbQuery;
use mysqli_result;
use PDOStatement;
use PrestaShopDatabaseException;
class TaxRepository
{
/**
* @var Db
*/
private $db;
/**
* @var Context
*/
private $context;
/**
* @var array
*/
private $countryIsoCodeCache = [];
public function __construct(Db $db, Context $context)
{
$this->db = $db;
$this->context = $context;
}
/**
* @return DbQuery
*/
private function getBaseQuery()
{
$query = new DbQuery();
$query->from('tax', 't')
->innerJoin('tax_rule', 'tr', 'tr.id_tax = t.id_tax')
->innerJoin('tax_rules_group', 'trg', 'trg.id_tax_rules_group = tr.id_tax_rules_group')
->innerJoin('tax_rules_group_shop', 'trgs', 'trgs.id_tax_rules_group = tr.id_tax_rules_group')
->innerJoin('tax_lang', 'tl', 'tl.id_tax = t.id_tax')
->where('trgs.id_shop = ' . (int) $this->context->shop->id)
->where('tl.id_lang = ' . (int) $this->context->language->id);
return $query;
}
/**
* @param int $zoneId
* @param int $taxRulesGroupId
* @param bool $active
*
* @return array|bool|mysqli_result|PDOStatement|resource|null
*
* @throws PrestaShopDatabaseException
*/
public function getCarrierTaxesByZone($zoneId, $taxRulesGroupId, $active = true)
{
$cacheKey = $zoneId . '-' . (int) $active;
if (!isset($this->countryIsoCodeCache[$cacheKey])) {
$query = $this->getBaseQuery();
$query->select('rate, c.iso_code as country_iso_code, GROUP_CONCAT(s.iso_code SEPARATOR ",") as state_iso_code');
$query->leftJoin('country', 'c', 'c.id_country = tr.id_country');
$query->leftJoin('state', 's', 's.id_state = tr.id_state');
$query->where('tr.id_tax_rules_group = ' . (int) $taxRulesGroupId);
$query->where('c.active = ' . (bool) $active);
$query->where('s.active = ' . (bool) $active . ' OR s.active IS NULL');
$query->where('t.active = ' . (bool) $active);
$query->where('c.id_zone = ' . (int) $zoneId . ' OR s.id_zone = ' . (int) $zoneId);
$query->where('c.iso_code IS NOT NULL');
$this->countryIsoCodeCache[$cacheKey] = $this->db->executeS($query);
}
return $this->countryIsoCodeCache[$cacheKey];
}
}

View File

@@ -0,0 +1,90 @@
<?php
namespace PrestaShop\Module\PsEventbus\Repository;
use Context;
use Db;
use PrestaShop\Module\PsEventbus\Config\Config;
use PrestaShop\PrestaShop\Core\Addon\Theme\ThemeManagerBuilder;
use Theme;
class ThemeRepository
{
/**
* @var Context
*/
private $context;
/**
* @var Db
*/
private $db;
public function __construct(Context $context, Db $db)
{
$this->context = $context;
$this->db = $db;
}
/**
* @return array|mixed|null
*/
public function getThemes()
{
if (version_compare(_PS_VERSION_, '1.7', '>')) {
$themeRepository = (new ThemeManagerBuilder($this->context, $this->db))
->buildRepository($this->context->shop);
$currentTheme = $this->context->shop->theme;
$themes = $themeRepository->getList();
return array_map(function ($key, $theme) use ($currentTheme) {
return [
'id' => md5((string) $key),
'collection' => Config::COLLECTION_THEMES,
'properties' => [
'theme_id' => md5((string) $key),
'name' => (string) $theme->getName(),
'theme_version' => (string) $theme->get('version'),
'active' => $theme->getName() == $currentTheme->getName(),
],
];
}, array_keys($themes), $themes);
} else {
/* @phpstan-ignore-next-line */
$themes = Theme::getAvailable(false);
return array_map(function ($theme) {
/* @phpstan-ignore-next-line */
$themeObj = Theme::getByDirectory($theme);
$themeData = [
'id' => md5($theme),
'collection' => Config::COLLECTION_THEMES,
'properties' => [],
];
/* @phpstan-ignore-next-line */
if ($themeObj instanceof Theme) {
/* @phpstan-ignore-next-line */
$themeInfo = Theme::getThemeInfo($themeObj->id);
$themeData['properties'] = [
'theme_id' => md5($theme),
'name' => isset($themeInfo['theme_name']) ? $themeInfo['theme_name'] : '',
'theme_version' => isset($themeInfo['theme_version']) ? $themeInfo['theme_version'] : '',
'active' => isset($themeInfo['theme_version']) ? false : (string) $this->context->theme->id == (string) $themeInfo['theme_id'],
];
} else {
$themeData['properties'] = [
'theme_id' => md5($theme),
'name' => $theme,
'theme_version' => '',
'active' => false,
];
}
return $themeData;
}, $themes);
}
}
}

View File

@@ -0,0 +1,28 @@
<?php
/**
* 2007-2020 PrestaShop and Contributors
*
* NOTICE OF LICENSE
*
* This source file is subject to the Academic Free License 3.0 (AFL-3.0)
* that is bundled with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* https://opensource.org/licenses/AFL-3.0
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@prestashop.com so we can send you a copy immediately.
*
* @author PrestaShop SA <contact@prestashop.com>
* @copyright 2007-2020 PrestaShop SA and Contributors
* @license https://opensource.org/licenses/AFL-3.0 Academic Free License 3.0 (AFL-3.0)
* International Registered Trademark & Property of PrestaShop SA
*/
header('Expires: Mon, 26 Jul 1997 05:00:00 GMT');
header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT');
header('Cache-Control: no-store, no-cache, must-revalidate');
header('Cache-Control: post-check=0, pre-check=0', false);
header('Pragma: no-cache');
header('Location: ../');
exit;

View File

@@ -0,0 +1,8 @@
drwxr-xr-x 2 30094 users 8 Oct 6 10:16 .
drwxr-xr-x 15 30094 users 16 Oct 6 10:16 ..
-rw-r--r-- 1 30094 users 1513 Oct 14 2021 ApiAuthorizationService.php
-rw-r--r-- 1 30094 users 908 Oct 14 2021 CompressionService.php
-rw-r--r-- 1 30094 users 2188 Oct 14 2021 DeletedObjectsService.php
-rw-r--r-- 1 30094 users 1906 Oct 14 2021 ProxyService.php
-rw-r--r-- 1 30094 users 5046 Oct 14 2021 SynchronizationService.php
-rw-r--r-- 1 30094 users 1083 Oct 14 2021 index.php

View File

@@ -0,0 +1,54 @@
<?php
namespace PrestaShop\Module\PsEventbus\Service;
use PrestaShop\Module\PsEventbus\Api\EventBusSyncClient;
use PrestaShop\Module\PsEventbus\Exception\EnvVarException;
use PrestaShop\Module\PsEventbus\Repository\EventbusSyncRepository;
use PrestaShopDatabaseException;
class ApiAuthorizationService
{
/**
* @var EventbusSyncRepository
*/
private $eventbusSyncStateRepository;
/**
* @var EventBusSyncClient
*/
private $eventBusSyncClient;
public function __construct(
EventbusSyncRepository $eventbusSyncStateRepository,
EventBusSyncClient $eventBusSyncClient
) {
$this->eventbusSyncStateRepository = $eventbusSyncStateRepository;
$this->eventBusSyncClient = $eventBusSyncClient;
}
/**
* Authorizes if the call to endpoint is legit and creates sync state if needed
*
* @param string $jobId
*
* @return array|bool
*
* @throws PrestaShopDatabaseException|EnvVarException
*/
public function authorizeCall($jobId)
{
$job = $this->eventbusSyncStateRepository->findJobById($jobId);
if ($job) {
return true;
}
$jobValidationResponse = $this->eventBusSyncClient->validateJobId($jobId);
if (is_array($jobValidationResponse) && (int) $jobValidationResponse['httpCode'] === 201) {
return $this->eventbusSyncStateRepository->insertJob($jobId, date(DATE_ATOM));
}
return $jobValidationResponse;
}
}

View File

@@ -0,0 +1,35 @@
<?php
namespace PrestaShop\Module\PsEventbus\Service;
use Symfony\Component\Cache\Adapter\FilesystemAdapter;
class CacheService
{
/**
* @param string $key
* @param string $value
*
* @return void
*/
public function setCacheProperty($key, $value)
{
$cache = new FilesystemAdapter();
$cacheItem = $cache->getItem($key);
$cacheItem->set($value);
$cache->save($cacheItem);
}
/**
* @param string $key
*
* @return mixed
*/
public function getCacheProperty($key)
{
$cache = new FilesystemAdapter();
$cacheItem = $cache->getItem($key);
return $cacheItem->get();
}
}

View File

@@ -0,0 +1,43 @@
<?php
namespace PrestaShop\Module\PsEventbus\Service;
use Exception;
use PrestaShop\Module\PsEventbus\Formatter\JsonFormatter;
class CompressionService
{
/**
* @var JsonFormatter
*/
private $jsonFormatter;
public function __construct(JsonFormatter $jsonFormatter)
{
$this->jsonFormatter = $jsonFormatter;
}
/**
* Compresses data with gzip
*
* @param array $data
*
* @return string
*
* @throws Exception
*/
public function gzipCompressData($data)
{
if (!extension_loaded('zlib')) {
throw new Exception('Zlib extension for PHP is not enabled');
}
$dataJson = $this->jsonFormatter->formatNewlineJsonString($data);
if (!$encodedData = gzencode($dataJson)) {
throw new Exception('Failed encoding data to GZIP');
}
return $encodedData;
}
}

Some files were not shown because too many files have changed in this diff Show More