view_mode_crop-1.0.x-dev/tests/src/Functional/ViewModeCropMediaLibraryWidgetTest.php

tests/src/Functional/ViewModeCropMediaLibraryWidgetTest.php
<?php

namespace Drupal\Tests\view_mode_crop\Functional;

use Drupal\field\Entity\FieldConfig;
use Drupal\field\Entity\FieldStorageConfig;
use Drupal\media\Entity\Media;
use Drupal\node\Entity\Node;
use Drupal\Tests\media\Functional\MediaFunctionalTestBase;
use Drupal\view_mode_crop\ViewModeCropData;

/**
 * Tests the image ViewModeCropMediaLibraryWidget field widget.
 *
 * @group view_mode_crop
 */
class ViewModeCropMediaLibraryWidgetTest extends MediaFunctionalTestBase {

  /**
   * {@inheritdoc}
   */
  protected $defaultTheme = 'stable';

  /**
   * {@inheritdoc}
   */
  protected static $modules = [
    'media_library',
    'node',
    'media',
    'text',
    'view_mode_crop',
  ];

  /**
   * PNG image.
   *
   * @var \Drupal\file\FileInterface
   */
  protected $publicPngFile;

  /**
   * Test media.
   *
   * @var \Drupal\media\MediaInterface
   */
  protected $media;

  /**
   * Media type image view display.
   *
   * @var \Drupal\Core\Entity\Display\EntityViewDisplayInterface
   */
  protected $mediaTypeImageViewDisplay;

  /**
   * The database connection.
   *
   * @var \Drupal\Core\Database\Connection
   */
  protected $database;

  /**
   * {@inheritDoc}
   */
  protected function setUp(): void {
    parent::setUp();
    $this->drupalCreateContentType(['type' => 'article']);
    $user = $this->drupalCreateUser([
      'access media overview',
      'create article content',
      'edit any article content',
      'delete any article content',
    ]);
    $media_type_image = $this->createMediaType('image', [
      'id' => 'image',
      'label' => 'Image',
    ]);

    /** @var \Drupal\file\FileRepositoryInterface $file_repository */
    $file_repository = $this->container->get('file.repository');
    $this->publicPngFile = $file_repository->writeData(file_get_contents(__DIR__ . '/assets/test.png'), 'public://test.png');
    $this->media = Media::create([
      'bundle' => 'image',
      'name' => 'Public png image',
      'field_media_image' => [
        [
          'target_id' => $this->publicPngFile->id(),
          'alt' => 'default alt',
          'title' => 'default title',
        ],
      ],
    ]);
    $this->media->save();

    FieldStorageConfig::create([
      'field_name' => 'field_media',
      'entity_type' => 'node',
      'type' => 'entity_reference',
      'settings' => [
        'target_type' => 'media',
      ],
      'cardinality' => 1,
    ])->save();

    $field_config = FieldConfig::create([
      'field_name' => 'field_media',
      'label' => 'field_media',
      'entity_type' => 'node',
      'bundle' => 'article',
      'required' => FALSE,
      'settings' => [
        'handler_settings' => [
          'target_bundles' => [
            $media_type_image->id() => $media_type_image->id(),
          ],
        ],
      ],
    ]);
    $field_config->save();

    /**
     * @var \Drupal\Core\Entity\EntityDisplayRepositoryInterface $display_repository
     */
    $display_repository = \Drupal::service('entity_display.repository');
    $display_repository->getFormDisplay('node', 'article')
      ->setComponent('field_media', [
        'type' => 'media_library_widget',
        'settings' => [],
      ])
      ->save();
    $display_repository->getViewDisplay('node', 'article')
      ->setComponent('field_media', [
        'type' => 'entity_reference_entity_view',
        'settings' => [
          'view_mode' => 'full',
        ],
      ])->save();

    $this->mediaTypeImageViewDisplay = $display_repository->getViewDisplay('media', 'image', 'full');
    $this->drupalLogin($user);

    $this->database = $this->container->get('database');
  }

  /**
   * Test the media library widget without cropping.
   *
   * When the media type doesn't have a view mode with cropping enabled,
   * no cropping button should be shown.
   */
  public function testCroppingNotAvailableWithoutViewModeCropFormatter(): void {
    $this->mediaTypeImageViewDisplay->setComponent('field_media_image', [
      'type' => 'image',
    ])->save();

    // When adding a node, the media library field is empty and the crop
    // open button should not be visible.
    $this->drupalGet('node/add/article');
    $this->assertSession()
      ->elementNotExists('xpath', '//input[contains(@class, "view_mode_crop_media_library_widget_crop_open")]');

    // When editing a node with an empty media field, the crop open button
    // should not be visible.
    $this->drupalGet('node/add/article');
    $this->submitForm([
      'title[0][value]' => $this->randomMachineName(),
    ], 'Save');
    preg_match('/node\/([0-9]+)/', $this->getUrl(), $matches);
    $this->drupalGet('node/' . $matches[1] . '/edit');
    $this->assertSession()
      ->elementNotExists('xpath', '//input[contains(@class, "view_mode_crop_media_library_widget_crop_open")]');

    // When editing a node with a filled media field, the crop open button
    // should not be visible.
    $node = Node::create([
      'type' => 'article',
      'title' => 'test',
      'field_media' => [$this->media->id()],
    ]);
    $node->save();
    $this->drupalGet('node/' . $node->id() . '/edit');
    $this->assertSession()
      ->elementNotExists('xpath', '//input[contains(@class, "view_mode_crop_media_library_widget_crop_open")]');
  }

