Laravel version update

Laravel version update
This commit is contained in:
Manish Verma
2018-08-06 18:48:58 +05:30
parent d143048413
commit 126fbb0255
13678 changed files with 1031482 additions and 778530 deletions

View File

@@ -1,10 +1,5 @@
.idea
phpunit.xml
composer.lock
composer.phar
vendor/
cache.properties
build/SebastianBergmann
build/LICENSE
build/README.md
build/*.tgz
/.idea
/composer.lock
/vendor
/.php_cs.cache
/from.txt.orig

View File

@@ -1,66 +1,81 @@
<?php
$finder = Symfony\CS\Finder\DefaultFinder::create()
->files()
->in('src')
->in('tests')
->name('*.php');
<?php declare(strict_types=1);
$header = <<<'EOF'
This file is part of sebastian/diff.
return Symfony\CS\Config\Config::create()
->level(\Symfony\CS\FixerInterface::NONE_LEVEL)
->fixers(
array(
'align_double_arrow',
'align_equals',
'braces',
'concat_with_spaces',
'duplicate_semicolon',
'elseif',
'empty_return',
'encoding',
'eof_ending',
'extra_empty_lines',
'function_call_space',
'function_declaration',
'indentation',
'join_function',
'line_after_namespace',
'linefeed',
'list_commas',
'lowercase_constants',
'lowercase_keywords',
'method_argument_space',
'multiple_use',
'namespace_no_leading_whitespace',
'no_blank_lines_after_class_opening',
'no_empty_lines_after_phpdocs',
'parenthesis',
'php_closing_tag',
'phpdoc_indent',
'phpdoc_no_access',
'phpdoc_no_empty_return',
'phpdoc_no_package',
'phpdoc_params',
'phpdoc_scalar',
'phpdoc_separation',
'phpdoc_to_comment',
'phpdoc_trim',
'phpdoc_types',
'phpdoc_var_without_name',
'remove_lines_between_uses',
'return',
'self_accessor',
'short_tag',
'single_line_after_imports',
'single_quote',
'spaces_before_semicolon',
'spaces_cast',
'ternary_spaces',
'trailing_spaces',
'trim_array_spaces',
'unused_use',
'visibility',
'whitespacy_lines'
)
(c) Sebastian Bergmann <sebastian@phpunit.de>
For the full copyright and license information, please view the LICENSE
file that was distributed with this source code.
EOF;
return PhpCsFixer\Config::create()
->setRiskyAllowed(true)
->setRules(
[
'array_syntax' => ['syntax' => 'short'],
'binary_operator_spaces' => [
'align_double_arrow' => true,
'align_equals' => true
],
'blank_line_after_namespace' => true,
'blank_line_before_return' => true,
'braces' => true,
'cast_spaces' => true,
'concat_space' => ['spacing' => 'one'],
'declare_strict_types' => true,
'elseif' => true,
'encoding' => true,
'full_opening_tag' => true,
'function_declaration' => true,
'header_comment' => ['header' => $header, 'separate' => 'none'],
'indentation_type' => true,
'line_ending' => true,
'lowercase_constants' => true,
'lowercase_keywords' => true,
'method_argument_space' => true,
'native_function_invocation' => true,
'no_alias_functions' => true,
'no_blank_lines_after_class_opening' => true,
'no_blank_lines_after_phpdoc' => true,
'no_closing_tag' => true,
'no_empty_phpdoc' => true,
'no_empty_statement' => true,
'no_extra_consecutive_blank_lines' => true,
'no_leading_namespace_whitespace' => true,
'no_singleline_whitespace_before_semicolons' => true,
'no_spaces_after_function_name' => true,
'no_spaces_inside_parenthesis' => true,
'no_trailing_comma_in_list_call' => true,
'no_trailing_whitespace' => true,
'no_unused_imports' => true,
'no_whitespace_in_blank_line' => true,
'phpdoc_align' => true,
'phpdoc_indent' => true,
'phpdoc_no_access' => true,
'phpdoc_no_empty_return' => true,
'phpdoc_no_package' => true,
'phpdoc_scalar' => true,
'phpdoc_separation' => true,
'phpdoc_to_comment' => true,
'phpdoc_trim' => true,
'phpdoc_types' => true,
'phpdoc_var_without_name' => true,
'pow_to_exponentiation' => true,
'self_accessor' => true,
'simplified_null_return' => true,
'single_blank_line_at_eof' => true,
'single_import_per_statement' => true,
'single_line_after_imports' => true,
'single_quote' => true,
'ternary_operator_spaces' => true,
'trim_array_spaces' => true,
'visibility_required' => true,
]
)
->finder($finder);
->setFinder(
PhpCsFixer\Finder::create()
->files()
->in(__DIR__ . '/src')
->in(__DIR__ . '/tests')
->name('*.php')
);

View File

@@ -1,16 +1,27 @@
language: php
install:
- travis_retry composer install --no-interaction --prefer-source
php:
- 5.3.3
- 5.3
- 5.4
- 5.5
- 5.6
- hhvm
- 7.0
- 7.0snapshot
- 7.1
- 7.1snapshot
- master
sudo: false
before_install:
- composer self-update
- composer clear-cache
install:
- travis_retry composer update --no-interaction --no-ansi --no-progress --no-suggest --optimize-autoloader --prefer-stable
script:
- ./vendor/bin/phpunit --coverage-clover=coverage.xml
after_success:
- bash <(curl -s https://codecov.io/bash)
notifications:
email: false
irc: "irc.freenode.org#phpunit"

22
vendor/sebastian/diff/ChangeLog.md vendored Normal file
View File

@@ -0,0 +1,22 @@
# ChangeLog
All notable changes are documented in this file using the [Keep a CHANGELOG](http://keepachangelog.com/) principles.
## [2.0.1] - 2017-08-03
### Fixed
* Fixed [#66](https://github.com/sebastianbergmann/diff/pull/66): Restored backwards compatibility for PHPUnit 6.1.4, 6.2.0, 6.2.1, 6.2.2, and 6.2.3
## [2.0.0] - 2017-07-11 [YANKED]
### Added
* Implemented [#64](https://github.com/sebastianbergmann/diff/pull/64): Show line numbers for chunks of a diff
### Removed
* This component is no longer supported on PHP 5.6
[2.0.1]: https://github.com/sebastianbergmann/diff/compare/c341c98ce083db77f896a0aa64f5ee7652915970...2.0.1
[2.0.0]: https://github.com/sebastianbergmann/diff/compare/1.4...c341c98ce083db77f896a0aa64f5ee7652915970

View File

@@ -1,6 +1,6 @@
Diff
sebastian/diff
Copyright (c) 2002-2015, Sebastian Bergmann <sebastian@phpunit.de>.
Copyright (c) 2002-2017, Sebastian Bergmann <sebastian@phpunit.de>.
All rights reserved.
Redistribution and use in source and binary forms, with or without

View File

@@ -1,16 +1,16 @@
# Diff
# sebastian/diff
Diff implementation for PHP, factored out of PHPUnit into a stand-alone component.
## Installation
To add this package as a local, per-project dependency to your project, simply add a dependency on `sebastian/diff` to your project's `composer.json` file. Here is a minimal example of a `composer.json` file that just defines a dependency on Diff:
You can add this library as a local, per-project dependency to your project using [Composer](https://getcomposer.org/):
{
"require": {
"sebastian/diff": "*"
}
}
composer require sebastian/diff
If you only need this library during development, for instance to run your project's test suite, then you should add it as a development-time dependency:
composer require --dev sebastian/diff
### Usage

View File

@@ -1,26 +1,22 @@
<?xml version="1.0" encoding="UTF-8"?>
<project name="diff">
<target name="clean" description="Cleanup build artifacts">
<delete dir="${basedir}/vendor"/>
<delete file="${basedir}/composer.lock"/>
</target>
<project name="diff" default="setup">
<target name="setup" depends="clean,composer"/>
<target name="composer" depends="clean" description="Install dependencies with Composer">
<tstamp>
<format property="thirty.days.ago" pattern="MM/dd/yyyy hh:mm aa" offset="-30" unit="day"/>
</tstamp>
<delete>
<fileset dir="${basedir}">
<include name="composer.phar" />
<date datetime="${thirty.days.ago}" when="before"/>
</fileset>
</delete>
<target name="clean" description="Cleanup build artifacts">
<delete dir="${basedir}/vendor"/>
<delete file="${basedir}/composer.lock"/>
</target>
<get src="https://getcomposer.org/composer.phar" dest="${basedir}/composer.phar" skipexisting="true"/>
<exec executable="php">
<arg value="composer.phar"/>
<arg value="install"/>
</exec>
</target>
<target name="composer" depends="clean" description="Install dependencies with Composer">
<exec executable="composer" taskname="composer">
<arg value="update"/>
<arg value="--no-interaction"/>
<arg value="--no-progress"/>
<arg value="--no-ansi"/>
<arg value="--no-suggest"/>
<arg value="--optimize-autoloader"/>
<arg value="--prefer-stable"/>
</exec>
</target>
</project>

View File

@@ -15,10 +15,10 @@
}
],
"require": {
"php": ">=5.3.3"
"php": "^7.0"
},
"require-dev": {
"phpunit/phpunit": "~4.8"
"phpunit/phpunit": "^6.2"
},
"autoload": {
"classmap": [
@@ -27,7 +27,7 @@
},
"extra": {
"branch-alias": {
"dev-master": "1.4-dev"
"dev-master": "2.0-dev"
}
}
}

19
vendor/sebastian/diff/phpunit.xml vendored Normal file
View File

@@ -0,0 +1,19 @@
<?xml version="1.0" encoding="UTF-8"?>
<phpunit xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="https://schema.phpunit.de/6.2/phpunit.xsd"
bootstrap="vendor/autoload.php"
forceCoversAnnotation="true"
beStrictAboutCoversAnnotation="true"
beStrictAboutOutputDuringTests="true"
beStrictAboutTodoAnnotatedTests="true"
verbose="true">
<testsuite>
<directory suffix="Test.php">tests</directory>
</testsuite>
<filter>
<whitelist processUncoveredFilesFromWhitelist="true">
<directory suffix=".php">src</directory>
</whitelist>
</filter>
</phpunit>

View File

@@ -1,17 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<phpunit xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="http://schema.phpunit.de/4.2/phpunit.xsd"
bootstrap="vendor/autoload.php"
backupGlobals="false"
verbose="true">
<testsuite name="Diff">
<directory suffix="Test.php">tests</directory>
</testsuite>
<filter>
<whitelist processUncoveredFilesFromWhitelist="true">
<directory suffix=".php">src</directory>
</whitelist>
</filter>
</phpunit>

View File

@@ -1,6 +1,6 @@
<?php
<?php declare(strict_types=1);
/*
* This file is part of the Diff package.
* This file is part of sebastian/diff.
*
* (c) Sebastian Bergmann <sebastian@phpunit.de>
*
@@ -10,9 +10,7 @@
namespace SebastianBergmann\Diff;
/**
*/
class Chunk
final class Chunk
{
/**
* @var int
@@ -28,6 +26,7 @@ class Chunk
* @var int
*/
private $end;
/**
* @var int
*/
@@ -38,65 +37,40 @@ class Chunk
*/
private $lines;
/**
* @param int $start
* @param int $startRange
* @param int $end
* @param int $endRange
* @param array $lines
*/
public function __construct($start = 0, $startRange = 1, $end = 0, $endRange = 1, array $lines = array())
public function __construct(int $start = 0, int $startRange = 1, int $end = 0, int $endRange = 1, array $lines = [])
{
$this->start = (int) $start;
$this->startRange = (int) $startRange;
$this->end = (int) $end;
$this->endRange = (int) $endRange;
$this->start = $start;
$this->startRange = $startRange;
$this->end = $end;
$this->endRange = $endRange;
$this->lines = $lines;
}
/**
* @return int
*/
public function getStart()
public function getStart(): int
{
return $this->start;
}
/**
* @return int
*/
public function getStartRange()
public function getStartRange(): int
{
return $this->startRange;
}
/**
* @return int
*/
public function getEnd()
public function getEnd(): int
{
return $this->end;
}
/**
* @return int
*/
public function getEndRange()
public function getEndRange(): int
{
return $this->endRange;
}
/**
* @return array
*/
public function getLines()
public function getLines(): array
{
return $this->lines;
}
/**
* @param array $lines
*/
public function setLines(array $lines)
{
$this->lines = $lines;

View File

@@ -1,6 +1,6 @@
<?php
<?php declare(strict_types=1);
/*
* This file is part of the Diff package.
* This file is part of sebastian/diff.
*
* (c) Sebastian Bergmann <sebastian@phpunit.de>
*
@@ -10,9 +10,7 @@
namespace SebastianBergmann\Diff;
/**
*/
class Diff
final class Diff
{
/**
* @var string
@@ -34,25 +32,19 @@ class Diff
* @param string $to
* @param Chunk[] $chunks
*/
public function __construct($from, $to, array $chunks = array())
public function __construct(string $from, string $to, array $chunks = [])
{
$this->from = $from;
$this->to = $to;
$this->chunks = $chunks;
}
/**
* @return string
*/
public function getFrom()
public function getFrom(): string
{
return $this->from;
}
/**
* @return string
*/
public function getTo()
public function getTo(): string
{
return $this->to;
}
@@ -60,7 +52,7 @@ class Diff
/**
* @return Chunk[]
*/
public function getChunks()
public function getChunks(): array
{
return $this->chunks;
}

View File

@@ -1,6 +1,6 @@
<?php
<?php declare(strict_types=1);
/*
* This file is part of the Diff package.
* This file is part of sebastian/diff.
*
* (c) Sebastian Bergmann <sebastian@phpunit.de>
*
@@ -10,226 +10,179 @@
namespace SebastianBergmann\Diff;
use SebastianBergmann\Diff\LCS\LongestCommonSubsequence;
use SebastianBergmann\Diff\LCS\TimeEfficientImplementation;
use SebastianBergmann\Diff\LCS\MemoryEfficientImplementation;
use SebastianBergmann\Diff\Output\DiffOutputBuilderInterface;
use SebastianBergmann\Diff\Output\UnifiedDiffOutputBuilder;
/**
* Diff implementation.
*/
class Differ
final class Differ
{
/**
* @var string
* @var DiffOutputBuilderInterface
*/
private $header;
private $outputBuilder;
/**
* @var bool
* @param DiffOutputBuilderInterface $outputBuilder
*
* @throws InvalidArgumentException
*/
private $showNonDiffLines;
/**
* @param string $header
*/
public function __construct($header = "--- Original\n+++ New\n", $showNonDiffLines = true)
public function __construct($outputBuilder = null)
{
$this->header = $header;
$this->showNonDiffLines = $showNonDiffLines;
if ($outputBuilder instanceof DiffOutputBuilderInterface) {
$this->outputBuilder = $outputBuilder;
} elseif (null === $outputBuilder) {
$this->outputBuilder = new UnifiedDiffOutputBuilder;
} elseif (\is_string($outputBuilder)) {
// PHPUnit 6.1.4, 6.2.0, 6.2.1, 6.2.2, and 6.2.3 support
// @see https://github.com/sebastianbergmann/phpunit/issues/2734#issuecomment-314514056
// @deprecated
$this->outputBuilder = new UnifiedDiffOutputBuilder($outputBuilder);
} else {
throw new InvalidArgumentException(
\sprintf(
'Expected builder to be an instance of DiffOutputBuilderInterface, <null> or a string, got %s.',
\is_object($outputBuilder) ? 'instance of "' . \get_class($outputBuilder) . '"' : \gettype($outputBuilder) . ' "' . $outputBuilder . '"'
)
);
}
}
/**
* Returns the diff between two arrays or strings as string.
*
* @param array|string $from
* @param array|string $to
* @param LongestCommonSubsequence $lcs
* @param array|string $from
* @param array|string $to
* @param LongestCommonSubsequenceCalculator|null $lcs
*
* @return string
*/
public function diff($from, $to, LongestCommonSubsequence $lcs = null)
public function diff($from, $to, LongestCommonSubsequenceCalculator $lcs = null): string
{
if (!is_array($from) && !is_string($from)) {
$from = (string) $from;
$from = $this->validateDiffInput($from);
$to = $this->validateDiffInput($to);
$diff = $this->diffToArray($from, $to, $lcs);
return $this->outputBuilder->getDiff($diff);
}
/**
* Casts variable to string if it is not a string or array.
*
* @param mixed $input
*
* @return string
*/
private function validateDiffInput($input): string
{
if (!\is_array($input) && !\is_string($input)) {
return (string) $input;
}
if (!is_array($to) && !is_string($to)) {
$to = (string) $to;
}
$buffer = $this->header;
$diff = $this->diffToArray($from, $to, $lcs);
$inOld = false;
$i = 0;
$old = array();
foreach ($diff as $line) {
if ($line[1] === 0 /* OLD */) {
if ($inOld === false) {
$inOld = $i;
}
} elseif ($inOld !== false) {
if (($i - $inOld) > 5) {
$old[$inOld] = $i - 1;
}
$inOld = false;
}
++$i;
}
$start = isset($old[0]) ? $old[0] : 0;
$end = count($diff);
if ($tmp = array_search($end, $old)) {
$end = $tmp;
}
$newChunk = true;
for ($i = $start; $i < $end; $i++) {
if (isset($old[$i])) {
$buffer .= "\n";
$newChunk = true;
$i = $old[$i];
}
if ($newChunk) {
if ($this->showNonDiffLines === true) {
$buffer .= "@@ @@\n";
}
$newChunk = false;
}
if ($diff[$i][1] === 1 /* ADDED */) {
$buffer .= '+' . $diff[$i][0] . "\n";
} elseif ($diff[$i][1] === 2 /* REMOVED */) {
$buffer .= '-' . $diff[$i][0] . "\n";
} elseif ($this->showNonDiffLines === true) {
$buffer .= ' ' . $diff[$i][0] . "\n";
}
}
return $buffer;
return $input;
}
/**
* Returns the diff between two arrays or strings as array.
*
* Each array element contains two elements:
* - [0] => string $token
* - [0] => mixed $token
* - [1] => 2|1|0
*
* - 2: REMOVED: $token was removed from $from
* - 1: ADDED: $token was added to $from
* - 0: OLD: $token is not changed in $to
*
* @param array|string $from
* @param array|string $to
* @param LongestCommonSubsequence $lcs
* @param array|string $from
* @param array|string $to
* @param LongestCommonSubsequenceCalculator $lcs
*
* @return array
*/
public function diffToArray($from, $to, LongestCommonSubsequence $lcs = null)
public function diffToArray($from, $to, LongestCommonSubsequenceCalculator $lcs = null): array
{
preg_match_all('(\r\n|\r|\n)', $from, $fromMatches);
preg_match_all('(\r\n|\r|\n)', $to, $toMatches);
if (is_string($from)) {
$from = preg_split('(\r\n|\r|\n)', $from);
if (\is_string($from)) {
$from = $this->splitStringByLines($from);
} elseif (!\is_array($from)) {
throw new \InvalidArgumentException('"from" must be an array or string.');
}
if (is_string($to)) {
$to = preg_split('(\r\n|\r|\n)', $to);
if (\is_string($to)) {
$to = $this->splitStringByLines($to);
} elseif (!\is_array($to)) {
throw new \InvalidArgumentException('"to" must be an array or string.');
}
$start = array();
$end = array();
$fromLength = count($from);
$toLength = count($to);
$length = min($fromLength, $toLength);
for ($i = 0; $i < $length; ++$i) {
if ($from[$i] === $to[$i]) {
$start[] = $from[$i];
unset($from[$i], $to[$i]);
} else {
break;
}
}
$length -= $i;
for ($i = 1; $i < $length; ++$i) {
if ($from[$fromLength - $i] === $to[$toLength - $i]) {
array_unshift($end, $from[$fromLength - $i]);
unset($from[$fromLength - $i], $to[$toLength - $i]);
} else {
break;
}
}
list($from, $to, $start, $end) = self::getArrayDiffParted($from, $to);
if ($lcs === null) {
$lcs = $this->selectLcsImplementation($from, $to);
}
$common = $lcs->calculate(array_values($from), array_values($to));
$diff = array();
if (isset($fromMatches[0]) && $toMatches[0] &&
count($fromMatches[0]) === count($toMatches[0]) &&
$fromMatches[0] !== $toMatches[0]) {
$diff[] = array(
'#Warning: Strings contain different line endings!', 0
);
}
$common = $lcs->calculate(\array_values($from), \array_values($to));
$diff = [];
foreach ($start as $token) {
$diff[] = array($token, 0 /* OLD */);
$diff[] = [$token, 0 /* OLD */];
}
reset($from);
reset($to);
\reset($from);
\reset($to);
foreach ($common as $token) {
while ((($fromToken = reset($from)) !== $token)) {
$diff[] = array(array_shift($from), 2 /* REMOVED */);
while (($fromToken = \reset($from)) !== $token) {
$diff[] = [\array_shift($from), 2 /* REMOVED */];
}
while ((($toToken = reset($to)) !== $token)) {
$diff[] = array(array_shift($to), 1 /* ADDED */);
while (($toToken = \reset($to)) !== $token) {
$diff[] = [\array_shift($to), 1 /* ADDED */];
}
$diff[] = array($token, 0 /* OLD */);
$diff[] = [$token, 0 /* OLD */];
array_shift($from);
array_shift($to);
\array_shift($from);
\array_shift($to);
}
while (($token = array_shift($from)) !== null) {
$diff[] = array($token, 2 /* REMOVED */);
while (($token = \array_shift($from)) !== null) {
$diff[] = [$token, 2 /* REMOVED */];
}
while (($token = array_shift($to)) !== null) {
$diff[] = array($token, 1 /* ADDED */);
while (($token = \array_shift($to)) !== null) {
$diff[] = [$token, 1 /* ADDED */];
}
foreach ($end as $token) {
$diff[] = array($token, 0 /* OLD */);
$diff[] = [$token, 0 /* OLD */];
}
if ($this->detectUnmatchedLineEndings($diff)) {
\array_unshift($diff, ["#Warning: Strings contain different line endings!\n", 3]);
}
return $diff;
}
/**
* Checks if input is string, if so it will split it line-by-line.
*
* @param string $input
*
* @return array
*/
private function splitStringByLines(string $input): array
{
return \preg_split('/(.*\R)/', $input, -1, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY);
}
/**
* @param array $from
* @param array $to
*
* @return LongestCommonSubsequence
* @return LongestCommonSubsequenceCalculator
*/
private function selectLcsImplementation(array $from, array $to)
private function selectLcsImplementation(array $from, array $to): LongestCommonSubsequenceCalculator
{
// We do not want to use the time-efficient implementation if its memory
// footprint will probably exceed this value. Note that the footprint
@@ -238,10 +191,10 @@ class Differ
$memoryLimit = 100 * 1024 * 1024;
if ($this->calculateEstimatedFootprint($from, $to) > $memoryLimit) {
return new MemoryEfficientImplementation;
return new MemoryEfficientLongestCommonSubsequenceCalculator;
}
return new TimeEfficientImplementation;
return new TimeEfficientLongestCommonSubsequenceCalculator;
}
/**
@@ -250,12 +203,119 @@ class Differ
* @param array $from
* @param array $to
*
* @return int
* @return int|float
*/
private function calculateEstimatedFootprint(array $from, array $to)
{
$itemSize = PHP_INT_SIZE == 4 ? 76 : 144;
$itemSize = PHP_INT_SIZE === 4 ? 76 : 144;
return $itemSize * pow(min(count($from), count($to)), 2);
return $itemSize * \min(\count($from), \count($to)) ** 2;
}
/**
* Returns true if line ends don't match in a diff.
*
* @param array $diff
*
* @return bool
*/
private function detectUnmatchedLineEndings(array $diff): bool
{
$newLineBreaks = ['' => true];
$oldLineBreaks = ['' => true];
foreach ($diff as $entry) {
if (0 === $entry[1]) { /* OLD */
$ln = $this->getLinebreak($entry[0]);
$oldLineBreaks[$ln] = true;
$newLineBreaks[$ln] = true;
} elseif (1 === $entry[1]) { /* ADDED */
$newLineBreaks[$this->getLinebreak($entry[0])] = true;
} elseif (2 === $entry[1]) { /* REMOVED */
$oldLineBreaks[$this->getLinebreak($entry[0])] = true;
}
}
// if either input or output is a single line without breaks than no warning should be raised
if (['' => true] === $newLineBreaks || ['' => true] === $oldLineBreaks) {
return false;
}
// two way compare
foreach ($newLineBreaks as $break => $set) {
if (!isset($oldLineBreaks[$break])) {
return true;
}
}
foreach ($oldLineBreaks as $break => $set) {
if (!isset($newLineBreaks[$break])) {
return true;
}
}
return false;
}
private function getLinebreak($line): string
{
if (!\is_string($line)) {
return '';
}
$lc = \substr($line, -1);
if ("\r" === $lc) {
return "\r";
}
if ("\n" !== $lc) {
return '';
}
if ("\r\n" === \substr($line, -2)) {
return "\r\n";
}
return "\n";
}
private static function getArrayDiffParted(array &$from, array &$to): array
{
$start = [];
$end = [];
\reset($to);
foreach ($from as $k => $v) {
$toK = \key($to);
if ($toK === $k && $v === $to[$k]) {
$start[$k] = $v;
unset($from[$k], $to[$k]);
} else {
break;
}
}
\end($from);
\end($to);
do {
$fromK = \key($from);
$toK = \key($to);
if (null === $fromK || null === $toK || \current($from) !== \current($to)) {
break;
}
\prev($from);
\prev($to);
$end = [$fromK => $from[$fromK]] + $end;
unset($from[$fromK], $to[$toK]);
} while (true);
return [$from, $to, $start, $end];
}
}

View File

@@ -0,0 +1,15 @@
<?php declare(strict_types=1);
/*
* This file is part of sebastian/diff.
*
* (c) Sebastian Bergmann <sebastian@phpunit.de>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace SebastianBergmann\Diff;
interface Exception
{
}

View File

@@ -0,0 +1,15 @@
<?php declare(strict_types=1);
/*
* This file is part of sebastian/diff.
*
* (c) Sebastian Bergmann <sebastian@phpunit.de>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace SebastianBergmann\Diff;
class InvalidArgumentException extends \InvalidArgumentException implements Exception
{
}

View File

@@ -1,93 +0,0 @@
<?php
/*
* This file is part of the Diff package.
*
* (c) Sebastian Bergmann <sebastian@phpunit.de>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace SebastianBergmann\Diff\LCS;
/**
* Memory-efficient implementation of longest common subsequence calculation.
*/
class MemoryEfficientImplementation implements LongestCommonSubsequence
{
/**
* Calculates the longest common subsequence of two arrays.
*
* @param array $from
* @param array $to
*
* @return array
*/
public function calculate(array $from, array $to)
{
$cFrom = count($from);
$cTo = count($to);
if ($cFrom == 0) {
return array();
} elseif ($cFrom == 1) {
if (in_array($from[0], $to)) {
return array($from[0]);
} else {
return array();
}
} else {
$i = intval($cFrom / 2);
$fromStart = array_slice($from, 0, $i);
$fromEnd = array_slice($from, $i);
$llB = $this->length($fromStart, $to);
$llE = $this->length(array_reverse($fromEnd), array_reverse($to));
$jMax = 0;
$max = 0;
for ($j = 0; $j <= $cTo; $j++) {
$m = $llB[$j] + $llE[$cTo - $j];
if ($m >= $max) {
$max = $m;
$jMax = $j;
}
}
$toStart = array_slice($to, 0, $jMax);
$toEnd = array_slice($to, $jMax);
return array_merge(
$this->calculate($fromStart, $toStart),
$this->calculate($fromEnd, $toEnd)
);
}
}
/**
* @param array $from
* @param array $to
*
* @return array
*/
private function length(array $from, array $to)
{
$current = array_fill(0, count($to) + 1, 0);
$cFrom = count($from);
$cTo = count($to);
for ($i = 0; $i < $cFrom; $i++) {
$prev = $current;
for ($j = 0; $j < $cTo; $j++) {
if ($from[$i] == $to[$j]) {
$current[$j + 1] = $prev[$j] + 1;
} else {
$current[$j + 1] = max($current[$j], $prev[$j + 1]);
}
}
}
return $current;
}
}

View File

@@ -1,6 +1,6 @@
<?php
<?php declare(strict_types=1);
/*
* This file is part of the Diff package.
* This file is part of sebastian/diff.
*
* (c) Sebastian Bergmann <sebastian@phpunit.de>
*
@@ -10,9 +10,7 @@
namespace SebastianBergmann\Diff;
/**
*/
class Line
final class Line
{
const ADDED = 1;
const REMOVED = 2;
@@ -28,28 +26,18 @@ class Line
*/
private $content;
/**
* @param int $type
* @param string $content
*/
public function __construct($type = self::UNCHANGED, $content = '')
public function __construct(int $type = self::UNCHANGED, string $content = '')
{
$this->type = $type;
$this->content = $content;
}
/**
* @return string
*/
public function getContent()
public function getContent(): string
{
return $this->content;
}
/**
* @return int
*/
public function getType()
public function getType(): int
{
return $this->type;
}

View File

@@ -1,6 +1,6 @@
<?php
<?php declare(strict_types=1);
/*
* This file is part of the Diff package.
* This file is part of sebastian/diff.
*
* (c) Sebastian Bergmann <sebastian@phpunit.de>
*
@@ -8,12 +8,9 @@
* file that was distributed with this source code.
*/
namespace SebastianBergmann\Diff\LCS;
namespace SebastianBergmann\Diff;
/**
* Interface for implementations of longest common subsequence calculation.
*/
interface LongestCommonSubsequence
interface LongestCommonSubsequenceCalculator
{
/**
* Calculates the longest common subsequence of two arrays.
@@ -23,5 +20,5 @@ interface LongestCommonSubsequence
*
* @return array
*/
public function calculate(array $from, array $to);
public function calculate(array $from, array $to): array;
}

View File

@@ -0,0 +1,81 @@
<?php declare(strict_types=1);
/*
* This file is part of sebastian/diff.
*
* (c) Sebastian Bergmann <sebastian@phpunit.de>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace SebastianBergmann\Diff;
final class MemoryEfficientLongestCommonSubsequenceCalculator implements LongestCommonSubsequenceCalculator
{
/**
* {@inheritdoc}
*/
public function calculate(array $from, array $to): array
{
$cFrom = \count($from);
$cTo = \count($to);
if ($cFrom === 0) {
return [];
}
if ($cFrom === 1) {
if (\in_array($from[0], $to, true)) {
return [$from[0]];
}
return [];
}
$i = (int) ($cFrom / 2);
$fromStart = \array_slice($from, 0, $i);
$fromEnd = \array_slice($from, $i);
$llB = $this->length($fromStart, $to);
$llE = $this->length(\array_reverse($fromEnd), \array_reverse($to));
$jMax = 0;
$max = 0;
for ($j = 0; $j <= $cTo; $j++) {
$m = $llB[$j] + $llE[$cTo - $j];
if ($m >= $max) {
$max = $m;
$jMax = $j;
}
}
$toStart = \array_slice($to, 0, $jMax);
$toEnd = \array_slice($to, $jMax);
return \array_merge(
$this->calculate($fromStart, $toStart),
$this->calculate($fromEnd, $toEnd)
);
}
private function length(array $from, array $to): array
{
$current = \array_fill(0, \count($to) + 1, 0);
$cFrom = \count($from);
$cTo = \count($to);
for ($i = 0; $i < $cFrom; $i++) {
$prev = $current;
for ($j = 0; $j < $cTo; $j++) {
if ($from[$i] === $to[$j]) {
$current[$j + 1] = $prev[$j] + 1;
} else {
$current[$j + 1] = \max($current[$j], $prev[$j + 1]);
}
}
}
return $current;
}
}

View File

@@ -0,0 +1,56 @@
<?php declare(strict_types=1);
/*
* This file is part of sebastian/diff.
*
* (c) Sebastian Bergmann <sebastian@phpunit.de>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace SebastianBergmann\Diff\Output;
abstract class AbstractChunkOutputBuilder implements DiffOutputBuilderInterface
{
/**
* Takes input of the diff array and returns the common parts.
* Iterates through diff line by line.
*
* @param array $diff
* @param int $lineThreshold
*
* @return array
*/
protected function getCommonChunks(array $diff, int $lineThreshold = 5): array
{
$diffSize = \count($diff);
$capturing = false;
$chunkStart = 0;
$chunkSize = 0;
$commonChunks = [];
for ($i = 0; $i < $diffSize; ++$i) {
if ($diff[$i][1] === 0 /* OLD */) {
if ($capturing === false) {
$capturing = true;
$chunkStart = $i;
$chunkSize = 0;
} else {
++$chunkSize;
}
} elseif ($capturing !== false) {
if ($chunkSize >= $lineThreshold) {
$commonChunks[$chunkStart] = $chunkStart + $chunkSize;
}
$capturing = false;
}
}
if ($capturing !== false && $chunkSize >= $lineThreshold) {
$commonChunks[$chunkStart] = $chunkStart + $chunkSize;
}
return $commonChunks;
}
}

View File

@@ -0,0 +1,63 @@
<?php declare(strict_types=1);
/*
* This file is part of sebastian/diff.
*
* (c) Sebastian Bergmann <sebastian@phpunit.de>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace SebastianBergmann\Diff\Output;
/**
* Builds a diff string representation in a loose unified diff format
* listing only changes lines. Does not include line numbers.
*/
final class DiffOnlyOutputBuilder implements DiffOutputBuilderInterface
{
/**
* @var string
*/
private $header;
public function __construct(string $header = "--- Original\n+++ New\n")
{
$this->header = $header;
}
public function getDiff(array $diff): string
{
$buffer = \fopen('php://memory', 'r+b');
if ('' !== $this->header) {
\fwrite($buffer, $this->header);
if ("\n" !== \substr($this->header, -1, 1)) {
\fwrite($buffer, "\n");
}
}
foreach ($diff as $diffEntry) {
if ($diffEntry[1] === 1 /* ADDED */) {
\fwrite($buffer, '+' . $diffEntry[0]);
} elseif ($diffEntry[1] === 2 /* REMOVED */) {
\fwrite($buffer, '-' . $diffEntry[0]);
} elseif ($diffEntry[1] === 3 /* WARNING */) {
\fwrite($buffer, ' ' . $diffEntry[0]);
continue; // Warnings should not be tested for line break, it will always be there
} else { /* Not changed (old) 0 */
continue; // we didn't write the non changs line, so do not add a line break either
}
$lc = \substr($diffEntry[0], -1);
if ($lc !== "\n" && $lc !== "\r") {
\fwrite($buffer, "\n"); // \No newline at end of file
}
}
$diff = \stream_get_contents($buffer, -1, 0);
\fclose($buffer);
return $diff;
}
}

View File

@@ -0,0 +1,19 @@
<?php declare(strict_types=1);
/*
* This file is part of sebastian/diff.
*
* (c) Sebastian Bergmann <sebastian@phpunit.de>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace SebastianBergmann\Diff\Output;
/**
* Defines how an output builder should take a generated
* diff array and return a string representation of that diff.
*/
interface DiffOutputBuilderInterface
{
public function getDiff(array $diff): string;
}

View File

@@ -0,0 +1,165 @@
<?php declare(strict_types=1);
/*
* This file is part of sebastian/diff.
*
* (c) Sebastian Bergmann <sebastian@phpunit.de>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace SebastianBergmann\Diff\Output;
/**
* Builds a diff string representation in unified diff format in chunks.
*/
final class UnifiedDiffOutputBuilder extends AbstractChunkOutputBuilder
{
/**
* @var string
*/
private $header;
/**
* @var bool
*/
private $addLineNumbers;
public function __construct(string $header = "--- Original\n+++ New\n", bool $addLineNumbers = false)
{
$this->header = $header;
$this->addLineNumbers = $addLineNumbers;
}
public function getDiff(array $diff): string
{
$buffer = \fopen('php://memory', 'r+b');
if ('' !== $this->header) {
\fwrite($buffer, $this->header);
if ("\n" !== \substr($this->header, -1, 1)) {
\fwrite($buffer, "\n");
}
}
$this->writeDiffChunked($buffer, $diff, $this->getCommonChunks($diff));
$diff = \stream_get_contents($buffer, -1, 0);
\fclose($buffer);
return $diff;
}
// `old` is an array with key => value pairs . Each pair represents a start and end index of `diff`
// of a list of elements all containing `same` (0) entries.
private function writeDiffChunked($output, array $diff, array $old)
{
$upperLimit = \count($diff);
$start = 0;
$fromStart = 0;
$toStart = 0;
if (\count($old)) { // no common parts, list all diff entries
\reset($old);
// iterate the diff, go from chunk to chunk skipping common chunk of lines between those
do {
$commonStart = \key($old);
$commonEnd = \current($old);
if ($commonStart !== $start) {
list($fromRange, $toRange) = $this->getChunkRange($diff, $start, $commonStart);
$this->writeChunk($output, $diff, $start, $commonStart, $fromStart, $fromRange, $toStart, $toRange);
$fromStart += $fromRange;
$toStart += $toRange;
}
$start = $commonEnd + 1;
$commonLength = $commonEnd - $commonStart + 1; // calculate number of non-change lines in the common part
$fromStart += $commonLength;
$toStart += $commonLength;
} while (false !== \next($old));
\end($old); // short cut for finding possible last `change entry`
$tmp = \key($old);
\reset($old);
if ($old[$tmp] === $upperLimit - 1) {
$upperLimit = $tmp;
}
}
if ($start < $upperLimit - 1) { // check for trailing (non) diff entries
do {
--$upperLimit;
} while (isset($diff[$upperLimit][1]) && $diff[$upperLimit][1] === 0);
++$upperLimit;
list($fromRange, $toRange) = $this->getChunkRange($diff, $start, $upperLimit);
$this->writeChunk($output, $diff, $start, $upperLimit, $fromStart, $fromRange, $toStart, $toRange);
}
}
private function writeChunk(
$output,
array $diff,
int $diffStartIndex,
int $diffEndIndex,
int $fromStart,
int $fromRange,
int $toStart,
int $toRange
) {
if ($this->addLineNumbers) {
\fwrite($output, '@@ -' . (1 + $fromStart));
if ($fromRange > 1) {
\fwrite($output, ',' . $fromRange);
}
\fwrite($output, ' +' . (1 + $toStart));
if ($toRange > 1) {
\fwrite($output, ',' . $toRange);
}
\fwrite($output, " @@\n");
} else {
\fwrite($output, "@@ @@\n");
}
for ($i = $diffStartIndex; $i < $diffEndIndex; ++$i) {
if ($diff[$i][1] === 1 /* ADDED */) {
\fwrite($output, '+' . $diff[$i][0]);
} elseif ($diff[$i][1] === 2 /* REMOVED */) {
\fwrite($output, '-' . $diff[$i][0]);
} else { /* Not changed (old) 0 or Warning 3 */
\fwrite($output, ' ' . $diff[$i][0]);
}
$lc = \substr($diff[$i][0], -1);
if ($lc !== "\n" && $lc !== "\r") {
\fwrite($output, "\n"); // \No newline at end of file
}
}
}
private function getChunkRange(array $diff, int $diffStartIndex, int $diffEndIndex): array
{
$toRange = 0;
$fromRange = 0;
for ($i = $diffStartIndex; $i < $diffEndIndex; ++$i) {
if ($diff[$i][1] === 1) { // added
++$toRange;
} elseif ($diff[$i][1] === 2) { // removed
++$fromRange;
} elseif ($diff[$i][1] === 0) { // same
++$fromRange;
++$toRange;
}
}
return [$fromRange, $toRange];
}
}

View File

@@ -1,6 +1,6 @@
<?php
<?php declare(strict_types=1);
/*
* This file is part of the Diff package.
* This file is part of sebastian/diff.
*
* (c) Sebastian Bergmann <sebastian@phpunit.de>
*
@@ -13,82 +13,89 @@ namespace SebastianBergmann\Diff;
/**
* Unified diff parser.
*/
class Parser
final class Parser
{
/**
* @param string $string
*
* @return Diff[]
*/
public function parse($string)
public function parse(string $string): array
{
$lines = preg_split('(\r\n|\r|\n)', $string);
$lineCount = count($lines);
$diffs = array();
$lines = \preg_split('(\r\n|\r|\n)', $string);
if (!empty($lines) && $lines[\count($lines) - 1] === '') {
\array_pop($lines);
}
$lineCount = \count($lines);
$diffs = [];
$diff = null;
$collected = array();
$collected = [];
for ($i = 0; $i < $lineCount; ++$i) {
if (preg_match('(^---\\s+(?P<file>\\S+))', $lines[$i], $fromMatch) &&
preg_match('(^\\+\\+\\+\\s+(?P<file>\\S+))', $lines[$i + 1], $toMatch)) {
if (\preg_match('(^---\\s+(?P<file>\\S+))', $lines[$i], $fromMatch) &&
\preg_match('(^\\+\\+\\+\\s+(?P<file>\\S+))', $lines[$i + 1], $toMatch)) {
if ($diff !== null) {
$this->parseFileDiff($diff, $collected);
$diffs[] = $diff;
$collected = array();
$collected = [];
}
$diff = new Diff($fromMatch['file'], $toMatch['file']);
++$i;
} else {
if (preg_match('/^(?:diff --git |index [\da-f\.]+|[+-]{3} [ab])/', $lines[$i])) {
if (\preg_match('/^(?:diff --git |index [\da-f\.]+|[+-]{3} [ab])/', $lines[$i])) {
continue;
}
$collected[] = $lines[$i];
}
}
if (count($collected) && ($diff !== null)) {
if ($diff !== null && \count($collected)) {
$this->parseFileDiff($diff, $collected);
$diffs[] = $diff;
}
return $diffs;
}
/**
* @param Diff $diff
* @param array $lines
*/
private function parseFileDiff(Diff $diff, array $lines)
{
$chunks = array();
$chunks = [];
$chunk = null;
foreach ($lines as $line) {
if (preg_match('/^@@\s+-(?P<start>\d+)(?:,\s*(?P<startrange>\d+))?\s+\+(?P<end>\d+)(?:,\s*(?P<endrange>\d+))?\s+@@/', $line, $match)) {
if (\preg_match('/^@@\s+-(?P<start>\d+)(?:,\s*(?P<startrange>\d+))?\s+\+(?P<end>\d+)(?:,\s*(?P<endrange>\d+))?\s+@@/', $line, $match)) {
$chunk = new Chunk(
$match['start'],
isset($match['startrange']) ? max(1, $match['startrange']) : 1,
$match['end'],
isset($match['endrange']) ? max(1, $match['endrange']) : 1
(int) $match['start'],
isset($match['startrange']) ? \max(1, (int) $match['startrange']) : 1,
(int) $match['end'],
isset($match['endrange']) ? \max(1, (int) $match['endrange']) : 1
);
$chunks[] = $chunk;
$diffLines = array();
$diffLines = [];
continue;
}
if (preg_match('/^(?P<type>[+ -])?(?P<line>.*)/', $line, $match)) {
if (\preg_match('/^(?P<type>[+ -])?(?P<line>.*)/', $line, $match)) {
$type = Line::UNCHANGED;
if ($match['type'] == '+') {
if ($match['type'] === '+') {
$type = Line::ADDED;
} elseif ($match['type'] == '-') {
} elseif ($match['type'] === '-') {
$type = Line::REMOVED;
}
$diffLines[] = new Line($type, $match['line']);
if (isset($chunk)) {
if (null !== $chunk) {
$chunk->setLines($diffLines);
}
}

View File

@@ -1,6 +1,6 @@
<?php
<?php declare(strict_types=1);
/*
* This file is part of the Diff package.
* This file is part of sebastian/diff.
*
* (c) Sebastian Bergmann <sebastian@phpunit.de>
*
@@ -8,26 +8,18 @@
* file that was distributed with this source code.
*/
namespace SebastianBergmann\Diff\LCS;
namespace SebastianBergmann\Diff;
/**
* Time-efficient implementation of longest common subsequence calculation.
*/
class TimeEfficientImplementation implements LongestCommonSubsequence
final class TimeEfficientLongestCommonSubsequenceCalculator implements LongestCommonSubsequenceCalculator
{
/**
* Calculates the longest common subsequence of two arrays.
*
* @param array $from
* @param array $to
*
* @return array
* {@inheritdoc}
*/
public function calculate(array $from, array $to)
public function calculate(array $from, array $to): array
{
$common = array();
$fromLength = count($from);
$toLength = count($to);
$common = [];
$fromLength = \count($from);
$toLength = \count($to);
$width = $fromLength + 1;
$matrix = new \SplFixedArray($width * ($toLength + 1));
@@ -42,7 +34,7 @@ class TimeEfficientImplementation implements LongestCommonSubsequence
for ($i = 1; $i <= $fromLength; ++$i) {
for ($j = 1; $j <= $toLength; ++$j) {
$o = ($j * $width) + $i;
$matrix[$o] = max(
$matrix[$o] = \max(
$matrix[$o - 1],
$matrix[$o - $width],
$from[$i - 1] === $to[$j - 1] ? $matrix[$o - $width - 1] + 1 : 0
@@ -54,12 +46,13 @@ class TimeEfficientImplementation implements LongestCommonSubsequence
$j = $toLength;
while ($i > 0 && $j > 0) {
if ($from[$i-1] === $to[$j-1]) {
$common[] = $from[$i-1];
if ($from[$i - 1] === $to[$j - 1]) {
$common[] = $from[$i - 1];
--$i;
--$j;
} else {
$o = ($j * $width) + $i;
if ($matrix[$o - $width] > $matrix[$o - 1]) {
--$j;
} else {
@@ -68,6 +61,6 @@ class TimeEfficientImplementation implements LongestCommonSubsequence
}
}
return array_reverse($common);
return \array_reverse($common);
}
}

View File

@@ -0,0 +1,68 @@
<?php declare(strict_types=1);
/*
* This file is part of sebastian/diff.
*
* (c) Sebastian Bergmann <sebastian@phpunit.de>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace SebastianBergmann\Diff;
use PHPUnit\Framework\TestCase;
/**
* @covers SebastianBergmann\Diff\Chunk
*/
final class ChunkTest extends TestCase
{
/**
* @var Chunk
*/
private $chunk;
protected function setUp()
{
$this->chunk = new Chunk;
}
public function testCanBeCreatedWithoutArguments()
{
$this->assertInstanceOf(Chunk::class, $this->chunk);
}
public function testStartCanBeRetrieved()
{
$this->assertSame(0, $this->chunk->getStart());
}
public function testStartRangeCanBeRetrieved()
{
$this->assertSame(1, $this->chunk->getStartRange());
}
public function testEndCanBeRetrieved()
{
$this->assertSame(0, $this->chunk->getEnd());
}
public function testEndRangeCanBeRetrieved()
{
$this->assertSame(1, $this->chunk->getEndRange());
}
public function testLinesCanBeRetrieved()
{
$this->assertSame([], $this->chunk->getLines());
}
public function testLinesCanBeSet()
{
$this->assertSame([], $this->chunk->getLines());
$testValue = ['line0', 'line1'];
$this->chunk->setLines($testValue);
$this->assertSame($testValue, $this->chunk->getLines());
}
}

View File

@@ -0,0 +1,55 @@
<?php declare(strict_types=1);
/*
* This file is part of sebastian/diff.
*
* (c) Sebastian Bergmann <sebastian@phpunit.de>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace SebastianBergmann\Diff;
use PHPUnit\Framework\TestCase;
/**
* @covers SebastianBergmann\Diff\Diff
*
* @uses SebastianBergmann\Diff\Chunk
*/
final class DiffTest extends TestCase
{
public function testGettersAfterConstructionWithDefault()
{
$from = 'line1a';
$to = 'line2a';
$diff = new Diff($from, $to);
$this->assertSame($from, $diff->getFrom());
$this->assertSame($to, $diff->getTo());
$this->assertSame([], $diff->getChunks(), 'Expect chunks to be default value "array()".');
}
public function testGettersAfterConstructionWithChunks()
{
$from = 'line1b';
$to = 'line2b';
$chunks = [new Chunk(), new Chunk(2, 3)];
$diff = new Diff($from, $to, $chunks);
$this->assertSame($from, $diff->getFrom());
$this->assertSame($to, $diff->getTo());
$this->assertSame($chunks, $diff->getChunks(), 'Expect chunks to be passed value.');
}
public function testSetChunksAfterConstruction()
{
$diff = new Diff('line1c', 'line2c');
$this->assertSame([], $diff->getChunks(), 'Expect chunks to be default value "array()".');
$chunks = [new Chunk(), new Chunk(2, 3)];
$diff->setChunks($chunks);
$this->assertSame($chunks, $diff->getChunks(), 'Expect chunks to be passed value.');
}
}

Binary file not shown.

View File

@@ -0,0 +1,83 @@
<?php declare(strict_types=1);
/*
* This file is part of sebastian/diff.
*
* (c) Sebastian Bergmann <sebastian@phpunit.de>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace SebastianBergmann\Diff;
use PHPUnit\Framework\TestCase;
/**
* @requires OS Linux
*/
final class DifferTestTest extends TestCase
{
private $fileFrom;
private $filePatch;
protected function setUp()
{
$dir = \realpath(__DIR__ . '/../') . '/';
$this->fileFrom = $dir . 'from.txt';
$this->filePatch = $dir . 'patch.txt';
}
/**
* @dataProvider provideDiffWithLineNumbers
*/
public function testTheTestProvideDiffWithLineNumbers($expected, $from, $to)
{
$this->runThisTest($expected, $from, $to);
}
public function provideDiffWithLineNumbers()
{
require_once __DIR__ . '/DifferTest.php';
$test = new DifferTest();
$tests = $test->provideDiffWithLineNumbers();
$tests = \array_filter(
$tests,
function ($key) {
return !\is_string($key) || false === \strpos($key, 'non_patch_compat');
},
ARRAY_FILTER_USE_KEY
);
return $tests;
}
private function runThisTest(string $expected, string $from, string $to)
{
$expected = \str_replace('--- Original', '--- from.txt', $expected);
$expected = \str_replace('+++ New', '+++ from.txt', $expected);
@\unlink($this->fileFrom);
@\unlink($this->filePatch);
$this->assertNotFalse(\file_put_contents($this->fileFrom, $from));
$this->assertNotFalse(\file_put_contents($this->filePatch, $expected));
$command = \sprintf(
'patch -u --verbose %s < %s', // --posix
\escapeshellarg($this->fileFrom),
\escapeshellarg($this->filePatch)
);
\exec($command, $output, $d);
$this->assertSame(0, $d, \sprintf('%s | %s', $command, \implode("\n", $output)));
$patched = \file_get_contents($this->fileFrom);
$this->assertSame($patched, $to);
@\unlink($this->fileFrom . '.orig');
@\unlink($this->fileFrom);
@\unlink($this->filePatch);
}
}

View File

@@ -1,175 +0,0 @@
<?php
/*
* This file is part of the Diff package.
*
* (c) Sebastian Bergmann <sebastian@phpunit.de>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace SebastianBergmann\Diff\LCS;
use PHPUnit_Framework_TestCase;
/**
* Some of these tests are volontary stressfull, in order to give some approximative benchmark hints.
*/
class TimeEfficientImplementationTest extends PHPUnit_Framework_TestCase
{
private $implementation;
private $memory_limit;
private $stress_sizes = array(1, 2, 3, 100, 500, 1000, 2000);
protected function setUp()
{
$this->memory_limit = ini_get('memory_limit');
ini_set('memory_limit', '256M');
$this->implementation = new TimeEfficientImplementation;
}
protected function tearDown()
{
ini_set('memory_limit', $this->memory_limit);
}
public function testBothEmpty()
{
$from = array();
$to = array();
$common = $this->implementation->calculate($from, $to);
$this->assertEquals(array(), $common);
}
public function testIsStrictComparison()
{
$from = array(
false, 0, 0.0, '', null, array(),
true, 1, 1.0, 'foo', array('foo', 'bar'), array('foo' => 'bar')
);
$to = $from;
$common = $this->implementation->calculate($from, $to);
$this->assertEquals($from, $common);
$to = array(
false, false, false, false, false, false,
true, true, true, true, true, true
);
$expected = array(
false,
true,
);
$common = $this->implementation->calculate($from, $to);
$this->assertEquals($expected, $common);
}
public function testEqualSequences()
{
foreach ($this->stress_sizes as $size) {
$range = range(1, $size);
$from = $range;
$to = $range;
$common = $this->implementation->calculate($from, $to);
$this->assertEquals($range, $common);
}
}
public function testDistinctSequences()
{
$from = array('A');
$to = array('B');
$common = $this->implementation->calculate($from, $to);
$this->assertEquals(array(), $common);
$from = array('A', 'B', 'C');
$to = array('D', 'E', 'F');
$common = $this->implementation->calculate($from, $to);
$this->assertEquals(array(), $common);
foreach ($this->stress_sizes as $size) {
$from = range(1, $size);
$to = range($size + 1, $size * 2);
$common = $this->implementation->calculate($from, $to);
$this->assertEquals(array(), $common);
}
}
public function testCommonSubsequence()
{
$from = array('A', 'C', 'E', 'F', 'G');
$to = array('A', 'B', 'D', 'E', 'H');
$expected = array('A', 'E');
$common = $this->implementation->calculate($from, $to);
$this->assertEquals($expected, $common);
$from = array('A', 'C', 'E', 'F', 'G');
$to = array('B', 'C', 'D', 'E', 'F', 'H');
$expected = array('C', 'E', 'F');
$common = $this->implementation->calculate($from, $to);
$this->assertEquals($expected, $common);
foreach ($this->stress_sizes as $size) {
$from = $size < 2 ? array(1) : range(1, $size + 1, 2);
$to = $size < 3 ? array(1) : range(1, $size + 1, 3);
$expected = $size < 6 ? array(1) : range(1, $size + 1, 6);
$common = $this->implementation->calculate($from, $to);
$this->assertEquals($expected, $common);
}
}
public function testSingleElementSubsequenceAtStart()
{
foreach ($this->stress_sizes as $size) {
$from = range(1, $size);
$to = array_slice($from, 0, 1);
$common = $this->implementation->calculate($from, $to);
$this->assertEquals($to, $common);
}
}
public function testSingleElementSubsequenceAtMiddle()
{
foreach ($this->stress_sizes as $size) {
$from = range(1, $size);
$to = array_slice($from, (int) $size / 2, 1);
$common = $this->implementation->calculate($from, $to);
$this->assertEquals($to, $common);
}
}
public function testSingleElementSubsequenceAtEnd()
{
foreach ($this->stress_sizes as $size) {
$from = range(1, $size);
$to = array_slice($from, $size - 1, 1);
$common = $this->implementation->calculate($from, $to);
$this->assertEquals($to, $common);
}
}
public function testReversedSequences()
{
$from = array('A', 'B');
$to = array('B', 'A');
$expected = array('A');
$common = $this->implementation->calculate($from, $to);
$this->assertEquals($expected, $common);
foreach ($this->stress_sizes as $size) {
$from = range(1, $size);
$to = array_reverse($from);
$common = $this->implementation->calculate($from, $to);
$this->assertEquals(array(1), $common);
}
}
}

View File

@@ -0,0 +1,44 @@
<?php declare(strict_types=1);
/*
* This file is part of sebastian/diff.
*
* (c) Sebastian Bergmann <sebastian@phpunit.de>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace SebastianBergmann\Diff;
use PHPUnit\Framework\TestCase;
/**
* @covers SebastianBergmann\Diff\Line
*/
final class LineTest extends TestCase
{
/**
* @var Line
*/
private $line;
protected function setUp()
{
$this->line = new Line;
}
public function testCanBeCreatedWithoutArguments()
{
$this->assertInstanceOf(Line::class, $this->line);
}
public function testTypeCanBeRetrieved()
{
$this->assertSame(Line::UNCHANGED, $this->line->getType());
}
public function testContentCanBeRetrieved()
{
$this->assertSame('', $this->line->getContent());
}
}

View File

@@ -0,0 +1,201 @@
<?php declare(strict_types=1);
/*
* This file is part of sebastian/diff.
*
* (c) Sebastian Bergmann <sebastian@phpunit.de>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace SebastianBergmann\Diff;
use PHPUnit\Framework\TestCase;
/**
* @coversNothing
*/
abstract class LongestCommonSubsequenceTest extends TestCase
{
/**
* @var LongestCommonSubsequenceCalculator
*/
private $implementation;
/**
* @var string
*/
private $memoryLimit;
/**
* @var int[]
*/
private $stress_sizes = [1, 2, 3, 100, 500, 1000, 2000];
protected function setUp()
{
$this->memoryLimit = \ini_get('memory_limit');
\ini_set('memory_limit', '256M');
$this->implementation = $this->createImplementation();
}
/**
* @return LongestCommonSubsequenceCalculator
*/
abstract protected function createImplementation();
protected function tearDown()
{
\ini_set('memory_limit', $this->memoryLimit);
}
public function testBothEmpty()
{
$from = [];
$to = [];
$common = $this->implementation->calculate($from, $to);
$this->assertSame([], $common);
}
public function testIsStrictComparison()
{
$from = [
false, 0, 0.0, '', null, [],
true, 1, 1.0, 'foo', ['foo', 'bar'], ['foo' => 'bar']
];
$to = $from;
$common = $this->implementation->calculate($from, $to);
$this->assertSame($from, $common);
$to = [
false, false, false, false, false, false,
true, true, true, true, true, true
];
$expected = [
false,
true,
];
$common = $this->implementation->calculate($from, $to);
$this->assertSame($expected, $common);
}
public function testEqualSequences()
{
foreach ($this->stress_sizes as $size) {
$range = \range(1, $size);
$from = $range;
$to = $range;
$common = $this->implementation->calculate($from, $to);
$this->assertSame($range, $common);
}
}
public function testDistinctSequences()
{
$from = ['A'];
$to = ['B'];
$common = $this->implementation->calculate($from, $to);
$this->assertSame([], $common);
$from = ['A', 'B', 'C'];
$to = ['D', 'E', 'F'];
$common = $this->implementation->calculate($from, $to);
$this->assertSame([], $common);
foreach ($this->stress_sizes as $size) {
$from = \range(1, $size);
$to = \range($size + 1, $size * 2);
$common = $this->implementation->calculate($from, $to);
$this->assertSame([], $common);
}
}
public function testCommonSubsequence()
{
$from = ['A', 'C', 'E', 'F', 'G'];
$to = ['A', 'B', 'D', 'E', 'H'];
$expected = ['A', 'E'];
$common = $this->implementation->calculate($from, $to);
$this->assertSame($expected, $common);
$from = ['A', 'C', 'E', 'F', 'G'];
$to = ['B', 'C', 'D', 'E', 'F', 'H'];
$expected = ['C', 'E', 'F'];
$common = $this->implementation->calculate($from, $to);
$this->assertSame($expected, $common);
foreach ($this->stress_sizes as $size) {
$from = $size < 2 ? [1] : \range(1, $size + 1, 2);
$to = $size < 3 ? [1] : \range(1, $size + 1, 3);
$expected = $size < 6 ? [1] : \range(1, $size + 1, 6);
$common = $this->implementation->calculate($from, $to);
$this->assertSame($expected, $common);
}
}
public function testSingleElementSubsequenceAtStart()
{
foreach ($this->stress_sizes as $size) {
$from = \range(1, $size);
$to = \array_slice($from, 0, 1);
$common = $this->implementation->calculate($from, $to);
$this->assertSame($to, $common);
}
}
public function testSingleElementSubsequenceAtMiddle()
{
foreach ($this->stress_sizes as $size) {
$from = \range(1, $size);
$to = \array_slice($from, (int) ($size / 2), 1);
$common = $this->implementation->calculate($from, $to);
$this->assertSame($to, $common);
}
}
public function testSingleElementSubsequenceAtEnd()
{
foreach ($this->stress_sizes as $size) {
$from = \range(1, $size);
$to = \array_slice($from, $size - 1, 1);
$common = $this->implementation->calculate($from, $to);
$this->assertSame($to, $common);
}
}
public function testReversedSequences()
{
$from = ['A', 'B'];
$to = ['B', 'A'];
$expected = ['A'];
$common = $this->implementation->calculate($from, $to);
$this->assertSame($expected, $common);
foreach ($this->stress_sizes as $size) {
$from = \range(1, $size);
$to = \array_reverse($from);
$common = $this->implementation->calculate($from, $to);
$this->assertSame([1], $common);
}
}
public function testStrictTypeCalculate()
{
$diff = $this->implementation->calculate(['5'], ['05']);
$this->assertInternalType('array', $diff);
$this->assertCount(0, $diff);
}
}

View File

@@ -0,0 +1,22 @@
<?php declare(strict_types=1);
/*
* This file is part of sebastian/diff.
*
* (c) Sebastian Bergmann <sebastian@phpunit.de>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace SebastianBergmann\Diff;
/**
* @covers SebastianBergmann\Diff\MemoryEfficientLongestCommonSubsequenceCalculator
*/
final class MemoryEfficientImplementationTest extends LongestCommonSubsequenceTest
{
protected function createImplementation()
{
return new MemoryEfficientLongestCommonSubsequenceCalculator;
}
}

View File

@@ -1,6 +1,6 @@
<?php
<?php declare(strict_types=1);
/*
* This file is part of the Diff package.
* This file is part of sebastian/diff.
*
* (c) Sebastian Bergmann <sebastian@phpunit.de>
*
@@ -10,9 +10,16 @@
namespace SebastianBergmann\Diff;
use PHPUnit_Framework_TestCase;
use PHPUnit\Framework\TestCase;
class ParserTest extends PHPUnit_Framework_TestCase
/**
* @covers SebastianBergmann\Diff\Parser
*
* @uses SebastianBergmann\Diff\Chunk
* @uses SebastianBergmann\Diff\Diff
* @uses SebastianBergmann\Diff\Line
*/
final class ParserTest extends TestCase
{
/**
* @var Parser
@@ -26,23 +33,28 @@ class ParserTest extends PHPUnit_Framework_TestCase
public function testParse()
{
$content = file_get_contents(__DIR__ . '/fixtures/patch.txt');
$content = \file_get_contents(__DIR__ . '/fixtures/patch.txt');
$diffs = $this->parser->parse($content);
$this->assertInternalType('array', $diffs);
$this->assertContainsOnlyInstancesOf(Diff::class, $diffs);
$this->assertCount(1, $diffs);
$chunks = $diffs[0]->getChunks();
$this->assertInternalType('array', $chunks);
$this->assertContainsOnlyInstancesOf(Chunk::class, $chunks);
$this->assertCount(1, $chunks);
$this->assertEquals(20, $chunks[0]->getStart());
$this->assertSame(20, $chunks[0]->getStart());
$this->assertCount(5, $chunks[0]->getLines());
$this->assertCount(4, $chunks[0]->getLines());
}
public function testParseWithMultipleChunks()
{
$content = file_get_contents(__DIR__ . '/fixtures/patch2.txt');
$content = \file_get_contents(__DIR__ . '/fixtures/patch2.txt');
$diffs = $this->parser->parse($content);
@@ -51,12 +63,89 @@ class ParserTest extends PHPUnit_Framework_TestCase
$chunks = $diffs[0]->getChunks();
$this->assertCount(3, $chunks);
$this->assertEquals(20, $chunks[0]->getStart());
$this->assertEquals(320, $chunks[1]->getStart());
$this->assertEquals(600, $chunks[2]->getStart());
$this->assertSame(20, $chunks[0]->getStart());
$this->assertSame(320, $chunks[1]->getStart());
$this->assertSame(600, $chunks[2]->getStart());
$this->assertCount(5, $chunks[0]->getLines());
$this->assertCount(5, $chunks[1]->getLines());
$this->assertCount(5, $chunks[2]->getLines());
$this->assertCount(4, $chunks[2]->getLines());
}
public function testParseWithRemovedLines()
{
$content = <<<A
diff --git a/Test.txt b/Test.txt
index abcdefg..abcdefh 100644
--- a/Test.txt
+++ b/Test.txt
@@ -49,9 +49,8 @@
A
-B
A;
$diffs = $this->parser->parse($content);
$this->assertInternalType('array', $diffs);
$this->assertContainsOnlyInstancesOf(Diff::class, $diffs);
$this->assertCount(1, $diffs);
$chunks = $diffs[0]->getChunks();
$this->assertInternalType('array', $chunks);
$this->assertContainsOnlyInstancesOf(Chunk::class, $chunks);
$this->assertCount(1, $chunks);
$chunk = $chunks[0];
$this->assertSame(49, $chunk->getStart());
$this->assertSame(49, $chunk->getEnd());
$this->assertSame(9, $chunk->getStartRange());
$this->assertSame(8, $chunk->getEndRange());
$lines = $chunk->getLines();
$this->assertInternalType('array', $lines);
$this->assertContainsOnlyInstancesOf(Line::class, $lines);
$this->assertCount(2, $lines);
/** @var Line $line */
$line = $lines[0];
$this->assertSame('A', $line->getContent());
$this->assertSame(Line::UNCHANGED, $line->getType());
$line = $lines[1];
$this->assertSame('B', $line->getContent());
$this->assertSame(Line::REMOVED, $line->getType());
}
public function testParseDiffForMulitpleFiles()
{
$content = <<<A
diff --git a/Test.txt b/Test.txt
index abcdefg..abcdefh 100644
--- a/Test.txt
+++ b/Test.txt
@@ -1,3 +1,2 @@
A
-B
diff --git a/Test123.txt b/Test123.txt
index abcdefg..abcdefh 100644
--- a/Test2.txt
+++ b/Test2.txt
@@ -1,2 +1,3 @@
A
+B
A;
$diffs = $this->parser->parse($content);
$this->assertCount(2, $diffs);
/** @var Diff $diff */
$diff = $diffs[0];
$this->assertSame('a/Test.txt', $diff->getFrom());
$this->assertSame('b/Test.txt', $diff->getTo());
$this->assertCount(1, $diff->getChunks());
$diff = $diffs[1];
$this->assertSame('a/Test2.txt', $diff->getFrom());
$this->assertSame('b/Test2.txt', $diff->getTo());
$this->assertCount(1, $diff->getChunks());
}
}

View File

@@ -0,0 +1,22 @@
<?php declare(strict_types=1);
/*
* This file is part of sebastian/diff.
*
* (c) Sebastian Bergmann <sebastian@phpunit.de>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace SebastianBergmann\Diff;
/**
* @covers SebastianBergmann\Diff\TimeEfficientLongestCommonSubsequenceCalculator
*/
final class TimeEfficientImplementationTest extends LongestCommonSubsequenceTest
{
protected function createImplementation()
{
return new TimeEfficientLongestCommonSubsequenceCalculator;
}
}