<?php

class CtoolsContextKeywordsSubstitutionTestCase extends DrupalWebTestCase {
  public static function getInfo() {
    return array(
      'name' => 'Keywords substitution',
      'description' => 'Verify that keywords are properly replaced with data.',
      'group' => 'ctools',
    );
  }

  public function setUp() {
    parent::setUp('ctools');

    ctools_include('context');
  }

  public function testKeywordsSubstitution() {
    // Create node context for substitution.
    $node = $this->drupalCreateNode();
    $context = ctools_context_create('node', $node);
    $contexts = array('argument_1' => $context);

    // Run tests on some edge cases.
    $checks = array(
      '%node:changed:raw:' => array(
        "{$node->changed}:",
        t('Multi-level token has been replaced. Colon left untouched.'),
      ),
      '%node:title' => array(
        "{$node->title}",
        t('Keyword and converter have been replaced.'),
      ),
      '%%node:title' => array(
        "%node:title",
        t('Keyword after escaped percent sign left untouched.'),
      ),
      '%node:title%node:nid' => array(
        "{$node->title}{$node->nid}",
        t('Multiple substitutions have been replaced.'),
      ),
      '%node:title:' => array(
        "{$node->title}:",
        t('Colon after keyword and converter left untouched.'),
      ),
      '%node:title%%' => array(
        "{$node->title}%",
        t('Escaped percent sign after keyword and converter left untouched.'),
      ),
      '%%%node:title' => array(
        "%{$node->title}",
        t('Keyword after escaped and unescaped percent sign has been replaced.'),
      ),
      '%%foo:bar' => array(
        "%foo:bar",
        t('Non-existant context ignored.'),
      ),
      'There was about 20%-30% difference in price.' => array(
        'There was about 20%-30% difference in price.',
        t('Non-keyword percent sign left untouched.'),
      ),
      'href="my%20file%2dname.pdf"' => array(
        'href="my%20file%2dname.pdf"',
        t('HTTP URL escape left untouched.'),
      ),
      'href="my%a0file%fdname.pdf"' => array(
        'href="my%a0file%fdname.pdf"',
        t('HTTP URL escape (high-chars) left untouched.'),
      ),
      '<a href="http://www.example.com/here%20is%20a%20pdf.pdf">Click here!</a>' => array(
        '<a href="http://www.example.com/here%20is%20a%20pdf.pdf">Click here!</a>',
        t('HTTP URL escape percent sign left untouched in HTML.'),
      ),
      'SELECT * FROM {table} WHERE field = "%s"' => array(
        'SELECT * FROM {table} WHERE field = "%s"',
        t('SQL percent sign left untouched.'),
      ),
    );
    foreach ($checks as $string => $expectations) {
      list($expected_result, $message) = $expectations;
      $actual_result = ctools_context_keyword_substitute($string, array(), $contexts);
      $this->assertEqual($actual_result, $expected_result, $message);
    }
  }

}