|
| 1 | +<?php |
| 2 | +declare(strict_types=1); |
| 3 | + |
| 4 | +namespace Markup\Sniffs\Next; |
| 5 | + |
| 6 | +use SlevomatCodingStandard\Helpers\FunctionHelper; |
| 7 | +use SlevomatCodingStandard\Helpers\ReturnTypeHint; |
| 8 | +use SlevomatCodingStandard\Helpers\TypeHintHelper; |
| 9 | +use SlevomatCodingStandard\Helpers\UseStatementHelper; |
| 10 | + |
| 11 | +class PreventingEntitiesInReadlayerSniff implements \PHP_CodeSniffer\Sniffs\Sniff |
| 12 | +{ |
| 13 | + private $useStatements = []; |
| 14 | + |
| 15 | + /** |
| 16 | + * @return mixed[] |
| 17 | + */ |
| 18 | + public function register() |
| 19 | + { |
| 20 | + return [ |
| 21 | + T_OPEN_TAG, |
| 22 | + T_FUNCTION, |
| 23 | + ]; |
| 24 | + } |
| 25 | + |
| 26 | + /** |
| 27 | + * @phpcsSuppress SlevomatCodingStandard.TypeHints.TypeHintDeclaration.MissingParameterTypeHint |
| 28 | + * @param \PHP_CodeSniffer\Files\File $phpcsFile |
| 29 | + * @param int $openTagPointer |
| 30 | + */ |
| 31 | + public function process(\PHP_CodeSniffer\Files\File $phpcsFile, $openTagPointer) |
| 32 | + { |
| 33 | + $tokens = $phpcsFile->getTokens(); |
| 34 | + $token = $tokens[$openTagPointer]; |
| 35 | + $filename = $phpcsFile->getFilename(); |
| 36 | + |
| 37 | + if (stripos($filename, 'Repository/Read/') === false) { |
| 38 | + return; |
| 39 | + } |
| 40 | + |
| 41 | + if ($token['type'] == 'T_OPEN_TAG') { |
| 42 | + $this->useStatements[$filename] = UseStatementHelper::getUseStatements( |
| 43 | + $phpcsFile, |
| 44 | + $openTagPointer |
| 45 | + ); |
| 46 | + |
| 47 | + return; |
| 48 | + } |
| 49 | + |
| 50 | + /** @var ReturnTypeHint $type */ |
| 51 | + $type = FunctionHelper::findReturnTypeHint($phpcsFile, $openTagPointer); |
| 52 | + |
| 53 | + if ($type === null) { |
| 54 | + return; |
| 55 | + } |
| 56 | + |
| 57 | + $type = TypeHintHelper::getFullyQualifiedTypeHint($phpcsFile, $openTagPointer, $type->getTypeHint()); |
| 58 | + |
| 59 | + if (stripos($type, 'Entity\\') !== false) { |
| 60 | + $phpcsFile->addError( |
| 61 | + sprintf( |
| 62 | + 'Read layer methods cannot return mutable objects %s in %s', |
| 63 | + $type, |
| 64 | + $filename |
| 65 | + ), |
| 66 | + $openTagPointer, |
| 67 | + 'ReadLayer' |
| 68 | + ); |
| 69 | + } |
| 70 | + |
| 71 | + |
| 72 | + } |
| 73 | +} |
| 74 | + |
0 commit comments