You are here

public static function BynderUpload::batchCreateEntities in Bynder 8.2

Same name and namespace in other branches
  1. 8.3 src/Plugin/EntityBrowser/Widget/BynderUpload.php \Drupal\bynder\Plugin\EntityBrowser\Widget\BynderUpload::batchCreateEntities()
  2. 8 src/Plugin/EntityBrowser/Widget/BynderUpload.php \Drupal\bynder\Plugin\EntityBrowser\Widget\BynderUpload::batchCreateEntities()
  3. 4.0.x src/Plugin/EntityBrowser/Widget/BynderUpload.php \Drupal\bynder\Plugin\EntityBrowser\Widget\BynderUpload::batchCreateEntities()

Upload batch operation callback which creates media entities.

File

src/Plugin/EntityBrowser/Widget/BynderUpload.php, line 336

Class

BynderUpload
Uses upload to create media entities.

Namespace

Drupal\bynder\Plugin\EntityBrowser\Widget

Code

public static function batchCreateEntities($file, $source_field, $bundle, &$context) {
  try {
    if (\Drupal::service('session')
      ->get('upload_permissions', FALSE) != 'MEDIAUPLOADFORAPPROVAL') {

      // Let's try to fetch the uploaded resource from the API as we will be
      // able to save it only if that succeeds.
      $uuid = $context['results'][$file['path']];
      $media_info = \Drupal::service('bynder_api')
        ->getMediaInfo($uuid);
      $entity = Media::create([
        'bundle' => $bundle,
        $source_field => $uuid,
        BynderMetadataItem::METADATA_FIELD_NAME => $media_info,
      ]);
      unset($context['results'][$file['path']]);
      $context['results'][] = $entity;
      $context['message'] = t('Mapped @file locally.', [
        '@file' => $file['filename'],
      ]);
    }
    else {
      \Drupal::messenger()
        ->addWarning(t('Your file was uploaded to Bynder but needs to be approved before you can use it. Please go to your Bynder waiting room and review the uploaded assets.'));
    }
    $context['finished'] = 1;
  } catch (\Exception $e) {

    // If fetching failed try few more times. If waiting doesn't help fail the
    // batch eventually.
    if (empty($context['sandbox']['fails'])) {
      $context['sandbox']['fails'] = 0;
    }
    $context['sandbox']['fails']++;
    $context['finished'] = 0;
    $context['message'] = t('Mapping @file locally.', [
      '@file' => $file['filename'],
    ]);
    sleep(3);
    if ($context['sandbox']['fails'] >= static::FAIL_LIMIT) {
      watchdog_exception('bynder', $e);
      (new UploadFailedException(t("There was an unexpected error after uploading the file to Bynder.")))
        ->displayMessage();
      \Drupal::messenger()
        ->addWarning(t('There was an unexpected error after uploading the file to Bynder. Please contact your site administrator for more info.'));
    }
  }
}