xref: /PHP-8.3/ext/spl/tests/heap_corruption.phpt (revision 6d805ed2)
1--TEST--
2SPL: SplHeap - heap corruption via compare exception (with top element deletion)
3--CREDITS--
4Mike Sullivan <mikesul@php.net>
5#TestFest 2009 (London)
6--FILE--
7<?php
8
9class myHeap extends SplHeap
10{
11    public $allow_compare = true;
12
13    public function compare($v1, $v2): int
14    {
15        if ($this->allow_compare == true)
16        {
17            if ($v1 > $v2)
18            {
19                return 1;
20            }
21            else if ($v1 < $v2)
22            {
23                return -1;
24            }
25            else
26            {
27                return 0;
28            }
29        }
30        else
31        {
32            throw new Exception('Compare exception');
33        }
34    }
35}
36
37$heap = new myHeap();
38$heap->insert(1);
39$heap->insert(2);
40$heap->insert(3);
41$heap->insert(4);
42
43$heap->allow_compare = false;
44
45var_dump($heap->isCorrupted());
46
47try {
48    $heap->extract();
49}
50catch (Exception $e) {
51    echo "Compare Exception: " . $e->getMessage() . PHP_EOL;
52}
53
54try {
55    $heap->top();
56}
57catch (Exception $e) {
58    echo "Corruption Exception: " . $e->getMessage() . PHP_EOL;
59}
60
61var_dump($heap->isCorrupted());
62$heap->recoverFromCorruption();
63var_dump($heap->isCorrupted());
64?>
65--EXPECT--
66bool(false)
67Compare Exception: Compare exception
68Corruption Exception: Heap is corrupted, heap properties are no longer ensured.
69bool(true)
70bool(false)
71