Skip to content

refactor: enhance input validation, console traits and repository methods - #41

Merged
loadinglucian merged 5 commits into
mainfrom
refactor/server-commands-validation
Oct 12, 2025
Merged

refactor: enhance input validation, console traits and repository methods#41
loadinglucian merged 5 commits into
mainfrom
refactor/server-commands-validation

Conversation

@loadinglucian

@loadinglucian loadinglucian commented Oct 12, 2025

Copy link
Copy Markdown
Owner
  • Include remaining test updates for ServerRepository
  • Ensure full test coverage for recent refactoring changes

Summary by CodeRabbit

  • New Features

    • Interactive prompts now support inline validation for name, host, and port; CLI-provided values are validated too.
    • Prevents adding servers when a host is already in use, with clear conflict messaging.
  • Refactor

    • Server-add flow fails early on missing/invalid inputs and returns consistent failure codes.
    • Validation now returns readable error messages and surface-friendly indicators instead of thrown exceptions.
  • Tests

    • Added coverage for validated prompts, duplicate-host handling, host lookups, and exit-code/output assertions.

- Add getValidatedOptionOrPrompt to ConsoleInputTrait for seamless option/prompt validation
- Update ServerValidationTrait with improved validation methods
- Enhance ServerAddCommand with new validation patterns
- Add comprehensive tests for validation traits and input handling
- Update documentation in rules for new patterns
- Enhance ServerRepository with better data handling
- Update corresponding unit tests for new repository behavior
- Fix validation trait updates in tests
- Include remaining test updates for ServerRepository
- Ensure full test coverage for recent refactoring changes
@coderabbitai

coderabbitai Bot commented Oct 12, 2025

Copy link
Copy Markdown
Contributor

Caution

Review failed

The pull request is closed.

Walkthrough

Adds getValidatedOptionOrPrompt for validated interactive prompts, applies it in ServerAddCommand, adds findByHost and host-duplication checks to ServerRepository, converts validators to return error strings, tweaks ServerHelpersTrait signature, and updates tests to assert exit codes/output and cover new validation flows.

Changes

Cohort / File(s) Summary
Console input validation
app/Traits/ConsoleInputTrait.php
Adds protected getValidatedOptionOrPrompt(string $optionName, Closure $promptCallback, Closure $validator): mixed to validate CLI-provided values, inject a validator into interactive prompts, return null and emit an error on validation failure.
Server add command validation flow
app/Console/Server/ServerAddCommand.php
Replaces getOptionOrPrompt with getValidatedOptionOrPrompt for name, host, and port; introduces inline validator callbacks, uses validateNameInput/validateHostInput/validatePortInput, and early-fails when required inputs are missing/invalid.
Server repository host check
app/Repositories/ServerRepository.php
Adds public findByHost(string $host): ?ServerDTO and updates create() to prevent duplicate hosts (throws RuntimeException referencing conflicting server name).
Server input validators
app/Traits/ServerValidationTrait.php
Replaces exception-throwing validators with validateNameInput(mixed): ?string, validateHostInput(mixed): ?string, validatePortInput(mixed): ?string that return error messages or null and perform type/format/uniqueness checks.
Server helper signature tidy
app/Traits/ServerHelpersTrait.php
Updates selectServer signature to protected function selectServer(string $optionName = 'server', string $promptLabel = 'Select server:'): array and reintroduces displayServerDeets(ServerDTO $server): void.
Tests: console input & fixture
tests/Unit/Traits/ConsoleInputTraitTest.php, tests/Fixtures/TestConsoleCommand.php
Adds tests for getValidatedOptionOrPrompt (valid/invalid/empty CLI options, validator injection into prompt) and fixture test cases exercising valid/invalid prompt flows.
Tests: server add integration
tests/Integration/Console/Server/ServerAddCommandTest.php
Converts exception-based assertions to exit-code/output assertions (Command::FAILURE), adds duplicate-host integration test, and updates validation-output expectations.
Tests: repository
tests/Unit/Repositories/ServerRepositoryTest.php
Adds tests for findByHost and duplicate-host prevention in create().
Tests: server validation
tests/Unit/Traits/ServerValidationTraitTest.php
Renames and reworks test wrappers to exercise validateNameInput, validateHostInput, validatePortInput; adjusts expectations to returned error strings and adds fixture wiring.
Docs / rules
.cursor/rules/03-commands.mdc, .cursor/rules/02-tests.mdc
Adds documentation/rule notes about validated prompting and minor test-assertion snippet changes.

