Inheritance: extends CI_Model
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());
 }
 /**
  * @param Diff $diff A Diff object.
  *
  * @return array[] List of associative arrays, each describing a difference.
  */
 public function format($diff)
 {
     $oldline = 1;
     $newline = 1;
     $retval = [];
     foreach ($diff->getEdits() as $edit) {
         switch ($edit->getType()) {
             case 'add':
                 foreach ($edit->getClosing() as $line) {
                     $retval[] = ['action' => 'add', 'new' => $line, 'newline' => $newline++];
                 }
                 break;
             case 'delete':
                 foreach ($edit->getOrig() as $line) {
                     $retval[] = ['action' => 'delete', 'old' => $line, 'oldline' => $oldline++];
                 }
                 break;
             case 'change':
                 foreach ($edit->getOrig() as $key => $line) {
                     $retval[] = ['action' => 'change', 'old' => $line, 'new' => $edit->getClosing($key), 'oldline' => $oldline++, 'newline' => $newline++];
                 }
                 break;
             case 'copy':
                 $oldline += count($edit->getOrig());
                 $newline += count($edit->getOrig());
         }
     }
     return $retval;
 }
Example #3
0
 public function saveTextRevision($moduleId, $moduleContentTypeId, $moduleContentId, $oldText, $newText, $textfieldIndex = 0, $revision = 0)
 {
     global $dbi, $login, $settings;
     if (!$settings->enableRevisioning) {
         return;
     }
     // Get latest revision number and increment
     $maxRevision = 0;
     if (empty($revision)) {
         $result = $dbi->query("SELECT MAX(revision) FROM " . revisionTableName . " WHERE moduleId=" . $dbi->quote($moduleId) . " AND moduleContentTypeId=" . $dbi->quote($moduleContentTypeId) . " AND moduleContentId=" . $dbi->quote($moduleContentId));
         if ($result->rows()) {
             list($maxRevision) = $result->fetchrow_array();
             $maxRevision++;
         }
     } else {
         $maxRevision = $revision;
     }
     // Parse text strings
     $newText = parseString($newText);
     $oldText = parseString($oldText);
     // Calculate diff
     $diff = new Diff();
     $result = $diff->stringDiff($newText, $oldText, " ");
     $changes = $diff->sequentialChanges($result);
     if (sizeof($changes) > 0) {
         $serializedChanges = serialize($changes);
         // Insert diff
         $dbi->query("INSERT INTO " . revisionTableName . "(moduleId,moduleContentTypeId,moduleContentId,textfieldIndex,diff,revision,userId,timestamp) VALUES(" . $dbi->quote($moduleId) . "," . $dbi->quote($moduleContentTypeId) . "," . $dbi->quote($moduleContentId) . "," . $dbi->quote($textfieldIndex) . "," . $dbi->quote($serializedChanges) . "," . $dbi->quote($maxRevision) . "," . $dbi->quote($login->id) . ",NOW())");
     }
     return $maxRevision;
 }
Example #4
0
 /**
  * @param Diff $diff
  * @param array $lines
  */
 private function parseFileDiff(Diff $diff, array $lines)
 {
     $chunks = array();
     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)) {
             $chunk = new Chunk($match['start'], isset($match['startrange']) ? max(1, $match['startrange']) : 1, $match['end'], isset($match['endrange']) ? max(1, $match['endrange']) : 1);
             $chunks[] = $chunk;
             $diffLines = array();
             continue;
         }
         if (preg_match('/^(?P<type>[+ -])?(?P<line>.*)/', $line, $match)) {
             $type = Line::UNCHANGED;
             if ($match['type'] == '+') {
                 $type = Line::ADDED;
             } elseif ($match['type'] == '-') {
                 $type = Line::REMOVED;
             }
             $diffLines[] = new Line($type, $match['line']);
             if (isset($chunk)) {
                 $chunk->setLines($diffLines);
             }
         }
     }
     $diff->setChunks($chunks);
 }
Example #5
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 #7
0
 function test_format()
 {
     $diff = new Diff(DIFF_SPACE);
     $one = 'a b c d e f g';
     $two = 'a c d e t t f';
     $res = $diff->compare($one, $two);
     $out = $diff->format($res);
     $expected = array(array('', 'a'), array('-', 'b'), array('', 'c'), array('', 'd'), array('', 'e'), array('+', 't'), array('+', 't'), array('', 'f'), array('-', 'g'));
     $this->assertEquals($out, $expected);
 }
