|
| 1 | +# Validation Rule Factory |
| 2 | + |
| 3 | +If you want to validate translated attributes it could get quite complex to list all rules with corresponding attributes their own. To simplify this we've added a `RuleFactory` class. It get's a list of rules and you can mark the key you want to get locale aware. The factory will take the rules assigned to this "placeholder" and copy it to all corresponding locale aware keys. |
| 4 | + |
| 5 | +```php |
| 6 | +$rules = [ |
| 7 | + 'title' => 'required', |
| 8 | + 'translations.%content%.body' => 'required', |
| 9 | +]; |
| 10 | + |
| 11 | +RuleFactory::make($rules); |
| 12 | +``` |
| 13 | + |
| 14 | +This will return an array which adjusted the `translations.%content%.body` key to match your configured key format. The result will be: |
| 15 | + |
| 16 | +```php |
| 17 | +[ |
| 18 | + 'title' => 'required', |
| 19 | + 'translations.en.content.body' => 'required', |
| 20 | + 'translations.de.content.body' => 'required', |
| 21 | + 'translations.de-DE.content.body' => 'required', |
| 22 | + 'translations.de-AT.content.body' => 'required', |
| 23 | +] |
| 24 | +``` |
| 25 | + |
| 26 | +### Configuration |
| 27 | + |
| 28 | +To adjust the default `format` , `prefix` or `suffix` used by the factory you can change them in the package configuration file. |
| 29 | + |
| 30 | +{% code-tabs %} |
| 31 | +{% code-tabs-item title="config/translatable.php" %} |
| 32 | +```php |
| 33 | +'rule_factory' => [ |
| 34 | + 'format' => \Astrotomic\Translatable\Validation\RuleFactory::FORMAT_ARRAY, |
| 35 | + 'prefix' => '%', |
| 36 | + 'suffix' => '%', |
| 37 | +] |
| 38 | +``` |
| 39 | +{% endcode-tabs-item %} |
| 40 | +{% endcode-tabs %} |
| 41 | + |
| 42 | +As `format` we support the two possible variants the `fill()` method supports. |
| 43 | + |
| 44 | +#### RuleFactory::FORMAT\_ARRAY |
| 45 | + |
| 46 | +This will create the dot-notation to support locale sub-arrays. `en.content`. |
| 47 | + |
| 48 | +#### RuleFactory::FORMAT\_KEY |
| 49 | + |
| 50 | +This will create the colon separated style. `content:en` |
| 51 | + |
| 52 | +### Runtime |
| 53 | + |
| 54 | +For sure you can change the default `format`, `prefix`, `suffix` and applied `locales` during runtime. To do so only pass them as parameter to the `make()` method. |
| 55 | + |
| 56 | +```php |
| 57 | +RuleFactory::make($rules, RuleFactory::FORMAT_KEY, '{', '}', [ |
| 58 | + 'en', |
| 59 | + 'de', |
| 60 | +]); |
| 61 | +``` |
| 62 | + |
| 63 | +This will use the colon style, use `{` and `}` as delimiter and use only `de` and `en` as locales. |
| 64 | + |
| 65 | +{% hint style="info" %} |
| 66 | +You can only use defined locales. Every locale that's not in `Locales::all()`will throw an `InvalidArgumentException`. |
| 67 | +{% endhint %} |
| 68 | + |
0 commit comments