You are here

class FeedsExJmesPath in Feeds extensible parsers 7.2

Same name and namespace in other branches
  1. 7 src/FeedsExJmesPath.inc \FeedsExJmesPath

Parses JSON documents with JMESPath.

Hierarchy

Expanded class hierarchy of FeedsExJmesPath

5 string references to 'FeedsExJmesPath'
FeedsExJmesPathUnitTests::testBatchParsing in src/Tests/FeedsExJmesPath.test
Tests batch parsing.
FeedsExJmesPathUnitTests::testEUCJPEncoded in src/Tests/FeedsExJmesPath.test
Tests a EUC-JP (Japanese) encoded file.
FeedsExJmesPathUnitTests::testSimpleParsing in src/Tests/FeedsExJmesPath.test
Tests simple parsing.
FeedsExJmesPathUnitTests::testValidateExpression in src/Tests/FeedsExJmesPath.test
Tests JMESPath validation.
feeds_ex_feeds_plugins in ./feeds_ex.feeds.inc
Implements hook_feeds_plugins().

File

src/FeedsExJmesPath.inc, line 14
Contains FeedsExJmesPath.

View source
class FeedsExJmesPath extends FeedsExBase {

  /**
   * The JMESPath parser.
   *
   * @var \JmesPath\Runtime\RuntimeInterface
   */
  protected $jmesPath;

  /**
   * {@inheritdoc}
   */
  protected function setUp(FeedsSource $source, FeedsFetcherResult $fetcher_result) {
    $this->jmesPath = new AstRuntime();
  }

  /**
   * {@inheritdoc}
   */
  protected function executeContext(FeedsSource $source, FeedsFetcherResult $fetcher_result) {
    $raw = trim($fetcher_result
      ->getRaw());
    if (!strlen($raw)) {
      throw new FeedsExEmptyException();
    }
    if ($encoding = $this
      ->detectEncoding($raw)) {
      $raw = $this
        ->convertEncoding($raw, $encoding);
    }
    $parsed = drupal_json_decode($raw);
    $parsed = $this->jmesPath
      ->search($this->config['context']['value'], $parsed);
    $state = $source
      ->state(FEEDS_PARSE);
    if (!$state->total) {
      $state->total = count($parsed);
    }

    // @todo Consider using array slice syntax when it is supported.
    $start = $state->pointer ? $state->pointer : 0;
    $state->pointer = $start + $source->importer
      ->getLimit();
    return array_slice($parsed, $start, $source->importer
      ->getLimit());
  }

  /**
   * {@inheritdoc}
   */
  protected function cleanUp(FeedsSource $source, FeedsParserResult $result) {
    unset($this->jmesPath);

    // Calculate progress.
    $state = $source
      ->state(FEEDS_PARSE);
    $state
      ->progress($state->total, $state->pointer);
  }

  /**
   * {@inheritdoc}
   */
  protected function executeSourceExpression($machine_name, $expression, $row) {
    $result = $this->jmesPath
      ->search($expression, $row);
    if (is_scalar($result)) {
      return $result;
    }

    // Return a single value if there's only one value.
    return count($result) === 1 ? reset($result) : $result;
  }

  /**
   * {@inheritdoc}
   */
  protected function validateExpression(&$expression) {
    $expression = trim($expression);
    if (!$expression) {
      return;
    }
    $parser = new AstRuntime();
    try {
      $parser
        ->search($expression, array());
    } catch (SyntaxErrorException $e) {

      // Remove newlines after nl2br() to make testing easier.
      return str_replace("\n", '', nl2br(check_plain(trim($e
        ->getMessage()))));
    }
  }

  /**
   * {@inheritdoc}
   */
  protected function getErrors() {
    if (!function_exists('json_last_error')) {
      return array();
    }
    if (!($error = json_last_error())) {
      return array();
    }
    $message = array(
      'message' => FeedsExJsonUtility::translateError($error),
      'variables' => array(),
      'severity' => WATCHDOG_ERROR,
    );
    return array(
      $message,
    );
  }

  /**
   * {@inheritdoc}
   */
  protected function loadLibrary() {
    if (!($path = feeds_ex_library_path('jmespath.php', 'vendor/autoload.php'))) {
      throw new RuntimeException(t('The JMESPath library is not installed.'));
    }
    require_once DRUPAL_ROOT . '/' . $path;
  }

}

Members

Namesort descending Modifiers Type Description Overrides
FeedsExBase::$isMultibyte protected property Whether the current system handles mb_* functions.
FeedsExBase::$messenger protected property The object used to display messages to the user.
FeedsExBase::configDefaults public function 1
FeedsExBase::configForm public function 1
FeedsExBase::configFormTableColumn protected function Returns a form element for a specific column. 1
FeedsExBase::configFormTableHeader protected function Reuturns the list of table headers. 1
FeedsExBase::configFormValidate public function
FeedsExBase::convertEncoding protected function Converts a string to UTF-8. 1
FeedsExBase::debug protected function Renders our debug messages into a list.
FeedsExBase::delegateParsing protected function Delegates parsing to the subclass.
FeedsExBase::detectEncoding protected function Detects the encoding of a string.
FeedsExBase::executeSources protected function Executes the source expressions.
FeedsExBase::getFormHeader protected function Returns the configuration form table header.
FeedsExBase::getMappingSources public function
FeedsExBase::getMessenger public function Returns the messenger.
FeedsExBase::hasConfigForm public function
FeedsExBase::hasConfigurableContext protected function Returns whether or not this parser uses a context query. 2
FeedsExBase::hasSourceConfig public function
FeedsExBase::logErrors protected function Logs errors.
FeedsExBase::parse public function
FeedsExBase::prepareExpressions protected function Prepares the expressions for parsing.
FeedsExBase::prepareVariables protected function Prepares the variable map used to substitution.
FeedsExBase::printErrors protected function Prints errors to the screen.
FeedsExBase::setMessenger public function Sets the messenger to be used to display messages.
FeedsExBase::setMultibyte public function Sets the multibyte handling.
FeedsExBase::sourceDefaults public function
FeedsExBase::sourceForm public function
FeedsExBase::sourceFormValidate public function
FeedsExBase::sourceSave public function
FeedsExBase::startErrorHandling protected function Starts internal error handling. 1
FeedsExBase::stopErrorHandling protected function Stops internal error handling. 1
FeedsExBase::__construct protected function 1
FeedsExJmesPath::$jmesPath protected property The JMESPath parser.
FeedsExJmesPath::cleanUp protected function Allows subclasses to cleanup after parsing. Overrides FeedsExBase::cleanUp 1
FeedsExJmesPath::executeContext protected function Returns rows to be parsed. Overrides FeedsExBase::executeContext 1
FeedsExJmesPath::executeSourceExpression protected function Executes a single source expression. Overrides FeedsExBase::executeSourceExpression 1
FeedsExJmesPath::getErrors protected function Returns the errors after parsing. Overrides FeedsExBase::getErrors
FeedsExJmesPath::loadLibrary protected function Loads the necessary library. Overrides FeedsExBase::loadLibrary
FeedsExJmesPath::setUp protected function Allows subclasses to prepare for parsing. Overrides FeedsExBase::setUp 1
FeedsExJmesPath::validateExpression protected function Validates an expression. Overrides FeedsExBase::validateExpression