Commit 49c53498 authored by masdzen's avatar masdzen
Browse files

refactor

parent e87e7502
......@@ -3,483 +3,106 @@
namespace Drupal\synhelper\Drush;
use Drush\Commands\DrushCommands;
use Drupal\Core\Url;
use Drupal\media\Entity\Media;
use Drupal\pathauto\PathautoState;
use Drupal\Core\Config\FileStorage;
use Drupal\Core\File\FileSystemInterface;
/**
* A Drush commandfile.
*/
class DrushContentImport extends DrushCommands {
/**
* Synhelper content import.
* Synhelper Content import.
*
* @param string $directory
* Content directory.
*
* @command synhelper:content
* @aliases scont
* @options arr An option that takes multiple values.
* @command synhelper:content_import
* @usage synhelper:scont $directory
* Import сontacts from
* $directory/contacts.
* Import nodes from
* $directory/nodes.
* Import taxonomy from
* $directory/taxonomy.
* Import menu from
* $directory/menu.
* Resets SynLandyng config from
* $directory/synlanding.
* Full import from $directory.
*/
public function import($directory) {
$this->output()->writeln("Import content from: $directory");
$contactsDirectory = $directory . '/contacts';
$this->output()->writeln("Import Contacts from: $contactsDirectory");
$sourceContacts = new FileStorage($contactsDirectory);
foreach ($sourceContacts->listAll() as $file) {
$data = $sourceContacts->read($file);
$this->importContacts($data);
}
$this->output()->writeln("!NOTE Done.");
$taxonomyDirectory = $directory . '/taxonomy';
$this->output()->writeln("Import Taxonomy from: $taxonomyDirectory");
$sourceTaxonomy = new FileStorage($taxonomyDirectory);
foreach ($sourceTaxonomy->listAll() as $file) {
$data = $sourceTaxonomy->read($file);
$this->importTaxonomy($data);
}
$this->output()->writeln("!NOTE Done.");
$nodeDirectory = $directory . '/nodes';
$this->output()->writeln("Import Nodes from: $nodeDirectory");
$sourceNode = new FileStorage($nodeDirectory);
foreach ($sourceNode->listAll() as $file) {
$data = $sourceNode->read($file);
$this->importNode($data);
}
$this->output()->writeln("!NOTE Done.");
$menuDirectory = $directory . '/menu';
$this->output()->writeln("Import Menu from: $menuDirectory");
$sourceMenu = new FileStorage($menuDirectory);
foreach ($sourceMenu->listAll() as $file) {
$data = $sourceMenu->read($file);
$this->importMenu($data);
}
$this->output()->writeln("!NOTE Done.");
$synLandingDirectory = $directory . '/synlanding';
$this->output()->writeln("Import Image for SynLanding(form_bg) from: $synLandingDirectory");
$sourceSynLanding = new FileStorage($synLandingDirectory);
foreach ($sourceSynLanding->listAll() as $file) {
$data = $sourceSynLanding->read($file);
$this->setSynLandingConfig($data);
}
$this->output()->writeln("Import Content from: $directory");
\Drupal::service('synhelper.content_import')->import($directory);
$this->output()->writeln("!NOTE Done.");
}
/**
* Import Paragraph(about && image_blocks).
* If needed more just copy one of them and
* set your fields
*/
private function importParagraph($field_paragraph) {
$storage = \Drupal::service('entity_type.manager')->getStorage('paragraph');
/* Importing About Us */
if (!empty($field_paragraph['about'])) {
$items = [];
$about = $field_paragraph['about'];
foreach ($about['field_about_items'] as $about_item) {
$item = $storage->create($about_item);
$item->save();
$items[] = [
'type' => $about_item['type'],
'target_id' => $item->id(),
'target_revision_id' => $item->getRevisionId(),
'field_title' => $about_item['field_title'],
'field_description' => $about_item['field_description'],
];
}
$about['field_about_items'] = $items;
$paragraph = $storage->create($about);
$paragraph->save();
$paragraphs = [];
$paragraphs[] = [
'type' => $about['type'],
'target_id' => $paragraph->id(),
'target_revision_id' => $paragraph->getRevisionId(),
];
}
/* Importing Image Blocks */
if (!empty($field_paragraph['image_blocks'])) {
$items = [];
$imageBloсks = $field_paragraph['image_blocks'];
foreach ($imageBloсks['field_image_blocks_items'] as $image_blocks_item) {
$image_blocks_item['field_image'] = $this->importImages($image_blocks_item['field_image']);
$item = $storage->create($image_blocks_item);
$item->save();
$items[] = [
'type' => $image_blocks_item['type'],
'target_id' => $item->id(),
'target_revision_id' => $item->getRevisionId(),
'field_title' => $image_blocks_item['field_title'],
'field_body' => $image_blocks_item['field_body'],
'field_image_text_sort' => $image_blocks_item['field_image_text_sort'],
];
}
$imageBloсks['field_image_blocks_items'] = $items;
$paragraph = $storage->create($imageBloсks);
$paragraph->save();
$paragraphs[] = [
'type' => $imageBloсks['type'],
'target_id' => $paragraph->id(),
'target_revision_id' => $paragraph->getRevisionId(),
];
}
return $paragraphs;
}
/**
* Import Taxonomy.
*/
private function importTaxonomy($data) {
$storage = \Drupal::entityTypeManager()->getStorage('taxonomy_term');
$vocabulary_storage = \Drupal::entityTypeManager()->getStorage('taxonomy_vocabulary');
if (empty($vocabulary_storage->load($data['vid']))) {
if (!empty($data['vname'])) {
$vocabulary_name = $data['vname'];
}
else {
$vocabulary_name = $data['vid'];
}
$t = [
'vid' => $data['vid'],
'name' => $vocabulary_name,
];
$vocabulary = $vocabulary_storage->create($t);
$vocabulary->save();
}
$t = [
'vid' => $data['vid'],
'name' => $data['name'],
'field_catalog_image' => $this->importImages($data['field_catalog_image']),
];
$taxonomyTerm = $storage->create($t);
$taxonomyTerm->save();
if (!empty($data['children_terms'])) {
$child_terms = [];
foreach ($data['children_terms'] as $child_term) {
$t = [
'vid' => $data['vid'],
'name' => $child_term['name'],
'field_catalog_image' => $this->importImages($child_term['field_catalog_image']),
'weight' => $child_term['weight'],
'parent' => [
['target_id' => $this->getTidByName($data['name'])],
],
];
$term = $storage->create($t);
$term->save();
}
}
}
/**
* Import TaxonomyField by name or name and vocabulary.
*/
private function importTaxonomyField($taxonomyTermName) {
if (!empty($taxonomyTermName)) {
$taxonomyTermId = $this->getTidByName($taxonomyTermName);
return $taxonomyTermId;
}
}
/**
* Import Menu.
*/
private function importMenu($data) {
// TODO: Create menu
if ($menu = \Drupal::entityTypeManager()->getStorage('menu')->load($data['menu']['id'])) {
$menu->set('label', $data['menu']['label']);
$menu->set('description', $data['menu']['description']);
$menu->save();
}
else {
\Drupal::entityTypeManager()->getStorage('menu')->create([
'id' => $data['menu']['id'],
'label' => $data['menu']['label'],
'description' => $data['menu']['description'],
])->save();
}
$this->addMenuLink($data['links'], NULL, $data['menu']['id']);
}
/**
* Import Menu Links.
*/
private function addMenuLink($links, $parent_id, $menu_id) {
if (empty($links)) {
return;
}
$link = \Drupal::entityTypeManager()->getStorage('menu_link_content');
foreach ($links as $menu_link) {
$t = [
'title' => $menu_link['title'],
'link' => ['uri' => $menu_link['uri']],
'menu_name' => $menu_id,
'expanded' => $menu_link['expanded'],
'weight' => $menu_link['weight'],
'parent' => $parent_id,
'description' => $menu_link['description'],
];
$children = $menu_link['children'];
$menu_link = $link->create($t);
$menu_link->save();
if (!empty($children[0])) {
$bundle = $menu_link->bundle();
$uuid = $menu_link->uuid();
$parent_id1 = $bundle . ":" . $uuid;
}
else {
$parent_id1 = NULL;
}
$this->addMenuLink($children, $parent_id1, $menu_id);
}
}
/**
* Import Contacts.
*/
private function importContacts($data) {
$path = \Drupal::service('path_alias.manager')->getPathByAlias('/contacts');
if ($path == '/contacts') {
$path = \Drupal::service('path_alias.manager')->getPathByAlias('/kontakty');
}
$params = Url::fromUri("internal:" . $path)->getRouteParameters();
$entity_type = key($params);
$node = \Drupal::entityTypeManager()->getStorage($entity_type)->load($params[$entity_type]);
$node->body->format = $data['body']['format'];
$node->body->value = $data['body']['value'];
$node->path = [
'alias' => $data['path'],
'pathauto' => PathautoState::SKIP,
];
$node->save();
}
/**
* Import Node.
* If you need to add a custom
* image/gallery, attach or taxonomy field,
* add a new 'case' to existing ones.
*/
private function importNode($data) {
$storage = \Drupal::entityTypeManager()->getStorage('node');
foreach ($data as $key => $value) {
switch ($key) {
case 'field_image':
case 'field_gallery':
$n[$key] = $this->importImages($value);
break;
case 'field_attach':
$n[$key] = $this->importAttach($value);
break;
case 'field_type_service':
case 'field_object_type':
$n[$key] = $this->importAttach($value);
break;
case 'field_paragraph':
$n[$key] = $this->importParagraph($value);
break;
default:
$n[$key] = $value;
break;
}
}
$node = $storage->create($n);
if (!empty($data['field_image_big'])) {
$node->set('field_image_big', $this->importMedia($data['field_image_big']));
}
if (!empty($data['path'])) {
$node->path = [
'alias' => $data['path'],
'pathauto' => PathautoState::SKIP,
];
}
$node->save();
if (array_key_exists('is_front', $data) && $data['is_front'] == TRUE) {
$id = $node->id();
$config = \Drupal::service('config.factory')->getEditable('system.site');
$config->set('page.front', "/node/$id");
$config->save();
}
}
/**
* Set Synlanding form background.
*/
private function setSynLandingConfig($data) {
$image = $this->importImages($data['form_bg_path']);
$idFile = array_shift($image)['target_id'];
$config = \Drupal::config($data['config_id']);
\Drupal::configFactory()
->getEditable($data['config_id'])
->set('form_bg', [$idFile])
->save();
}
/**
* Import File.
* Synhelper Taxonomy import.
*
* @param string $directory
* Content directory.
*
* @TODO: FileSystemInterface::EXISTS_RENAME.
* @command synhelper:taxonomy_import
* @usage synhelper:scont $directory
* Taxonomy import from $directory/taxonomy.
*/
private function importFiles($filenames) {
$file_storage = \Drupal::service('entity_type.manager')->getStorage('file');
$tmp = "/tmp";
$result = [];
if (is_string($filenames)) {
$filenames = [$filenames];
}
if (is_array($filenames) && !empty($filenames)) {
$fs = \Drupal::service('file_system');
$directory = "public://import/";
if (!file_exists($fs->realpath($directory))) {
\Drupal::service('file_system')->mkdir($directory, NULL, TRUE);
}
foreach ($filenames as $fname) {
$filename = explode("/", $fname);
$filename = end($filename);
$f = file_get_contents("$fname");
$destination = "{$directory}{$filename}";
$uri = \Drupal::service('file_system')->saveData($f, $destination, FileSystemInterface::EXISTS_RENAME);
$file = $file_storage->create([
'filename' => $filename,
'uri' => $uri,
'status' => 1,
]);
$file->save();
$fid = $file->id();
if (!empty($fid)) {
$result[$fid] = [
'target_id' => $fid,
];
}
}
}
return $result;
public function importTaxonomy($directory) {
$this->output()->writeln("Import Taxonomy from: $directory/taxonomy");
\Drupal::service('synhelper.content_import')->importTaxonomy($directory);
$this->output()->writeln("!NOTE Done.");
}
/**
* Import Images.
* Synhelper Menu import.
*
* @param string $directory
* Content directory.
*
* @command synhelper:menu_import
* @usage synhelper:scont $directory
* Menu import from $directory/menu.
*/
private function importImages($images) {
if (!empty($images)) {
$files = $this->importFiles($images);
return $files;
}
public function importMenu($directory) {
$this->output()->writeln("Import Menu from: $directory/menu");
\Drupal::service('synhelper.content_import')->importMenu($directory);
$this->output()->writeln("!NOTE Done.");
}
/**
* Import Attach.
* Synhelper Contacts import.
*
* @param string $directory
* Content directory.
*
* @command synhelper:contacts_import
* @usage synhelper:scont $directory
* Contacts import from $directory/contacts.
*/
private function importAttach($attachFiles) {
if (!empty($attachFiles)) {
$i = 0;
$filenames = [];
$descriptions = [];
foreach ($attachFiles as $attach) {
$filenames[$i] = $attach['source'];
$descriptions[$i] = $attach['description'];
$i++;
}
$files = $this->importFiles($filenames);
$i = 0;
foreach ($files as $k => $file) {
$files[$k]['description'] = $descriptions[$i];
$files[$k]['display'] = 1;
$i++;
}
return $files;
}
public function importContacts($directory) {
$this->output()->writeln("Import Contacts from: $directory/contacts");
\Drupal::service('synhelper.content_import')->importContacts($directory);
$this->output()->writeln("!NOTE Done.");
}
/**
* Import Media.
* Synhelper Nodes import.
*
* @param string $directory
* Content directory.
*
* @TODO: FileSystemInterface::EXISTS_RENAME.
* @command synhelper:node_import
* @usage synhelper:scont $directory
* Nodes import from $directory/nodes.
*/
private function importMedia($filenames) {
$file_storage = \Drupal::service('entity_type.manager')->getStorage('file');
$tmp = "/tmp";
$result = [];
if (is_string($filenames)) {
$filenames = [$filenames];
}
if (is_array($filenames) && !empty($filenames)) {
$fs = \Drupal::service('file_system');
$directory = "public://import/media";
if (!file_exists($fs->realpath($directory))) {
\Drupal::service('file_system')->mkdir($directory, NULL, TRUE);
}
foreach ($filenames as $fname) {
$filename = explode("/", $fname);
$filename = end($filename);
$f = file_get_contents("$fname");
$destination = "{$directory}{$filename}";
$uri = \Drupal::service('file_system')->saveData($f, $destination, FileSystemInterface::EXISTS_REPLACE);
$file = $file_storage->create([
'filename' => $filename,
'uri' => $uri,
'status' => 1,
]);
$file->save();
$fid = $file->id();
$media = Media::create([
'bundle' => 'image',
'uid' => 1,
'field_media_image' => [
'target_id' => $fid,
],
]);
$media->setName($filename)->setPublished(TRUE)->save();
$mid = $media->id();
}
if (!empty($mid)) {
$result[] = $mid;
}
}
return $result;
public function importNode($directory) {
$this->output()->writeln("Import Nodes from: $directory/nodes");
\Drupal::service('synhelper.content_import')->importNode($directory);
$this->output()->writeln("!NOTE Done.");
}
/**
* Get taxonomy term id by name or by name and vocabulary id.
* Synhelper Synlanding Config import.
*
* @param string $directory
* Content directory.
*
* @command synhelper:synlanding_config_import
* @usage synhelper:scont $directory
* Synlanding Config import from $directory/synlanding.
*/
private function getTidByName($name = NULL, $vid = NULL) {
$properties = [];
if (!empty($name)) {
$properties['name'] = $name;
}
if (!empty($vid)) {
$properties['vid'] = $vid;
}
$terms = \Drupal::entityTypeManager()->getStorage('taxonomy_term')->loadByProperties($properties);
$term = reset($terms);
return !empty($term) ? $term->id() : 0;
public function setSynLandingConfig($directory) {
$this->output()->writeln("Import SynLandingConfig from: $directory/synlanding");
\Drupal::service('synhelper.content_import')->setSynLandingConfig($directory);
$this->output()->writeln("!NOTE Done.");
}
}
<?php
namespace Drupal\synhelper\Service;
use Drupal\Core\Url;
use Drupal\media\Entity\Media;
use Drupal\pathauto\PathautoState;
use Drupal\Core\Config\FileStorage;
use Drupal\Core\File\FileSystemInterface;
/**
* Defines Content Import.
* ContactsImport.
* NodesImport.
* TaxonomyImport.
* MenuImport.
* SynlandingConfigImport.
*
* @internal
* For internal usage by the Commerce synhelper module.
*/
class SynhelperContentImport {
/**
* Import Full Content.
*/
public function import(string $directory) {
$this->importContacts($directory);
$this->importTaxonomy($directory);
$this->importNode($directory);
$this->importMenu($directory);
$this->setSynLandingConfig($directory);
}
/**
* Import Taxonomy.
*/
public function importTaxonomy(string $directory) {
$sourceTaxonomy = new FileStorage($directory . '/taxonomy');
foreach ($sourceTaxonomy->listAll() as $file) {
$data = $sourceTaxonomy->read($file);
if (!$this->checkVocabularyExistence($data['vid'])) {
$this->createVocabulary($data);
}
$this->createTaxonomyTerm($data);
if (!empty($data['children_terms'])) {
$this->createChildTerms($data, $data['vid']);
}
}
}
/**
* Import Menu.
*/
public function importMenu(string $directory) {
$sourceMenu = new FileStorage($directory . '/menu');
foreach ($sourceMenu->listAll() as $file) {
$data = $sourceMenu->read($file);
if ($menu = \Drupal::entityTypeManager()->getStorage('menu')->load($data['menu']['id'])) {
$menu->set('label', $data['menu']['label']);
$menu->set('description', $data['menu']['description']);
$menu->save();
}