Example #8
0
 function paintDiff($stringA, $stringB)
 {
     $diff = new Diff(explode("\n", $stringA), explode("\n", $stringB));
     if ($diff->isEmpty()) {
         echo '<p>Erreur diff : bizarre, aucune différence d\'aprés la difflib...</p>';
     } else {
         $fmt = new HtmlUnifiedDiffFormatter();
         echo $fmt->format($diff);
     }
 }
 public function testPrintAsJson_usingSlimVersion_shouldReturnSimpleJson()
 {
     $object = 'EmpresaConf';
     $property = 'descricao';
     $value1 = 'Hosanna';
     $value2 = 'Hosanna Tecnologia';
     $diff = new Diff($object, $property, $value1, $value2);
     $expectedJson = sprintf('{"%s%s%s":["%s","%s"]}', $object, Diff::SEPARATOR, $property, $value1, $value2);
     $this->assertEquals($expectedJson, $diff->printAsJson(true));
 }
Example #10
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 #11
0
 protected function showDiff($str1, $str2)
 {
     $diff = new Diff(explode("\n", $str1), explode("\n", $str2));
     if ($diff->isEmpty()) {
         $this->fail("No difference ???");
     } else {
         $fmt = new UnifiedDiffFormatter();
         $this->fail($fmt->format($diff));
     }
 }
 function paintDiff($stringA, $stringB)
 {
     $diff = new Diff(explode("\n", $stringA), explode("\n", $stringB));
     if ($diff->isEmpty()) {
         $this->_response->addContent('<p>Erreur diff : bizarre, aucune différence d\'aprés la difflib...</p>');
     } else {
         $fmt = new UnifiedDiffFormatter();
         $this->_response->addContent($fmt->format($diff));
     }
 }
Example #13
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 #14
0
function diff($path, $action, $title, $content)
{
    $Head = '<meta name="robots" content="noindex, nofollow" />';
    $content['PageNav']->Active("Page History");
    if (is_numeric($action[1])) {
        $pageQuery = mysql_query("SELECT `PageID`,`AccountID`,`EditTime`,`Name`,`Description`,`Title`,`Content` FROM `Wiki_Edits` WHERE `ID`='{$action['1']}' and `Archived` = 0");
        list($PageID, $AccountID, $PageEditTime, $PageName, $PageDescription, $PageTitle, $pageContent) = mysql_fetch_array($pageQuery);
        $previousQuery = mysql_query("Select `ID`, `Content` from `Wiki_Edits` where `ID` < '{$action['1']}' and `PageID`='{$PageID}' and `Archived` = 0 order by `ID` desc limit 1");
        list($previousID, $previousContent) = mysql_fetch_array($previousQuery);
        $nextQuery = mysql_query("Select `ID` from `Wiki_Edits` where `ID` > '{$action['1']}' and `PageID`='{$PageID}' and `Archived` = 0 order by `ID` limit 1");
        list($nextID) = mysql_fetch_array($nextQuery);
        if (!empty($previousID)) {
            $previousPath = FormatPath("/{$path}/?diff/{$previousID}");
            $content['Title'] = "<a href='{$previousPath}' title='Previous Revision'>⟨</a> ";
        }
        $content['Title'] .= FishFormat($PageTitle);
        if (!empty($nextID)) {
            $nextPath = FormatPath("/{$path}/?diff/{$nextID}");
            $content['Title'] .= " <a href='{$nextPath}' title='Next Revision'>⟩</a>";
        }
        $content['Body'] .= <<<JavaScript
        
        <script>
            \$(document).ready(function ()
            {
                \$('body').on('keydown', function(event)
                {
                    event.stopImmediatePropagation()
                    
                    if(event.keyCode == 37) // Previous
                        location.href = '{$previousPath}';
                    else if(event.keyCode == 39) // Next
                        location.href = '{$nextPath}';
                });
            });
        </script>
JavaScript;
        $old = explode("\n", html_entity_decode($previousContent, ENT_QUOTES));
        $new = explode("\n", html_entity_decode($pageContent, ENT_QUOTES));
        // Initialize the diff class
        $diff = new Diff($old, $new);
        require_once dirname(__FILE__) . '/../libraries/Diff/Renderer/Html/SideBySide.php';
        $renderer = new Diff_Renderer_Html_SideBySide();
        $content['Body'] .= $diff->Render($renderer);
        date_default_timezone_set('America/New_York');
        $PageEditTime = formatTime($PageEditTime);
        $content['Footer'] = "This page is an old revision made by <b><a href='/names?id={$AccountID}'>{$PageName}</a></b> on {$PageEditTime}.";
        if ($PageDescription) {
            $content['Footer'] .= "<br />'{$PageDescription}'";
        }
    }
    return array($title, $content);
}
Example #15
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());
 }
