|
| 1 | +<?php |
| 2 | + |
| 3 | +declare(strict_types=1); |
| 4 | + |
| 5 | +namespace Munus\Generators\Tuple\FragmentGenerator; |
| 6 | + |
| 7 | +use Munus\Exception\UnsupportedOperationException; |
| 8 | +use Munus\Generators\Tuple\FragmentGenerator; |
| 9 | +use Nette\PhpGenerator\ClassType; |
| 10 | +use Nette\PhpGenerator\PhpNamespace; |
| 11 | + |
| 12 | +abstract class AppendPrependMethodAbstractGenerator extends FragmentGenerator |
| 13 | +{ |
| 14 | + public function append(PhpNamespace $namespace, ClassType $class, int $tupleSize, int $maxTupleSize): void |
| 15 | + { |
| 16 | + $resultTupleSize = $tupleSize + 1; |
| 17 | + |
| 18 | + $method = $class->addMethod($this->methodName()); |
| 19 | + $method->addParameter('value'); |
| 20 | + |
| 21 | + if ($this->isMaxSizeTuple($tupleSize, $maxTupleSize)) { |
| 22 | + $namespace->addUse(UnsupportedOperationException::class); |
| 23 | + $method->setBody($this->getMaxTupleSizeExceptionThrowBody()); |
| 24 | + |
| 25 | + return; |
| 26 | + } |
| 27 | + |
| 28 | + $method->setReturnType($this->getMethodReturnType($namespace, $resultTupleSize)); |
| 29 | + $method->addComment('@template T'); |
| 30 | + $method->addComment(self::EMPTY_COMMENT_LINE); |
| 31 | + $method->addComment('@param T $value'); |
| 32 | + $method->addComment(self::EMPTY_COMMENT_LINE); |
| 33 | + $method->addComment($this->getReturnTypeComment($resultTupleSize, $tupleSize)); |
| 34 | + $method->setBody($this->getMethodBody($resultTupleSize, $tupleSize)); |
| 35 | + } |
| 36 | + |
| 37 | + private function getMaxTupleSizeExceptionThrowBody(): string |
| 38 | + { |
| 39 | + return sprintf( |
| 40 | + 'throw new UnsupportedOperationException(\'Can\\\'t %s next value. This is biggest possible Tuple\');', |
| 41 | + $this->methodName(), |
| 42 | + ); |
| 43 | + } |
| 44 | + |
| 45 | + private function getMethodReturnType(PhpNamespace $namespace, int $resultTupleSize): string |
| 46 | + { |
| 47 | + return sprintf('%s\Tuple%s', $namespace->getName(), $resultTupleSize); |
| 48 | + } |
| 49 | + |
| 50 | + private function getReturnTypeComment(int $resultTupleSize, int $tupleSize): string |
| 51 | + { |
| 52 | + return sprintf('@returns Tuple%s<%s>', $resultTupleSize, $this->listOfTypes($tupleSize)); |
| 53 | + } |
| 54 | + |
| 55 | + private function getMethodBody(int $resultTupleSize, int $tupleSize): string |
| 56 | + { |
| 57 | + return sprintf('return new Tuple%s(%s);', $resultTupleSize, $this->listOfValues($tupleSize)); |
| 58 | + } |
| 59 | + |
| 60 | + abstract protected function listOfValues(int $tupleSize): string; |
| 61 | + |
| 62 | + abstract protected function listOfTypes(int $tupleSize): string; |
| 63 | + |
| 64 | + abstract protected function methodName(): string; |
| 65 | +} |
0 commit comments