Skip to content

Commit 4b170cd

Browse files
committed
feat: add methods to get diff statistics
- $differ->getStatistics(); - DiffHelper->getStatistics(); Signed-off-by: Jack Cherng <[email protected]>
1 parent d95e0b8 commit 4b170cd

File tree

2 files changed

+41
-0
lines changed

2 files changed

+41
-0
lines changed

src/DiffHelper.php

+10
Original file line numberDiff line numberDiff line change
@@ -104,6 +104,16 @@ public static function getStyleSheet(): string
104104
return $fileContent = $file->fread($file->getSize());
105105
}
106106

107+
/**
108+
* Gets the diff statistics such as inserted and deleted etc...
109+
*
110+
* @return array<string,float> the statistics
111+
*/
112+
public static function getStatistics(): array
113+
{
114+
return Differ::getInstance()->getStatistics();
115+
}
116+
107117
/**
108118
* All-in-one static method to calculate the diff between two strings (or arrays of strings).
109119
*

src/Differ.php

+31
Original file line numberDiff line numberDiff line change
@@ -265,6 +265,37 @@ public static function getInstance(): self
265265
return $singleton = $singleton ?? new static([], []);
266266
}
267267

268+
/**
269+
* Gets the diff statistics such as inserted and deleted etc...
270+
*
271+
* @return array<string,float> the statistics
272+
*/
273+
public function getStatistics(): array
274+
{
275+
$ret = [
276+
'inserted' => 0,
277+
'deleted' => 0,
278+
'unmodified' => 0,
279+
'changedRatio' => 0.0,
280+
];
281+
282+
foreach ($this->getGroupedOpcodes() as $hunk) {
283+
foreach ($hunk as [$op, $i1, $i2, $j1, $j2]) {
284+
if ($op & (SequenceMatcher::OP_INS | SequenceMatcher::OP_REP)) {
285+
$ret['inserted'] += $j2 - $j1;
286+
}
287+
if ($op & (SequenceMatcher::OP_DEL | SequenceMatcher::OP_REP)) {
288+
$ret['deleted'] += $i2 - $i1;
289+
}
290+
}
291+
}
292+
293+
$ret['unmodified'] = $this->oldSrcLength - $ret['deleted'];
294+
$ret['changedRatio'] = 1 - ($ret['unmodified'] / $this->oldSrcLength);
295+
296+
return $ret;
297+
}
298+
268299
/**
269300
* Generate a list of the compiled and grouped opcodes for the differences between the
270301
* two strings. Generally called by the renderer, this class instantiates the sequence

0 commit comments

Comments
 (0)