Skip to content

Instantly share code, notes, and snippets.

@westonruter
Last active February 23, 2024 01:43
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save westonruter/18d2889e0beb0c51670c7ab3dfb456be to your computer and use it in GitHub Desktop.
Save westonruter/18d2889e0beb0c51670c7ab3dfb456be to your computer and use it in GitHub Desktop.
Test case to demonstrate erroneous static analysis in PhpStorm
<?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