function DiffOpOutputBuilder::toOpsArray

Same name in other branches
  1. 11.x core/lib/Drupal/Component/Diff/DiffOpOutputBuilder.php \Drupal\Component\Diff\DiffOpOutputBuilder::toOpsArray()

Converts the output of Differ to an array of DiffOp* value objects.

Parameters

array $diff: The array output of Differ::diffToArray().

Return value

\Drupal\Component\Diff\Engine\DiffOp[] An array of DiffOp* value objects.

1 call to DiffOpOutputBuilder::toOpsArray()
DiffOpOutputBuilder::getDiff in core/lib/Drupal/Component/Diff/DiffOpOutputBuilder.php

File

core/lib/Drupal/Component/Diff/DiffOpOutputBuilder.php, line 39

Class

DiffOpOutputBuilder
Returns a diff as an array of DiffOp operations.

Namespace

Drupal\Component\Diff

Code

public function toOpsArray(array $diff) : array {
    $ops = [];
    $hunkMode = NULL;
    $hunkSource = [];
    $hunkTarget = [];
    for ($i = 0; $i < count($diff); $i++) {
        // Handle a sequence of removals + additions as a sequence of changes, and
        // manages the tail if required.
        if ($diff[$i][1] === Differ::REMOVED) {
            if ($hunkMode !== NULL) {
                $ops[] = $this->hunkOp($hunkMode, $hunkSource, $hunkTarget);
                $hunkSource = [];
                $hunkTarget = [];
            }
            for ($n = $i; $n < count($diff) && $diff[$n][1] === Differ::REMOVED; $n++) {
                $hunkSource[] = $diff[$n][0];
            }
            for (; $n < count($diff) && $diff[$n][1] === Differ::ADDED; $n++) {
                $hunkTarget[] = $diff[$n][0];
            }
            if (count($hunkTarget) === 0) {
                $ops[] = $this->hunkOp(Differ::REMOVED, $hunkSource, $hunkTarget);
            }
            else {
                $ops[] = $this->hunkOp(self::CHANGED, $hunkSource, $hunkTarget);
            }
            $hunkMode = NULL;
            $hunkSource = [];
            $hunkTarget = [];
            $i = $n - 1;
            continue;
        }
        // When here, we are adding or copying the item. Removing or changing is
        // managed above.
        if ($hunkMode === NULL) {
            $hunkMode = $diff[$i][1];
        }
        elseif ($hunkMode !== $diff[$i][1]) {
            $ops[] = $this->hunkOp($hunkMode, $hunkSource, $hunkTarget);
            $hunkMode = $diff[$i][1];
            $hunkSource = [];
            $hunkTarget = [];
        }
        $hunkSource[] = $diff[$i][0];
    }
    if ($hunkMode !== NULL) {
        $ops[] = $this->hunkOp($hunkMode, $hunkSource, $hunkTarget);
    }
    return $ops;
}

Buggy or inaccurate documentation? Please file an issue. Need support? Need help programming? Connect with the Drupal community.