ProteinTranslation.php 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  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 ProteinError {
  25. protected string $msg;
  26. public function __construct(string $msg) {
  27. $this->msg = $msg;
  28. }
  29. public function Error(): string {
  30. return $this->msg;
  31. }
  32. }
  33. const STOP = "STOP";
  34. const ErrStop = new ProteinError(STOP);
  35. const ErrInvalidCodon = new ProteinError("Invalid codon");
  36. class ProteinTranslation {
  37. public function getProteins(string $rna) {
  38. return $this->FromRNA($rna);
  39. }
  40. private function FromRNA(string $rna): array|ProteinError {
  41. $names = [];
  42. for ($i = 0; $i < strlen($rna); $i += 3) {
  43. $codon = substr($rna, $i, 3);
  44. $nameOrError = $this->FromCodon($codon);
  45. if (is_string($nameOrError)) {
  46. $names[] = $nameOrError;
  47. continue;
  48. }
  49. if ($nameOrError == ErrStop) {
  50. return $names;
  51. }
  52. throw new InvalidArgumentException($nameOrError->Error());
  53. }
  54. return $names;
  55. }
  56. private function FromCodon(string $codon): string|ProteinError {
  57. $names = [
  58. "AUG" => "Methionine",
  59. "UUU" => "Phenylalanine",
  60. "UUC" => "Phenylalanine",
  61. "UUA" => "Leucine",
  62. "UUG" => "Leucine",
  63. "UCU" => "Serine",
  64. "UCC" => "Serine",
  65. "UCA" => "Serine",
  66. "UCG" => "Serine",
  67. "UAU" => "Tyrosine",
  68. "UAC" => "Tyrosine",
  69. "UGU" => "Cysteine",
  70. "UGC" => "Cysteine",
  71. "UGG" => "Tryptophan",
  72. "UAA" => STOP,
  73. "UAG" => STOP,
  74. "UGA" => STOP,
  75. ];
  76. @$name = $names[$codon];
  77. if (empty($name)) {
  78. return ErrInvalidCodon;
  79. }
  80. if ($name == STOP) {
  81. return ErrStop;
  82. }
  83. return $name;
  84. }
  85. }