1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798 |
- <?php
- /*
- * By adding type hints and enabling strict type checking, code can become
- * easier to read, self-documenting and reduce the number of potential bugs.
- * By default, type declarations are non-strict, which means they will attempt
- * to change the original type to match the type specified by the
- * type-declaration.
- *
- * In other words, if you pass a string to a function requiring a float,
- * it will attempt to convert the string value to a float.
- *
- * To enable strict mode, a single declare directive must be placed at the top
- * of the file.
- * This means that the strictness of typing is configured on a per-file basis.
- * This directive not only affects the type declarations of parameters, but also
- * a function's return type.
- *
- * For more info review the Concept on strict type checking in the PHP track
- * <link>.
- *
- * To disable strict typing, comment out the directive below.
- */
- declare(strict_types=1);
- class ProteinError {
- protected string $msg;
- public function __construct(string $msg) {
- $this->msg = $msg;
- }
- public function Error(): string {
- return $this->msg;
- }
- }
- const STOP = "STOP";
- const ErrStop = new ProteinError(STOP);
- const ErrInvalidCodon = new ProteinError("Invalid codon");
- class ProteinTranslation {
- public function getProteins(string $rna) {
- return $this->FromRNA($rna);
- }
- private function FromRNA(string $rna): array|ProteinError {
- $names = [];
- for ($i = 0; $i < strlen($rna); $i += 3) {
- $codon = substr($rna, $i, 3);
- $nameOrError = $this->FromCodon($codon);
- if (is_string($nameOrError)) {
- $names[] = $nameOrError;
- continue;
- }
- if ($nameOrError == ErrStop) {
- return $names;
- }
- throw new InvalidArgumentException($nameOrError->Error());
- }
- return $names;
- }
- private function FromCodon(string $codon): string|ProteinError {
- $names = [
- "AUG" => "Methionine",
- "UUU" => "Phenylalanine",
- "UUC" => "Phenylalanine",
- "UUA" => "Leucine",
- "UUG" => "Leucine",
- "UCU" => "Serine",
- "UCC" => "Serine",
- "UCA" => "Serine",
- "UCG" => "Serine",
- "UAU" => "Tyrosine",
- "UAC" => "Tyrosine",
- "UGU" => "Cysteine",
- "UGC" => "Cysteine",
- "UGG" => "Tryptophan",
- "UAA" => STOP,
- "UAG" => STOP,
- "UGA" => STOP,
- ];
- @$name = $names[$codon];
- if (empty($name)) {
- return ErrInvalidCodon;
- }
- if ($name == STOP) {
- return ErrStop;
- }
- return $name;
- }
- }
|