commerce_import-8.x-1.x-dev/src/Plugin/CommerceImport/JsonImportPlugin.php
src/Plugin/CommerceImport/JsonImportPlugin.php
<?php
namespace Drupal\commerce_import\Plugin\CommerceImport;
use Drupal\commerce_import\PluginManager\ImportPluginBase;
use Drupal\commerce_import\PluginManager\ImportPluginInterface;
use GuzzleHttp\Exception\RequestException;
use Drupal\Core\File\FileSystemInterface;
/**
* Provides a 'CSV' Template.
*
* @CommerceImportAnnotation(
* id = "json",
* title = @Translation("Json"),
* )
*/
class JsonImportPlugin extends ImportPluginBase implements ImportPluginInterface {
/**
* {@inheritdoc}
*/
public function init() {
$this->file_system = \Drupal::service('file_system');
$this->realpath = $this->getRealpath();
}
/**
* {@inheritdoc}
*/
private function getRealpath() :? string {
$file = $this->getFile();
if (!$file) {
return NULL;
}
$file = $this->getFile();
$uri = $file->getFileUri();
return \Drupal::service('file_system')->realpath($uri);
}
/**
* {@inheritdoc}
*/
private function getFile() {
$file = FALSE;
$files = $this->query();
if (!empty($files)) {
$file = array_shift($files);
}
return $file;
}
/**
* {@inheritdoc}
*/
public function catalog() {
$weight = 1;
$catalog = [];
$data = $this->parse();
foreach ($data->categories as $row) {
$id = $row->id;
$name = $row->name;
$parent_id = $row->parent_id ?? NULL;
$catalog[$id] = [
'id' => (int) $id,
'name' => $name,
'parent' => $parent_id,
'weight' => $weight++,
];
}
$catalog = $this->sortCatalogChildrens([], $catalog);
return $catalog;
}
/**
* {@inheritdoc}
*/
private function sortCatalogChildrens(array $catalog, array $childrens) : array {
$iterations = 0;
while (count($childrens) > 0 && $iterations < 10) {
$iterations++;
foreach ($childrens as $children) {
$id = $children['id'];
$parent_id = $children['parent'] ?? NULL;
if (empty($parent_id) || !empty($catalog[$parent_id])) {
$catalog[$id] = $children;
}
}
}
return $catalog;
}
/**
* {@inheritdoc}
*/
public function product() {
$products = [];
$data = $this->parse();
foreach ($data->offers as $product) {
$id = $product->id;
$products[$id] = [
'id' => $id,
'title' => $product->title,
'body' => $product->description,
'catalog' => $product->category_id ?? NULL,
'field_article' => $product->article ?? NULL,
];
$image_path = $this->getImagePath($product);
if ($image_path) {
$products[$id]['img'] = ['uri' => $image_path];
}
}
return $products;
}
/**
* {@inheritdoc}
*/
private function getImagePath($product) :? string {
if (empty($product->image)) {
return NULL;
}
$pathinfo = $this->getPathInfo($product->image);
$directory = sprintf('public://commerce-import/json-import%s', $pathinfo['dirname']);
$this->file_system->prepareDirectory(
$directory, FileSystemInterface:: CREATE_DIRECTORY | FileSystemInterface::MODIFY_PERMISSIONS
);
return implode('/', [$directory, $pathinfo['basename']]);
}
/**
* {@inheritdoc}
*/
private function getPathInfo(string $url) :? array {
if (empty($url)) {
return NULL;
}
$parse_url = parse_url($url);
$pathinfo = pathinfo($parse_url['path']);
return $pathinfo ?? [];
}
/**
* {@inheritdoc}
*/
public function image() {
$data = $this->parse();
$products = $data->offers;
if (empty($products)) {
return [];
}
$lang = \Drupal::languageManager()->getCurrentLanguage()->getId();
$images = [];
foreach ($products as $product) {
if (empty($product->image)) {
continue;
}
$image_path = $this->getImagePath($product);
if (empty($image_path)) {
continue;
}
$pathinfo = $this->getPathInfo($product->image);
if (!file_exists($image_path)) {
$image_content = file_get_contents($product->image);
$image_path = $this->file_system->saveData(
$image_content, $image_path, FileSystemInterface::EXISTS_REPLACE
);
}
$id = $product->id;
$images[$id] = [
'id' => $id,
'uid' => 1,
'status' => TRUE,
'langcode' => $lang,
'uri' => $image_path,
'filename' => $pathinfo['basename'],
];
}
return $images;
}
/**
* Parse Products.
*/
public function parse() {
$data = [];
$path = $this->realpath;
if (file_exists($path)) {
$file = file_get_contents($path);
$data = json_decode($file);
$data = $data->catalog;
}
return $data;
}
/**
* {@inheritdoc}
*/
public function variation() {
$data = $this->parse();
$rows = $data->offers ?? [];
if (empty($data)) {
return [];
}
$variations = [];
foreach ($rows as $row) {
if (empty($row->id)) {
continue;
}
$id = $row->id;
$variations[$id] = [
'id' => $id,
'type' => 'variation',
'title' => $row->title,
'sku' => $row->article ?? NULL,
'price' => (int) $row->price ?? 0,
'field_oldprice' => (int) $row->price_old ?? NULL,
'field_stock' => (int) $row->quantity ?? NULL,
'product_id' => $id,
'product_key' => $id,
];
}
return $variations;
}
/**
* Client.
*/
public function client($url, array $query = []) {
$options = $this->options;
$options['query'] = $query;
try {
$response = $this->client->get($url, $options);
$code = $response->getStatusCode();
if ($code == 200) {
return $response->getBody()->getContents();
}
return [
'code' => $code,
'header' => $response->getHeaders(),
'body' => $response->getBody()->getContents(),
];
}
catch (RequestException $e) {
\Drupal::messenger()->addError($e->getMessage());
}
return FALSE;
}
/**
* {@inheritdoc}
*/
public function paragraphs() {
return [];
}
/**
* {@inheritdoc}
*/
private function query() {
$files = [];
$storage = \Drupal::entityTypeManager()->getStorage('file');
$query = $storage->getQuery()
->condition('status', 0)
->condition('uri', '%commerce-import/%', 'LIKE')
->sort('created', 'DESC')
->accessCheck(TRUE)
->range(0, 1);
$ids = $query->execute();
if (!empty($ids)) {
foreach ($storage->loadMultiple($ids) as $id => $entity) {
$files[$id] = $entity;
}
}
return $files;
}
}
