You are here

class FeedsExJsonPath in Feeds extensible parsers 7

Same name and namespace in other branches
  1. 7.2 src/FeedsExJsonPath.inc \FeedsExJsonPath

Parses JSON via JSONPath.

Hierarchy

Expanded class hierarchy of FeedsExJsonPath

3 string references to 'FeedsExJsonPath'
FeedsExJsonPath.test in src/Tests/FeedsExJsonPath.test
feeds_ex_feeds_plugins in ./feeds_ex.feeds.inc
Implements hook_feeds_plugins().
feeds_ex_update_7102 in ./feeds_ex.install
Checks if for any importers libraries got missing.

File

src/FeedsExJsonPath.inc, line 11
Contains FeedsExJsonPath.

View source
class FeedsExJsonPath extends FeedsExBase {

  /**
   * The JSONPath parser implementation.
   *
   * @var FeedsExJsonPathParserInterface
   */
  protected $parser;

  /**
   * {@inheritdoc}
   */
  protected function executeContext(FeedsSource $source, FeedsFetcherResult $fetcher_result) {
    $raw = $this
      ->prepareRaw($fetcher_result);
    $parsed = FeedsExJsonUtility::decodeJsonArray($raw);
    $parsed = $this
      ->getParser()
      ->search($parsed, $this->config['context']['value']);
    if (!is_array($parsed) || empty($parsed)) {
      throw new RuntimeException(t('The context expression must return an object or array.'));
    }
    $state = $source
      ->state(FEEDS_PARSE);
    if (!$state->total) {
      $state->total = count($parsed);
    }
    $start = (int) $state->pointer;
    $state->pointer = $start + $source->importer
      ->getLimit();
    return array_slice($parsed, $start, $source->importer
      ->getLimit());
  }

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

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

  /**
   * {@inheritdoc}
   */
  protected function executeSourceExpression($machine_name, $expression, $row) {
    $result = $this
      ->getParser()
      ->search($row, $expression);
    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);

    // Try to validate if possible.
    if (!class_exists('Flow\\JSONPath\\JSONPathLexer')) {
      return;
    }
    try {

      // Use class as string for PHP 5.2 compat.
      $class = 'Flow\\JSONPath\\JSONPathLexer';
      $lexer = new $class($expression);
      $lexer
        ->parseExpression();
    } catch (Exception $e) {
      return check_plain($e
        ->getMessage());
    }
  }

  /**
   * {@inheritdoc}
   */
  protected function startErrorHandling() {

    // Clear the json errors from previous parsing.
    json_decode('{}');
  }

  /**
   * {@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 (!FeedsExJsonUtility::jsonPathParserInstalled()) {
      if (user_access('administer site configuration')) {
        $link = l(t('status report'), 'admin/reports/status');
      }
      else {
        $link = t('status report');
      }
      throw new RuntimeException(t('The JSONPath library is not installed. Check the !status_report_link for more info.', array(
        '!status_report_link' => $link,
      )));
    }
  }

  /**
   * Returns the JSONPath parser.
   *
   * @return FeedsExJsonPathParserInterface
   *   The JSONPath parser.
   */
  protected function getParser() {
    if (!isset($this->parser)) {
      if (class_exists('Flow\\JSONPath\\JSONPath')) {
        $this->parser = new FeedsExJsonPathParserFlow();
      }
    }
    if (!isset($this->parser)) {
      throw new RuntimeException(t('Could not load the JSONPath library.'));
    }
    return $this->parser;
  }

}

Members

Namesort descending Modifiers Type Description Overrides
FeedsExBase::$encoder protected property The encoder used to convert encodings.
FeedsExBase::$encoderClass protected property The class used as the text encoder. 1
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 1
FeedsExBase::debug protected function Renders our debug messages into a list.
FeedsExBase::executeSources protected function Executes the source expressions.
FeedsExBase::getEncoder public function Returns the encoder.
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::parseItems protected function Performs the actual parsing. 2
FeedsExBase::prepareExpressions protected function Prepares the expressions for parsing.
FeedsExBase::prepareRaw protected function Prepares the raw string for parsing.
FeedsExBase::prepareVariables protected function Prepares the variable map used to substitution.
FeedsExBase::printErrors protected function Prints errors to the screen.
FeedsExBase::setEncoder public function Sets the encoder.
FeedsExBase::setMessenger public function Sets the messenger to be used to display messages.
FeedsExBase::setUp protected function Allows subclasses to prepare for parsing. 3
FeedsExBase::sourceDefaults public function
FeedsExBase::sourceForm public function
FeedsExBase::sourceFormValidate public function
FeedsExBase::sourceSave public function
FeedsExBase::stopErrorHandling protected function Stops internal error handling. 1
FeedsExJsonPath::$parser protected property The JSONPath parser implementation.
FeedsExJsonPath::cleanUp protected function Allows subclasses to cleanup after parsing. Overrides FeedsExBase::cleanUp 1
FeedsExJsonPath::executeContext protected function Returns rows to be parsed. Overrides FeedsExBase::executeContext
FeedsExJsonPath::executeSourceExpression protected function Executes a single source expression. Overrides FeedsExBase::executeSourceExpression 1
FeedsExJsonPath::getErrors protected function Returns the errors after parsing. Overrides FeedsExBase::getErrors
FeedsExJsonPath::getParser protected function Returns the JSONPath parser.
FeedsExJsonPath::loadLibrary protected function Loads the necessary library. Overrides FeedsExBase::loadLibrary
FeedsExJsonPath::startErrorHandling protected function Starts internal error handling. Overrides FeedsExBase::startErrorHandling
FeedsExJsonPath::validateExpression protected function Validates an expression. Overrides FeedsExBase::validateExpression