Example #1
0
  /**
   * {@inheritdoc}
   */
  public function getCropEntity(FileInterface $file, $crop_type) {
    if (Crop::cropExists($file->getFileUri(), $crop_type)) {
      /** @var \Drupal\crop\CropInterface $crop */
      $crop = Crop::findCrop($file->getFileUri(), $crop_type);
    }
    else {
      $values = [
        'type' => $crop_type,
        'entity_id' => $file->id(),
        'entity_type' => 'file',
        'uri' => $file->getFileUri(),
      ];

      $crop = \Drupal::entityTypeManager()
        ->getStorage('crop')
        ->create($values);
    }

    return $crop;
  }
  /**
   * Form submission handler for image_widget_crop.
   */
  public function submitFormCrops(array &$form, FormStateInterface $form_state, $form_state_values = array(), $entity = NULL) {
    // @var \Drupal\file_entity\Entity\FileEntity $entity.

      // @var \Drupal\image_widget_crop\ImageWidgetCropManager $image_widget_crop_manager.
      $image_widget_crop_manager = \Drupal::service('image_widget_crop.manager');
      // Parse all values and get properties associate with the crop type.
      foreach ($form_state_values['image_crop']['crop_wrapper'] as $crop_type_name => $properties) {
        $properties = $properties['crop_container']['values'];
        // @var \Drupal\crop\Entity\CropType $crop_type.
        $crop_type = \Drupal::entityTypeManager()
          ->getStorage('crop_type')
          ->load($crop_type_name);

        // If the crop type needed is disabled or delete.
        if (empty($crop_type) && $crop_type instanceof \Drupal\crop\Entity\CropType) {
          drupal_set_message(t("The CropType ('@cropType') is not active or not defined. Please verify configuration of image style or ImageWidgetCrop formatter configuration", ['@cropType' => $crop_type->id()]), 'error');
          return;
        }

        if (is_array($properties) && isset($properties)) {
          $crop_exists = \Drupal\crop\Entity\Crop::cropExists($entity->getFileUri(), $crop_type_name);
          if (!$crop_exists) {
            if ($properties['crop_applied'] == '1' && isset($properties) && (!empty($properties['width']) && !empty($properties['height']))) {
              $image_widget_crop_manager->applyCrop($properties, $form_state_values['image_crop'], $crop_type);
            }
          }
          else {
            // Get all imagesStyle used this crop_type.
            $image_styles = $image_widget_crop_manager->getImageStylesByCrop($crop_type_name);
            $crops = $image_widget_crop_manager->loadImageStyleByCrop($image_styles, $crop_type, $entity->getFileUri());
            // If the entity already exist & is not deleted by user update
            // $crop_type_name crop entity.
            if ($properties['crop_applied'] == '0' && !empty($crops)) {
              $image_widget_crop_manager->deleteCrop($entity->getFileUri(), $crop_type, $entity->id());
            }
            elseif (isset($properties) && (!empty($properties['width']) && !empty($properties['height']))) {
              $image_widget_crop_manager->updateCrop($properties, [
                'file-uri' => $entity->getFileUri(),
                'file-id' => $entity->id(),
              ], $crop_type);
            }
          }
        }
      }
  }
  /**
   * {@inheritdoc}
   *
   * Form API callback. Retrieves the value for the file_generic field element.
   *
   * This method is assigned as a #value_callback in formElement() method.
   */
  public static function value($element, $input, FormStateInterface $form_state) {
    $return = parent::value($element, $input, $form_state);

    // When an element is loaded, focal_point needs to be set. During a form
    // submission the value will already be there.
    if (isset($return['target_id']) && !isset($return['focal_point'])) {
      /** @var \Drupal\file\FileInterface $file */
      $file = \Drupal::service('entity_type.manager')
        ->getStorage('file')
        ->load($return['target_id']);
      $crop_type = \Drupal::config('focal_point.settings')->get('crop_type');
      $crop = Crop::findCrop($file->getFileUri(), $crop_type);
      if ($crop) {
        $anchor = \Drupal::service('focal_point.manager')
          ->absoluteToRelative($crop->x->value, $crop->y->value, $return['width'], $return['height']);
        $return['focal_point'] = "{$anchor['x']},{$anchor['y']}";
      }
    }
    return $return;
  }
Example #4
0
  /**
   * Tests crop save.
   */
  public function testCropSave() {
    // Test file.
    $file = $this->getTestFile();
    $file->save();

    /** @var \Drupal\crop\CropInterface $crop */
    $values = [
      'type' => $this->cropType->id(),
      'entity_id' => $file->id(),
      'entity_type' => $file->getEntityTypeId(),
      'uri' => $file->getFileUri(),
      'x' => '100',
      'y' => '150',
      'width' => '200',
      'height' => '250',
    ];
    $crop = $this->cropStorage->create($values);

    $this->assertEquals(['x' => 100, 'y' => 150], $crop->position(), t('Position correctly returned.'));
    $this->assertEquals(['width' => 200, 'height' => 250], $crop->size(), t('Size correctly returned.'));
    $this->assertEquals(['x' => 0, 'y' => 25], $crop->anchor(), t('Anchor correctly returned.'));

    $crop->setPosition(10, 10);
    $crop->setSize(20, 20);

    $this->assertEquals(['x' => 10, 'y' => 10], $crop->position(), t('Position correctly returned.'));
    $this->assertEquals(['width' => 20, 'height' => 20], $crop->size(), t('Size correctly returned.'));
    $this->assertEquals(['x' => 0, 'y' => 0], $crop->anchor(), t('Anchor correctly returned.'));

    $crop->setPosition($values['x'], $values['y']);
    $crop->setSize($values['width'], $values['height']);

    try {
      $crop->save();
      $this->assertTrue(TRUE, 'Crop saved correctly.');
    }
    catch (\Exception $exception) {
      $this->assertTrue(FALSE, 'Crop not saved correctly.');
    }

    $loaded_crop = $this->cropStorage->loadUnchanged(1);
    foreach ($values as $key => $value) {
      switch ($key) {
        case 'type':
          $this->assertEqual($loaded_crop->{$key}->target_id, $value, new FormattableMarkup('Correct value for @field found.', ['@field' => $key]));
          break;

        default:
          $this->assertEqual($loaded_crop->{$key}->value, $value, new FormattableMarkup('Correct value for @field found.', ['@field' => $key]));
          break;
      }
    }

    $this->assertTrue(Crop::cropExists($file->getFileUri()), t('Crop::cropExists() correctly found saved crop.'));
    $this->assertTrue(Crop::cropExists($file->getFileUri(), $this->cropType->id()), t('Crop::cropExists() correctly found saved crop.'));
    $this->assertFalse(Crop::cropExists($file->getFileUri(), 'nonexistent_type'), t('Crop::cropExists() correctly handled wrong type.'));
    $this->assertFalse(Crop::cropExists('public://nonexistent.png'), t('Crop::cropExists() correctly handled wrong uri.'));

    $loaded_crop = Crop::findCrop($file->getFileUri(), $this->cropType->id());
    $this->assertEquals($crop->id(), $loaded_crop->id(), t('Crop::findCrop() correctly loaded crop entity.'));
    $this->assertEquals($crop->position(), $loaded_crop->position(), t('Crop::findCrop() correctly loaded crop entity.'));
    $this->assertEquals($crop->size(), $loaded_crop->size(), t('Crop::findCrop() correctly loaded crop entity.'));
    $this->assertEquals($crop->uri->value, $loaded_crop->uri->value, t('Crop::findCrop() correctly loaded crop entity.'));
    $this->assertNull(Crop::findCrop('public://nonexistent.png', $this->cropType->id()), t('Crop::findCrop() correctly handled nonexistent crop.'));
    $this->assertNull(Crop::findCrop('public://nonexistent.png', 'nonexistent_crop'), t('Crop::findCrop() correctly handled nonexistent crop.'));
  }
Example #5
0
  /**
   * Gets crop entity for the image.
   *
   * @param ImageInterface $image
   *   Image object.
   *
   * @return \Drupal\Core\Entity\EntityInterface|\Drupal\crop\CropInterface|FALSE
   *   Crop entity or FALSE if crop doesn't exist.
   */
  protected function getCrop(ImageInterface $image) {
    if (!isset($this->crop)) {
      $this->crop = FALSE;
      if ($crop = Crop::findCrop($image->getSource(), $this->configuration['crop_type'])) {
        $this->crop = $crop;
      }
    }

    return $this->crop;
  }
  /**
   * Applies the crop effect to an image.
   *
   * @param ImageInterface $image
   *   The image resource to crop.
   *
   * @return bool
   *   TRUE if the image is successfully cropped, otherwise FALSE.
   */
  public function applyCrop(ImageInterface $image) {
    $crop_type = $this->focalPointConfig->get('crop_type');

    /** @var \Drupal\crop\CropInterface $crop */
    if ($crop = Crop::findCrop($image->getSource(), $crop_type)) {
      // An existing crop has been found; set the size.
      $crop->setSize($this->configuration['width'], $this->configuration['height']);
    }
    else {
      // No existing crop could be found; create a new one using the size.
      $crop = $this->cropStorage->create([
        'type' => $crop_type,
        'x' => (int) round($image->getWidth() / 2),
        'y' => (int) round($image->getHeight() / 2),
        'width' => $this->configuration['width'],
        'height' => $this->configuration['height'],
      ]);
    }

    // Get the top-left anchor position of the crop area.
    $anchor = $this->getAnchor($image, $crop);

    if (!$image->crop($anchor['x'], $anchor['y'], $this->configuration['width'], $this->configuration['height'])) {
      $this->logger->error(
        'Focal point scale and crop failed while scaling and cropping using the %toolkit toolkit on %path (%mimetype, %dimensions, anchor: %anchor)',
        [
          '%toolkit' => $image->getToolkitId(),
          '%path' => $image->getSource(),
          '%mimetype' => $image->getMimeType(),
          '%dimensions' => $image->getWidth() . 'x' . $image->getHeight(),
          '%anchor' => $anchor,
        ]
      );
      return FALSE;
    }

    return TRUE;
  }