Example #1
0
 /**
  * Get the difference between two files
  *
  * @static
  * @access private
  * @param string $a The path to the existing file
  * @param string $b The path to the new (replacement) file
  * @return string The unified diff between the two
  */
 private static function diff($a, $b)
 {
     $a_code = explode("\n", file_get_contents($a));
     $b_code = explode("\n", file_get_contents($b));
     $diff = new \Diff($b_code, $a_code, array('ignoreWhitespace' => TRUE, 'ignoreNewLines' => TRUE));
     return $diff->render(new \Diff_Renderer_Text_Unified());
 }
Example #2
0
 public function buildPatch($originalFile, $modfiedFileName, PatchBuffer $buffer)
 {
     if (!$buffer->isModified()) {
         return '';
     }
     $diff = new \Diff($buffer->getOriginalContents(), $buffer->getModifiedContents());
     $renderer = new \Diff_Renderer_Text_Unified();
     return "--- {$originalFile}\n" . "+++ {$modfiedFileName}\n" . $diff->render($renderer);
 }
 public function testReplace()
 {
     $old = ['first', 'equal'];
     $new = ['second', 'equal'];
     $diff = new \Diff($old, $new);
     $renderer = new \VisualAppeal\Connect\Extensions\DiffRenderer();
     $render = @$diff->render($renderer);
     $this->assertContains('diff-change-replace', $render);
 }
Example #4
0
 /**
  * Show difference between two versions.
  *
  * @param  \App\Version
  * @param  \App\Version
  * @return void
  */
 protected function compareVersions(Version $before, Version $after)
 {
     // Parse source
     $beforeArray = explode("\n", $before->source);
     $afterArray = explode("\n", $after->source);
     // Compare versions
     $diff = new \Diff($beforeArray, $afterArray, $options = []);
     // Load view
     return view('version.compare', ['title' => _('Versions'), 'subtitle' => _('Compare'), 'before' => $before, 'after' => $after, 'sideBySideDiff' => $diff->Render(new \Diff_Renderer_Html_SideBySide()), 'inlineDiff' => $diff->render(new \Diff_Renderer_Html_Inline())]);
 }
Example #5
0
 public function compare(IResource $resourceA, IResource $resourceB)
 {
     $data_a = $resourceA->getCleanFields();
     $data_b = $resourceB->getCleanFields();
     $a = explode("\n", $data_a['snippet']);
     $b = explode("\n", $data_b['snippet']);
     $d = new \Diff($a, $b, []);
     $renderer = new \Diff_Renderer_Html_SideBySide();
     $diffc = $d->render($renderer);
     return !empty($diffc);
 }
Example #6
0
 public function getDiffHtml()
 {
     $old = explode("\n", $this->old_value);
     $new = explode("\n", $this->new_value);
     foreach ($old as $i => $line) {
         $old[$i] = rtrim($line, "\r\n");
     }
     foreach ($new as $i => $line) {
         $new[$i] = rtrim($line, "\r\n");
     }
     $diff = new \Diff($old, $new);
     return $diff->render(new \Diff_Renderer_Html_Inline());
 }
Example #7
0
 protected function assertJsonResponseContent($response, $filename)
 {
     $expectedResponse = file_get_contents(__DIR__ . sprintf('/../Tests/Responses/%s.json', $filename));
     $actualResponse = $response->getContent();
     $actualResponse = json_encode(json_decode($actualResponse), JSON_PRETTY_PRINT);
     $factory = new SimpleFactory();
     $matcher = $factory->createMatcher();
     $result = $matcher->match($actualResponse, $expectedResponse);
     if (!$result) {
         echo $matcher->getError();
         $expectedResponse = explode(PHP_EOL, (string) $expectedResponse);
         $actualResponse = explode(PHP_EOL, (string) $actualResponse);
         $diff = new \Diff($expectedResponse, $actualResponse, array());
         $renderer = new \Diff_Renderer_Text_Unified();
         echo $diff->render($renderer);
     }
     $this->assertTrue($result);
 }
 public function compare($expected, $actual)
 {
     $expected = explode(PHP_EOL, (string) $expected);
     $actual = explode(PHP_EOL, (string) $actual);
     $diff = new \Diff($expected, $actual, array());
     $renderer = new \Diff_Renderer_Text_Unified();
     $text = $diff->render($renderer);
     $lines = array();
     foreach (explode("\n", $text) as $line) {
         if (0 === strpos($line, '-')) {
             $lines[] = sprintf('<diff-del>%s</diff-del>', $line);
         } elseif (0 === strpos($line, '+')) {
             $lines[] = sprintf('<diff-add>%s</diff-add>', $line);
         } else {
             $lines[] = $line;
         }
     }
     return sprintf("<code>%s%s</code>", PHP_EOL, implode(PHP_EOL, $lines));
 }
