From cae41f6ff7ec6897519d055758223608ad117509 Mon Sep 17 00:00:00 2001 From: Michael Dyrynda Date: Mon, 12 Mar 2018 23:57:42 +1030 Subject: [PATCH] [5.7] Make MessageBag constructor behaviour consistent with `add` (#23485) * Make MessageBag constructor behaviour consistent with `add` Addresses laravel/ideas#56 and the (long-closed) #13196. This change in constructor behaviour aims to bring consistency with the public `add` method on the MessageBag class, which would prevent duplicate values in any given MessageBag's key. * update test to show consistency of behaviour --- src/Illuminate/Support/MessageBag.php | 5 +++-- tests/Support/SupportMessageBagTest.php | 15 +++++++++++++++ 2 files changed, 18 insertions(+), 2 deletions(-) diff --git a/src/Illuminate/Support/MessageBag.php b/src/Illuminate/Support/MessageBag.php index da2c31e29dbe..41672fe7640c 100755 --- a/src/Illuminate/Support/MessageBag.php +++ b/src/Illuminate/Support/MessageBag.php @@ -34,8 +34,9 @@ class MessageBag implements Arrayable, Countable, Jsonable, JsonSerializable, Me public function __construct(array $messages = []) { foreach ($messages as $key => $value) { - $this->messages[$key] = $value instanceof Arrayable - ? $value->toArray() : (array) $value; + $value = $value instanceof Arrayable ? $value->toArray() : (array) $value; + + $this->messages[$key] = array_unique($value); } } diff --git a/tests/Support/SupportMessageBagTest.php b/tests/Support/SupportMessageBagTest.php index 1d77c5b37c55..c487345f359c 100755 --- a/tests/Support/SupportMessageBagTest.php +++ b/tests/Support/SupportMessageBagTest.php @@ -298,4 +298,19 @@ public function testGetFormat() $container->setFormat(':message'); $this->assertEquals(':message', $container->getFormat()); } + + public function testConstructorUniquenessConsistency() + { + $messageBag = new MessageBag(['messages' => ['first', 'second', 'third', 'third']]); + $messages = $messageBag->getMessages(); + $this->assertEquals(['first', 'second', 'third'], $messages['messages']); + + $messageBag = new MessageBag; + $messageBag->add('messages', 'first'); + $messageBag->add('messages', 'second'); + $messageBag->add('messages', 'third'); + $messageBag->add('messages', 'third'); + $messages = $messageBag->getMessages(); + $this->assertEquals(['first', 'second', 'third'], $messages['messages']); + } }