|
| 1 | +<?php declare(strict_types = 1); |
| 2 | + |
| 3 | +namespace PHPStan\DependencyInjection; |
| 4 | + |
| 5 | +use Generator; |
| 6 | +use PHPStan\ShouldNotHappenException; |
| 7 | +use PHPStan\Testing\PHPStanTestCase; |
| 8 | + |
| 9 | +class BleedingEdgeToggleTest extends PHPStanTestCase |
| 10 | +{ |
| 11 | + |
| 12 | + public function testWithBleedingEdgeRunsCallbackWithToggleSet(): void |
| 13 | + { |
| 14 | + $backup = BleedingEdgeToggle::isBleedingEdge(); |
| 15 | + try { |
| 16 | + BleedingEdgeToggle::setBleedingEdge(false); |
| 17 | + |
| 18 | + $observed = BleedingEdgeToggle::withBleedingEdge(true, static fn (): bool => BleedingEdgeToggle::isBleedingEdge()); |
| 19 | + |
| 20 | + $this->assertTrue($observed); |
| 21 | + } finally { |
| 22 | + BleedingEdgeToggle::setBleedingEdge($backup); |
| 23 | + } |
| 24 | + } |
| 25 | + |
| 26 | + public function testWithBleedingEdgeRestoresPreviousValue(): void |
| 27 | + { |
| 28 | + $backup = BleedingEdgeToggle::isBleedingEdge(); |
| 29 | + try { |
| 30 | + BleedingEdgeToggle::setBleedingEdge(false); |
| 31 | + |
| 32 | + BleedingEdgeToggle::withBleedingEdge(true, static fn (): bool => true); |
| 33 | + |
| 34 | + $this->assertFalse(BleedingEdgeToggle::isBleedingEdge()); |
| 35 | + } finally { |
| 36 | + BleedingEdgeToggle::setBleedingEdge($backup); |
| 37 | + } |
| 38 | + } |
| 39 | + |
| 40 | + public function testWithBleedingEdgeRejectsGeneratorCallbackAndRestoresValue(): void |
| 41 | + { |
| 42 | + $backup = BleedingEdgeToggle::isBleedingEdge(); |
| 43 | + try { |
| 44 | + BleedingEdgeToggle::setBleedingEdge(false); |
| 45 | + |
| 46 | + $generatorCallback = static function (): Generator { |
| 47 | + yield BleedingEdgeToggle::isBleedingEdge(); |
| 48 | + }; |
| 49 | + |
| 50 | + try { |
| 51 | + BleedingEdgeToggle::withBleedingEdge(true, $generatorCallback); |
| 52 | + $this->fail('Expected ShouldNotHappenException was not thrown.'); |
| 53 | + } catch (ShouldNotHappenException $e) { |
| 54 | + // A generator callback would hold the toggle across a `yield` and leak it |
| 55 | + // into unrelated tests - it must be rejected eagerly. |
| 56 | + $this->assertStringContainsString('not allowed to yield', $e->getMessage()); |
| 57 | + } |
| 58 | + |
| 59 | + // The toggle must be restored even when the callback is rejected. |
| 60 | + $this->assertFalse(BleedingEdgeToggle::isBleedingEdge()); |
| 61 | + } finally { |
| 62 | + BleedingEdgeToggle::setBleedingEdge($backup); |
| 63 | + } |
| 64 | + } |
| 65 | + |
| 66 | +} |
0 commit comments