Allergies.php 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. <?php
  2. /*
  3. * By adding type hints and enabling strict type checking, code can become
  4. * easier to read, self-documenting and reduce the number of potential bugs.
  5. * By default, type declarations are non-strict, which means they will attempt
  6. * to change the original type to match the type specified by the
  7. * type-declaration.
  8. *
  9. * In other words, if you pass a string to a function requiring a float,
  10. * it will attempt to convert the string value to a float.
  11. *
  12. * To enable strict mode, a single declare directive must be placed at the top
  13. * of the file.
  14. * This means that the strictness of typing is configured on a per-file basis.
  15. * This directive not only affects the type declarations of parameters, but also
  16. * a function's return type.
  17. *
  18. * For more info review the Concept on strict type checking in the PHP track
  19. * <link>.
  20. *
  21. * To disable strict typing, comment out the directive below.
  22. */
  23. declare(strict_types=1);
  24. class Allergies {
  25. /**
  26. * @var \Allergen[]
  27. */
  28. private array $allergies = [];
  29. public function __construct(int $score) {
  30. $score &= Allergen::CATS * 2 - 1;
  31. $id = Allergen::EGGS;
  32. while ($id <= Allergen::CATS) {
  33. if ($id & $score) {
  34. $this->allergies[] = new Allergen($id);
  35. }
  36. $id <<= 1;
  37. }
  38. }
  39. public function isAllergicTo(Allergen $allergen): bool {
  40. return in_array($allergen, $this->allergies);
  41. }
  42. /**
  43. * @return \Allergen[]
  44. */
  45. public function getList(): array {
  46. return $this->allergies;
  47. }
  48. }
  49. class Allergen {
  50. public const EGGS = 1;
  51. public const PEANUTS = 2;
  52. public const SHELLFISH = 4;
  53. public const STRAWBERRIES = 8;
  54. public const TOMATOES = 16;
  55. public const CHOCOLATE = 32;
  56. public const POLLEN = 64;
  57. public const CATS = 128;
  58. private int $id;
  59. public function __construct(int $id) {
  60. $this->id = $id;
  61. }
  62. public static function allergenList(): array {
  63. return [];
  64. }
  65. public function getScore(): int {
  66. return $this->id;
  67. }
  68. }