Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Include attribute name in error messages when it's present #644

Merged
merged 42 commits into from
Mar 4, 2024

Conversation

dood-
Copy link
Contributor

@dood- dood- commented Jan 2, 2024

Q A
Is bugfix?
New feature? ✔️
Breaks BC?
Fixed issues #630

Copy link

codecov bot commented Jan 2, 2024

Codecov Report

Attention: Patch coverage is 93.25843% with 6 lines in your changes are missing coverage. Please review.

Project coverage is 94.72%. Comparing base (e019e5c) to head (43e9f45).

Files Patch % Lines
src/Rule/Count.php 0.00% 3 Missing ⚠️
src/Rule/Length.php 0.00% 3 Missing ⚠️
Additional details and impacted files
@@             Coverage Diff              @@
##             master     #644      +/-   ##
============================================
+ Coverage     94.60%   94.72%   +0.12%     
- Complexity      796      801       +5     
============================================
  Files            93       93              
  Lines          2426     2483      +57     
============================================
+ Hits           2295     2352      +57     
  Misses          131      131              

☔ View full report in Codecov by Sentry.
📢 Have feedback on the report? Share it here.

Copy link

what-the-diff bot commented Jan 2, 2024

PR Summary

  • New Label Features
    Introduced the feature of labels in error messages. This improvement allows custom labels to be used in classes, enhancing error readability by providing more specific descriptions. This will help update error messages on the application resulting in a more user-friendly interface.

  • New Method for Label Retrieve
    Addition of a getLabels() method enabling easy access to the labels of class properties, which will aid in greater error specificity.

  • Modification of Various Validation Rules
    Updated various validation rules both in files like Each.php, Email.php, In.php, Ip.php, Json.php, Length.php, Nested.php, Number.php, OneOf.php, Regex.php, Required.php, etc., and their corresponding "Rule Handler" files. These modifications equip each rule with a 'label' parameter to provide more lucid error messages, leading to an improved user experience.

  • Adjustments in Defined Classes
    Changes in defined classes including StringValue, StringValueHandler, Subset, SubsetHandler, CountableLimitHandlerTrait, TrueValue, TrueValueHandler, Url, UrlHandler, ValidationContext, Validator and more. These changes result in improved handling and processing of error messages in various conditions.

  • Changes and Additions in Test Classes
    Numerous test classes like ConfigTest, ObjectDataSetTest, RulesDumperTest, AtLeastTest, BooleanValueTest, CompositeTest and others, were updated. Modifications vary from changing default error messages, templates to adding the 'label' parameter. These alterations ensure comprehensive testing of the new feature, guaranteeing reliable functionality and performance.

  • Default Messages Enhanced in Rule Tests
    Numerous rule test files such as CountTest.php, EachTest.php, EmailTest.php, EqualTest.php, GreaterThanTest.php and so on were updated. The improvement enables error messages to use a label placeholder instead of hard-coded values. This brings flexibility in error messages, making them more informative and helpful to users.

  • Updates to Documentation
    The documentation has been updated to guide configuring rules via PHP attributes, promoting clarity for users.

  • Implementation of Debug Collector
    The addition of a new feature for the debug collector aims at enhancing debugging capabilities.

Please note this is a high overview of the changes and not a granular breakdown.

@samdark samdark requested review from vjik and arogachev January 3, 2024 16:53
@dood-
Copy link
Contributor Author

dood- commented Jan 3, 2024

Since I added a new placeholder {label}, perhaps it is better to make the placeholder {attribute} always be replaced by the name of the property?

@samdark
Copy link
Member

samdark commented Jan 5, 2024

@vjik, @arogachev what do you think?

Copy link
Member

@vjik vjik left a comment

Choose a reason for hiding this comment

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

Hm. Is there a case when need attribute in message and at the same time, there is a label?

Seems, it's overhead. I suggest use placeholder {attribute} only and return translated label, if it exist, or translated attribute otherwise.

@samdark
Copy link
Member

samdark commented Jan 7, 2024

No, I can't imagine such a case and I agree with @vjik. @dood- would you please adjust the name to be {attribute}? Thanks.

@dood-
Copy link
Contributor Author

dood- commented Jan 7, 2024

@samdark, @vjik If we leave "The value" as a default value, then there is a problem with displaying the attribute names of arrays.

Here is a test for an example:

