diff --git a/AGENTS.md b/AGENTS.md index c4f9750f..617e2cba 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -204,6 +204,7 @@ declare(strict_types=1); - **Все изменения — через ветку + PR.** Прямой пуш в `master` запрещён. - Создать ветку `task/`, сделать коммиты, открыть PR, дождаться CI, смержить, удалить ветку. +- **Ссылка на PR — в каждом ответе**, где PR создан, обновлён или ожидает действия (`https://github.com/prikotov/coding-standard/pull/N`). Не заставляй владельца спрашивать. Правила работы с git — ветки, коммиты, PR, релизы, `SemVer`: diff --git a/config/deptrac/depfile.yaml b/config/deptrac/depfile.yaml index 5ef9904a..9022486f 100644 --- a/config/deptrac/depfile.yaml +++ b/config/deptrac/depfile.yaml @@ -20,21 +20,13 @@ deptrac: layers: # --- Main layers --- + # Entities only (Domain\Entity\*Model, except Embeddable VO); everything else under + # Domain lives in its own layer: DomainContract, DomainVo, DomainEnum, DomainDto, + # DomainSpecification, DomainEmbeddable. - name: Domain collectors: - - type: bool - must: - - type: classLike - value: ^(?:[A-Za-z_][A-Za-z0-9_]*\\)?Common\\Module\\[^\\]+\\Domain\\.* - must_not: - - type: classLike - value: ^(?:[A-Za-z_][A-Za-z0-9_]*\\)?Common\\Module\\[^\\]+\\Domain\\(Entity\\)?ValueObject\\.*Vo$ - - type: classLike - value: ^(?:[A-Za-z_][A-Za-z0-9_]*\\)?Common\\Module\\[^\\]+\\Domain\\Specification\\.* - - type: classLike - value: ^(?:[A-Za-z_][A-Za-z0-9_]*\\)?Common\\Module\\[^\\]+\\Domain\\Enum\\.* - - type: classLike - value: ^(?:[A-Za-z_][A-Za-z0-9_]*\\)?Common\\Module\\[^\\]+\\Domain\\.*Dto$ + - type: classLike + value: ^(?:[A-Za-z_][A-Za-z0-9_]*\\)?Common\\Module\\[^\\]+\\Domain\\Entity\\(?!ValueObject\\).*$ - name: Application collectors: @@ -110,7 +102,46 @@ deptrac: - name: DomainVo collectors: - type: classLike - value: ^(?:[A-Za-z_][A-Za-z0-9_]*\\)?Common\\Module\\[^\\]+\\Domain\\(Entity\\)?ValueObject\\.*Vo$ + value: ^(?:[A-Za-z_][A-Za-z0-9_]*\\)?Common\\Module\\[^\\]+\\Domain\\ValueObject\\.*Vo$ + + # Domain exceptions: thrown by any domain type, caught by the layers that call domain + # services. Not a "contract" — VO, DTO and specifications may use them. + - name: DomainException + collectors: + - type: classLike + value: ^(?:[A-Za-z_][A-Za-z0-9_]*\\)?Common\\Module\\[^\\]+\\Domain\\Exception\\.* + + # Domain contracts and pure domain types: everything under Domain that is not an + # entity, value object, enum, DTO or specification — service/repository interfaces + # and implementations, find criteria, calculators, helpers, normalizers, exceptions. + # This is the only part of Domain the Application layer may use directly; + # entities (Domain, DomainEmbeddable) stay behind handlers and repositories. + - name: DomainContract + collectors: + - type: bool + must: + - type: classLike + value: ^(?:[A-Za-z_][A-Za-z0-9_]*\\)?Common\\Module\\[^\\]+\\Domain\\.* + must_not: + - type: classLike + value: ^(?:[A-Za-z_][A-Za-z0-9_]*\\)?Common\\Module\\[^\\]+\\Domain\\Entity\\.* + - type: classLike + value: ^(?:[A-Za-z_][A-Za-z0-9_]*\\)?Common\\Module\\[^\\]+\\Domain\\ValueObject\\.*Vo$ + - type: classLike + value: ^(?:[A-Za-z_][A-Za-z0-9_]*\\)?Common\\Module\\[^\\]+\\Domain\\Enum\\.* + - type: classLike + value: ^(?:[A-Za-z_][A-Za-z0-9_]*\\)?Common\\Module\\[^\\]+\\Domain\\.*Dto$ + - type: classLike + value: ^(?:[A-Za-z_][A-Za-z0-9_]*\\)?Common\\Module\\[^\\]+\\Domain\\Specification\\.* + - type: classLike + value: ^(?:[A-Za-z_][A-Za-z0-9_]*\\)?Common\\Module\\[^\\]+\\Domain\\Exception\\.* + + # Embeddable VO are a persistence part of entities: isolated like Domain (entities), + # not shared like DomainVo. See docs/conventions/layers/domain/entity.md. + - name: DomainEmbeddable + collectors: + - type: classLike + value: ^(?:[A-Za-z_][A-Za-z0-9_]*\\)?Common\\Module\\[^\\]+\\Domain\\Entity\\ValueObject\\.*Vo$ - name: DomainEnum collectors: @@ -177,15 +208,36 @@ deptrac: ruleset: # DTO boundary Domain: + - DomainException - Domain + - DomainContract - DomainDto - DomainEnum - DomainSpecification - DomainVo + - DomainEmbeddable DomainVo: + - DomainException - Domain - DomainEnum - DomainVo + + DomainEmbeddable: + - DomainEnum + + DomainException: + - DomainException + - DomainContract + - DomainVo + - DomainEnum + DomainContract: + - DomainException + - Domain + - DomainContract + - DomainDto + - DomainEnum + - DomainSpecification + - DomainVo DomainEnum: - DomainEnum ApplicationDto: @@ -199,6 +251,8 @@ deptrac: - IntegrationDto InfrastructureDto: - Domain + - DomainContract + - DomainException - DomainDto - DomainEnum - DomainVo @@ -207,11 +261,14 @@ deptrac: - InfrastructureDto DomainDto: - Domain + - DomainContract - DomainDto - DomainEnum - DomainVo DomainSpecification: - Domain + - DomainContract + - DomainException - DomainDto - DomainEnum - DomainSpecification @@ -236,6 +293,8 @@ deptrac: - DomainEnum - DomainSpecification - DomainVo + - DomainContract + - DomainException ApplicationQueryHandler: - Application - +ApplicationQuery @@ -244,6 +303,8 @@ deptrac: - DomainEnum - DomainSpecification - DomainVo + - DomainContract + - DomainException # Layer dependencies Presentation: @@ -252,14 +313,30 @@ deptrac: - +ApplicationQuery - ApplicationCommandHandler - ApplicationQueryHandler + # Application orchestrates domain services, repositories and entities + # (docs/conventions/layers/application.md, core-patterns/mapper.md: mappers take Entity). + # Embeddable stay behind entities — not granted. No `+Layer` here: it is a transitive + # closure and would grant the handlers' dependencies. Application: - Application - - +ApplicationCommandHandler - - +ApplicationQueryHandler + - ApplicationCommandHandler + - ApplicationQueryHandler + - ApplicationDto + - ApplicationCommonDto + - ApplicationEnum + - Domain + - DomainDto + - DomainEnum + - DomainVo + - DomainSpecification + - DomainContract + - DomainException Integration: - Integration - IntegrationDto - Application + - DomainContract + - DomainException - ApplicationCommand - ApplicationQuery - ApplicationCommandHandler @@ -268,6 +345,7 @@ deptrac: - ApplicationCommonDto - ApplicationEnum - Domain + - DomainEmbeddable - DomainDto - DomainEnum - DomainVo @@ -277,6 +355,9 @@ deptrac: - InfrastructureDto - InfrastructureEnum - Domain + - DomainContract + - DomainException + - DomainEmbeddable - DomainDto - DomainEnum - DomainVo @@ -316,3 +397,10 @@ services: autowire: true tags: - { name: kernel.event_subscriber } + - class: PrikotovCodingStandard\Deptrac\DomainTypeCatalogRule + autowire: true + tags: + - { name: kernel.event_subscriber } + - class: PrikotovCodingStandard\Deptrac\PolymorphismDependencyRule + tags: + - { name: kernel.event_subscriber } diff --git a/src/Deptrac/DomainTypeCatalogRule.php b/src/Deptrac/DomainTypeCatalogRule.php new file mode 100644 index 00000000..5e9bee65 --- /dev/null +++ b/src/Deptrac/DomainTypeCatalogRule.php @@ -0,0 +1,144 @@ +[A-Za-z][A-Za-z0-9]*)\\\\' + . 'Domain\\\\' + . '(?P[^\\\\]+.*)$/'; + + /** + * Directories of Domain types found in the conventions and in the consumer + * projects (stocks2, TasK, task-orchestrator). + * + * @var list + */ + private const ALLOWED_TYPE_DIRECTORIES = [ + 'Calculator', + 'Criteria', + 'Dto', + 'Entity', + 'Enum', + 'Exception', + 'Factory', + 'Helper', + 'List', + 'Mapper', + 'Provider', + 'Repository', + 'Service', + 'Specification', + 'Strategy', + 'ValueObject', + ]; + + public function __construct(private readonly AstMapExtractor $astMapExtractor) + { + } + + public static function getSubscribedEvents(): array + { + return [ + PostProcessEvent::class => ['onPostProcessEvent'], + ]; + } + + public function onPostProcessEvent(PostProcessEvent $event): void + { + foreach ($this->astMapExtractor->extract()->getClassLikeReferences() as $reference) { + $className = $reference->getToken()->toString(); + $violation = self::classify($className); + if ($violation !== null) { + $event->getResult()->addError(new Error($violation . '.' . self::DOC_REF)); + } + } + } + + /** + * Returns the violation message for a class outside the catalog, null if it fits. + */ + public static function classify(string $className): ?string + { + if (1 !== preg_match(self::MODULE_DOMAIN_PATTERN, $className, $matches)) { + return null; + } + + $path = $matches['path']; + + // Only interfaces directly in the Domain namespace (e.g. ChainDefinitionInterface). + if (str_contains($path, '\\') === false) { + return str_ends_with($path, 'Interface') === false + ? sprintf( + 'Class "%s" sits directly in the Domain namespace; only interfaces are allowed there. ' + . 'The Domain catalog is closed: %s.', + $className, + implode(', ', self::ALLOWED_TYPE_DIRECTORIES), + ) + : null; + } + + $directory = explode('\\', $path, 2)[0]; + if (in_array($directory, self::ALLOWED_TYPE_DIRECTORIES, true) === false) { + return sprintf( + 'Class "%s" is in Domain\\%s, which is not a Domain type directory. ' + . 'The Domain catalog is closed: %s.', + $className, + $directory, + implode(', ', self::ALLOWED_TYPE_DIRECTORIES), + ); + } + + // Classes in ValueObject must carry the "Vo" suffix (MissingVoSuffixSniff covers PHPCS projects). + if ($directory === 'ValueObject' && str_ends_with($path, 'Vo') === false) { + return sprintf( + 'Class "%s" is in Domain\\ValueObject without the "Vo" suffix. ' + . 'Value Object names are suffixed with "Vo" (docs/conventions/core-patterns/value-object.md).', + $className, + ); + } + + return null; + } + + public function ruleName(): string + { + return 'DomainTypeCatalogRule'; + } + + public function ruleDescription(): string + { + return 'Domain classes must live in a recognized type directory; the Domain root' + . ' namespace contains only interfaces. A class fitting no convention type' + . ' is a violation by definition.'; + } +} diff --git a/src/Deptrac/PolymorphismDependencyRule.php b/src/Deptrac/PolymorphismDependencyRule.php new file mode 100644 index 00000000..5d26f184 --- /dev/null +++ b/src/Deptrac/PolymorphismDependencyRule.php @@ -0,0 +1,83 @@ + + */ + private const DATA_OBJECT_LAYERS = [ + 'ApplicationCommand', + 'ApplicationQuery', + ]; + + private function isPolymorphismOrData(Violation $violation): bool + { + $type = $violation->getDependency()->getContext()->dependencyType; + + if (in_array($type, self::IGNORED_TYPES, true) === true) { + return true; + } + + return $type === DependencyType::PARAMETER + && in_array($violation->getDependentLayer(), self::DATA_OBJECT_LAYERS, true) === true; + } + + public static function getSubscribedEvents(): array + { + return [ + PostProcessEvent::class => ['onPostProcessEvent'], + ]; + } + + public function onPostProcessEvent(PostProcessEvent $event): void + { + $result = $event->getResult(); + + foreach ($result->rules() as $violations) { + foreach ($violations as $violation) { + if ($violation instanceof Violation && $this->isPolymorphismOrData($violation) === true) { + $result->removeRule($violation); + } + } + } + } +} diff --git a/tests/Deptrac/DepfileRootNamespaceRegexTest.php b/tests/Deptrac/DepfileRootNamespaceRegexTest.php index 4f67beb2..710c7975 100644 --- a/tests/Deptrac/DepfileRootNamespaceRegexTest.php +++ b/tests/Deptrac/DepfileRootNamespaceRegexTest.php @@ -131,7 +131,9 @@ private function groupMatches(array $group, string $className): bool public static function provideDigitRootNamespaceClasses(): array { return [ - 'Domain service' => ['Domain', 'Stocks2\Common\Module\Billing\Domain\Service\Invoice\CreateInvoiceService'], + 'Domain entity' => ['Domain', 'Stocks2\Common\Module\Billing\Domain\Entity\Invoice\InvoiceModel'], + 'Domain service (its interface is the contract)' => ['DomainContract', 'Stocks2\Common\Module\Billing\Domain\Service\Invoice\CreateInvoiceServiceInterface'], + 'Domain repository find criteria' => ['DomainContract', 'Stocks2\Common\Module\Billing\Domain\Repository\Invoice\Criteria\InvoiceFindCriteria'], 'Application service' => ['Application', 'Stocks2\Common\Module\Billing\Application\Service\Invoice\PrepareInvoiceService'], 'Application command handler' => ['ApplicationCommandHandler', 'Stocks2\Common\Module\Billing\Application\UseCase\Command\Invoice\Create\CreateCommandHandler'], 'Infrastructure' => ['Infrastructure', 'Stocks2\Common\Module\Billing\Infrastructure\Repository\Invoice\InvoiceRepository'], diff --git a/tests/Deptrac/DepfileRulesetSemanticsTest.php b/tests/Deptrac/DepfileRulesetSemanticsTest.php new file mode 100644 index 00000000..19c352b1 --- /dev/null +++ b/tests/Deptrac/DepfileRulesetSemanticsTest.php @@ -0,0 +1,439 @@ +fixturesDir = sys_get_temp_dir() . '/cs-deptrac-' . uniqid(); + mkdir($this->fixturesDir . '/src', 0777, true); + + // The shipped depfile with paths pointed at generated fixtures: tests its layers + // and ruleset as-is, without the `imports` path semantics. + $depfile = (string) preg_replace( + '/(\n paths:\n)(\s+- [^\n]+\n)+/', + "$1 - " . $this->fixturesDir . "/src\n", + (string) file_get_contents(self::DEPFILE), + 1, + ); + // Fresh AST per run: the default cache_file lives next to the config and would + // otherwise serve a stale AST between tests that share class names. + $depfile = (string) preg_replace( + '/\ndeptrac:\n/', + "\ndeptrac:\n cache_file: " . $this->fixturesDir . "/deptrac.cache\n", + $depfile, + 1, + ); + self::assertStringContainsString($this->fixturesDir . '/src', $depfile, 'paths section was not replaced'); + self::assertStringContainsString('cache_file:', $depfile, 'cache_file was not injected'); + + $this->probeDepfile = $this->fixturesDir . '/depfile.yaml'; + file_put_contents($this->probeDepfile, $depfile); + } + + protected function tearDown(): void + { + if (is_dir($this->fixturesDir)) { + $this->removeDir($this->fixturesDir); + } + + parent::tearDown(); + } + + public function testApplicationServiceMustNotDependOnDomainEmbeddable(): void + { + $this->writeClass('Domain/Entity/ValueObject/DeviceVo.php', 'final readonly class DeviceVo'); + $this->writeClass( + 'Application/Service/LeakyService.php', + 'final class LeakyService', + 'public function __construct(private readonly DeviceVo $device) {}', + ['DeviceVo' => 'Domain\Entity\ValueObject\DeviceVo'], + ); + + self::assertSame( + ['Application\Service\LeakyService on DomainEmbeddable'], + $this->edges($this->analyse(), 'LeakyService'), + 'Application must not reach Embeddable VO: they are a persistence part of entities.', + ); + } + + public function testApplicationMayUseDomainEntities(): void + { + // docs/conventions/layers/application.md: Application orchestrates services, + // repositories and entities; core-patterns/mapper.md: mappers take Entity as input. + $this->writeClass('Domain/Entity/PaymentModel.php', 'final class PaymentModel'); + $this->writeClass( + 'Application/Mapper/PaymentDtoMapper.php', + 'final readonly class PaymentDtoMapper', + 'public function map(PaymentModel $model): string { return $model->name; }', + ['PaymentModel' => 'Domain\Entity\PaymentModel'], + ); + + self::assertSame([], $this->edges($this->analyse(), 'PaymentDtoMapper')); + } + + public function testApplicationServiceMayBuildRepositoryFindCriteria(): void + { + $this->writeClass('Domain/Repository/Payment/Criteria/PaymentFindCriteria.php', 'final class PaymentFindCriteria'); + $this->writeClass( + 'Application/Service/LeakyService.php', + 'final class LeakyService', + 'public function find(): PaymentFindCriteria { return new PaymentFindCriteria(); }', + ['PaymentFindCriteria' => 'Domain\Repository\Payment\Criteria\PaymentFindCriteria'], + ); + + self::assertSame([], $this->edges($this->analyse(), 'LeakyService')); + } + + public function testCommandHandlerMayUseEntitiesButNotEmbeddable(): void + { + $this->writeClass('Domain/Entity/PaymentModel.php', 'final class PaymentModel'); + $this->writeClass('Domain/Entity/ValueObject/ClientCostVo.php', 'final readonly class ClientCostVo'); + $this->writeClass( + 'Application/UseCase/Command/Pay/DoPayCommandHandler.php', + 'final class DoPayCommandHandler', + 'public function __construct(private readonly PaymentModel $model, private readonly ClientCostVo $cost) {}', + [ + 'PaymentModel' => 'Domain\Entity\PaymentModel', + 'ClientCostVo' => 'Domain\Entity\ValueObject\ClientCostVo', + ], + ); + + self::assertSame( + ['Application\UseCase\Command\Pay\DoPayCommandHandler on DomainEmbeddable'], + $this->edges($this->analyse(), 'DoPayCommandHandler'), + 'Handlers work with entities; Embeddable stay behind the entity.', + ); + } + + public function testApplicationServiceMayCallDomainContracts(): void + { + $this->writeClass('Domain/Service/PaymentServiceInterface.php', 'interface PaymentServiceInterface'); + $this->writeClass( + 'Application/Service/LeakyService.php', + 'final class LeakyService', + 'public function __construct(private readonly PaymentServiceInterface $payments) {}', + ['PaymentServiceInterface' => 'Domain\Service\PaymentServiceInterface'], + ); + + self::assertSame([], $this->edges($this->analyse(), 'LeakyService')); + } + + public function testDomainValueTypesMustNotOwnEmbeddable(): void + { + $this->writeClass('Domain/Entity/ValueObject/DeviceVo.php', 'final readonly class DeviceVo'); + $this->writeClass( + 'Domain/Dto/SessionDto.php', + 'final readonly class SessionDto', + 'public function __construct(public readonly DeviceVo $device) {}', + ['DeviceVo' => 'Domain\Entity\ValueObject\DeviceVo'], + ); + $this->writeClass( + 'Domain/Specification/HasDeviceSpecification.php', + 'final class HasDeviceSpecification', + 'public function __construct(private readonly DeviceVo $device) {}', + ['DeviceVo' => 'Domain\Entity\ValueObject\DeviceVo'], + ); + + $violations = $this->analyse(); + + self::assertSame(['Domain\Dto\SessionDto on DomainEmbeddable'], $this->edges($violations, 'SessionDto')); + self::assertSame( + ['Domain\Specification\HasDeviceSpecification on DomainEmbeddable'], + $this->edges($violations, 'HasDeviceSpecification'), + ); + } + + /** + * The Domain layer is "entities only"; every other domain type must land in a + * dedicated layer. A class under Domain\ that matches no layer is never checked. + * Deptrac reports "uncovered" only for referenced classes, so each probe class + * is referenced by an Application service. + */ + #[DataProvider('provideDomainTypesOutsideEntities')] + public function testEveryDomainTypeOutsideEntitiesIsCovered(string $relativePath, string $declaration, string $shortName): void + { + $this->writeClass($relativePath, $declaration); + // An Application DTO may not depend on any Domain layer: a covered probe + // becomes a violation, an uncovered one is reported as "uncovered". + $this->writeClass( + 'Application/Dto/Probe/LeakyDto.php', + 'final readonly class LeakyDto', + 'public function __construct(public readonly ' . $shortName . ' $dependency) {}', + [$shortName => str_replace('/', '\\', dirname($relativePath)) . '\\' . $shortName], + ); + + $report = $this->analyseReport(); + + self::assertSame(0, $report['Uncovered'], 'domain type without a layer: ' . $relativePath); + self::assertSame(1, $report['Violations'], 'covered domain type referenced from an Application DTO must be a violation: ' . $relativePath); + } + + /** @return iterable */ + public static function provideDomainTypesOutsideEntities(): iterable + { + yield 'service interface' => ['Domain/Service/Pay/PayServiceInterface.php', 'interface PayServiceInterface', 'PayServiceInterface']; + yield 'service implementation' => ['Domain/Service/Pay/PayService.php', 'final class PayService', 'PayService']; + yield 'find criteria' => ['Domain/Repository/Payment/Criteria/PaymentFindCriteria.php', 'final class PaymentFindCriteria', 'PaymentFindCriteria']; + yield 'calculator' => ['Domain/Calculator/RateCalculator.php', 'final readonly class RateCalculator', 'RateCalculator']; + yield 'normalizer in domain root' => ['Domain/FieldNormalizer.php', 'final class FieldNormalizer', 'FieldNormalizer']; + yield 'exception' => ['Domain/Exception/InvalidAmountException.php', 'final class InvalidAmountException', 'InvalidAmountException']; + yield 'value object interface without Vo suffix' => ['Domain/ValueObject/Parameters/ParametersInterface.php', 'interface ParametersInterface', 'ParametersInterface']; + yield 'value object without Vo suffix' => ['Domain/ValueObject/CleanupList.php', 'final class CleanupList', 'CleanupList']; + } + + public function testDomainValueObjectMayThrowDomainException(): void + { + $this->writeClass('Domain/Exception/InvalidAmountException.php', 'final class InvalidAmountException extends \\InvalidArgumentException'); + $this->writeClass( + 'Domain/ValueObject/AmountVo.php', + 'final readonly class AmountVo', + "public function __construct(private int \$amount) { if (\$amount < 0) { throw new InvalidAmountException(); } }", + ['InvalidAmountException' => 'Domain\Exception\InvalidAmountException'], + ); + + self::assertSame([], $this->edges($this->analyse(), 'AmountVo')); + } + + public function testEntityAndDomainServiceMayThrowDomainException(): void + { + $this->writeClass('Domain/Exception/InvalidAmountException.php', 'final class InvalidAmountException extends \\InvalidArgumentException'); + $this->writeClass( + 'Domain/Entity/PaymentModel.php', + 'final class PaymentModel', + "public function __construct(private int \$amount) { if (\$amount < 0) { throw new InvalidAmountException(); } }", + ['InvalidAmountException' => 'Domain\Exception\InvalidAmountException'], + ); + $this->writeClass( + 'Domain/Service/PayService.php', + 'final class PayService', + "public function pay(PaymentModel \$m): void { if (\$m->amount < 0) { throw new InvalidAmountException(); } }", + ['InvalidAmountException' => 'Domain\Exception\InvalidAmountException', 'PaymentModel' => 'Domain\Entity\PaymentModel'], + ); + + $violations = $this->analyse(); + + self::assertSame([], $this->edges($violations, 'PaymentModel')); + self::assertSame([], $this->edges($violations, 'PayService')); + } + + public function testDomainValueObjectMustNotDependOnEmbeddable(): void + { + $this->writeClass('Domain/Entity/ValueObject/DeviceVo.php', 'final readonly class DeviceVo'); + $this->writeClass( + 'Domain/ValueObject/ResolutionVo.php', + 'final readonly class ResolutionVo', + 'public function __construct(private readonly DeviceVo $device) {}', + ['DeviceVo' => 'Domain\Entity\ValueObject\DeviceVo'], + ); + + self::assertSame( + ['Domain\ValueObject\ResolutionVo on DomainEmbeddable'], + $this->edges($this->analyse(), 'ResolutionVo'), + ); + } + + public function testEntityMayOwnItsEmbeddable(): void + { + $this->writeClass('Domain/Entity/ValueObject/DeviceVo.php', 'final readonly class DeviceVo'); + $this->writeClass( + 'Domain/Entity/AttributionSessionModel.php', + 'final class AttributionSessionModel', + 'public function __construct(private readonly DeviceVo $device) {}', + ['DeviceVo' => 'Domain\Entity\ValueObject\DeviceVo'], + ); + + $violations = $this->analyse(); + + self::assertSame([], $this->edges($violations, 'AttributionSessionModel')); + self::assertSame([], $this->edges($violations, 'DeviceVo')); + } + + /** + * @param array $imports short name => namespace-qualified path under the module + */ + private function writeClass(string $relativePath, string $declaration, string $members = '', array $imports = []): void + { + $path = $this->fixturesDir . '/src/' . $relativePath; + $namespace = self::MODULE . '\\' . str_replace('/', '\\', dirname($relativePath)); + + $uses = implode( + "\n", + array_map( + static fn (string $fq): string => 'use ' . self::MODULE . '\\' . $fq . ';', + $imports, + ), + ); + + is_dir(dirname($path)) || mkdir(dirname($path), 0777, true); + file_put_contents( + $path, + " + */ + private function analyse(): array + { + $result = (new ProcessRunner())->run( + [ + PHP_BINARY, + dirname(self::DEPFILE, 3) . '/vendor/bin/deptrac', + 'analyse', + '--config-file=' . $this->probeDepfile, + '--no-progress', + '--no-ansi', + '--formatter=json', + ], + ['pipe', 'r'], + ); + + self::assertNotNull($result, 'deptrac process could not start'); + [, $stdout, $stderr] = $result; + + // The json formatter reports to stdout; diagnostics (syntax errors etc.) go to stderr. + $decoded = json_decode($stdout, true); + self::assertIsArray($decoded, 'deptrac json output expected; stdout: ' . $stdout . ' stderr: ' . $stderr); + + $report = $decoded['Report'] ?? null; + self::assertIsArray($report); + self::assertSame('', trim($stderr), 'deptrac stderr: ' . $stderr); + + $files = $decoded['files'] ?? []; + self::assertIsArray($files); + + $messages = []; + foreach ($files as $file) { + self::assertIsArray($file); + $fileMessages = $file['messages'] ?? []; + self::assertIsArray($fileMessages); + foreach ($fileMessages as $message) { + self::assertIsArray($message); + self::assertIsString($message['message'] ?? null); + $messages[] = ['message' => $message['message']]; + } + } + + return $messages; + } + + /** + * @return array{Violations: int, Uncovered: int, Errors: int} + */ + private function analyseReport(): array + { + $result = (new ProcessRunner())->run( + [ + PHP_BINARY, + dirname(self::DEPFILE, 3) . '/vendor/bin/deptrac', + 'analyse', + '--config-file=' . $this->probeDepfile, + '--no-progress', + '--no-ansi', + '--formatter=json', + ], + ['pipe', 'r'], + ); + + self::assertNotNull($result, 'deptrac process could not start'); + [, $stdout, $stderr] = $result; + + $decoded = json_decode($stdout, true); + self::assertIsArray($decoded, 'deptrac json output expected; stdout: ' . $stdout . ' stderr: ' . $stderr); + $report = $decoded['Report'] ?? null; + self::assertIsArray($report); + + foreach (['Violations', 'Uncovered', 'Errors'] as $key) { + self::assertIsInt($report[$key] ?? null, 'deptrac report field missing: ' . $key); + } + + return [ + 'Violations' => $report['Violations'], + 'Uncovered' => $report['Uncovered'], + 'Errors' => $report['Errors'], + ]; + } + + /** + * Violations where `$className` is the depender, as `DependerPath on TargetLayer`. + * Deptrac message format: `X must not depend on Y (DependerLayer on TargetLayer)`. + * + * @param list $violations + * + * @return list + */ + private function edges(array $violations, string $className): array + { + $prefix = self::MODULE . '\\'; + $edges = []; + foreach ($violations as $violation) { + $message = $violation['message']; + if (preg_match('/^(?\S+) must not depend on \S+ \([^)]+ on (?[^)]+)\)$/', $message, $m) !== 1) { + continue; + } + + if (str_ends_with($m['from'], '\\' . $className)) { + $edges[] = str_replace($prefix, '', $m['from']) . ' on ' . $m['target']; + } + } + + sort($edges); + + return $edges; + } + + private function removeDir(string $dir): void + { + foreach (scandir($dir) ?: [] as $entry) { + if ($entry === '.' || $entry === '..') { + continue; + } + + $path = $dir . '/' . $entry; + if (is_dir($path) && is_link($path) === false) { + $this->removeDir($path); + } else { + unlink($path); + } + } + + rmdir($dir); + } +} diff --git a/tests/Deptrac/DomainTypeCatalogRuleTest.php b/tests/Deptrac/DomainTypeCatalogRuleTest.php new file mode 100644 index 00000000..0901296b --- /dev/null +++ b/tests/Deptrac/DomainTypeCatalogRuleTest.php @@ -0,0 +1,70 @@ + */ + public static function provideViolations(): iterable + { + yield 'class directly in Domain root (stocks2 FieldNormalizer)' => ['Stocks2\Common\Module\Maintenance\Domain\TransactionFieldNormalizer']; + yield 'class in Domain root in another module' => ['Stocks2\Common\Module\Income\Domain\DohodDividendFieldNormalizer']; + yield 'ValueObject class without Vo suffix (TasK CleanupErrorList)' => ['Task\Common\Module\Source\Domain\ValueObject\CleanupErrorList']; + yield 'unknown directory under Domain (task-orchestrator Contract)' => ['TaskOrchestrator\Common\Module\ChainExecution\Domain\Contract\Chain\ExecutionStrategyInterface']; + yield 'nested ValueObject class without Vo suffix' => ['Task\Common\Module\Source\Domain\ValueObject\SourceVariant\CanonicalProfileParametersInterface']; + } + + /** @return iterable */ + public static function provideAllowed(): iterable + { + yield 'interface directly in Domain root' => ['TaskOrchestrator\Common\Module\ChainDefinition\Domain\ChainDefinitionInterface']; + yield 'entity' => ['Task\Common\Module\Billing\Domain\Entity\PaymentModel']; + yield 'service' => ['Task\Common\Module\Billing\Domain\Service\Pay\PayService']; + yield 'repository' => ['Task\Common\Module\Billing\Domain\Repository\Payment\PaymentRepository']; + yield 'value object' => ['Task\Common\Module\Billing\Domain\ValueObject\MoneyVo']; + yield 'enum' => ['Task\Common\Module\Billing\Domain\Enum\StatusEnum']; + yield 'exception' => ['Task\Common\Module\Billing\Domain\Exception\InvalidAmountException']; + yield 'specification' => ['Task\Common\Module\Billing\Domain\Specification\OverdueSpecification']; + yield 'calculator' => ['Stocks2\Common\Module\Trading\Domain\Calculator\RateCalculator']; + yield 'mapper' => ['Stocks2\Common\Module\Moex\Domain\Mapper\RateMapper']; + yield 'strategy' => ['Task\Common\Module\Attribution\Domain\Strategy\AttributionStrategyInterface']; + yield 'helper' => ['TaskOrchestrator\Common\Module\DynamicLoop\Domain\Helper\LoopHelper']; + yield 'factory' => ['Task\Common\Module\Billing\Domain\Factory\PaymentCreateFactory']; + yield 'not a domain class' => ['Task\Common\Module\Billing\Application\Service\PayService']; + } +} diff --git a/tests/Deptrac/PolymorphismDependencyRuleTest.php b/tests/Deptrac/PolymorphismDependencyRuleTest.php new file mode 100644 index 00000000..cfba5afd --- /dev/null +++ b/tests/Deptrac/PolymorphismDependencyRuleTest.php @@ -0,0 +1,107 @@ +runRule([$this->violation($type, $depender, $dependent, $dependentLayer)]); + + self::assertSame([], $kept); + } + + #[DataProvider('provideKept')] + public function testKeepsRealCoupling(DependencyType $type, string $depender, string $dependent, string $dependentLayer): void + { + $violation = $this->violation($type, $depender, $dependent, $dependentLayer); + + self::assertSame([$violation], $this->runRule([$violation])); + } + + public function testKeepsCommandAsReturnValueAndNew(): void + { + $asReturn = $this->violation(DependencyType::RETURN_TYPE, self::SERVICE, self::COMMAND, 'ApplicationCommand'); + $asNew = $this->violation(DependencyType::NEW, self::SERVICE, self::COMMAND, 'ApplicationCommand'); + + self::assertSame([$asReturn, $asNew], $this->runRule([$asReturn, $asNew])); + } + + /** @return iterable */ + public static function provideRemoved(): iterable + { + yield 'VO implements a domain interface' => [DependencyType::INHERIT, self::DEPENDER, self::CONTRACT, 'DomainContract']; + yield 'strategy receives the command as a parameter' => [DependencyType::PARAMETER, self::SERVICE, self::COMMAND, 'ApplicationCommand']; + yield 'strategy receives the query as a parameter' => [DependencyType::PARAMETER, self::SERVICE, self::COMMAND . 'Query', 'ApplicationQuery']; + } + + /** @return iterable */ + public static function provideKept(): iterable + { + yield 'VO calls a domain service (parameter)' => [DependencyType::PARAMETER, self::DEPENDER, 'Task\Common\Module\X\Domain\Service\YService', 'DomainContract']; + yield 'service throws a domain exception' => [DependencyType::THROW, self::SERVICE, 'Task\Common\Module\X\Domain\Exception\YException', 'DomainException']; + yield 'service instantiates a domain contract' => [DependencyType::NEW, self::SERVICE, self::CONTRACT, 'DomainContract']; + yield 'service instantiates a command (dispatch)' => [DependencyType::NEW, self::SERVICE, self::COMMAND, 'ApplicationCommand']; + yield 'command passed as parameter to a non-data layer' => [DependencyType::PARAMETER, self::SERVICE, self::COMMAND, 'Domain']; + } + + /** + * @param list $violations + * + * @return list + */ + private function runRule(array $violations): array + { + $result = new AnalysisResult(); + foreach ($violations as $violation) { + $result->addRule($violation); + } + + (new PolymorphismDependencyRule())->onPostProcessEvent(new PostProcessEvent($result)); + + $kept = []; + foreach ($result->rules() as $violations) { + foreach ($violations as $violation) { + $kept[] = $violation; + } + } + + return $kept; + } + + private function violation(DependencyType $type, string $depender, string $dependent, string $dependentLayer): Violation + { + return new Violation( + new Dependency( + ClassLikeToken::fromFQCN($depender), + ClassLikeToken::fromFQCN($dependent), + new DependencyContext(new FileOccurrence('/tmp/test.php', 10), $type), + ), + 'SourceLayer', + $dependentLayer, + $this->createStub(ViolationCreatingInterface::class), + ); + } +} diff --git a/todo/done/TASK-feat-deptrac-embeddable-layer.todo.md b/todo/done/TASK-feat-deptrac-embeddable-layer.todo.md new file mode 100644 index 00000000..35c149fc --- /dev/null +++ b/todo/done/TASK-feat-deptrac-embeddable-layer.todo.md @@ -0,0 +1,111 @@ +--- +type: feat +created: 2026-11-25 05:56:08 (1795586168) +due: +started: 2026-11-25 05:56:08 (1795586168) +completed: 2026-11-25 10:03:40 (1795601020) +cancelled: +value: V3 +complexity: C3 +priority: P1 +cost_plan: +cost_fact: +depends_on: +epic: +author: Лид Арагорн (pi) +assignee: Лид Арагорн (pi) +consultants: [] +reviewer: +approver: +informed: [] +branch: task/deptrac-embeddable-layer +pr: https://github.com/prikotov/coding-standard/pull/139 +status: done +--- + +# TASK-feat-deptrac-embeddable-layer: Deptrac: выделить Embeddable VO в слой DomainEmbeddable и изолировать от Application/Presentation + +## 0. Простое описание (Human Brief) + +### Проблема простыми словами (Problem) +- Embeddable VO (`Domain\Entity\ValueObject\*Vo`) — persistence-часть сущности (конвенция [Entity](../../docs/conventions/layers/domain/entity.md)), но в поставляемом depfile они попадали в общий слой `DomainVo` через regex `Domain\(Entity\\)?ValueObject\\…` и были доступны везде, где `DomainVo`. В TasK 4 Embeddable утекли в **25+ файлов**: Application-сервисы и их интерфейсы, мапперы, CommandHandler, Domain Strategy. +- Сниффер ловит только типы **свойств** VO; утечка идёт через параметры/возвраты/контракты — нужен архитектурный gate. +- ❗ При реализации вскрылась **вторая, более крупная дыра**: `Application: [+ApplicationCommandHandler]`. В Deptrac 4 `+Layer` — **транзитивное замыкание**: весь Application-слой наследовал все зависимости handler'ов (`Domain`, `DomainEnum`, `DomainVo`, `Presentation`…). Поэтому violation'ы на `Application → Domain` не выдавались вообще, а слой `Domain` в ruleset для `Application` был прописан пустым (`Application: [Application]`) — всё держалось на `+`. В TasK это скрывало 82 прямые зависимости мапперов/сервисов на сущности. + +### Варианты или путь решения (Solution Sketch) +- Embeddable → отдельный слой `DomainEmbeddable`, изолированный как сущности: доступен `Domain` (сущность владеет своей частью) и тем, кто работает с сущностями через `Domain`; запрещён `DomainVo`, handler'ам, Application, Presentation. +- Убрать `+` у handler'ов; правила `Application` прописать явно: DTO/Enum/VO/Specification своего и Domain-слоёв + **доменные контракты** (новый слой `DomainContract` — интерфейсы `Domain\Service\…Interface`, `Repository`, `Strategy`, `Provider`, `Criteria`, `Helper`), **без** `Domain\Entity` (сущности — только через handler'ы/репозитории). +- Закрепить **семантику** ruleset регрессионным тестом, запускающим реальный deptrac на генерируемых фикстурах (regex-тесты это не ловят). + +### Ожидаемый результат (Expected Result) +- На TasK: все утечки Embeddable и прямые зависимости Application на сущности видны как violations; ложных нет; базовые сценарии (handler работает с сущностью, сущность владеет Embeddable, сервис вызывает доменный интерфейс) — чисто. + +## 1. Концепция и Цель (Concept and Goal) + +### История (User Story) +> Как архитектор, я хочу, чтобы deptrac реально изолировал persistence-типы (сущности, Embeddable) от Application/Presentation, чтобы gate не был дырявым, а конвенция Entity/VO — проверяемой. + +### Цель по SMART (Goal) +- К ближайшему релизу: слой `DomainEmbeddable` выделен; `+` в ruleset не используется; правила Application явные; семантика закреплена тестом на реальном deptrac; на TasK остаются только истинные нарушения. + +## 2. Контекст и Границы (Context and Scope) + +- **Где делаем:** `config/deptrac/depfile.yaml` (слои `DomainEmbeddable`, `DomainContract`; `Domain` must_not; ruleset `Application`, handler'ы, все, кто видел `Domain`); `tests/Deptrac/DepfileRulesetSemanticsTest.php` (новый). +- **Аудит на TasK (2026-11-25, deptrac 4.7.2, кэш очищен):** базeline 0 violations (из-за `+`); после: 151, из них 82 — Application Mapper/Service/Factory → `Entity\*Model` (истинные), 36 — утечки Embeddable, 11 — сервис диспатчит `ApplicationCommand` напрямую, 2 — `DomainVo → DomainContract`. Ложных нет. +- **Границы (Out of Scope):** рефакторинг утечек в TasK (TasK#3221 + отдельные задачи); поведение `imports` (пути импортированного depfile резолвятся относительно импортирующего файла, а `paths` суммируются — задокументировано в тесте). + +## 3. Требования, MoSCoW (Requirements) +### 🔴 Обязательно (Must Have) +- [x] Слой `DomainEmbeddable` (`Domain\Entity\ValueObject\…Vo`); исключён из `Domain` и `DomainVo`. +- [x] `DomainEmbeddable` доступна `Domain` (сущность владеет), запрещена `DomainVo`, handler'ам, `Application`, `Presentation`. +- [x] `+Layer` не используется в ruleset; правила `Application` прописаны явно. +- [x] Слой `DomainContract` (доменные интерфейсы без `*Model`/`*Entity`) разрешён `Application`, handler'ам, `Domain`, `Integration`; запрещён VO/DTO/Specification. +- [x] Регрессионный тест на реальном deptrac: Embeddable/Entity/Contract сценарии. +- [x] `composer check` зелёный. + +### ⚫ Won't Have (Не будем делать) +- Изменения в TasK; смягчение правил через `skip_violations` в поставляемом depfile. + +## 4. План реализации (Implementation Plan) +1. [x] Воспроизвести: reproducer внутри пакета (фикстуры вне `tests/` — depfile исключает `#.*tests.*#`). +2. [x] Выделить `DomainEmbeddable`, убрать `\(Entity\\)?` из `DomainVo`. +3. [x] Найти причину пропуска `Application → Domain`: транзитивное замыкание `+ApplicationCommandHandler` (`vendor/deptrac/…/LayerProvider.php:44`). +4. [x] Убрать `+`, прописать `Application` явно; ввести `DomainContract`. +5. [x] Тест `DepfileRulesetSemanticsTest` (реальный deptrac, json-formatter, фикстуры в tempdir, `cache_file` в tempdir). +6. [x] Прогон на TasK с чистым кэшем — разбор 151 нарушения, все истинные. + +**Заметки по реализации:** +- Reproducer в TasK не сработал (TasK#3221): причина была не в окружении, а в `+`. Первые прогоны на фикстурах в `tests/fixtures/` давали 0/0 из-за `exclude_files: '#.*tests.*#'` — фикстуры теста живут в `sys_get_temp_dir()`. +- Deptrac кладёт токен во **все** матчящиеся слои; violation считается по каждому. Поэтому `DomainContract` исключён из `Domain` (`must_not`), а классы с суффиксами `*Model`/`*Entity` — из `DomainContract`. +- Имена фикстур должны соответствовать конвенции (`*CommandHandler$`), иначе класс не попадает в слой handler'а. +- Зависит от PR #138 (обновление зависимостей): на PHPUnit 13 старые `@dataProvider` в Deptrac-тестах падают — там уже починено. + +## 5. Критерии приёмки (Definition of Done) +- [x] Reproducer-тесты зелёные на новом depfile и **красные** на depfile из master (проверено: 4 failures). +- [x] На TasK все утечки Embeddable видны; ложных нет. +- [x] `composer check` зелёный (после rebase на #138). + +## 6. Самопроверка (Verification) +```bash +composer check +vendor/bin/phpunit tests/Deptrac/DepfileRulesetSemanticsTest.php +``` + +## 7. Риски и зависимости (Risks and Dependencies) +- **BREAKING для потребителей:** после обновления `make deptrac` покажет ранее скрытые нарушения (TasK: ~151). Это ожидаемый эффект — gate стал честным. Освободить команды заранее. +- `ApplicationCommand`/`ApplicationQuery` прямо из Application-сервисов (TasK: 11) — теперь нарушение; если команда считает это допустимым, расширить правила осознанно. +- Зависит от #138; связана с TasK#3221 (задача в потребителе создана до нахождения причины — закрыть как устранённую). + +## 8. Источники (Sources) +- [Entity](../../docs/conventions/layers/domain/entity.md) — Embeddable как часть сущности; [Value Object](../../docs/conventions/core-patterns/value-object.md). +- Deptrac 4: `LayerProvider::getTransitiveDependencies` — семантика `+Layer`. +- Аудит: `~/MyProjects/TasK/Development`, `vendor/bin/deptrac analyse --config-file=depfile.yaml` с подменённым vendor-depfile. + +## 9. Комментарии (Comments) +- Задача выросла из запланированного «добавить слой»: главный результат — найденная и устранённая дыра `+` в ruleset, из-за которой gate молчал для Application. + +## История изменений (Change History) +| Дата | Автор (роль) | Изменение | +| :--- | :--- | :--- | +| 2026-11-25 05:56:08 (1795586168) | Лид Арагорн (pi) | Создание задачи, взятие в работу (pi) | +| 2026-11-25 13:33:48 (1795588428) | Лид Арагорн (pi) | Реализация: слой DomainEmbeddable; найдена и устранена дыра `+` (транзитивное замыкание) — правила Application прописаны явно, введён DomainContract; тест на реальном deptrac; TasK 0 → 151 (все истинные) |