/**
   * Calculate the anchor such that the crop will not exceed the image boundary.
   *
   * Given the top-left anchor (in pixels), the crop size and the image size,
   * reposition the anchor to ensure the crop area does not exceed the bounds of
   * the image.
   *
   * @param array $anchor
   *   An array with the keys 'x' and 'y'. Values are in pixels representing the
   *   top left corner of the of the crop area relative to the image.
   * @param ImageInterface $image
   *   The image to which the crop area must be constrained.
   * @param CropInterface $crop
   *   The crop object used to define the crop.
   *
   * @return array
   *   An array with the keys 'x' and 'y'.
   */
  protected function constrainCropArea($anchor, ImageInterface $image, CropInterface $crop) {
    $image_size = [
      'width' => $image->getWidth(),
      'height' => $image->getHeight(),
    ];
    $crop_size = $crop->size();

    // Ensure that the crop area doesn't fall off the bottom right of the image.
    $anchor = [
      'x' => $anchor['x'] + $crop_size['width'] <= $image_size['width'] ? $anchor['x'] : $image_size['width'] - $crop_size['width'],
      'y' => $anchor['y'] = $anchor['y'] + $crop_size['height'] <= $image_size['height'] ? $anchor['y'] : $image_size['height'] - $crop_size['height'],
    ];

    // Ensure that the crop area doesn't fall off the top left of the image.
    $anchor = [
      'x' => max(0, $anchor['x']),
      'y' => max(0, $anchor['y']),
    ];

    return $anchor;
  }