Skip to content

Conversation

@shaedrich
Copy link
Contributor

@shaedrich shaedrich commented Oct 28, 2025

Follow-up to #57556 (comment)

✅ Improves readability by making the methods more compact without the "internal logic" in each of them
✅ Improves maintainability by having a single source of truth/failure
✅ Makes adapting this in new methods quite easy

@AndrewMast
Copy link
Contributor

Hey, just pointing out, your code introduces using Str::lower onto the replace value where the original code does not. I don't know if it actually changes anything, but thought I'd mention it.

@shaedrich
Copy link
Contributor Author

@AndrewMast Thanks for the reminder 👍🏻 Yeah, I thought, I'd make it more robust but maybe, it's too much for one PR and should be done separately 🤔

@shaedrich
Copy link
Contributor Author

shaedrich commented Oct 28, 2025

Technically, this could also be used for

when modifying this:

- function replaceKeepCase($message, $mapping)
+ function replaceKeepCase($message, $mapping, $wordSeparators = [])
{
-   $fn = [Str::lower(...), Str::upper(...), Str::ucfirst(...)];
+   $fn = [
+       Str::lower(...),
+       Str::upper(...),
+       //fn (string $placeholder, ?string $parameter = null) => ucwords($parameter ?? $placeholder, $parameter !== null ? ($wordSeparators[$placeholder] ?? ' ') : ' '),
+       fn (string $placeholder, ?string $parameter = null) => $parameter !== null && array_key_exists($placeholder, $wordSeparators)
+           ? ucwords($parameter ?? $placeholder, $wordSeparators[$placeholder])
+           : ucfirst($parameter ?? $placeholder),
+   ];
    $cases = array_reduce(
        array_keys($mapping),
-       fn (array $carry, string $placeholder) => [...$carry, ...array_map(fn (callable $fn) => ':'.$fn($placeholder), $fn)],
+       fn (array $carry, string $placeholder) => [...$carry, ...array_map(fn (callable $fn) => ':' . $fn($placeholder), $fn)],
        [],
    );
    $replacements = array_reduce(
-       array_values($mapping),
+       array_keys($mapping),
-       fn (array $carry, string $parameter) => [...$carry, ...array_map(fn (callable $fn) => $fn($parameter), $fn)],
+       fn (array $carry, string $placeholder) => [...$carry, ...array_map(fn (callable $fn) => $fn($placeholder, $mapping[$placeholder]), $fn)],
        [],
    );

    return str_replace($cases, $replacements, $message);
}

@taylorotwell taylorotwell merged commit d91db74 into laravel:12.x Oct 29, 2025
66 checks passed
@shaedrich shaedrich deleted the validator-replace-keep-case branch October 29, 2025 16:27
shaedrich added a commit to shaedrich/framework that referenced this pull request Oct 29, 2025
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.

3 participants