shiyan/iterator-regex

此包已被弃用且不再维护。作者建议使用shiyan/iterate包代替。

按场景迭代迭代器。

2.0.0 2018-04-08 12:34 UTC

This package is not auto-updated.

Last update: 2022-02-01 13:11:13 UTC


README

Build Status

PHP类和接口,通过场景迭代\Iterator,或者通过场景在迭代器元素上执行正则表达式匹配。

场景是一个实现了ScenarioInterface接口或扩展了BaseScenarioBaseRegexScenario抽象类的类。它接收一个Iterator实例,并在迭代过程中的某些时刻执行逻辑 - 例如,在执行正则表达式匹配时,当某些模式与主题匹配,或没有匹配,或在进行搜索前后等。

将其视为迭代器的array_walk()iterator_apply(),但是您提供一个具有多个方法的对象(场景),而不是单个回调。您可以将这些场景用作插件。

迭代器是任何实现了\Iterator接口的对象。

主类是Iterate,它只需实例化,并使用迭代器和场景对象调用。

非常适合作为Composer库使用。

要求

  • PHP ≥ 7.1

安装

要将此库添加到您的Composer项目

composer require shiyan/iterate

用法

包含2个基本场景

  • 最基本的场景是无条件地对迭代器的每个元素执行一些逻辑。
  • 并且基于正则表达式的一个,它对迭代器元素(转换为字符串)执行正则表达式匹配(使用一个或多个模式),并允许根据匹配的模式执行不同的逻辑,或者如果没有模式匹配。

示例

假设有一个字符串数组$array。迭代它,将所有空字符串转换为0(零),打印所有包含"PHP"的字符串,并简单地计算所有其他元素。

首先,创建一个场景类

use Shiyan\Iterate\Scenario\BaseRegexScenario;

class ExampleScenario extends BaseRegexScenario {

  const PATTERN_EMPTY = '/^$/';
  const PATTERN_PHP = '/PHP/';

  public $counter;

  public function getPatterns(): array {
    return [self::PATTERN_EMPTY, self::PATTERN_PHP];
  }

  public function preRun(): void {
    $this->counter = 0;
  }

  public function onMatch(array $matches, string $pattern): void {
    switch ($pattern) {
      case self::PATTERN_EMPTY:
        $this->iterator[$this->iterator->key()] = 0;
        break;

      case self::PATTERN_PHP:
        print $this->iterator->current() . "\n";
        break;
    }
  }

  public function ifNotMatched(): void {
    ++$this->counter;
  }

}

然后

use Shiyan\Iterate\Iterate;

// Convert our array of strings to the iterator object.
$iterator = new ArrayIterator($array);
$scenario = new ExampleScenario();
$iterate = new Iterate();

// Invoke iterate with our scenario.
$iterate($iterator, $scenario);
print "Found {$scenario->counter} non-empty, non-PHP strings.\n";

// Let's check that empty strings were converted to zeros.
print_r($iterator->getArrayCopy());

// If we invoke Iterate with the same scenario once again, it won't find empty
// strings anymore. Instead, we'll have a higher number in the $counter property
// of the $scenario object, because the "0" doesn't match our patterns.
$iterate($iterator, $scenario);
print "Found {$scenario->counter} non-empty, non-PHP strings.\n";