'custom incorrect input message with parameters, attribute set' => [
['attribute' => 1],
[
'attribute' => new OneOf(
['attr1', 'attr2'],
incorrectInputMessage: 'Attribute - {attribute}, type - {type}.',
),
],
['attribute' => ['Attribute - attribute, type - int.']],

We can not specify a Label attribute for the array or implement the LabelsProviderInterface, so the placeholder value will always be "The value"

@vjik
Copy link
Member

vjik commented Jan 8, 2024

If we leave "The value" as a default value

There will be no default value.

Will be one attribute {attribute}. Value of this placeholder by priority:

  1. Translated label (if label exist).
  2. Translated attribute.

For case with arrays always will be used translated attribute.

@dood-
Copy link
Contributor Author

dood- commented Jan 8, 2024

If necessary, I can remove Attribute::TARGET_CLASS from the Label attribute.
I also fixed the error messages when using "StopOnError". There, instead of the attribute name, a number was displayed

@samdark
Copy link
Member

samdark commented Jan 9, 2024

If necessary, I can remove Attribute::TARGET_CLASS from the Label attribute.

Yes, makes sense.

tests/Rule/AtLeastTest.php Outdated Show resolved Hide resolved
src/ValidationContext.php Outdated Show resolved Hide resolved
@dood-
Copy link
Contributor Author

dood- commented Feb 1, 2024

Also need kill mutants from mutation testing.

Is it possible to disable mutants for a specific php version or just use @infection-ignore-all?

@samdark
Copy link
Member

samdark commented Feb 9, 2024

I guess @vjik meant fixing tests so there are no mutants, not ignoring these.

@samdark samdark requested a review from vjik February 9, 2024 20:33
Copy link
Member

@vjik vjik left a comment

Choose a reason for hiding this comment

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

Overall looks good 👍
There's just a little bit left to finish.

messages/ru/yii-validator.php Show resolved Hide resolved
tests/Rule/DateTimeTest.php Outdated Show resolved Hide resolved
@arogachev
Copy link
Contributor

Thanks for you great work! I will review this as well.

@@ -74,7 +74,7 @@ final class User

> **Note:** [readonly properties] are supported only starting from PHP 8.1.

Error messages may include an `{attribute}` placeholder that is replaced with the name of the property. If you would
Error messages may include `{attribute}` or `{Attribute}` placeholder that is replaced with the name of the property. If you would
Copy link
Contributor

Choose a reason for hiding this comment

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

Need to cover the differences between the two.

Comment on lines 57 to 58
'attribute' => $context->getTranslatedAttribute(),
'Attribute' => StringHelper::uppercaseFirstCharacter($context->getTranslatedAttribute()),
Copy link
Contributor

Choose a reason for hiding this comment

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

These seem to be redundant in this case, because here there are multiple error attributes, not just a single one.

*/
public function getTranslatedAttribute(): ?string
public function getTranslatedAttribute(): string
Copy link
Contributor

Choose a reason for hiding this comment

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

Maybe add a method like getCapitalizedTranslatedAttribute() or additional argument in existing method with already applied StringHelper? That would reduce the code a bit.

@@ -61,6 +63,7 @@ public function validate(mixed $value, object $rule, ValidationContext $context)

return (new Result())->addError($rule->getMessage(), [
'attribute' => $context->getTranslatedAttribute(),
'Attribute' => StringHelper::uppercaseFirstCharacter($context->getTranslatedAttribute()),
Copy link
Contributor

Choose a reason for hiding this comment

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

Maybe group common parameters here and in other similar places?

CHANGELOG.md Outdated Show resolved Hide resolved
src/ValidationContext.php Show resolved Hide resolved
src/ValidationContext.php Show resolved Hide resolved
'>=' => 'Value must be greater than or equal to "{targetValueOrAttribute}".',
'<' => 'Value must be less than "{targetValueOrAttribute}".',
'<=' => 'Value must be less than or equal to "{targetValueOrAttribute}".',
'==', => '{Attribute} must be equal to "{targetValueOrAttribute}".',
Copy link
Contributor

Choose a reason for hiding this comment

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

targetValueOrAttribute - support capitalization as well?

@@ -62,7 +62,7 @@ final class AtLeast implements DumpedRuleInterface, SkipOnErrorInterface, WhenIn
public function __construct(
private array $attributes,
private int $min = 1,
private string $incorrectInputMessage = 'The value must be an array or an object.',
private string $incorrectInputMessage = '{Attribute} must be an array or an object.',
private string $message = 'At least {min, number} {min, plural, one{attribute} other{attributes}} from this ' .
Copy link
Contributor

Choose a reason for hiding this comment

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

attributes - support capitalization as well?

docs/guide/en/customizing-error-messages.md Outdated Show resolved Hide resolved
messages/ru/yii-validator.php Outdated Show resolved Hide resolved
Co-authored-by: Alexander Makarov <[email protected]>
@samdark samdark merged commit f060162 into yiisoft:master Mar 4, 2024
22 of 26 checks passed
@samdark
Copy link
Member

samdark commented Mar 4, 2024

Thank you!

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.

4 participants