You are here

public function BookEventSubscriber::importBookOutlines in Tome 8

Imports all book outlines.

File

modules/tome_sync/src/EventSubscriber/BookEventSubscriber.php, line 93

Class

BookEventSubscriber
Event subscriber that keep book outlines in sync with content changes.

Namespace

Drupal\tome_sync\EventSubscriber

Code

public function importBookOutlines() {
  $this->connection
    ->truncate('book')
    ->execute();
  $directory = $this
    ->getExportDirectory();
  $storage = $this->entityTypeManager
    ->getStorage('node');
  if (!file_exists("{$directory}/book_outlines.json")) {
    return;
  }
  $rows = json_decode(file_get_contents("{$directory}/book_outlines.json"), TRUE);
  $id_map = [];
  foreach ($rows as $row) {
    foreach ($row as $key => $value) {
      if (!$value || in_array($key, [
        'has_children',
        'weight',
        'depth',
      ], TRUE)) {
        $row[$key] = $value;
      }
      else {
        if (!isset($id_map[$value]) && ($results = $storage
          ->loadByProperties([
          'uuid' => $value,
        ]))) {
          $node = reset($results);
          $id_map[$value] = $node
            ->id();
        }
        $row[$key] = $id_map[$value];
      }
    }
    $this->connection
      ->insert('book')
      ->fields($row)
      ->execute();
  }
}