You are here

FeedImportVectorReader.php in Feed Import 8

File

feed_import_base/src/FeedImportVectorReader.php
View source
<?php

namespace Drupal\feed_import_base;


/**
 * This class is a helper for vector (n dimensions) reader.
 * Path format is like a/b/c which results in [a, b, c] array.
 */
abstract class FeedImportVectorReader extends FeedImportReader {
  const WILDCARD = '*';

  /**
   * {@inheritdoc}
   */
  public function map(&$vector, &$path) {
    $ret = array();
    $count = 0;
    foreach ($path as $p) {
      if (($p = $this
        ->submap($vector, $p)) !== NULL) {
        if ($p instanceof ArrayObject) {
          $ret = array_merge($ret, $p
            ->getArrayCopy());
          $count += count($p);
        }
        else {
          $ret[] = $p;
          $count++;
        }
      }
    }
    return $count == 0 ? NULL : ($count == 1 ? $ret[0] : $ret);
  }

  /**
   * Gets an element by path.
   *
   * @param mixed $vector
   *    The vector to search
   * @param array $path
   *    Path parts
   * @param int $index
   *    Path index
   *
   * @return mixed
   *    Found value or NULL
   */
  public function submap(&$vector, &$path, $index = 0) {
    while (isset($path[$index])) {
      $p =& $path[$index++];
      if ($p == static::WILDCARD) {
        if (is_scalar($vector)) {
          return NULL;
        }
        $result = new ArrayObject();
        foreach ($vector as &$value) {
          if (($res = $this
            ->submap($value, $path, $index)) !== NULL) {
            if ($res instanceof ArrayObject) {
              foreach ($res as &$r) {
                $result[] = $r;
              }
              unset($r);
            }
            else {
              $result[] = $res;
            }
          }
          unset($res);
        }
        return $result ? $result : NULL;
      }
      elseif (is_array($vector)) {
        if (isset($vector[$p])) {
          $vector =& $vector[$p];
          continue;
        }
      }
      elseif (is_object($vector)) {
        if (isset($vector->{$p})) {
          $vector =& $vector->{$p};
          continue;
        }
      }
      return NULL;
    }
    return $vector;
  }

  /**
   * {@inheritdoc}
   */
  public function formatPath($path) {
    $path = preg_split('/(\\s?\\|\\s?)/', $path, -1, PREG_SPLIT_NO_EMPTY);
    foreach ($path as &$p) {
      $p = explode('/', $p);
    }
    return $path;
  }

}

Classes

Namesort descending Description
FeedImportVectorReader This class is a helper for vector (n dimensions) reader. Path format is like a/b/c which results in [a, b, c] array.