|
| 1 | +<?php |
| 2 | + |
| 3 | +use PHPUnit\Framework\TestCase; |
| 4 | + |
| 5 | +class TestIterableToArray extends TestCase |
| 6 | +{ |
| 7 | + |
| 8 | + public function testFunctionExists() |
| 9 | + { |
| 10 | + $this->assertTrue(function_exists('iterable_to_array')); |
| 11 | + } |
| 12 | + |
| 13 | + public function testIteratorToArray() |
| 14 | + { |
| 15 | + $iterator = new ArrayIterator(array('foo', 'bar')); |
| 16 | + $this->assertEquals(array('foo', 'bar'), iterable_to_array($iterator)); |
| 17 | + } |
| 18 | + |
| 19 | + public function testArrayToArray() |
| 20 | + { |
| 21 | + $array = array('foo', 'bar'); |
| 22 | + $this->assertEquals(array('foo', 'bar'), iterable_to_array($array)); |
| 23 | + } |
| 24 | + |
| 25 | + public function testScalarToArray() |
| 26 | + { |
| 27 | + $scalar = 'foobar'; |
| 28 | + $this->assertTrue($this->triggersError($scalar)); |
| 29 | + } |
| 30 | + |
| 31 | + public function testObjectToArray() |
| 32 | + { |
| 33 | + $object = new stdClass(); |
| 34 | + $this->assertTrue($this->triggersError($object)); |
| 35 | + } |
| 36 | + |
| 37 | + public function testResourceToArray() |
| 38 | + { |
| 39 | + $resource = fopen('php://temp', 'rb'); |
| 40 | + $this->assertTrue($this->triggersError($resource)); |
| 41 | + } |
| 42 | + |
| 43 | + private function triggersError($input) |
| 44 | + { |
| 45 | + return version_compare(PHP_VERSION, '7.0.0') >= 0 ? $this->triggersErrorPHP7($input) : $this->triggersErrorPHP5($input); |
| 46 | + } |
| 47 | + |
| 48 | + private function triggersErrorPHP7($input) |
| 49 | + { |
| 50 | + $errorOccured = false; |
| 51 | + |
| 52 | + try { |
| 53 | + iterable_to_array($input); |
| 54 | + } |
| 55 | + catch (\TypeError $e) { |
| 56 | + $errorOccured = true; |
| 57 | + } |
| 58 | + |
| 59 | + return $errorOccured; |
| 60 | + } |
| 61 | + |
| 62 | + private function triggersErrorPHP5($input) |
| 63 | + { |
| 64 | + $errorOccured = false; |
| 65 | + |
| 66 | + set_error_handler(function ($errno) { |
| 67 | + return E_RECOVERABLE_ERROR === $errno; |
| 68 | + }); |
| 69 | + |
| 70 | + if (false === @iterable_to_array($input)) { |
| 71 | + $errorOccured = true; |
| 72 | + } |
| 73 | + |
| 74 | + restore_error_handler(); |
| 75 | + |
| 76 | + return $errorOccured; |
| 77 | + } |
| 78 | + |
| 79 | +} |
0 commit comments