Last active
February 23, 2024 01:43
-
-
Save westonruter/18d2889e0beb0c51670c7ab3dfb456be to your computer and use it in GitHub Desktop.
Test case to demonstrate erroneous static analysis in PhpStorm
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php declare(strict_types = 1); | |
final class Grouped_Numbers { | |
/** | |
* Grouped numbers. | |
* | |
* @var array<string, int[]> | |
*/ | |
private $grouped_numbers; | |
/** | |
* Constructor. | |
* | |
* @param int[] $numbers Numbers. | |
*/ | |
public function __construct( array $numbers ) { | |
$this->grouped_numbers = $this->group_numbers( $numbers ); | |
} | |
/** | |
* Adds a new number. | |
* | |
* @param int $number New number. | |
*/ | |
public function add( int $number ) { | |
// 👉 The use of array_values() is required or else PhpStorm's static analysis complains | |
// below when passing $numbers into the group_numbers method: | |
// > Expected parameter of type 'int[]', 'int[][]' provided . | |
// Interestingly, this is also bypassed by just putting parentheses around $this->grouped_numbers. | |
$numbers = array_merge( ...array_values( $this->grouped_numbers ) ); | |
array_unshift( $numbers, $number ); | |
$this->grouped_numbers = $this->group_numbers( $numbers ); | |
} | |
/** | |
* Groups numbers. | |
* | |
* @param int[] $numbers URL metrics. | |
* @return array<string, int[]> Grouped numbers. | |
*/ | |
private function group_numbers( array $numbers ): array { | |
$groups = array( | |
'negative' => array(), | |
'positive' => array(), | |
); | |
foreach ( $numbers as $number ) { | |
if ( $number < 0 ) { | |
$groups['negative'][] = $number; | |
} else { | |
$groups['positive'][] = $number; | |
} | |
} | |
return $groups; | |
} | |
/** | |
* Prints the grouped numbers. | |
*/ | |
public function print() { | |
print_r( $this->grouped_numbers ); | |
} | |
} | |
$group = new Grouped_Numbers( array( -1, 1 ) ); | |
$group->add( 0 ); | |
$group->print(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment