Skip to content

Instantly share code, notes, and snippets.

@diwms
Created September 26, 2019 11:31
Show Gist options
  • Select an option

  • Save diwms/647662d025fcfe8d34c2c9d93f0c59d4 to your computer and use it in GitHub Desktop.

Select an option

Save diwms/647662d025fcfe8d34c2c9d93f0c59d4 to your computer and use it in GitHub Desktop.

It's useful trick in situation when you need to sort certain groups of data. Preserve chronological order of items inserted in Heap. Good use-case is php_error_log. Each log entry has own majority of error. And it's usefull to sort file using max heap.

The soulution is - override default SplPriorityQueue

<?php
class OrderedPriority extends SplPriorityQueue
{
    protected $serial = PHP_INT_MAX;

    public function insert($value, $priority)
    {
        parent::insert($value, array($priority, $this->serial--));
    }
}

function setPriority($line) {
    $start = strpos($line, 'PHP');
    $end = strpos($line, ':', $start);
    $error = substr($line, $start, $end-$start);

    switch ($error) {
        case 'PHP Fatal error':
        case 'PHP Catchable fatal error':
            return 10;
        case 'PHP Warning':
            return 8;
        case 'PHP Deprecated':
            return 7;
        case 'PHP Parse error':
            return 5;
        case 'PHP Notice':
            return 2;
        default:
            return 0;
    }
}

$log = new OrderedPriority(); // SplPriorityQueue can be here, but then we'll lose chronolocial order
$file = new SplFileObject('php_error_log');

while (!$file->eof()) {
    $line = $file->fgets();
    $log->insert($line, setPriority($line));
}

while (!$log->isEmpty()) {
    echo $log->extract() . '<br>';
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment