File: SplPriorityQueue.php

package info (click to toggle)
zendframework 1.12.9%2Bdfsg-2
  • links: PTS, VCS
  • area: main
  • in suites: jessie-kfreebsd
  • size: 133,584 kB
  • sloc: xml: 1,311,829; php: 570,173; sh: 170; makefile: 125; sql: 121
file content (499 lines) | stat: -rw-r--r-- 13,601 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
<?php
/**
 * Zend Framework
 *
 * LICENSE
 *
 * This source file is subject to the new BSD license that is bundled
 * with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://framework.zend.com/license/new-bsd
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@zend.com so we can send you a copy immediately.
 *
 * @category   Zend
 * @package    Zend_Stdlib
 * @copyright  Copyright (c) 2005-2014 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */

if (version_compare(PHP_VERSION, '5.3.0', '<')) {
    /**
     * SplPriorityQueue 
     *
     * PHP 5.2.X userland implementation of PHP's SplPriorityQueue
     */
    class SplPriorityQueue implements Iterator , Countable 
    {
        /**
         * Extract data only
         */
        const EXTR_DATA = 0x00000001;

        /**
         * Extract priority only
         */
        const EXTR_PRIORITY = 0x00000002;

        /**
         * Extract an array of ('data' => $value, 'priority' => $priority)
         */
        const EXTR_BOTH = 0x00000003;

        /**
         * Count of items in the queue
         * @var int
         */
        protected $count = 0;

        /**
         * Flag indicating what should be returned when iterating or extracting
         * @var int
         */
        protected $extractFlags = self::EXTR_DATA;

        /**
         * @var bool|array
         */
        protected $preparedQueue = false;

        /**
         * All items in the queue
         * @var array
         */
        protected $queue = array();

        /**
         * Constructor
         * 
         * Creates a new, empty queue
         * 
         * @return void
         */
        public function __construct()
        {
        }

        /**
         * Compare two priorities
         *
         * Returns positive integer if $priority1 is greater than $priority2, 0 
         * if equal, negative otherwise.
         *
         * Unused internally, and only included in order to retain the same 
         * interface as PHP's SplPriorityQueue.
         *
         * @param  mixed $priority1
         * @param  mixed $priority2
         * @return int
         */
        public function compare($priority1, $priority2)
        {
            if ($priority1 > $priority2) {
                return 1;
            }
            if ($priority1 == $priority2) {
                return 0;
            }

            return -1;
        }

        /**
         * Countable: return number of items composed in the queue
         * 
         * @return int
         */
        public function count()
        {
            return $this->count;
        }

        /**
         * Iterator: return current item
         *
         * @return mixed
         */
        public function current()
        {
            if (!$this->preparedQueue) {
                $this->rewind();
            }
            if (!$this->count) {
                throw new OutOfBoundsException('Cannot iterate SplPriorityQueue; no elements present');
            }

if (!is_array($this->preparedQueue)) {
    throw new DomainException(sprintf(
        "Queue was prepared, but is empty?\n    PreparedQueue: %s\n    Internal Queue: %s\n",
        var_export($this->preparedQueue, 1),
        var_export($this->queue, 1)
    ));
}

            $return      = array_shift($this->preparedQueue);
            $priority    = $return['priority'];
            $priorityKey = $return['priorityKey'];
            $key         = $return['key'];
            unset($return['key']);
            unset($return['priorityKey']);
            unset($this->queue[$priorityKey][$key]);

            switch ($this->extractFlags) {
                case self::EXTR_DATA:
                    return $return['data'];
                case self::EXTR_PRIORITY:
                    return $return['priority'];
                case self::EXTR_BOTH:
                default:
                    return $return;
            };
        }

        /**
         * Extract a node from top of the heap and sift up
         *
         * Returns either the value, the priority, or both, depending on the extract flag.
         *
         * @return mixed;
         */
        public function extract()
        {
            if (!$this->count) {
                return null;
            }

            if (!$this->preparedQueue) {
                $this->prepareQueue();
            }

            if (empty($this->preparedQueue)) {
                return null;
            }

            $return      = array_shift($this->preparedQueue);
            $priority    = $return['priority'];
            $priorityKey = $return['priorityKey'];
            $key         = $return['key'];
            unset($return['key']);
            unset($return['priorityKey']);
            unset($this->queue[$priorityKey][$key]);
            $this->count--;

            switch ($this->extractFlags) {
                case self::EXTR_DATA:
                    return $return['data'];
                case self::EXTR_PRIORITY:
                    return $return['priority'];
                case self::EXTR_BOTH:
                default:
                    return $return;
            };
        }

        /**
         * Insert a value into the heap, at the specified priority
         *
         * @param  mixed $value
         * @param  mixed $priority
         * @return void
         */
        public function insert($value, $priority)
        {
            if (!is_scalar($priority)) {
                $priority = serialize($priority);
            }
            if (!isset($this->queue[$priority])) {
                $this->queue[$priority] = array();
            }
            $this->queue[$priority][] = $value;
            $this->count++;
            $this->preparedQueue = false;
        }

        /**
         * Is the queue currently empty?
         *
         * @return bool
         */
        public function isEmpty()
        {
            return (0 == $this->count);
        }

        /**
         * Iterator: return current key
         *
         * @return mixed Usually an int or string
         */
        public function key()
        {
            return $this->count;
        }

        /**
         * Iterator: Move pointer forward
         *
         * @return void
         */
        public function next()
        {
            $this->count--;
        }

        /**
         * Recover from corrupted state and allow further actions on the queue
         *
         * Unimplemented, and only included in order to retain the same interface as PHP's 
         * SplPriorityQueue.
         *
         * @return void
         */
        public function recoverFromCorruption()
        {
        }

        /**
         * Iterator: Move pointer to first item
         *
         * @return void
         */
        public function rewind()
        {
            if (!$this->preparedQueue) {
                $this->prepareQueue();
            }
        }

        /**
         * Set the extract flags
         * 
         * Defines what is extracted by SplPriorityQueue::current(), 
         * SplPriorityQueue::top() and SplPriorityQueue::extract().
         * 
         * - SplPriorityQueue::EXTR_DATA (0x00000001): Extract the data
         * - SplPriorityQueue::EXTR_PRIORITY (0x00000002): Extract the priority
         * - SplPriorityQueue::EXTR_BOTH (0x00000003): Extract an array containing both
         *
         * The default mode is SplPriorityQueue::EXTR_DATA.
         *
         * @param  int $flags
         * @return void
         */
        public function setExtractFlags($flags)
        {
            $expected = array(
                self::EXTR_DATA => true,
                self::EXTR_PRIORITY => true,
                self::EXTR_BOTH => true,
            );
            if (!isset($expected[$flags])) {
                throw new InvalidArgumentException(sprintf('Expected an EXTR_* flag; received %s', $flags));
            }
            $this->extractFlags = $flags;
        }

        /**
         * Return the value or priority (or both) of the top node, depending on 
         * the extract flag
         *
         * @return mixed
         */
        public function top()
        {
            $this->sort();
            $keys = array_keys($this->queue);
            $key  = array_shift($keys);
            if (preg_match('/^(a|O):/', $key)) {
                $key = unserialize($key);
            }

            if ($this->extractFlags == self::EXTR_PRIORITY) {
                return $key;
            }

            if ($this->extractFlags == self::EXTR_DATA) {
                return $this->queue[$key][0];
            }

            return array(
                'data'     => $this->queue[$key][0],
                'priority' => $key,
            );
        }

        /**
         * Iterator: is the current position valid for the queue
         *
         * @return bool
         */
        public function valid()
        {
            return (bool) $this->count;
        }

        /**
         * Sort the queue
         * 
         * @return void
         */
        protected function sort()
        {
            krsort($this->queue);
        }

        /**
         * Prepare the queue for iteration and/or extraction
         * 
         * @return void
         */
        protected function prepareQueue()
        {
            $this->sort();
            $count = $this->count;
            $queue = array();
            foreach ($this->queue as $priority => $values) {
                $priorityKey = $priority;
                if (preg_match('/^(a|O):/', $priority)) {
                    $priority = unserialize($priority);
                }
                foreach ($values as $key => $value) {
                    $queue[$count] = array(
                        'data'        => $value,
                        'priority'    => $priority,
                        'priorityKey' => $priorityKey,
                        'key'         => $key,
                    );
                    $count--;
                }
            }
            $this->preparedQueue = $queue;
        }
    }
}