Example #9
0
 public function diffWithOnline($file)
 {
     $localSourceDir = $this->config->getDeployFromDir();
     $remoteSourceDir = $this->config->getTargetWorkspace();
     $cmd[] = "cat {$remoteSourceDir}/{$file}";
     $command = implode(' && ', $cmd);
     $host = GlobalHelper::str2arr($this->config->hosts)[0];
     if ($this->runRemoteCommand($command, 0, $host)) {
         $contentOld = explode(PHP_EOL, substr($this->log, strlen($host . ' : ')));
         array_walk($contentOld, function (&$line) {
             $line = rtrim($line, "\r\n");
         });
     } else {
         $contentOld = [];
     }
     $contentNew = file("{$localSourceDir}/{$file}");
     array_walk($contentNew, function (&$line) {
         $line = rtrim($line, "\r\n");
     });
     $diff = new \Diff($contentOld, $contentNew);
     return $diff->render(new \Diff_Renderer_Html_Array());
 }
Example #10
0
 public function diff()
 {
     $this->test();
     if ($this->wasSuccessfull()) {
         return;
     }
     global $HTML;
     $HTML->p('Diff', '.label');
     $a = explode("\n", $this->prediction);
     $b = explode("\n", $this->_result);
     $options = array();
     // Initialize the diff class
     $diff = new \Diff($a, $b, $options);
     $renderer = new \Diff_Renderer_Html_Inline();
     echo $diff->render($renderer);
 }
 /**
  * @Then /^the response JSON matches "([^"]*)"$/
  *
  * @param string $expectedJsonFilePath
  *
  * @throws \Exception
  */
 public function theResponseJSONMatches($expectedJsonFilePath)
 {
     $factory = new PHPMatcherFactory();
     $matcher = $factory->createMatcher();
     $responseJson = json_encode(json_decode($this->getResponseWithAssertion()->getContent()), JSON_PRETTY_PRINT);
     $expectedJson = file_get_contents($this->getFilePath($expectedJsonFilePath));
     if ($matcher->match($responseJson, $expectedJson) === false) {
         echo $matcher->getError();
         $difference = new \Diff(explode(PHP_EOL, $expectedJson), explode(PHP_EOL, $responseJson));
         echo $difference->render(new \Diff_Renderer_Text_Unified());
         throw new \Exception('Response JSON did not match.');
     }
 }
 public function getDiff($field, $new, $old)
 {
     $config = ['ignoreNewLines' => true, 'ignoreWhitespace' => true, 'ignoreCase' => true];
     $diff = new \Diff((array) $old, (array) $new, $config);
     return $diff->render(new \Diff_Renderer_Html_SideBySide());
 }
Example #13
0
 /**
  * Shows a visual diff of what has changed
  */
 public function diffAction()
 {
     $id = (int) $this->dispatcher->getParam('id');
     $revision = (int) $this->dispatcher->getParam('revision');
     $diffVersion = Versions::findFirst(array('page_id = :id: AND version = :revision:', 'bind' => array('id' => $id, 'revision' => $revision)));
     if ($diffVersion === false) {
         return $this->dispatcher->forward(array('action' => 'error404'));
     }
     $currentVersion = Pages::findFirst($id);
     $diffEngine = new \Diff(explode("\n", $diffVersion->content), explode("\n", $currentVersion->content), []);
     $renderer = new \Diff_Renderer_Html_SideBySide();
     $this->view->diff = $diffEngine->render($renderer);
     $this->view->page = $currentVersion;
     $this->view->revision = $diffVersion->version;
     $this->view->title = "diff – " . $currentVersion->title;
 }
Example #14
0
// Initialize the diff class
$diff = new Diff($a, $b, $options);
?>
		<h2>Side by Side Diff</h2>
		<?php 
// Generate a side by side diff
require_once __DIR__ . '/../lib/Diff/Renderer/Html/SideBySide.php';
$renderer = new Diff_Renderer_Html_SideBySide();
echo $diff->Render($renderer);
?>
		<h2>Inline Diff</h2>
		<?php 
// Generate an inline diff
require_once __DIR__ . '/../lib/Diff/Renderer/Html/Inline.php';
$renderer = new Diff_Renderer_Html_Inline();
echo $diff->render($renderer);
?>
		<h2>Unified Diff</h2>
		<pre><?php 
// Generate a unified diff
require_once __DIR__ . '/../lib/Diff/Renderer/Text/Unified.php';
$renderer = new Diff_Renderer_Text_Unified();
echo htmlspecialchars($diff->render($renderer));
?>
		</pre>
		<h2>Context Diff</h2>
		<pre><?php 
// Generate a context diff
require_once __DIR__ . '/../lib/Diff/Renderer/Text/Context.php';
$renderer = new Diff_Renderer_Text_Context();
echo htmlspecialchars($diff->render($renderer));
 /**
  * Compare given content with the subject's one in the given language.
  *
  * @param mixed  $subject
  * @param array  $content
  * @param string $language
  * @param bool   $original
  *
  * @return array
  */
 protected function compareContent($subject, array $content, $language, $original = true)
 {
     $properties = array_keys($content);
     $values = $this->getProperties($subject, $properties, $language);
     $diffs = [];
     $renderer = new \Diff_Renderer_Html_SideBySide();
     foreach ($values as $property => $value) {
         $a = [$value];
         $b = [$content[$property]];
         if ($original) {
             $b = [$content[$property]['original_phrase']];
         }
         $diff = new \Diff($a, $b);
         $diffs[$property] = $diff->render($renderer);
     }
     return $diffs;
 }
 /**
  * Handle the patching cycle for a extractor.
  *
  * @param string          $path          The path to patch.
  *
  * @param AuthorExtractor $extractor     The extractor to patch.
  *
  * @param array           $wantedAuthors The authors that shall be contained in the result.
  *
  * @return bool True if the patch has been collected, false otherwise.
  */
 private function patchExtractor($path, $extractor, $wantedAuthors)
 {
     if (!($this->diff && $extractor instanceof PatchingExtractor)) {
         return false;
     }
     $original = explode("\n", $extractor->getBuffer($path));
     $new = explode("\n", $extractor->getBuffer($path, $wantedAuthors));
     $diff = new \Diff($original, $new);
     $patch = $diff->render($this->diff);
     if (empty($patch)) {
         return false;
     }
     $patchFile = $path;
     foreach ($this->config->getIncludedPaths() as $prefix) {
         $prefixLength = strlen($prefix);
         if (substr($path, 0, $prefixLength) === $prefix) {
             $patchFile = substr($path, $prefixLength);
             if ($patchFile[0] == '/') {
                 $patchFile = substr($patchFile, 1);
             }
             break;
         }
     }
     $this->patchSet[] = 'diff ' . $patchFile . ' ' . $patchFile . "\n" . '--- ' . $patchFile . "\n" . '+++ ' . $patchFile . "\n" . $patch;
     return true;
 }
Example #17
0
 /**
  * @param mixed $x
  * @param mixed $y
  *
  * @return string
  */
 private function diff($x, $y)
 {
     $exporter = new Exporter();
     $diff = new Diff(preg_split('/\\n/', $exporter->export($x)), preg_split('/\\n/', $exporter->export($y)));
     return $diff->render(new Diff_Renderer_Text_Unified());
 }
Example #18
0
 * @var string $field
 * @var string $old
 * @var string $new
 */
$this->title = \Yii::t('log', 'Field "{0}" updated', [$log->goal->getAttributeLabel($field)]);
$this->params['breadcrumbs'][] = ['label' => $log->goal->title, 'url' => $log->goal->url()];
$this->params['breadcrumbs'][] = ['label' => Yii::t('log', 'Logs'), 'url' => $log->goal->urlLogList()];
$this->params['breadcrumbs'][] = ['label' => $log->id, 'url' => ['log/update', 'id' => $log->id]];
$this->params['breadcrumbs'][] = Yii::t('app', 'Diff');
\app\assets\DiffAsset::register($this);
$a = explode("\n", $old);
$b = explode("\n", $new);
// Options for generating the diff
$options = array('ignoreWhitespace' => true);
// Initialize the diff class
$diff = new Diff($a, $b, $options);
$renderer = new Diff_Renderer_Html_Inline();
$text = $diff->render($renderer);
?>

<h1><?php 
echo $this->title;
?>
:</h1>

<?php 
echo $text;
?>


Example #19
0
     
      
      <p>Besucheranzahl:<?php 
echo $visits;
?>
</p>
      <p>Titel:<?php 
echo $title;
?>
</p>

     <p> <?php 
// Generate an inline diff
require_once dirname(__FILE__) . '/lib/Diff/Renderer/Html/Inline.php';
$renderer = new Diff_Renderer_Html_Inline();
echo $diff->render($renderer);
?>
     </p>
      </div>

      


    </div><!--Ende content-->

    <footer>
        
    </footer><!-- Ende footer--> 

  </div><!--Ende Wrapper-->
  </body>
 /**
  * Compares the current to the original template
  *
  * @param DataContainer $dc
  *
  * @return string
  *
  * @throws Contao\CoreBundle\Exception\InternalServerErrorException
  */
 public function compareTemplate(DataContainer $dc)
 {
     $objCurrentFile = new File($dc->id);
     $strName = $objCurrentFile->filename;
     $strExtension = $objCurrentFile->extension;
     $arrTemplates = TemplateLoader::getFiles();
     $blnOverridesAnotherTpl = isset($arrTemplates[$strName]);
     $strPrefix = '';
     if (($pos = strpos($strName, '_')) !== false) {
         $strPrefix = substr($strName, 0, $pos + 1);
     }
     $strBuffer = '';
     $strCompareName = null;
     $strComparePath = null;
     // By default it's the original template to compare against
     if ($blnOverridesAnotherTpl) {
         $strCompareName = $strName;
         $strComparePath = $arrTemplates[$strCompareName] . '/' . $strCompareName . '.' . $strExtension;
         if ($strComparePath !== null) {
             $strBuffer .= '<p class="tl_info" style="margin-bottom:1em">' . sprintf($GLOBALS['TL_LANG']['tl_templates']['overridesAnotherTpl'], $strComparePath) . '</p>';
         }
     } else {
         // Try to find the base template by strippig suffixes
         while (strpos($strName, '_') !== false) {
             $strName = substr($strName, 0, strrpos($strName, '_'));
             if (isset($arrTemplates[$strName])) {
                 $strCompareName = $strName;
                 $strComparePath = $arrTemplates[$strCompareName] . '/' . $strCompareName . '.' . $strExtension;
                 break;
             }
         }
     }
     // User selected template to compare against
     if (Input::post('from') && isset($arrTemplates[Input::post('from')])) {
         $strCompareName = Input::post('from');
         $strComparePath = $arrTemplates[$strCompareName] . '/' . $strCompareName . '.' . $strExtension;
     }
     if ($strComparePath !== null) {
         $objCompareFile = new File($strComparePath);
         // Abort if one file is missing
         if (!$objCurrentFile->exists() || !$objCompareFile->exists()) {
             throw new Contao\CoreBundle\Exception\InternalServerErrorException('The source or target file does not exist.');
         }
         $objDiff = new Diff($objCompareFile->getContentAsArray(), $objCurrentFile->getContentAsArray());
         $strDiff = $objDiff->render(new DiffRenderer(array('field' => $dc->id)));
         // Identical versions
         if ($strDiff == '') {
             $strBuffer .= '<p>' . $GLOBALS['TL_LANG']['MSC']['identicalVersions'] . '</p>';
         } else {
             $strBuffer .= $strDiff;
         }
     } else {
         $strBuffer .= '<p class="tl_info">' . $GLOBALS['TL_LANG']['tl_templates']['pleaseSelect'] . '</p>';
     }
     // Templates to compare against
     $arrComparable = array();
     $intPrefixLength = strlen($strPrefix);
     foreach ($arrTemplates as $k => $v) {
         if (substr($k, 0, $intPrefixLength) === $strPrefix) {
             $arrComparable[$k] = array('version' => $k, 'info' => $k . '.' . $strExtension);
         }
     }
     /** @var BackendTemplate|object $objTemplate */
     $objTemplate = new BackendTemplate('be_diff');
     // Template variables
     $objTemplate->staticTo = $dc->id;
     $objTemplate->versions = $arrComparable;
     $objTemplate->from = $strCompareName;
     $objTemplate->showLabel = StringUtil::specialchars($GLOBALS['TL_LANG']['MSC']['showDifferences']);
     $objTemplate->content = $strBuffer;
     $objTemplate->theme = Backend::getTheme();
     $objTemplate->base = Environment::get('base');
     $objTemplate->language = $GLOBALS['TL_LANGUAGE'];
     $objTemplate->title = StringUtil::specialchars($GLOBALS['TL_LANG']['MSC']['showDifferences']);
     $objTemplate->charset = Config::get('characterSet');
     Config::set('debugMode', false);
     throw new Contao\CoreBundle\Exception\ResponseException($objTemplate->getResponse());
 }
 /**
  * Handle the patching cycle for a extractor.
  *
  * @param string          $path          The path to patch.
  *
  * @param AuthorExtractor $extractor     The extractor to patch.
  *
  * @param array           $wantedAuthors The authors that shall be contained in the result.
  *
  * @return bool True if the patch has been collected, false otherwise.
  */
 private function patchExtractor($path, $extractor, $wantedAuthors)
 {
     if (!($this->diff && $extractor instanceof PatchingExtractor)) {
         return false;
     }
     $original = explode("\n", $extractor->getBuffer($path));
     $new = explode("\n", $extractor->getBuffer($path, $wantedAuthors));
     $diff = new \Diff($original, $new);
     $patch = $diff->render($this->diff);
     if (empty($patch)) {
         return false;
     }
     $patchFile = $path;
     foreach ($this->config->getIncludedPaths() as $prefix) {
         $prefixLength = strlen($prefix);
         if (substr($path, 0, $prefixLength) === $prefix) {
             $patchFile = substr($path, $prefixLength);
             if ($patchFile[0] == '/') {
                 $patchFile = substr($patchFile, 1);
             }
             break;
         }
     }
     /**
      *
      * diff --git a/bin/check-author.php b/bin/check-author.php
      * index 6c031df..75a3d96 100755
      * --- a/bin/check-author.php
      * +++ b/bin/check-author.php
      * @@ -12,7 +12,6 @@
      *
      */
     $this->patchSet[] = 'diff ' . $patchFile . ' ' . $patchFile . "\n" . '--- ' . $patchFile . "\n" . '+++ ' . $patchFile . "\n" . $patch;
     return true;
 }
Example #22
0
 /**
  * @Then /^final source of template "([^"]*)" should be:$/
  */
 public function finalSourceOfTemplateShouldBe($template, PyStringNode $expected)
 {
     if (null !== $this->override) {
         $this->registry->add($this->override);
     }
     $actual = preg_replace("/\r|\n/", "", $this->twig->getLoader()->getSource($template));
     $expected = preg_replace("/\r|\n/", "", $expected->getRaw());
     $actual = preg_replace('~>\\s+<~m', '><', $actual);
     $expected = preg_replace('~>\\s+<~m', '><', $expected);
     if ($expected !== $actual) {
         $actual = explode(PHP_EOL, (string) $actual);
         $expected = explode(PHP_EOL, (string) $expected);
         $diff = new \Diff($expected, $actual, array());
         $renderer = new \Diff_Renderer_Text_Unified();
         $text = $diff->render($renderer);
         throw new \Exception(sprintf("Output does not match expected template. \n\n %s", $text));
     }
 }
Example #23
0
 /**
  * @param string $actualResponse
  * @param string $filename
  * @param string $mimeType
  */
 protected function assertResponseContent($actualResponse, $filename, $mimeType)
 {
     $responseSource = $this->getExpectedResponsesFolder();
     $expectedResponse = file_get_contents(sprintf('%s/%s.%s', $responseSource, $filename, $mimeType));
     $factory = new SimpleFactory();
     $matcher = $factory->createMatcher();
     $result = $matcher->match($actualResponse, $expectedResponse);
     if (!$result) {
         $difference = $matcher->getError();
         $difference = $difference . PHP_EOL;
         $expectedResponse = explode(PHP_EOL, (string) $expectedResponse);
         $actualResponse = explode(PHP_EOL, (string) $actualResponse);
         $diff = new \Diff($expectedResponse, $actualResponse, array());
         $renderer = new \Diff_Renderer_Text_Unified();
         $difference = $difference . $diff->render($renderer);
         $this->fail($difference);
     }
 }
 /**
  * Compares two strings or string arrays, and return their differences.
  * This is a wrapper of the [phpspec/php-diff](https://packagist.org/packages/phpspec/php-diff) package.
  * @param string|array $lines1 the first string or string array to be compared. If it is a string,
  * it will be converted into a string array by breaking at newlines.
  * @param string|array $lines2 the second string or string array to be compared. If it is a string,
  * it will be converted into a string array by breaking at newlines.
  * @param string $format the output format. It must be 'inline', 'unified', 'context', 'side-by-side', or 'array'.
  * @return string|array the comparison result. An array is returned if `$format` is 'array'. For all other
  * formats, a string is returned.
  * @throws InvalidParamException if the format is invalid.
  */
 public static function diff($lines1, $lines2, $format = 'inline')
 {
     if (!is_array($lines1)) {
         $lines1 = explode("\n", $lines1);
     }
     if (!is_array($lines2)) {
         $lines2 = explode("\n", $lines2);
     }
     foreach ($lines1 as $i => $line) {
         $lines1[$i] = rtrim($line, "\r\n");
     }
     foreach ($lines2 as $i => $line) {
         $lines2[$i] = rtrim($line, "\r\n");
     }
     switch ($format) {
         case 'inline':
             $renderer = new \Diff_Renderer_Html_Inline();
             break;
         case 'array':
             $renderer = new \Diff_Renderer_Html_Array();
             break;
         case 'side-by-side':
             $renderer = new \Diff_Renderer_Html_SideBySide();
             break;
         case 'context':
             $renderer = new \Diff_Renderer_Text_Context();
             break;
         case 'unified':
             $renderer = new \Diff_Renderer_Text_Unified();
             break;
         default:
             throw new InvalidParamException("Output format must be 'inline', 'side-by-side', 'array', 'context' or 'unified'.");
     }
     $diff = new \Diff($lines1, $lines2);
     return $diff->render($renderer);
 }
