php merge
1.0.0
在處理文本修訂時,有時會面臨這樣的問題:同一原始文本有多個修訂。我們不想選擇一個並放棄另一個,而是希望合併兩個修訂。
Git 已經做得很好了。在 php 應用程式中,我們需要一個具有相同功能的簡單工具。 xdiff PECL 擴充具有 xdiff_string_merge3 函數。但xdiff_string_merge3
行為方式與 git 不同,而 xdiff 可能在您的系統上不可用。
PhpMerge 是一個解決這個問題的小型函式庫。有兩個類別: PhpMergePhpMerge
和PhpMergeGitMerge
實作了PhpMergePhpMergeInterface
,它只有一個merge
方法。
PhpMerge
使用SebastianBergmannDiffDiffer
取得不同版本之間的差異並從中計算合併的文字。 GitMerge
使用SymplifyGitWrapperGitWrapper
,將文字寫入暫存檔案並使用命令列 git 合併文字。
簡單的例子:
use PhpMerge PhpMerge ;
// Create a merger instance.
$ merger = new PhpMerge ();
// Get the texts to merge.
$ original = <<<'EOD'
unchanged
replaced
unchanged
normal
unchanged
unchanged
removed
EOD;
$ version1 = <<<'EOD'
added
unchanged
replacement
unchanged
normal
unchanged
unchanged
EOD;
$ version2 = <<<'EOD'
unchanged
replaced
unchanged
normal??
unchanged
unchanged
EOD;
$ expected = <<<'EOD'
added
unchanged
replacement
unchanged
normal??
unchanged
unchanged
EOD;
$ result = $ merger -> merge ( $ original , $ version1 , $ version2 );
// $result === $expected;
合併衝突時:
// Continuing from before with:
use Phpmerge MergeException ;
use PhpMerge MergeConflict ;
$ conflicting = <<<'EOD'
unchanged
replaced
unchanged
normal!!
unchanged
unchanged
EOD;
try {
$ merger -> merge ( $ original , $ version2 , $ conflicting );
} catch ( MergeException $ exception ) {
/** @var MergeConflict[] $conflicts */
$ conflicts = $ exception -> getConflicts ();
$ original_lines = $ conflicts [ 0 ]-> getBase ();
// $original_lines === ["normaln"];
$ version2_lines = $ conflicts [ 0 ]-> getRemote ();
// $version2_lines === ["normal??n"];
$ conflicting_lines = $ conflicts [ 0 ]-> getLocal ();
// $conflicting_lines === ["normal!!n"];
$ line_numer_of_conflict = $ conflicts [ 0 ]-> getBaseLine ();
// $line_numer_of_conflict === 3; // Count starts with 0.
// It is also possible to get the merged version using the first version
// to resolve conflicts.
$ merged = $ exception -> getMerged ();
// $merged === $version2;
// In this case, but in general there could be non-conflicting changes.
$ line_in_merged = $ conflicts [ 0 ]-> getMergedLine ();
// $line_in_merged === 3; // Count starts with 0.
}
使用命令列git執行合併:
use PhpMerge GitMerge ;
$ merger = new GitMerge ();
// Use as the previous example.
PhpMerge 可以與 Composer 一起安裝,只需將庫新增為 Composer.json 檔案的依賴項即可。
{
"require" : {
"bircher/php-merge" : " ~4.0 "
}
}
要將命令列 git 與GitMerge
結合使用:
{
"require" : {
"bircher/php-merge" : " ~4.0 " ,
"symplify/git-wrapper" : " ^9.1|^10.0 "
}
}
請參閱 Composer 的文件以取得安裝和使用說明。
在 ~4.0 版本中,我們從cpliakas/git-wrapper
切換到symplify/git-wrapper
,因為前者已被棄用。此更新意味著僅使用PhpMergePhpMerge
時沒有任何變化。