/**
 * Serializable version of SplPriorityQueue
 *
 * Also, provides predictable heap order for datums added with the same priority
 * (i.e., they will be emitted in the same order they are enqueued).
 *
 * @category   Zend
 * @package    Zend_Stdlib
 * @copyright  Copyright (c) 2005-2014 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
class Zend_Stdlib_SplPriorityQueue extends SplPriorityQueue implements Serializable
{
    /**
     * @var int Seed used to ensure queue order for items of the same priority
     */
    protected $serial = PHP_INT_MAX;

    /**
     * @var bool
     */
    protected $isPhp53;

    /**
     * Constructor
     * 
     * @return void
     */
    public function __construct()
    {
        $this->isPhp53 = version_compare(PHP_VERSION, '5.3', '>=');
    }

    /**
     * Insert a value with a given priority
     *
     * Utilizes {@var $serial} to ensure that values of equal priority are 
     * emitted in the same order in which they are inserted.
     * 
     * @param  mixed $datum 
     * @param  mixed $priority 
     * @return void
     */
    public function insert($datum, $priority)
    {
        // If using the native PHP SplPriorityQueue implementation, we need to
        // hack around it to ensure that items registered at the same priority
        // return in the order registered. In the userland version, this is not
        // necessary.
        if ($this->isPhp53) {
            if (!is_array($priority)) {
                $priority = array($priority, $this->serial--);
            }
        }
        parent::insert($datum, $priority);
    }

    /**
     * Serialize to an array
     *
     * Array will be priority => data pairs
     * 
     * @return array
     */
    public function toArray()
    {
        $this->setExtractFlags(self::EXTR_BOTH);
        $array = array();
        while ($this->valid()) {
            $array[] = $this->current();
            $this->next();
        }
        $this->setExtractFlags(self::EXTR_DATA);

        // Iterating through a priority queue removes items
        foreach ($array as $item) {
            $this->insert($item['data'], $item['priority']);
        }

        // Return only the data
        $return = array();
        foreach ($array as $item) {
            $return[] = $item['data'];
        }

        return $return;
    }

    /**
     * Serialize
     * 
     * @return string
     */
    public function serialize()
    {
        $data = array();
        $this->setExtractFlags(self::EXTR_BOTH);
        while ($this->valid()) {
            $data[] = $this->current();
            $this->next();
        }
        $this->setExtractFlags(self::EXTR_DATA);

        // Iterating through a priority queue removes items
        foreach ($data as $item) {
            $this->insert($item['data'], $item['priority']);
        }

        return serialize($data);
    }

    /**
     * Deserialize
     * 
     * @param  string $data
     * @return void
     */
    public function unserialize($data)
    {
        foreach (unserialize($data) as $item) {
            $this->insert($item['data'], $item['priority']);
        }
    }
}