refactor: use readonly classes with promoted constructors for DTOs#618
Conversation
| /** | ||
| * Constructor. | ||
| * | ||
| * @param array<string> $errorCodes |
There was a problem hiding this comment.
I like it, let's also keep the comments which are informative.
| * @param array<string> $errorCodes | |
| * @param bool $success Success or failure. | |
| * @param array<string> $errorCodes Error code strings. | |
| * @param string $hostname The hostname of the site where the reCAPTCHA was solved. | |
| * @param string $challengeTs Timestamp of the challenge load (ISO format yyyy-MM-dd'T'HH:mm:ssZZ). | |
| * @param string $apkPackageName APK package name. | |
| * @param ?float $score Score assigned to the request. | |
| * @param string $action Action as specified by the page. |
There was a problem hiding this comment.
I like it, let's also keep the comments which are informative.
Hey @NiklasBr, totally agree — those descriptions are genuinely useful, especially for the less obvious params like $challengeTs and $score. I've updated the constructor PHPDoc to include all the descriptive @param tags. Done!
cc472ad to
e76864b
Compare
rowan-m
left a comment
There was a problem hiding this comment.
The code changes make sense, but I'm not convinced on the addition of testClassIsReadonly(). This feels like it's testing implementation detail, not behaviour.
Hey @rowan-m, fair point! Testing if a class is readonly is definitely overkill and just tests PHP itself. I've dropped those tests in the latest commit. Thanks for keeping the suite focused! |
Hi!
Since the project bumped its requirement to PHP 8.4, I noticed an easy win to clean up a lot of boilerplate in the two DTOs (RequestParameters and Response).
Right now, both classes declare every property manually with PHPDoc and then assign them one by one inside the constructor. I've updated both to use native PHP constructor property promotion, which squashes all those property assignments into a clean, single-signature constructor.
I also added the
readonly classmodifier to both. Since these objects hold request data and API responses, they really shouldn't ever be mutated once they're built. This locks them down at the engine level, so no one can accidentally modify them later.Note: I didn't touch a single method or getter logic. toArray(), fromJson(), etc., are all the same, and the constructor signatures haven't changed, so anything calling these classes won't notice a difference.
I also added two quick
ReflectionClasstests just to prove thereadonlyconstraint is working properly.Tests are perfectly green, and it deletes over 60 lines of unnecessary repetition! Let me know what you think.
What Changed
All 68 tests pass, 183 assertions, PHPStan Level Max clean.