/**
 * function plugin : show a diff between two string
 *
 * @param jTpl $tpl template engine
 * @param string $str1 the first string
 * @param string $str2 the second string
 * @param array $options contains : 'nodiffmsg' message when no diff found ; 'version1' ; 'version2' to be compared ; 'type' of display
 */
function jtpl_function_html_diff($tpl, $str1, $str2, $options = array())
{
    $nodiffmsg = 'Pas de différence';
    $version1 = '';
    $version2 = '';
    $type = 'unifieddiff';
    $supported_output_format = array('unifieddiff', 'inlinetable', 'sidebyside');
    if (!is_array($options)) {
        $nodiffmsg = $options;
    } else {
        if (array_key_exists('nodiffmsg', $options)) {
            $nodiffmsg = $options['nodiffmsg'];
        }
        if (array_key_exists('version1', $options)) {
            $version1 = $options['version1'];
        }
        if (array_key_exists('version2', $options)) {
            $version2 = $options['version2'];
        }
        //the type of ouput format of the diff
        //1) type option exists ?
        if (array_key_exists('type', $options)) {
            $type = $options['type'];
        }
        //2) is it a supported type ouput format ?
        if (!in_array($type, $supported_output_format)) {
            $type = 'unifieddiff';
        }
    }
    $diff = new Diff(explode("\n", $str1), explode("\n", $str2));
    if ($diff->isEmpty()) {
        echo $nodiffmsg;
    } else {
        switch ($type) {
            case 'unifieddiff':
                $fmt = new HtmlUnifiedDiffFormatter();
                break;
            case 'inlinetable':
                require_once LIB_PATH . 'diff/difftableformatter.php';
                $fmt = new HtmlInlineTableDiffFormatter($version1, $version2);
                break;
            case 'sidebyside':
                require_once LIB_PATH . 'diff/difftableformatter.php';
                $fmt = new HtmlTableDiffFormatter($version1, $version2);
                break;
        }
        echo $fmt->format($diff);
    }
}
 private function parseFileDiff(Diff $diff, array $lines)
 {
     $chunks = array();
     while (count($lines)) {
         while (!preg_match('(^@@\\s+-(?P<start>\\d+)(?:,\\s*(?P<startrange>\\d+))?\\s+\\+(?P<end>\\d+)(?:,\\s*(?P<endrange>\\d+))?\\s+@@)', $last = array_shift($lines), $match)) {
             if ($last === null) {
                 break 2;
             }
         }
         $chunk = new Chunk($match['start'], isset($match['startrange']) ? max(1, $match['startrange']) : 1, $match['end'], isset($match['endrange']) ? max(1, $match['endrange']) : 1);
         $diffLines = array();
         $last = null;
         while (count($lines) && (preg_match('(^(?P<type>[+ -])(?P<line>.*))', $last = array_shift($lines), $match) || strpos($last, '\\ No newline at end of file') === 0)) {
             if (count($match)) {
                 $type = Line::UNCHANGED;
                 if ($match['type'] == '+') {
                     $type = Line::ADDED;
                 } else {
                     if ($match['type'] == '-') {
                         $type = Line::REMOVED;
                     }
                 }
                 $diffLines[] = new Line($type, $match['line']);
             }
         }
         $chunk->setLines($diffLines);
         $chunks[] = $chunk;
         if ($last !== null) {
             array_unshift($lines, $last);
         }
     }
     $diff->setChunks($chunks);
 }