Example #25
0
 /**
  * Get diff using php-diff
  *
  * @param string $fromData from file data
  * @param string $toData to file data
  * @param integer $context context lines
  * @return string diff content
  */
 private function GetPhpDiff($fromData, $toData, $context = 3)
 {
     $options = array('context' => $context);
     $diffObj = new Diff(explode("\n", $fromData), explode("\n", $toData), $options);
     $renderer = new Diff_Renderer_Text_Unified();
     return $diffObj->render($renderer);
 }
Example #26
0
 /**
  * Compare versions
  */
 public function compare()
 {
     $strBuffer = '';
     $arrVersions = array();
     $intTo = 0;
     $intFrom = 0;
     $objVersions = $this->Database->prepare("SELECT * FROM tl_version WHERE pid=? AND fromTable=? ORDER BY version DESC")->execute($this->intPid, $this->strTable);
     if ($objVersions->numRows < 2) {
         $strBuffer = '<p>There are no versions of ' . $this->strTable . '.id=' . $this->intPid . '</p>';
     } else {
         $intIndex = 0;
         $from = array();
         // Store the versions and mark the active one
         while ($objVersions->next()) {
             if ($objVersions->active) {
                 $intIndex = $objVersions->version;
             }
             $arrVersions[$objVersions->version] = $objVersions->row();
             $arrVersions[$objVersions->version]['info'] = $GLOBALS['TL_LANG']['MSC']['version'] . ' ' . $objVersions->version . ' (' . \Date::parse(\Config::get('datimFormat'), $objVersions->tstamp) . ') ' . $objVersions->username;
         }
         // To
         if (\Input::post('to') && isset($arrVersions[\Input::post('to')])) {
             $intTo = \Input::post('to');
             $to = \StringUtil::deserialize($arrVersions[\Input::post('to')]['data']);
         } elseif (\Input::get('to') && isset($arrVersions[\Input::get('to')])) {
             $intTo = \Input::get('to');
             $to = \StringUtil::deserialize($arrVersions[\Input::get('to')]['data']);
         } else {
             $intTo = $intIndex;
             $to = \StringUtil::deserialize($arrVersions[$intTo]['data']);
         }
         // From
         if (\Input::post('from') && isset($arrVersions[\Input::post('from')])) {
             $intFrom = \Input::post('from');
             $from = \StringUtil::deserialize($arrVersions[\Input::post('from')]['data']);
         } elseif (\Input::get('from') && isset($arrVersions[\Input::get('from')])) {
             $intFrom = \Input::get('from');
             $from = \StringUtil::deserialize($arrVersions[\Input::get('from')]['data']);
         } elseif ($intIndex > 1) {
             $intFrom = $intIndex - 1;
             $from = \StringUtil::deserialize($arrVersions[$intFrom]['data']);
         }
         // Only continue if both version numbers are set
         if ($intTo > 0 && $intFrom > 0) {
             \System::loadLanguageFile($this->strTable);
             $this->loadDataContainer($this->strTable);
             // Get the order fields
             $objDcaExtractor = \DcaExtractor::getInstance($this->strTable);
             $arrOrder = $objDcaExtractor->getOrderFields();
             // Find the changed fields and highlight the changes
             foreach ($to as $k => $v) {
                 if ($from[$k] != $to[$k]) {
                     if ($GLOBALS['TL_DCA'][$this->strTable]['fields'][$k]['eval']['doNotShow'] || $GLOBALS['TL_DCA'][$this->strTable]['fields'][$k]['eval']['hideInput']) {
                         continue;
                     }
                     $blnIsBinary = $GLOBALS['TL_DCA'][$this->strTable]['fields'][$k]['inputType'] == 'fileTree' || in_array($k, $arrOrder);
                     // Decrypt the values
                     if ($GLOBALS['TL_DCA'][$this->strTable]['fields'][$k]['eval']['encrypt']) {
                         $to[$k] = \Encryption::decrypt($to[$k]);
                         $from[$k] = \Encryption::decrypt($from[$k]);
                     }
                     // Convert serialized arrays into strings
                     if (is_array($tmp = \StringUtil::deserialize($to[$k])) && !is_array($to[$k])) {
                         $to[$k] = $this->implodeRecursive($tmp, $blnIsBinary);
                     }
                     if (is_array($tmp = \StringUtil::deserialize($from[$k])) && !is_array($from[$k])) {
                         $from[$k] = $this->implodeRecursive($tmp, $blnIsBinary);
                     }
                     unset($tmp);
                     // Convert binary UUIDs to their hex equivalents (see #6365)
                     if ($blnIsBinary && \Validator::isBinaryUuid($to[$k])) {
                         $to[$k] = \StringUtil::binToUuid($to[$k]);
                     }
                     if ($blnIsBinary && \Validator::isBinaryUuid($from[$k])) {
                         $to[$k] = \StringUtil::binToUuid($from[$k]);
                     }
                     // Convert date fields
                     if ($GLOBALS['TL_DCA'][$this->strTable]['fields'][$k]['eval']['rgxp'] == 'date') {
                         $to[$k] = \Date::parse(\Config::get('dateFormat'), $to[$k] ?: '');
                         $from[$k] = \Date::parse(\Config::get('dateFormat'), $from[$k] ?: '');
                     } elseif ($GLOBALS['TL_DCA'][$this->strTable]['fields'][$k]['eval']['rgxp'] == 'time') {
                         $to[$k] = \Date::parse(\Config::get('timeFormat'), $to[$k] ?: '');
                         $from[$k] = \Date::parse(\Config::get('timeFormat'), $from[$k] ?: '');
                     } elseif ($GLOBALS['TL_DCA'][$this->strTable]['fields'][$k]['eval']['rgxp'] == 'datim' || $k == 'tstamp') {
                         $to[$k] = \Date::parse(\Config::get('datimFormat'), $to[$k] ?: '');
                         $from[$k] = \Date::parse(\Config::get('datimFormat'), $from[$k] ?: '');
                     }
                     // Convert strings into arrays
                     if (!is_array($to[$k])) {
                         $to[$k] = explode("\n", $to[$k]);
                     }
                     if (!is_array($from[$k])) {
                         $from[$k] = explode("\n", $from[$k]);
                     }
                     $objDiff = new \Diff($from[$k], $to[$k]);
                     $strBuffer .= $objDiff->render(new DiffRenderer(array('field' => $GLOBALS['TL_DCA'][$this->strTable]['fields'][$k]['label'][0] ?: (isset($GLOBALS['TL_LANG']['MSC'][$k]) ? is_array($GLOBALS['TL_LANG']['MSC'][$k]) ? $GLOBALS['TL_LANG']['MSC'][$k][0] : $GLOBALS['TL_LANG']['MSC'][$k] : $k))));
                 }
             }
         }
     }
     // Identical versions
     if ($strBuffer == '') {
         $strBuffer = '<p>' . $GLOBALS['TL_LANG']['MSC']['identicalVersions'] . '</p>';
     }
     /** @var BackendTemplate|object $objTemplate */
     $objTemplate = new \BackendTemplate('be_diff');
     // Template variables
     $objTemplate->content = $strBuffer;
     $objTemplate->versions = $arrVersions;
     $objTemplate->to = $intTo;
     $objTemplate->from = $intFrom;
     $objTemplate->showLabel = \StringUtil::specialchars($GLOBALS['TL_LANG']['MSC']['showDifferences']);
     $objTemplate->theme = \Backend::getTheme();
     $objTemplate->base = \Environment::get('base');
     $objTemplate->language = $GLOBALS['TL_LANGUAGE'];
     $objTemplate->title = \StringUtil::specialchars($GLOBALS['TL_LANG']['MSC']['showDifferences']);
     $objTemplate->charset = \Config::get('characterSet');
     $objTemplate->action = ampersand(\Environment::get('request'));
     throw new ResponseException($objTemplate->getResponse());
 }
                    right: right,
                    pupupResult: true,
                    debug: true,
                    merged: function(result /*, left, right */) {
                        console.log('Merge completed with: ', result.join('\n'));
                    }
                });
            });
        </script>
    </head>
    <body>
        <div id="wrap">
            <h2>Hi!</h2>
            <p>This is an example of Xiphes <a href="https://github.com/Xiphe/jQuery-Merge-for-php-diff">jQuery-Merge-for-php-diff</a>, a client side merge tool for Chris Boultons <a href="https://github.com/chrisboulton/php-diff">PHP DIFF</a>.</p>
            <p>You can choose which version of the conflicts you would like to use by clicking on them.<br /> Once the conflicts are resolved you can click "Merge" to see a pup-up of the result.</p>
        </div>
        <?php 
