Skip to content

Commit

Permalink
Add getMessages method to CategorySource (#94)
Browse files Browse the repository at this point in the history
* Add getMessages method

* [ci-review] Apply changes from Rector action.

* Add changelog

* Add a test

* PR fixes

Co-authored-by: rector-bot <rector@yiiframework.com>
Co-authored-by: Sergei Predvoditelev <sergei@predvoditelev.ru>
  • Loading branch information
3 people committed Nov 24, 2022
1 parent 96ea5a9 commit 46dbefc
Show file tree
Hide file tree
Showing 3 changed files with 64 additions and 1 deletion.
3 changes: 2 additions & 1 deletion CHANGELOG.md
Expand Up @@ -6,7 +6,8 @@

## 2.1.1 November 23, 2022

- Bug #93: Throw exceptions on empty and not passed parameters, cast `null` to empty string in `SimpleMessageFormatter`
- New #94: Add `getMessages()` method to `CategorySource` (@xepozz)
- Bug #93: Throw exceptions on empty and not passed parameters, cast `null` to empty string in `SimpleMessageFormatter`
(@arogachev)

## 2.1.0 November 15, 2022
Expand Down
29 changes: 29 additions & 0 deletions src/CategorySource.php
Expand Up @@ -51,6 +51,35 @@ public function getMessage(string $id, string $locale, array $parameters = []):
return $this->reader->getMessage($id, $this->name, $locale, $parameters);
}

/**
* @param string $locale Locale of messages to get.
*
* @psalm-return array<string, array<string, string>>
*
* @return array All messages from category. The format is the following:
*
* ```php
* [
* 'key1' => [
* 'message' => 'translation1',
* // Extra metadata that writer may use:
* 'comment' => 'Translate carefully!',
* ],
* 'key2' => [
* 'message' => 'translation2',
* // Extra metadata that writer may use:
* 'comment' => 'Translate carefully!',
* ],
* ]
* ```
*
* @see MessageReaderInterface::getMessages()
*/
public function getMessages(string $locale): array
{
return $this->reader->getMessages($this->name, $locale);
}

/**
* Format the message given parameters and locale.
*
Expand Down
33 changes: 33 additions & 0 deletions tests/CategoryTest.php
Expand Up @@ -68,6 +68,39 @@ public function testWithoutFormatter(
);
}

public function testGetMessages(): void
{
$categorySource = new CategorySource(
'test',
new class () implements MessageReaderInterface {
public function getMessage(
string $id,
string $category,
string $locale,
array $parameters = []
): ?string {
return null;
}

public function getMessages(string $category, string $locale): array
{
return [
'message1' => ['message' => 'message1'],
'message2' => ['message' => 'message2'],
];
}
}
);

$this->assertEquals(
[
'message1' => ['message' => 'message1'],
'message2' => ['message' => 'message2'],
],
$categorySource->getMessages('en'),
);
}

private function createMessageReader(): MessageReaderInterface
{
return new class () implements MessageReaderInterface {
Expand Down

0 comments on commit 46dbefc

Please sign in to comment.