Example #18
0
 /**
  * Wrapper function to get differences
  *
  * @return	string	Diff data
  */
 function get_diff($str1, $str2, $type = 'side_by_side')
 {
     $type = isset($this->diff_types[$type]) ? $this->diff_types[$type] : current($this->diff_types);
     #		require_once $this->module_path.'Diff.php';
     // Options for generating the diff
     $options = [];
     //Prepare content
     $str1 = explode("\n", $str1);
     $str2 = explode("\n", $str2);
     // Initialize the diff class
     $diff = new Diff($str1, $str2, $options);
     #		require_once $this->module_path.'Diff/Renderer/Html/'.$type.'.php';
     $diff_type_class = 'Diff_Renderer_Html_' . $type;
     $renderer = new $diff_type_class();
     return $this->custom_style() . $diff->Render($renderer);
 }
Example #19
0
 /**
  * @param string[] $linesBefore
  * @param string[] $linesAfter
  */
 public function __construct($linesBefore, $linesAfter)
 {
     list($wordsBefore, $wordsBeforeStripped) = $this->split($linesBefore);
     list($wordsAfter, $wordsAfterStripped) = $this->split($linesAfter);
     try {
         parent::__construct($wordsBeforeStripped, $wordsAfterStripped);
     } catch (ComplexityException $ex) {
         // Too hard to diff, just show whole paragraph(s) as changed
         $this->edits = [new DiffOpChange($linesBefore, $linesAfter)];
     }
     $xi = $yi = 0;
     $editCount = count($this->edits);
     for ($i = 0; $i < $editCount; $i++) {
         $orig =& $this->edits[$i]->orig;
         if (is_array($orig)) {
             $orig = array_slice($wordsBefore, $xi, count($orig));
             $xi += count($orig);
         }
         $closing =& $this->edits[$i]->closing;
         if (is_array($closing)) {
             $closing = array_slice($wordsAfter, $yi, count($closing));
             $yi += count($closing);
         }
     }
 }
Example #20
0
 public function __construct($productName)
 {
     self::$rootPath = File::normalize(dirname(__FILE__));
     //        FILE::delete(self::$rootPath."/".$productName);
     self::loadConfig(self::$rootPath . '/config' . $_SESSION['o'] . '.php');
     $product = self::getConfig('product');
     $this->proInfo = $product[$productName];
     //        $this->analyze = new Analyze();
 }
Example #21
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);
 }
Example #22
0
function vote()
{
    if (isset($_GET['dir']) && isset($_GET['did'])) {
        $d = new Diff();
        if ($d->populateDiff($_GET['did'])) {
            if ($_GET['dir'] == 1 || $_GET['dir'] == -1) {
                $db = new DB();
                $db->query("SELECT * FROM `rating` WHERE `did` = '{$_GET['did']}' AND `uid` = '{$_SESSION['uid']}';");
                if ($db->numRows() == 0) {
                    $db->query("INSERT INTO `rating` (`did`, `uid`, `rating`) VALUES ('{$_GET['did']}', '{$_SESSION['uid']}', '{$_GET['dir']}');");
                } else {
                    $db->query("UPDATE `rating` SET `rating` = '{$_GET['dir']}' WHERE `did` = '{$_GET['did']}' AND `uid` = '{$_SESSION['uid']}';");
                }
                $db->close();
            }
        }
    }
}
Example #23
0
/**
 * Afficher le diff d'un champ texte generique
 *
 * @param string $champ
 * @param string $old
 * @param string $new
 * @param string $format
 *   apercu, diff ou complet
 * @return string
 */
function afficher_diff_champ_dist($champ, $old, $new, $format = 'diff')
{
    // ne pas se compliquer la vie !
    if ($old == $new) {
        $out = $format != 'complet' ? '' : $new;
    } else {
        if ($f = charger_fonction($champ, 'afficher_diff', true)) {
            return $f($champ, $old, $new, $format);
        }
        $diff = new Diff(new DiffTexte());
        $n = preparer_diff($new);
        $o = preparer_diff($old);
        $out = afficher_diff($diff->comparer($n, $o));
        if ($format == 'diff' or $format == 'apercu') {
            $out = afficher_para_modifies($out, $format == 'apercu');
        }
    }
    return $out;
}
 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 #25
