You are here

public function RestfulViewModeAndFormatterTestCase::testFormatterIntegration in RESTful 7.2

Same name and namespace in other branches
  1. 7 tests/RestfulViewModeAndFormatterTestCase.test \RestfulViewModeAndFormatterTestCase::testFormatterIntegration()

Test the field API formatter integration.

File

tests/RestfulViewModeAndFormatterTestCase.test, line 49
Contains RestfulViewModeFormatterTestCase

Class

RestfulViewModeAndFormatterTestCase

Code

public function testFormatterIntegration() {
  $resource_manager = restful()
    ->getResourceManager();
  $handler = $resource_manager
    ->getPlugin('articles:1.5');

  // Create node.
  $text = 'Some body with long text';
  $settings = array(
    'type' => 'article',
    'body' => array(
      LANGUAGE_NONE => array(
        array(
          'value' => $text,
        ),
      ),
    ),
  );
  $node = $this
    ->drupalCreateNode($settings);

  // Field with no formatter.
  $request = Request::create('api/articles/v1.5/' . $node->nid);
  $handler
    ->setRequest($request);
  $handler
    ->setPath($node->nid);
  $result = drupal_json_decode(restful()
    ->getFormatterManager()
    ->format($handler
    ->process(), 'json'));
  $result = $result['data'];
  $this
    ->assertEqual(trim(strip_tags($result[0]['body'])), $text, 'Raw value passed without a formatter.');

  // Add formatter settings.
  $field_definitions = $handler
    ->getFieldDefinitions();
  $display = array(
    'type' => 'text_summary_or_trimmed',
    'settings' => array(
      'trim_length' => 10,
    ),
  );

  /* @var \Drupal\restful\Plugin\resource\Field\ResourceFieldEntityText $body */
  $body = $field_definitions
    ->get('body');
  $body
    ->setFormatter($display);
  $field_definitions
    ->set('body', $body);
  $handler
    ->setFieldDefinitions($field_definitions);
  $resource_manager
    ->clearPluginCache('articles:1.5');
  $handler
    ->setRequest($request);
  $handler
    ->setPath($node->nid);
  $result = drupal_json_decode(restful()
    ->getFormatterManager()
    ->format($handler
    ->process(), 'json'));
  $result = $result['data'];

  // Core's trim formatter also inclues the opening <p> tag in the calculation
  // of number of chars.
  $this
    ->assertEqual($result[0]['body'], '<p>Some bo</p>', 'Value trimmed by formatter.');
}