ExcludeList.php 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  1. <?php declare(strict_types=1);
  2. /*
  3. * This file is part of sebastian/global-state.
  4. *
  5. * (c) Sebastian Bergmann <sebastian@phpunit.de>
  6. *
  7. * For the full copyright and license information, please view the LICENSE
  8. * file that was distributed with this source code.
  9. */
  10. namespace SebastianBergmann\GlobalState;
  11. use function in_array;
  12. use function str_starts_with;
  13. use ReflectionClass;
  14. final class ExcludeList
  15. {
  16. private array $globalVariables = [];
  17. private array $classes = [];
  18. private array $classNamePrefixes = [];
  19. private array $parentClasses = [];
  20. private array $interfaces = [];
  21. private array $staticProperties = [];
  22. public function addGlobalVariable(string $variableName): void
  23. {
  24. $this->globalVariables[$variableName] = true;
  25. }
  26. public function addClass(string $className): void
  27. {
  28. $this->classes[] = $className;
  29. }
  30. public function addSubclassesOf(string $className): void
  31. {
  32. $this->parentClasses[] = $className;
  33. }
  34. public function addImplementorsOf(string $interfaceName): void
  35. {
  36. $this->interfaces[] = $interfaceName;
  37. }
  38. public function addClassNamePrefix(string $classNamePrefix): void
  39. {
  40. $this->classNamePrefixes[] = $classNamePrefix;
  41. }
  42. public function addStaticProperty(string $className, string $propertyName): void
  43. {
  44. if (!isset($this->staticProperties[$className])) {
  45. $this->staticProperties[$className] = [];
  46. }
  47. $this->staticProperties[$className][$propertyName] = true;
  48. }
  49. public function isGlobalVariableExcluded(string $variableName): bool
  50. {
  51. return isset($this->globalVariables[$variableName]);
  52. }
  53. /**
  54. * @psalm-param class-string $className
  55. */
  56. public function isStaticPropertyExcluded(string $className, string $propertyName): bool
  57. {
  58. if (in_array($className, $this->classes, true)) {
  59. return true;
  60. }
  61. foreach ($this->classNamePrefixes as $prefix) {
  62. if (str_starts_with($className, $prefix)) {
  63. return true;
  64. }
  65. }
  66. $class = new ReflectionClass($className);
  67. foreach ($this->parentClasses as $type) {
  68. if ($class->isSubclassOf($type)) {
  69. return true;
  70. }
  71. }
  72. foreach ($this->interfaces as $type) {
  73. if ($class->implementsInterface($type)) {
  74. return true;
  75. }
  76. }
  77. return isset($this->staticProperties[$className][$propertyName]);
  78. }
  79. }