Sequence Diagram(s)

sequenceDiagram
  autonumber
  actor User
  participant Cmd as ServerAddCommand
  participant CIT as ConsoleInputTrait
  participant Prompt as Prompter
  participant Val as ServerValidationTrait
  participant Repo as ServerRepository

  User->>Cmd: run add server
  Cmd->>CIT: getValidatedOptionOrPrompt(option, promptCb, validator)
  alt CLI option provided
    CIT->>Val: validator(optionValue)
    alt valid
      CIT-->>Cmd: value
    else invalid
      CIT-->>Cmd: null (emit error)
    end
  else no CLI option
    CIT->>Prompt: promptCb(validator)
    Prompt-->>CIT: userInput (validated interactively)
    CIT-->>Cmd: userInput
  end
  Cmd->>Val: validateNameInput(name)
  alt name invalid
    Cmd-->>User: FAILURE (message)
  else
    Cmd->>Val: validateHostInput(host)
    alt host invalid
      Cmd-->>User: FAILURE (message)
    else
      Cmd->>Val: validatePortInput(port)
      alt port invalid
        Cmd-->>User: FAILURE (message)
      else
        Cmd->>Repo: findByHost(host)
        alt host exists
          Repo-->>Cmd: existing ServerDTO
          Cmd-->>User: FAILURE (host already used)
        else
          Cmd->>Repo: create(...)
          Repo-->>Cmd: ServerDTO
          Cmd-->>User: SUCCESS (details)
        end
      end
    end
  end
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~60 minutes

Possibly related PRs

  • bigpixelrocket/deployer-php#26 — Extends ConsoleInputTrait prompting; likely the PR that introduced or nearby changes to validated prompting integration.
  • bigpixelrocket/deployer-php#35 — Modifies ServerHelpersTrait (select/display server changes); overlaps with signature and helper adjustments here.
  • bigpixelrocket/deployer-php#25 — Prior ServerRepository work; this PR adds host-based lookup and duplicate-host checks building on repository patterns.

Poem

I tap my paw on the terminal bright,
Validators hop in to guard each byte.
Hosts no longer duel, names stand apart,
Ports checked and tidy — tidy art.
Tests pass, I thump — a happy heart. 🐰✨

Pre-merge checks and finishing touches

