DrushContentImport.php 13.2 KB
Newer Older
masdzen's avatar
masdzen committed
1
2
3
4
5
<?php

namespace Drupal\synhelper\Drush;

use Drush\Commands\DrushCommands;
APolitsin's avatar
APolitsin committed
6
7
8
9

use Drupal\Core\Form\ConfigFormBase;
use Drupal\Core\Url;
use Drupal\media\Entity\Media;
masdzen's avatar
masdzen committed
10
use Drupal\Core\Config\FileStorage;
masdzen's avatar
masdzen committed
11
use Drupal\Core\File\FileSystemInterface;
masdzen's avatar
masdzen committed
12

APolitsin's avatar
APolitsin committed
13
14
// use App\Utility\StepBase;
// use Symfony\Component\Yaml\Yaml;
masdzen's avatar
masdzen committed
15
16
17
18
19
20
/**
 * A Drush commandfile.
 */
class DrushContentImport extends DrushCommands {

  /**
APolitsin's avatar
APolitsin committed
21
   * Synhrlper content import.
masdzen's avatar
masdzen committed
22
23
   *
   * @param string $directory
APolitsin's avatar
APolitsin committed
24
   *   Content directory.
masdzen's avatar
masdzen committed
25
26
27
28
   *
   * @command synhelper:content
   * @aliases scont
   * @options arr An option that takes multiple values.
Aleksey.Alekseev's avatar
Aleksey.Alekseev committed
29
   * @usage synhelper:scont  $directory
APolitsin's avatar
APolitsin committed
30
   *   Import сontacts from
Aleksey.Alekseev's avatar
Aleksey.Alekseev committed
31
   *    $directory/contacts.
APolitsin's avatar
APolitsin committed
32
   *   Import nodes from
Aleksey.Alekseev's avatar
Aleksey.Alekseev committed
33
   *    $directory/nodes.
APolitsin's avatar
APolitsin committed
34
   *   Import taxonomy from
Aleksey.Alekseev's avatar
Aleksey.Alekseev committed
35
   *    $directory/taxonomy.
APolitsin's avatar
APolitsin committed
36
   *   Resets SynLandyng config from
Aleksey.Alekseev's avatar
Aleksey.Alekseev committed
37
   *    $directory/synlanding.
masdzen's avatar
masdzen committed
38
39
40
   */
  public function import($directory) {
    $this->output()->writeln("Import content from: $directory");
APolitsin's avatar
APolitsin committed
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64

    $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);
masdzen's avatar
masdzen committed
65
66
      $this->importNode($data);
    }
APolitsin's avatar
APolitsin committed
67
    $this->output()->writeln("!NOTE Done.");
masdzen's avatar
masdzen committed
68

APolitsin's avatar
APolitsin committed
69
70
71
72
73
74
75
76
    $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("!NOTE Done.");