echo $Diff->render($Renderer);
?>
        <script type="text/javascript">
            var left=<?php 
echo json_encode($left);
?>
;
            var right=<?php 
echo json_encode($right);
?>
;
        </script>
    </body>
</html>
Example #28
0
 /**
  * Renders diff between two sets of lines
  *
  * @param mixed $lines1
  * @param mixed $lines2
  * @return string
  */
 private function renderDiff($lines1, $lines2)
 {
     if (!is_array($lines1)) {
         $lines1 = explode("\n", $lines1);
     }
     if (!is_array($lines2)) {
         $lines2 = explode("\n", $lines2);
     }
     foreach ($lines1 as $i => $line) {
         $lines1[$i] = rtrim($line, "\r\n");
     }
     foreach ($lines2 as $i => $line) {
         $lines2[$i] = rtrim($line, "\r\n");
     }
     $renderer = new DiffRendererHtmlInline();
     $diff = new \Diff($lines1, $lines2);
     return $diff->render($renderer);
 }
 /**
  * Compare two versions of a ProjectPhaseDocument.
  *
  * @param Request $request
  * @param int $projectId
  * @param int $projectPhaseId
  * @param int $projectPhaseDocumentId
  *
  * @return Response
  */
 public function compare(Request $request, $projectId, $projectPhaseId, $projectPhaseDocumentId)
 {
     $projectPhaseDocument = ProjectPhaseDocument::where('id', '=', $projectPhaseDocumentId)->where('project_phase_id', '=', $projectPhaseId)->with(['history', 'phase', 'phase.project'])->firstOrFail();
     $old = ProjectPhaseDocument::where('id', '=', $request->input('old'))->where(function (\Illuminate\Database\Eloquent\Builder $query) use($projectPhaseDocument) {
         $query->where('parent_project_phase_document_id', '=', $projectPhaseDocument->id)->orWhere('id', '=', $projectPhaseDocument->id);
     })->firstOrFail();
     $new = ProjectPhaseDocument::where('id', '=', $request->input('new'))->where(function (\Illuminate\Database\Eloquent\Builder $query) use($projectPhaseDocument) {
         $query->where('parent_project_phase_document_id', '=', $projectPhaseDocument->id)->orWhere('id', '=', $projectPhaseDocument->id);
     })->firstOrFail();
     if (!isset($old) || !isset($new)) {
         abort(404);
     }
     $diff = new \Diff(explode("\n", $old->content), explode("\n", $new->content));
     $renderer = new \VisualAppeal\Connect\Extensions\DiffRenderer();
     $renderer->oldTitle = $old->created_at->timezone(\Sentry::getUser()->timezone)->format(\Config::get('app.format.dateTime'));
     $renderer->newTitle = $new->created_at->timezone(\Sentry::getUser()->timezone)->format(\Config::get('app.format.dateTime'));
     $render = $diff->render($renderer);
     return view('project.phase.document.compare', ['project' => $projectPhaseDocument->phase->project, 'projectPhase' => $projectPhaseDocument->phase, 'projectPhaseDocument' => $projectPhaseDocument, 'render' => $render]);
 }