✅ Passed checks (3 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title Check ✅ Passed The pull request title succinctly captures the main refactoring objectives by highlighting enhanced input validation, updates to console traits, and modifications to repository methods, which align with the changes made across multiple files. It clearly reflects the core areas of work without unnecessary detail or noise, making it easy for reviewers to understand the purpose at a glance. Therefore, it meets the criteria for a concise and descriptive title.
Docstring Coverage ✅ Passed Docstring coverage is 100.00% which is sufficient. The required threshold is 80.00%.

📜 Recent review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 8f7e5d4 and f47c4e6.

📒 Files selected for processing (1)
  • app/Traits/ServerHelpersTrait.php (3 hunks)

Comment @coderabbitai help to get the list of available commands and usage tips.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 7

🧹 Nitpick comments (9)
tests/Fixtures/TestConsoleCommand.php (1)

178-209: Silence unused-parameter warning in invalid validator

Rename the unused parameter to signal intent and appease PHPMD.

Based on static analysis hints

-            fn ($value) => 'Always invalid'
+            fn ($_value) => 'Always invalid'
app/Repositories/ServerRepository.php (1)

52-61: Host uniqueness check added; confirm desired uniqueness scope and import RuntimeException

  • Behavior: disallows duplicate hosts regardless of port. Is the intent to uniquely constrain by host only, or host+port? Please confirm.
  • Style: avoid FQCN; import RuntimeException and use it directly.

As per coding guidelines

Apply within this range:

-        if (null !== $existingName) {
-            throw new \RuntimeException("Server '{$server->name}' already exists");
+        if (null !== $existingName) {
+            throw new RuntimeException("Server '{$server->name}' already exists");
         }
@@
-        if (null !== $existingHost) {
-            throw new \RuntimeException("Host '{$server->host}' is already used by server '{$existingHost->name}'");
+        if (null !== $existingHost) {
+            throw new RuntimeException("Host '{$server->host}' is already used by server '{$existingHost->name}'");
         }

And add import at the top (outside this range):

use RuntimeException;
app/Traits/ServerHelpersTrait.php (1)

59-66: Use repository lookup instead of manual loop

Replace the loop with servers->findByName() for clarity and reuse.

-        $server = null;
-        foreach ($allServers as $s) {
-            if ($s->name === $name) {
-                $server = $s;
-                break;
-            }
-        }
+        $server = $this->servers->findByName($name);
app/Traits/ServerValidationTrait.php (2)

42-63: Host validation: consider localhost and case normalization

  • format: FILTER_VALIDATE_DOMAIN(FILTER_FLAG_HOSTNAME) rejects 'localhost'. Do we want to accept 'localhost'?
  • uniqueness: should host comparisons be case-insensitive for domains?

If desired, you can allow localhost cheaply:

-        $isValidIp = filter_var($host, FILTER_VALIDATE_IP) !== false;
-        $isValidDomain = filter_var($host, FILTER_VALIDATE_DOMAIN, FILTER_FLAG_HOSTNAME) !== false;
+        $isValidIp = filter_var($host, FILTER_VALIDATE_IP) !== false;
+        $isValidDomain = filter_var($host, FILTER_VALIDATE_DOMAIN, FILTER_FLAG_HOSTNAME) !== false;
+        $isLocalhost = strtolower($host) === 'localhost';
@@
-        if (!$isValidIp && !$isValidDomain) {
+        if (!$isValidIp && !$isValidDomain && !$isLocalhost) {
             return 'Must be a valid IP address or domain name (e.g., 192.168.1.100, example.com)';
         }

70-86: Accept int or string for port; use union type and simpler checks

Prompts return strings, but options/callers may pass ints. Support both and keep messages stable.

As per coding guidelines

-    protected function validatePortInput(mixed $portString): ?string
+    protected function validatePortInput(string|int $port): ?string
     {
-        if (!is_string($portString)) {
-            return 'Port must be a string';
-        }
-
-        if (!ctype_digit($portString)) {
-            return 'Port must be a number';
-        }
-
-        $port = (int) $portString;
+        if (is_string($port)) {
+            if (!ctype_digit($port)) {
+                return 'Port must be a number';
+            }
+            $port = (int) $port;
+        }
         if ($port < 1 || $port > 65535) {
             return 'Port must be between 1 and 65535 (common SSH ports: 22, 2222, 22000)';
         }
 
         return null;
     }
tests/Unit/Traits/ConsoleInputTraitTest.php (1)

188-203: Clarify intent of “non-interactive” wording (optional)

This test exercises the prompt path; “non-interactive mode” could be misread. Consider renaming to “validator is passed to prompt callback when prompting,” or extend MockPrompter to assert the validate callable was received.

.cursor/rules/03-commands.mdc (1)

298-436: Great validation pattern; add two clarifications

  • Note that getValidatedOptionOrPrompt is intended for VALUE_REQUIRED data options, not boolean flags.
  • Add a brief generics note: it returns T|null, where T is the prompt’s return type.

Example insert:

+Note:
+- Use getValidatedOptionOrPrompt only with VALUE_REQUIRED data options (e.g., --name, --host, --port).
+- For boolean flags (VALUE_NONE), continue using getOptionOrPrompt.
+
+Types:
+- Conceptually returns T|null where T is the prompt’s return type (string/int/etc.). Document this in phpdoc for better static analysis.
app/Traits/ConsoleInputTrait.php (1)

101-149: Logic LGTM; document scope and add phpdoc generics

  • Intended for VALUE_REQUIRED options; avoid using on boolean flags (VALUE_NONE). Add this to phpdoc.
  • Improve phpdoc typing to mirror getOptionOrPrompt: declare template T and return T|null for better static analysis.

Suggested phpdoc tweak:

- * @param Closure(Closure): mixed $promptCallback ...
- * @return mixed The validated value, or null if validation failed
+ * @template T
+ * @param Closure(callable(mixed): (?string)): T $promptCallback Closure receiving the validator and returning T
+ * @param Closure(mixed): (?string) $validator Validation closure that returns error or null
+ * @return T|null The validated value, or null if validation failed
+ *
+ * Note: Use only with VALUE_REQUIRED options (data inputs), not boolean flags.

As per coding guidelines

tests/Integration/Console/Server/ServerAddCommandTest.php (1)

179-197: Invalid port scenario covered; consider more robust regex

Pattern '/Port must be|between 1 and 65535/' works but could be clearer:

- ->toMatch('/Port must be|between 1 and 65535/')
+ ->toMatch('/(Port must be|between 1 and 65535)/')
+ // or assert the full canonical message if stable:
+ // ->toContain('Port must be between 1 and 65535')
📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between bfde1ce and 1559435.

📒 Files selected for processing (11)
  • .cursor/rules/03-commands.mdc (2 hunks)
  • app/Console/Server/ServerAddCommand.php (1 hunks)
  • app/Repositories/ServerRepository.php (2 hunks)
  • app/Traits/ConsoleInputTrait.php (1 hunks)
  • app/Traits/ServerHelpersTrait.php (2 hunks)
  • app/Traits/ServerValidationTrait.php (1 hunks)
  • tests/Fixtures/TestConsoleCommand.php (2 hunks)
  • tests/Integration/Console/Server/ServerAddCommandTest.php (3 hunks)
  • tests/Unit/Repositories/ServerRepositoryTest.php (2 hunks)
  • tests/Unit/Traits/ConsoleInputTraitTest.php (1 hunks)
  • tests/Unit/Traits/ServerValidationTraitTest.php (3 hunks)
🧰 Additional context used
📓 Path-based instructions (8)
**/*.php

📄 CodeRabbit inference engine (.cursor/rules/00-main.mdc)

**/*.php: Eliminate single-use private methods by inlining them directly
Cache expensive computed values by initializing them in the constructor instead of recomputing
Prefer direct property access over method calls when appropriate to avoid call overhead
Organize code into comment-separated sections; prefer alphabetical ordering when it does not conflict with logical grouping

**/*.php: Adhere to PSR-12 coding style in all PHP files
Declare strict_types=1 at the top of every PHP file
Prefer PHP 8.x features (union types, match, attributes, readonly) where appropriate
Always import classes with use statements; avoid fully qualified class names in code bodies
All methods must declare explicit return types; use proper generics in types/docblocks (e.g., Collection<int, User>)
Use dependency injection instead of manually resolving or instantiating classes
Prefer Symfony component classes (e.g., Filesystem, Process) over native PHP functions for testability
All object creation must use $container->build(ClassName::class) instead of new, except for value objects/DTOs/pure data structures
In production code, access the Container via constructor injection, not via static/global access
Add minimal DocBlock comments with descriptions, parameters, and return types for classes and functions
Use comments as visual separators for sections/subsections with a single newline between header, subheader, and paragraph; avoid obvious or stale comments
Run rector on changed PHP files before completing a task
Run pint on changed PHP files to fix code style before completing a task

Files:

  • app/Repositories/ServerRepository.php
  • app/Traits/ConsoleInputTrait.php
  • app/Console/Server/ServerAddCommand.php
  • tests/Unit/Repositories/ServerRepositoryTest.php
  • app/Traits/ServerValidationTrait.php
  • tests/Integration/Console/Server/ServerAddCommandTest.php
  • tests/Unit/Traits/ConsoleInputTraitTest.php
  • app/Traits/ServerHelpersTrait.php
  • tests/Fixtures/TestConsoleCommand.php
  • tests/Unit/Traits/ServerValidationTraitTest.php
app/{Contracts/BaseCommand.php,Traits/ConsoleOutputTrait.php,Traits/ConsoleInputTrait.php}

📄 CodeRabbit inference engine (.cursor/rules/03-commands.mdc)

If output functionality is missing, add a new method to BaseCommand (and the appropriate Console*Trait) with modern styling and documentation

Files:

  • app/Traits/ConsoleInputTrait.php
app/{Console/**,Traits/ConsoleInputTrait.php}

📄 CodeRabbit inference engine (.cursor/rules/03-commands.mdc)

Use laravel/prompts for all user interactions (text, password, confirm, select, multiselect, suggest, search, spin)

Files:

  • app/Traits/ConsoleInputTrait.php
  • app/Console/Server/ServerAddCommand.php
app/Traits/ConsoleInputTrait.php

📄 CodeRabbit inference engine (.cursor/rules/03-commands.mdc)

Add input gathering methods to ConsoleInputTrait; methods should work with $this->input and wrap Laravel Prompts

Files:

  • app/Traits/ConsoleInputTrait.php
**/*Command.php

📄 CodeRabbit inference engine (.cursor/rules/01-architecture.mdc)

**/*Command.php: Commands handle user interaction (input/output) and orchestrate services
Commands must not contain business logic; delegate business logic to Services
Commands must not duplicate orchestration logic; extract shared orchestration to Services
Commands should not invoke other commands (no proxy commands)
Use SymfonyStyle consistently for all user-facing console output

Files:

  • app/Console/Server/ServerAddCommand.php
  • tests/Fixtures/TestConsoleCommand.php
app/Console/**/*.php

📄 CodeRabbit inference engine (.cursor/rules/03-commands.mdc)

app/Console/**/*.php: Never use Symfony IO methods directly in console commands; use BaseCommand custom IO methods (writeln, hr, h1, info, success, error, warning) exclusively
Use status helper methods (success, error, warning, info) for all status messages to ensure consistent formatting
Commands handle all user interaction (input/output) and format output; validation errors bubble up to commands for display
Support both interactive prompts and CLI options using getOptionOrPrompt(optionName, promptCallback) for dual-mode commands
Use only options, never arguments, in commands (to enable getOptionOrPrompt)
Pair every option with getOptionOrPrompt to provide interactive fallbacks
Boolean flags must use InputOption::VALUE_NONE
Data input options must use InputOption::VALUE_REQUIRED
Only the --yes option gets a short flag (-y)
Use standardized option names: --server, --site, --name, --host, --port, --yes/-y, --skip per their specified types and usages
Always call showCommandHint() before returning Command::SUCCESS to teach non-interactive usage
Do not access $this->io->writeln/text/success/etc. directly in commands; route all output through BaseCommand helpers

Files:

  • app/Console/Server/ServerAddCommand.php
{tests/**,test/**,**/*@(Test|Spec).php}

📄 CodeRabbit inference engine (.cursor/rules/00-main.mdc)

Do not run or edit tests unless explicitly instructed

Files:

  • tests/Unit/Repositories/ServerRepositoryTest.php
  • tests/Integration/Console/Server/ServerAddCommandTest.php
  • tests/Unit/Traits/ConsoleInputTraitTest.php
  • tests/Fixtures/TestConsoleCommand.php
  • tests/Unit/Traits/ServerValidationTraitTest.php
tests/**/*.php

📄 CodeRabbit inference engine (.cursor/rules/01-architecture.mdc)

tests/**/*.php: In tests, direct Container instantiation and bind() for mocks is allowed and encouraged for isolation
Do not run PHPStan on test files; tests are excluded from static analysis

tests/**/*.php: Unit tests must instantiate services manually (no DI container)
Command/integration tests must use mockCommandContainer() for building commands and overriding services
Only use container auto-wiring in tests to verify DI configuration or multi-service integration (edge cases)
Keep test files under 1.8x the size of the source they test (without sacrificing readability)
Test core business logic; avoid testing the framework itself
Prefer dataset-driven testing using ->with([...]) for multiple scenarios
Consolidate related assertions (e.g., expect($x)->toBe(...)->and($y)->toBe(...))
Mock only external dependencies; keep unit tests isolated from filesystem/HTTP/processes
Avoid performance tests unless performance is the primary concern
Use the AAA pattern in tests (Arrange, Act, Assert; optional Cleanup)
In exception tests, use a combined // ACT & ASSERT step when the act triggers the assertion
Organize tests with describe() blocks, beforeEach() setup, and shared helpers/traits for DRY
Forbidden assertions in tests: type-only or generic checks (e.g., toBeInstanceOf, toBeArray, not->toBeNull, expect(true)->toBeTrue) and sleep(...); prefer time mocking
Preferred assertions: assert observable behavior and interactions (e.g., domain values, validator outcomes, mock expectations)
Unit tests: mock all external dependencies, test single units in isolation, and complete in milliseconds
Integration tests: use real file operations and external processes; cover CLI commands and full workflows
Do not require PHPStan compliance in tests; avoid excessive phpdoc solely to satisfy types in tests

Files:

  • tests/Unit/Repositories/ServerRepositoryTest.php
  • tests/Integration/Console/Server/ServerAddCommandTest.php
  • tests/Unit/Traits/ConsoleInputTraitTest.php
  • tests/Fixtures/TestConsoleCommand.php
  • tests/Unit/Traits/ServerValidationTraitTest.php
🧠 Learnings (7)
📚 Learning: 2025-10-11T15:19:19.495Z
Learnt from: CR
PR: bigpixelrocket/deployer-php#0
File: .cursor/rules/03-commands.mdc:0-0
Timestamp: 2025-10-11T15:19:19.495Z
Learning: Applies to app/Console/**/*.php : Support both interactive prompts and CLI options using getOptionOrPrompt(optionName, promptCallback) for dual-mode commands

Applied to files:

  • app/Traits/ConsoleInputTrait.php
  • tests/Unit/Traits/ConsoleInputTraitTest.php
📚 Learning: 2025-10-11T15:19:19.496Z
Learnt from: CR
PR: bigpixelrocket/deployer-php#0
File: .cursor/rules/03-commands.mdc:0-0
Timestamp: 2025-10-11T15:19:19.496Z
Learning: Applies to app/Traits/ConsoleInputTrait.php : Add input gathering methods to ConsoleInputTrait; methods should work with $this->input and wrap Laravel Prompts

Applied to files:

  • app/Traits/ConsoleInputTrait.php
  • .cursor/rules/03-commands.mdc
📚 Learning: 2025-10-11T15:19:19.495Z
Learnt from: CR
PR: bigpixelrocket/deployer-php#0
File: .cursor/rules/03-commands.mdc:0-0
Timestamp: 2025-10-11T15:19:19.495Z
Learning: Applies to app/Console/**/*.php : Pair every option with getOptionOrPrompt to provide interactive fallbacks

Applied to files:

  • app/Traits/ConsoleInputTrait.php
  • tests/Unit/Traits/ConsoleInputTraitTest.php
  • .cursor/rules/03-commands.mdc
📚 Learning: 2025-10-11T15:19:19.495Z
Learnt from: CR
PR: bigpixelrocket/deployer-php#0
File: .cursor/rules/03-commands.mdc:0-0
Timestamp: 2025-10-11T15:19:19.495Z
Learning: Applies to app/{Console/**,Traits/ConsoleInputTrait.php} : Use laravel/prompts for all user interactions (text, password, confirm, select, multiselect, suggest, search, spin)

Applied to files:

  • app/Traits/ConsoleInputTrait.php
  • .cursor/rules/03-commands.mdc
📚 Learning: 2025-10-11T15:19:19.495Z
Learnt from: CR
PR: bigpixelrocket/deployer-php#0
File: .cursor/rules/03-commands.mdc:0-0
Timestamp: 2025-10-11T15:19:19.495Z
Learning: Applies to app/{Contracts/BaseCommand.php,Traits/ConsoleOutputTrait.php,Traits/ConsoleInputTrait.php} : If output functionality is missing, add a new method to BaseCommand (and the appropriate Console*Trait) with modern styling and documentation

Applied to files:

  • .cursor/rules/03-commands.mdc
📚 Learning: 2025-10-11T15:19:19.496Z
Learnt from: CR
PR: bigpixelrocket/deployer-php#0
File: .cursor/rules/03-commands.mdc:0-0
Timestamp: 2025-10-11T15:19:19.496Z
Learning: Applies to app/Traits/ConsoleOutputTrait.php : Add output/formatting methods to ConsoleOutputTrait; methods should work with $this->io (SymfonyStyle)

Applied to files:

  • .cursor/rules/03-commands.mdc
📚 Learning: 2025-10-11T15:19:19.495Z
Learnt from: CR
PR: bigpixelrocket/deployer-php#0
File: .cursor/rules/03-commands.mdc:0-0
Timestamp: 2025-10-11T15:19:19.495Z
Learning: Applies to app/Console/**/*.php : Use status helper methods (success, error, warning, info) for all status messages to ensure consistent formatting

Applied to files:

  • .cursor/rules/03-commands.mdc
🧬 Code graph analysis (10)
app/Repositories/ServerRepository.php (1)
app/DTOs/ServerDTO.php (1)
  • ServerDTO (7-17)
app/Traits/ConsoleInputTrait.php (1)
app/Traits/ConsoleOutputTrait.php (1)
  • error (62-65)
app/Console/Server/ServerAddCommand.php (2)
app/Traits/ConsoleInputTrait.php (2)
  • getValidatedOptionOrPrompt (126-148)
  • promptText (166-182)
app/Traits/ServerValidationTrait.php (3)
  • validateNameInput (17-35)
  • validateHostInput (42-63)
  • validatePortInput (70-86)
tests/Unit/Repositories/ServerRepositoryTest.php (4)
app/Repositories/ServerRepository.php (5)
  • findByHost (86-97)
  • findByName (70-81)
  • ServerRepository (15-189)
  • loadInventory (31-43)
  • create (48-65)
tests/TestHelpers.php (1)
  • mockInventoryService (143-159)
app/Services/InventoryService.php (1)
  • loadInventoryFile (97-111)
app/DTOs/ServerDTO.php (1)
  • ServerDTO (7-17)
app/Traits/ServerValidationTrait.php (1)
app/Repositories/ServerRepository.php (2)
  • findByName (70-81)
  • findByHost (86-97)
tests/Integration/Console/Server/ServerAddCommandTest.php (2)
app/Console/Server/ServerAddCommand.php (1)
  • execute (50-217)
tests/TestHelpers.php (1)
  • mockSSHServiceWithBehavior (213-216)
tests/Unit/Traits/ConsoleInputTraitTest.php (3)
tests/TestHelpers.php (2)
  • mockCommandContainer (369-408)
  • mockPrompter (243-254)
tests/Fixtures/TestConsoleCommand.php (3)
  • TestConsoleCommand (27-286)
  • setTestMethod (62-66)
  • execute (77-110)
tests/Fixtures/MockPrompter.php (1)
  • text (41-54)
app/Traits/ServerHelpersTrait.php (2)
app/DTOs/ServerDTO.php (1)
  • ServerDTO (7-17)
app/Traits/ConsoleOutputTrait.php (1)
  • writeln (23-29)
tests/Fixtures/TestConsoleCommand.php (3)
app/Traits/ConsoleInputTrait.php (2)
  • getValidatedOptionOrPrompt (126-148)
  • promptText (166-182)
tests/Fixtures/MockPrompter.php (1)
  • text (41-54)
app/Services/PrompterService.php (1)
  • text (33-51)
tests/Unit/Traits/ServerValidationTraitTest.php (2)
app/Traits/ServerValidationTrait.php (3)
  • validateNameInput (17-35)
  • validateHostInput (42-63)
  • validatePortInput (70-86)
tests/TestHelpers.php (1)
  • mockServerRepository (298-311)
🪛 PHPMD (2.15.0)
tests/Fixtures/TestConsoleCommand.php

204-204: Avoid unused parameters such as '$value'. (undefined)

(UnusedFormalParameter)

🔇 Additional comments (18)
tests/Fixtures/TestConsoleCommand.php (1)

94-96: New match arms wired correctly

Covers both valid/invalid validated-prompt flows. Good dispatch coverage.

app/Repositories/ServerRepository.php (1)

83-98: findByHost mirrors findByName; clear and correct

Straightforward lookup and DTO hydration. No issues.

app/Traits/ServerHelpersTrait.php (2)

22-26: Typed return on selectServer

Explicit array return matches documented shape. Good.


76-90: displayServerDeets output remains consistent

Presentation is concise; no behavior change. LGTM.

app/Traits/ServerValidationTrait.php (1)

13-35: Name validation refactor is clean

Type check, emptiness, and uniqueness with string|null return. Good.

tests/Unit/Repositories/ServerRepositoryTest.php (2)

51-60: findByHost tests exercise both hit and miss

Good coverage for existing and non-existent hosts.

Also applies to: 63-63


95-107: Duplicate-host creation test validates new guard

Asserts exception type and message. Solid.

tests/Unit/Traits/ConsoleInputTraitTest.php (3)

148-158: Good coverage for valid CLI option path

Asserts happy-path behavior and output. Looks solid.


160-172: Invalid CLI option flow tested correctly

Verifies error symbol, message, and null result. Matches ConsoleOutputTrait::error format.


174-186: Empty CLI value validation path covered

Correctly expects validation error and null result when option is explicitly empty.

.cursor/rules/03-commands.mdc (1)

66-66: Method list update is accurate

Including getValidatedOptionOrPrompt here is correct and helpful.

app/Console/Server/ServerAddCommand.php (3)

61-71: Validated name input flow is correct

Uses getValidatedOptionOrPrompt with required prompt and early failure. Good.


77-87: Validated host input flow is correct

Proper prompt + validator wiring and early failure on null.


93-107: Validated port handling is correct

Validates string input, then casts to int. Matches ServerValidationTrait expectations.

tests/Integration/Console/Server/ServerAddCommandTest.php (3)

150-168: Invalid host scenario assertions match new flow

Exit code FAILURE and presence of error marker/message are asserted correctly.


239-239: Updated duplicate-name assertion is appropriate

Aligns with validator message (“already exists”).


243-280: New duplicate host test is valuable

Covers repository uniqueness via findByHost and validator messaging. Good end-to-end coverage.

tests/Unit/Traits/ServerValidationTraitTest.php (1)

17-17: Add explicit type declaration to the property.

The $servers property lacks a type declaration, which violates PSR-12 and the coding guideline requiring explicit types. Based on the usage in tests and the return type of mockServerRepository, this should be ServerRepository.

Apply this diff:

-    public $servers;
+    public ServerRepository $servers;

As per coding guidelines.

Likely an incorrect or invalid review comment.

Comment thread tests/Unit/Traits/ServerValidationTraitTest.php Outdated
Comment thread tests/Unit/Traits/ServerValidationTraitTest.php Outdated
Comment thread tests/Unit/Traits/ServerValidationTraitTest.php Outdated
Comment thread tests/Unit/Traits/ServerValidationTraitTest.php Outdated
Comment thread tests/Unit/Traits/ServerValidationTraitTest.php Outdated
Comment thread tests/Unit/Traits/ServerValidationTraitTest.php Outdated
Comment thread tests/Unit/Traits/ServerValidationTraitTest.php Outdated
@loadinglucian loadinglucian changed the title refactor(server-repo): update repository tests for consistency refactor: enhance input validation, console traits and repository methods Oct 12, 2025
@loadinglucian
loadinglucian merged commit 6a7d2dc into main Oct 12, 2025
4 of 5 checks passed
@loadinglucian
loadinglucian deleted the refactor/server-commands-validation branch October 12, 2025 15:48
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant