protected function ParagraphsType::restoreDefaultIcon

Restores the icon file from the default icon value.

Return value

\Drupal\file\FileInterface|bool The icon's file entity or FALSE if no default icon set.

1 call to ParagraphsType::restoreDefaultIcon()
ParagraphsType::getIconFile in paragraphs/src/Entity/ParagraphsType.php
Returns the icon file entity.

File

paragraphs/src/Entity/ParagraphsType.php, line 116

Class

ParagraphsType
Defines the ParagraphsType entity.

Namespace

Drupal\paragraphs\Entity

Code

protected function restoreDefaultIcon() {

  // Default icon data in RFC 2397 format ("data" URL scheme).
  if ($this->icon_default && ($icon_data = fopen($this->icon_default, 'r'))) {

    // Compose the default icon file destination.
    $icon_meta = stream_get_meta_data($icon_data);

    // File extension from MIME, only JPG/JPEG, PNG and SVG expected.
    [
      ,
      $icon_file_ext,
    ] = explode('image/', $icon_meta['mediatype']);

    // SVG special case.
    if ($icon_file_ext == 'svg+xml') {
      $icon_file_ext = 'svg';
    }
    $filesystem = \Drupal::service('file_system');
    $icon_upload_path = ParagraphsTypeInterface::ICON_UPLOAD_LOCATION;
    $icon_file_destination = $icon_upload_path . $this
      ->id() . '-default-icon.' . $icon_file_ext;

    // Check the directory exists before writing data to it.
    $filesystem
      ->prepareDirectory($icon_upload_path, FileSystemInterface::CREATE_DIRECTORY | FileSystemInterface::MODIFY_PERMISSIONS);

    // Save the default icon file.
    $icon_file_uri = $filesystem
      ->saveData($icon_data, $icon_file_destination);
    if ($icon_file_uri) {

      // Create the icon file entity.
      $icon_entity_values = [
        'uri' => $icon_file_uri,
        'uid' => \Drupal::currentUser()
          ->id(),
        'uuid' => $this->icon_uuid,
        'status' => FileInterface::STATUS_PERMANENT,
      ];

      // Delete existent icon file if it exists.
      if ($old_icon = $this
        ->getFileByUuid($this->icon_uuid)) {
        $old_icon
          ->delete();
      }
      $new_icon = File::create($icon_entity_values);
      $new_icon
        ->save();
      $this
        ->updateFileIconUsage($new_icon, $old_icon);
      return $new_icon;
    }
  }
  return FALSE;
}