  /**
   * Test the media library widget with cropping.
   *
   * When the media type does have a view mode with cropping enabled,
   * a cropping button should be shown.
   */
  public function testCroppingAvailableWithViewModeCropFormatter(): void {
    $this->mediaTypeImageViewDisplay->setComponent('field_media_image', [
      'type' => 'view_mode_crop_image',
    ])->save();

    // When adding a node, the media library field is empty and the crop
    // open button should not be visible.
    $this->drupalGet('node/add/article');
    $this->assertSession()
      ->elementNotExists('xpath', '//input[contains(@class, "view_mode_crop_media_library_widget_crop_open")]');

    // When editing a node with an empty media field, the crop open button
    // should not be visible.
    $this->drupalGet('node/add/article');
    $this->submitForm([
      'title[0][value]' => $this->randomMachineName(),
    ], 'Save');
    preg_match('/node\/([0-9]+)/', $this->getUrl(), $matches);
    $this->drupalGet('node/' . $matches[1] . '/edit');
    $this->assertSession()
      ->elementNotExists('xpath', '//input[contains(@class, "view_mode_crop_media_library_widget_crop_open")]');

    // When editing a node with a filled media field, the crop open button
    // should be visible.
    $view_mode_crop = [
      'full' => new ViewModeCropData('full', 'full label', 1, 2, 3, 4),
    ];
    $node = Node::create([
      'type' => 'article',
      'title' => 'test',
      'field_media' => [
        0 => [
          'target_id' => $this->media->id(),
          'view_mode_crop' => json_encode($view_mode_crop),
        ],
      ],
    ]);
    $node->save();

    $this->drupalGet('node/' . $node->id() . '/edit');

    $this->assertSession()
      ->elementExists('xpath', '//input[contains(@class, "view_mode_crop_media_library_widget_crop_open")]');

  }

  /**
   * Test that cropping data is saved into the database.
   */
  public function testSaveCroppingData(): void {
    $this->mediaTypeImageViewDisplay->setComponent('field_media_image', [
      'type' => 'view_mode_crop_image',
    ])->save();

    $view_mode_crop = [
      'full' => new ViewModeCropData('full', 'full label', 1, 2, 3, 4),
    ];

    $node = Node::create([
      'type' => 'article',
      'title' => 'test',
      'field_media' => [
        0 => [
          'target_id' => $this->media->id(),
          'view_mode_crop' => json_encode($view_mode_crop),
        ],
      ],
    ]);
    $node->save();

    $view_mode_crop_records = $this->database->select('view_mode_crop', 'vmc')
      ->fields('vmc', [
        'entity_type',
        'entity_id',
        'field_name',
        'delta',
        'data',
      ])
      ->condition('entity_type', 'node')
      ->condition('entity_id', $node->uuid())
      ->execute()
      ->fetchAll();
    $this->assertCount(1, $view_mode_crop_records);
    $this->assertEquals('field_media', $view_mode_crop_records[0]->field_name);
    $this->assertEquals(0, $view_mode_crop_records[0]->delta);
    $this->assertEquals(json_encode($view_mode_crop), $view_mode_crop_records[0]->data);

    $this->drupalGet('node/' . $node->id() . '/edit');

    $view_mode_crop['full']->x = 10;
    $view_mode_crop['full']->y = 20;
    $view_mode_crop['full']->w = 30;
    $view_mode_crop['full']->h = 40;

    $view_mode_crop_state = [
      'entityTypeId' => 'node',
      'id' => $node->uuid(),
      'fieldName' => 'field_media',
      'delta' => 0,
      'imageUrl' => '',
      'data' => $view_mode_crop,
    ];

    $this->submitForm([
      'field_media[selection][0][view_mode_crop_state]' => json_encode($view_mode_crop_state),
    ], 'Save');

    $view_mode_crop_records = $this->database->select('view_mode_crop', 'vmc')
      ->fields('vmc', [
        'entity_type',
        'entity_id',
        'field_name',
        'delta',
        'data',
      ])
      ->condition('entity_type', 'node')
      ->condition('entity_id', $node->uuid())
      ->execute()
      ->fetchAll();
    $this->assertCount(1, $view_mode_crop_records);
    $this->assertEquals('field_media', $view_mode_crop_records[0]->field_name);
    $this->assertEquals(0, $view_mode_crop_records[0]->delta);
    $this->assertEquals(json_encode($view_mode_crop), $view_mode_crop_records[0]->data);
  }

}

Главная | Обратная связь

drupal hosting | друпал хостинг | it patrol .inc