0
 public function process_ajax()
 {
     $a = __Request::get('a');
     $b = __Request::get('b');
     $it = org_glizy_objectFactory::createModelIterator('org.glizycms.core.models.Content');
     $it->where("document_detail_id", $a)->allStatuses();
     $ar_a = $it->first();
     $it = org_glizy_objectFactory::createModelIterator('org.glizycms.core.models.Content');
     $it->where("document_detail_id", $b)->allStatuses();
     $ar_b = $it->first();
     $a = explode("\n", str_replace("<\\/p>", "<\\/p>\n", json_encode(json_decode($ar_a->document_detail_object), JSON_PRETTY_PRINT)));
     $b = explode("\n", str_replace("<\\/p>", "<\\/p>\n", json_encode(json_decode($ar_b->document_detail_object), JSON_PRETTY_PRINT)));
     glz_importLib('Diff/Diff.php');
     glz_importLib('Diff/Diff/Renderer/Html/SideBySide.php');
     // Options for generating the diff
     $options = array();
     $diff = new Diff($a, $b, $options);
     $renderer = new Diff_Renderer_Html_SideBySide();
     $result = $diff->Render($renderer);
     return array('html' => $result);
 }
 /**
  * Compile a list of changes to the current page, excluding non-published and explicitly secured versions.
  *
  * @param int $highestVersion Top version number to consider.
  * @param int $limit Limit to the amount of items returned.
  *
  * @returns ArrayList List of cleaned records.
  */
 public function getDiffList($highestVersion = null, $limit = 100)
 {
     // This can leak secured content if it was protected via inherited setting.
     // For now the users will need to be aware about this shortcoming.
     $offset = $highestVersion ? "AND \"SiteTree_versions\".\"Version\"<='" . (int) $highestVersion . "'" : '';
     // Get just enough elements for diffing. We need one more than desired to have something to compare to.
     $qLimit = (int) $limit + 1;
     $versions = $this->owner->allVersions("\"WasPublished\"='1' AND \"CanViewType\" IN ('Anyone', 'Inherit') {$offset}", "\"LastEdited\" DESC", $qLimit);
     // Process the list to add the comparisons.
     $changeList = new ArrayList();
     $previous = null;
     $count = 0;
     foreach ($versions as $version) {
         $changed = false;
         // Check if we have something to compare with.
         if (isset($previous)) {
             // Produce the diff fields for use in the template.
             if ($version->Title != $previous->Title) {
                 $diffTitle = Diff::compareHTML($version->Title, $previous->Title);
                 $version->DiffTitle = new HTMLText();
                 $version->DiffTitle->setValue(sprintf('<div><em>%s</em> ' . $diffTitle . '</div>', _t('RSSHistory.TITLECHANGED', 'Title has changed:')));
                 $changed = true;
             }
             if ($version->Content != $previous->Content) {
                 $diffContent = Diff::compareHTML($version->Content, $previous->Content);
                 $version->DiffContent = new HTMLText();
                 $version->DiffContent->setValue('<div>' . $diffContent . '</div>');
                 $changed = true;
             }
             // Copy the link so it can be cached by SS_Cache.
             $version->GeneratedLink = $version->AbsoluteLink();
         }
         // Omit the versions that haven't been visibly changed (only takes the above fields into consideration).
         if ($changed) {
             $changeList->push($version);
             $count++;
         }
         // Store the last version for comparison.
         $previous = $version;
     }
     // Make sure enough diff items have been generated to satisfy the $limit. If we ran out, add the final,
     // non-diffed item (the initial version). This will also work for a single-diff request: if we are requesting
     // a diff on the initial version we will just get that version, verbatim.
     if ($previous && $versions->count() < $qLimit) {
         $first = clone $previous;
         $first->DiffContent = new HTMLText();
         $first->DiffContent->setValue('<div>' . $first->Content . '</div>');
         // Copy the link so it can be cached by SS_Cache.
         $first->GeneratedLink = $first->AbsoluteLink();
         $changeList->push($first);
     }
     return $changeList;
 }
Example #27
0
 function update(Airport $airport)
 {
     Diff::compare($airport, Input::all(), function ($key, $value, $model) {
         $change = new AirportChange();
         $change->airport_id = $model->id;
         $change->user_id = Auth::id();
         $change->key = $key;
         $change->value = $value;
         $change->save();
     });
     Messages::success('Thank you for your submission. We will be evaluating your feedback soon.');
     return Redirect::route('airport.show', $airport->icao);
 }