masdzen's avatar
masdzen committed
77
78
79
  }

  /**
APolitsin's avatar
APolitsin committed
80
   * Import Paragraph.
masdzen's avatar
masdzen committed
81
82
83
   */
  private function importParagraph($field_paragraph) {
    $storage = \Drupal::service('entity_type.manager')->getStorage('paragraph');
APolitsin's avatar
APolitsin committed
84
85

    /* Importing About Us */
masdzen's avatar
masdzen committed
86
    $items = [];
APolitsin's avatar
APolitsin committed
87
88
    $about = $field_paragraph['about'];
    foreach ($about['field_about_items'] as $about_item) {
masdzen's avatar
masdzen committed
89
90
91
      $item = $storage->create($about_item);
      $item->save();
      $items[] = [
APolitsin's avatar
APolitsin committed
92
        'type' => $about_item['type'],
masdzen's avatar
masdzen committed
93
94
        'target_id' => $item->id(),
        'target_revision_id' => $item->getRevisionId(),
APolitsin's avatar
APolitsin committed
95
96
        'field_title' => $about_item['field_title'],
        'field_description' => $about_item['field_description'],
masdzen's avatar
masdzen committed
97
98
      ];
    }
APolitsin's avatar
APolitsin committed
99
100
101
    $about['field_about_items'] = $items;
    $paragraph = $storage->create($about);
    $paragraph->save();
masdzen's avatar
masdzen committed
102
    $paragraphs = [];
APolitsin's avatar
APolitsin committed
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
    $paragraphs[] = [
      'type' => $about['type'],
      'target_id' => $paragraph->id(),
      'target_revision_id' => $paragraph->getRevisionId(),
    ];

    /* Importing 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);
masdzen's avatar
masdzen committed
127
    $paragraph->save();
APolitsin's avatar
APolitsin committed
128

masdzen's avatar
masdzen committed
129
    $paragraphs[] = [
APolitsin's avatar
APolitsin committed
130
      'type' => $imageBloсks['type'],
masdzen's avatar
masdzen committed
131
132
133
134
135
136
137
      'target_id' => $paragraph->id(),
      'target_revision_id' => $paragraph->getRevisionId(),
    ];
    return $paragraphs;
  }

  /**
APolitsin's avatar
APolitsin committed
138
   * Import Taxonomy.
masdzen's avatar
masdzen committed
139
   */
APolitsin's avatar
APolitsin committed
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
  private function importTaxonomy($data) {
    $storage = \Drupal::entityTypeManager()->getStorage('taxonomy_term');
    $t = [
      'vid' => $data['vid'],
      'name' => $data['name'],
    ];
    $taxonomyTerm = $storage->create($t);
    $taxonomyTerm->save();
  }

  /**
   * Import TaxonomyField.
   */
  private function importTaxonomyField($taxonomyTermName) {
    if (!empty($taxonomyTermName)) {
      $taxonomyTermId = $this->getTidByName($taxonomyTermName);
      return $taxonomyTermId;
    }
  }

  /**
   * Import Contacts.
   */
  private function importContacts($data) {
    $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->save();
  }

  /**
   * Import Node.
   */
  private function importNode($data) {
    $storage = \Drupal::entityTypeManager()->getStorage('node');
    if ($data['type'] == 'project') {
      $n = [
        'uid' => 1,
        'type' => $data['type'],
        'title' => $data['title'],
        'status' => $data['status'],
        'path' => $data['path'],
        'created' => $data['created'],
        'changed' => $data['changed'],
        'promote' => $data['promote'],
        'sticky' => $data['sticky'],
        'field_short' => $data['field_short'],
        'field_size' => $data['field_size'],
        'field_material' => $data['field_material'],
        'field_area' => $data['field_area'],
        'body' => $data['body'],
        'field_count_floors' => $data['field_count_floors'],
        'field_count_rooms' => $data['field_count_rooms'],
        'field_price' => $data['field_price'],
        'field_object_type' => $this->importTaxonomyField($data['field_object_type']),
        'field_image' => $this->importImages($data['field_image']),
        'field_attach' => $this->importAttach($data['field_attach']),
        'field_gallery' => $this->importImages($data['field_gallery']),
      ];
    }
Aleksey.Alekseev's avatar
Aleksey.Alekseev committed
204
    elseif ($data['type'] == 'portfolio') {
APolitsin's avatar
APolitsin committed
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
      $n = [
        'uid' => 1,
        'type' => $data['type'],
        'title' => $data['title'],
        'status' => $data['status'],
        'path' => $data['path'],
        'created' => $data['created'],
        'changed' => $data['changed'],
        'promote' => $data['promote'],
        'sticky' => $data['sticky'],
        'field_short' => $data['field_short'],
        'body' => $data['body'],
        'field_image' => $this->importImages($data['field_image']),
        'field_attach' => $this->importAttach($data['field_attach']),
        'field_gallery' => $this->importImages($data['field_gallery']),
      ];
    }
    elseif ($data['type'] == 'page') {
      $n = [
        'uid' => 1,
        'type' => $data['type'],
        'title' => $data['title'],
        'status' => $data['status'],
        'path' => $data['path'],
        'created' => $data['created'],
        'changed' => $data['changed'],
        'promote' => $data['promote'],
        'sticky' => $data['sticky'],
        'body' => $data['body'],
        'field_metatag' => $data['field_metatag'],
        'field_attach' => $this->importAttach($data['field_attach']),
      ];
    }
    elseif ($data['type'] == 'service') {
      $n = [
        'uid' => 1,
        'type' => $data['type'],
        'title' => $data['title'],
        'status' => $data['status'],
        'path' => $data['path'],
        'created' => $data['created'],
        'changed' => $data['changed'],
        'promote' => $data['promote'],
        'sticky' => $data['sticky'],
        'field_service_info' => $data['field_service_info'],
        'field_short' => $data['field_short'],
        'field_metatag' => $data['field_metatag'],
        'field_type_service' => $this->importTaxonomyField($data['field_type_service']),
        'field_attach' => $this->importAttach($data['field_attach']),
        'field_paragraph' => $this->importParagraph($data['field_paragraph']),
      ];
    }
    $node = $storage->create($n);
    if (!empty($data['field_image_big'])) {
      $node->set('field_image_big', $this->importMedia($data['field_image_big']));
    }
    $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 SynlandingConfig for form_bg.
   */
  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.
   *
   * @TODO: FileSystemInterface::EXISTS_RENAME.
   */
  private function importFiles($filenames) {
masdzen's avatar
masdzen committed
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
    $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}";
APolitsin's avatar
APolitsin committed
306
        $uri = \Drupal::service('file_system')->saveData($f, $destination, FileSystemInterface::EXISTS_RENAME);
masdzen's avatar
masdzen committed
307
        $file = $file_storage->create([
APolitsin's avatar
APolitsin committed
308
          'filename' => $filename,
masdzen's avatar
masdzen committed
309
310
311
312
313
314
          'uri' => $uri,
          'status' => 1,
        ]);
        $file->save();
        $fid = $file->id();
        if (!empty($fid)) {
APolitsin's avatar
APolitsin committed
315
316
317
          $result[$fid] = [
            'target_id' => $fid,
          ];
masdzen's avatar
masdzen committed
318
319
320
321
        }
      }
    }
    return $result;
masdzen's avatar
masdzen committed
322
323
  }

APolitsin's avatar
APolitsin committed
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
  /**
   * Import Images.
   */
  private function importImages($images) {
    if (!empty($images)) {
      $files = $this->importFiles($images);
      return $files;
    }
  }

  /**
   * Import Attach.
   */
  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;
    }
  }

  /**
   * Import Media.
   *
   * @TODO: FileSystemInterface::EXISTS_RENAME.
   */
  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;
  }

  /**
   * Get taxonomy term id by name or by name and vocabulary id.
   */
  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;
  }

masdzen's avatar
masdzen committed
422
}