Example #28
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());
 }
 public function testMake()
 {
     // Null case.
     $patches = $this->p->make("", "");
     $this->assertEquals("", $this->p->toText($patches));
     $text1 = "The quick brown fox jumps over the lazy dog.";
     $text2 = "That quick brown fox jumped over a lazy dog.";
     // Text2 + Text1 inputs.
     // The second patch must be "-21,17 +21,18", not "-22,17 +21,18" due to rolling context.
     $expected = "@@ -1,8 +1,7 @@\n Th\n-at\n+e\n  qui\n@@ -21,17 +21,18 @@\n jump\n-ed\n+s\n  over \n-a\n+the\n  laz\n";
     $patches = $this->p->make($text2, $text1);
     $this->assertEquals($expected, $this->p->toText($patches));
     // Text1 + Text2 inputs.
     $expected = "@@ -1,11 +1,12 @@\n Th\n-e\n+at\n  quick b\n@@ -22,18 +22,17 @@\n jump\n-s\n+ed\n  over \n-the\n+a\n  laz\n";
     $patches = $this->p->make($text1, $text2);
     $this->assertEquals($expected, $this->p->toText($patches));
     // Diff input.
     $diffs = $this->d->main($text1, $text2, false)->getChanges();
     $patches = $this->p->make($diffs);
     $this->assertEquals($expected, $this->p->toText($patches));
     // Text1+Diff inputs.
     $patches = $this->p->make($text1, $diffs);
     $this->assertEquals($expected, $this->p->toText($patches));
     // Text1+Text2+Diff inputs (deprecated).
     $patches = $this->p->make($text1, $text2, $diffs);
     $this->assertEquals($expected, $this->p->toText($patches));
     // Character encoding.
     $patches = $this->p->make("`1234567890-=[]\\;',./", "~!@#\$%^&*()_+{}|:\"<>?");
     $this->assertEquals("@@ -1,21 +1,21 @@\n-%601234567890-=%5B%5D%5C;',./\n+~!@#\$%25%5E&*()_+%7B%7D%7C:%22%3C%3E?\n", $this->p->toText($patches));
     // Character decoding.
     $diffs = array(array(Diff::DELETE, "`1234567890-=[]\\;',./"), array(Diff::INSERT, "~!@#\$%^&*()_+{}|:\"<>?"));
     $patches = $this->p->fromText("@@ -1,21 +1,21 @@\n-%601234567890-=%5B%5D%5C;',./\n+~!@#\$%25%5E&*()_+%7B%7D%7C:%22%3C%3E?\n");
     $this->assertEquals($diffs, $patches[0]->getChanges());
     // Long string with repeats.
     $text1 = "";
     for ($i = 0; $i < 100; $i++) {
         $text1 .= "abcdef";
     }
     $text2 = $text1 . "123";
     $expected = "@@ -573,28 +573,31 @@\n cdefabcdefabcdefabcdefabcdef\n+123\n";
     $patches = $this->p->make($text1, $text2);
     $this->assertEquals($expected, $this->p->toText($patches));
     // Test null inputs.
     try {
         $this->p->make(null, null);
         $this->fail();
     } catch (\InvalidArgumentException $e) {
     }
 }
 public function testDiffMainMemoryLeaks()
 {
     $text1 = file_get_contents(__DIR__ . '/fixtures/S_performance1.txt');
     $text2 = file_get_contents(__DIR__ . '/fixtures/S_performance2.txt');
     $n = 20;
     // Warm up
     $diff = new Diff();
     $diff->setTimeout(0);
     $diff->main($text1, $text2);
     unset($diff);
     $timeStart = microtime(1);
     $memoryStart = memory_get_usage();
     for ($i = 0; $i < $n; $i++) {
         $diff = new Diff();
         $diff->setTimeout(0);
         $diff->main($text1, $text2);
         unset($diff);
     }
     $timeElapsed = microtime(1) - $timeStart;
     $memoryUsage = (memory_get_usage() - $memoryStart) / 1024 / 1024;
     $this->assertLessThan(0.001, $memoryUsage);
     echo 'Elapsed time: ' . round($timeElapsed, 3) . PHP_EOL;
     echo 'Memory usage: ' . round($memoryUsage, 10) . PHP_EOL;
 }