Browse Source

Code formatting

main
Cédric Belin 2 months ago
parent
commit
b936197b32
24 changed files with 655 additions and 646 deletions
  1. +8
    -3
      .editorconfig
  2. +1
    -1
      .github/workflows/build.yaml
  3. +5
    -5
      .vscode/settings.json
  4. +57
    -57
      composer.json
  5. +5
    -5
      doc/installation.md
  6. +60
    -60
      doc/usage.md
  7. +9
    -5
      etc/mkdocs.yaml
  8. +22
    -22
      etc/phpdoc.xml
  9. +4
    -4
      etc/phpstan.neon
  10. +13
    -13
      etc/phpunit.xml
  11. +7
    -7
      example/main.php
  12. +11
    -11
      src/ExtendedPhpMessageSource.php
  13. +58
    -58
      src/FileMessageSource.php
  14. +11
    -11
      src/JsonMessageSource.php
  15. +11
    -11
      src/YamlMessageSource.php
  16. +117
    -117
      test/ExtendedPhpMessageSourceTest.php
  17. +117
    -117
      test/JsonMessageSourceTest.php
  18. +117
    -117
      test/YamlMessageSourceTest.php
  19. +6
    -6
      test/fixtures/fr/messages.json
  20. +6
    -6
      test/fixtures/fr/messages.php
  21. +5
    -5
      test/index.php
  22. +3
    -3
      tool/clean.ps1
  23. +1
    -1
      tool/doc.ps1
  24. +1
    -1
      tool/upgrade.ps1

+ 8
- 3
.editorconfig View File

@@ -3,11 +3,16 @@ root = true

[*]
charset = utf-8
indent_size = 2
indent_style = space
indent_style = tab
insert_final_newline = true
max_line_length = 200
quote_type = double
tab_width = 2
trim_trailing_whitespace = true

[*.md]
indent_size = 4
trim_trailing_whitespace = false

[*.{yaml,yml}]
indent_size = 2
indent_style = space

+ 1
- 1
.github/workflows/build.yaml View File

@@ -3,7 +3,7 @@ on:
pull_request:
push:
schedule:
- cron: '0 0 1 * *'
- cron: "0 0 1 * *"
jobs:
test:
runs-on: ubuntu-latest


+ 5
- 5
.vscode/settings.json View File

@@ -1,7 +1,7 @@
{
"editor.insertSpaces": true,
"editor.tabSize": 2,
"files.encoding": "utf8",
"files.insertFinalNewline": true,
"files.trimFinalNewlines": true
"editor.insertSpaces": false,
"editor.tabSize": 2,
"files.encoding": "utf8",
"files.insertFinalNewline": true,
"files.trimFinalNewlines": true
}

+ 57
- 57
composer.json View File

@@ -1,59 +1,59 @@
{
"description": "JSON and YAML message sources for the Yii Framework.",
"homepage": "https://docs.belin.io/yii2-json-messages",
"license": "MIT",
"name": "cedx/yii2-json-messages",
"type": "yii2-extension",
"version": "6.2.0",
"authors": [
{"email": "cedric@belin.io", "homepage": "https://belin.io", "name": "Cédric Belin"}
],
"autoload": {
"psr-4": {"yii\\i18n\\": "src/"}
},
"autoload-dev": {
"psr-4": {"yii\\i18n\\": "test/"}
},
"config": {
"fxp-asset": {"enabled": false},
"optimize-autoloader": true
},
"funding": [
{"type": "patreon", "url": "https://www.patreon.com/cedx"}
],
"keywords": [
"catalog",
"i18n",
"internationalization",
"json",
"locale",
"messages",
"translation",
"yaml",
"yii2"
],
"repositories": [
{"type": "composer", "url": "https://asset-packagist.org"}
],
"require": {
"php": ">=7.4.0",
"ext-json": "*",
"ext-pcre": "*",
"ext-spl": "*",
"symfony/yaml": "^5.0.8",
"yiisoft/yii2": "^2.0.35"
},
"require-dev": {
"cedx/coveralls": "^13.0.0",
"phpstan/phpstan": "^0.12.25",
"phpunit/phpunit": "^9.1.4"
},
"scripts": {
"coverage": "coveralls var/coverage.xml",
"test": "phpunit --configuration=etc/phpunit.xml"
},
"support": {
"docs": "https://api.belin.io/yii2-json-messages",
"issues": "https://git.belin.io/cedx/yii2-json-messages/issues"
}
"description": "JSON and YAML message sources for the Yii Framework.",
"homepage": "https://docs.belin.io/yii2-json-messages",
"license": "MIT",
"name": "cedx/yii2-json-messages",
"type": "yii2-extension",
"version": "6.2.0",
"authors": [
{"email": "cedric@belin.io", "homepage": "https://belin.io", "name": "Cédric Belin"}
],
"autoload": {
"psr-4": {"yii\\i18n\\": "src/"}
},
"autoload-dev": {
"psr-4": {"yii\\i18n\\": "test/"}
},
"config": {
"fxp-asset": {"enabled": false},
"optimize-autoloader": true
},
"funding": [
{"type": "patreon", "url": "https://www.patreon.com/cedx"}
],
"keywords": [
"catalog",
"i18n",
"internationalization",
"json",
"locale",
"messages",
"translation",
"yaml",
"yii2"
],
"repositories": [
{"type": "composer", "url": "https://asset-packagist.org"}
],
"require": {
"php": ">=7.4.0",
"ext-json": "*",
"ext-pcre": "*",
"ext-spl": "*",
"symfony/yaml": "^5.0.8",
"yiisoft/yii2": "^2.0.35"
},
"require-dev": {
"cedx/coveralls": "^13.0.0",
"phpstan/phpstan": "^0.12.25",
"phpunit/phpunit": "^9.1.4"
},
"scripts": {
"coverage": "coveralls var/coverage.xml",
"test": "phpunit --configuration=etc/phpunit.xml"
},
"support": {
"docs": "https://api.belin.io/yii2-json-messages",
"issues": "https://git.belin.io/cedx/yii2-json-messages/issues"
}
}

+ 5
- 5
doc/installation.md View File

@@ -3,7 +3,7 @@
## Requirements
Before installing **JSON & YAML Messages for Yii**, you need to make sure you have [PHP](https://www.php.net)
and [Composer](https://getcomposer.org), the PHP package manager, up and running.
You can verify if you're already good to go with the following commands:

```shell
@@ -15,8 +15,8 @@ composer --version
```

!!! info
If you plan to play with the package sources, you will also need the latest versions of
[PowerShell](https://docs.microsoft.com/en-us/powershell) and [Material for MkDocs](https://squidfunk.github.io/mkdocs-material).
If you plan to play with the package sources, you will also need the latest versions of
[PowerShell](https://docs.microsoft.com/en-us/powershell) and [Material for MkDocs](https://squidfunk.github.io/mkdocs-material).

## Installing with Composer package manager

@@ -33,7 +33,7 @@ Now in your [PHP](https://www.php.net) code, you can use:
```php
<?php
use yii\i18n\{
JsonMessageSource,
YamlMessageSource
JsonMessageSource,
YamlMessageSource
};
```

+ 60
- 60
doc/usage.md View File

@@ -3,20 +3,20 @@ This package provides a set of classes which are message sources that store tran
They extends from [`yii\i18n\PhpMessageSource`](https://www.yiiframework.com/doc/api/2.0/yii-i18n-phpmessagesource) class, so their usage is basically the same.

!!! tip
See the [Yii guide](https://www.yiiframework.com/doc/guide/2.0/en/tutorial-i18n#message-translation) for more information about internationalization and message translation.
See the [Yii guide](https://www.yiiframework.com/doc/guide/2.0/en/tutorial-i18n#message-translation) for more information about internationalization and message translation.

## Using a JSON catalog
In your [application configuration](https://www.yiiframework.com/doc/guide/2.0/en/concept-configurations#application-configurations) file, use the following message source:

```php
<?php return [
'components' => [
'i18n' => [
'translations' => [
'app*' => 'yii\i18n\JsonMessageSource'
]
]
]
"components" => [
"i18n" => [
"translations" => [
"app*" => "yii\\i18n\\JsonMessageSource"
]
]
]
];
```

@@ -24,8 +24,8 @@ Within a [JSON](https://json.org) file, an object literal of (source, translatio

```json
{
"original message 1": "translated message 1",
"original message 2": "translated message 2"
"original message 1": "translated message 1",
"original message 2": "translated message 2"
}
```

@@ -34,13 +34,13 @@ In your [application configuration](https://www.yiiframework.com/doc/guide/2.0/e

```php
<?php return [
'components' => [
'i18n' => [
'translations' => [
'app*' => 'yii\i18n\YamlMessageSource'
]
]
]
"components" => [
"i18n" => [
"translations" => [
"app*" => "yii\\i18n\\YamlMessageSource"
]
]
]
];
```

@@ -56,8 +56,8 @@ It is a common practice to use keys instead of original messages, alongside the

```json
{
"foo.bar": "translated message for key 'foo.bar'",
"bar.qux": "translated message for key 'bar.qux'"
"foo.bar": "translated message for key 'foo.bar'",
"bar.qux": "translated message for key 'bar.qux'"
}
```

@@ -66,15 +66,15 @@ This means that you can have JSON files that look like this:

```json
{
"foo": "translated message for key path 'foo'",
"bar": {
"qux": "translated message for key path 'bar.qux'"
},
"baz": {
"qux": {
"quux": "translated message for key path 'baz.qux.quux'"
}
}
"foo": "translated message for key path 'foo'",
"bar": {
"qux": "translated message for key path 'bar.qux'"
},
"baz": {
"qux": {
"quux": "translated message for key path 'baz.qux.quux'"
}
}
}
```

@@ -83,10 +83,10 @@ Or YAML files that look like that:
```yaml
foo: "translated message for key path 'foo'"
bar:
qux: "translated message for key path 'bar.qux'"
qux: "translated message for key path 'bar.qux'"
baz:
qux:
quux: "translated message for key path 'baz.qux.quux'"
qux:
quux: "translated message for key path 'baz.qux.quux'"
```

And use dot notation to access a translation:
@@ -94,8 +94,8 @@ And use dot notation to access a translation:
```php
<?php
function main(): void {
echo \Yii::t('app', 'baz.qux.quux');
// Prints: translated message for key path 'baz.qux.quux'
echo \Yii::t("app", "baz.qux.quux");
// Prints: translated message for key path 'baz.qux.quux'
}
```

@@ -104,16 +104,16 @@ In the application configuration file:

```php
<?php return [
'components' => [
'i18n' => [
'translations' => [
'app*' => [
'class' => 'yii\i18n\JsonMessageSource',
'enableNesting' => true
]
]
]
]
"components" => [
"i18n" => [
"translations" => [
"app*" => [
"class" => "yii\\i18n\\JsonMessageSource",
"enableNesting" => true
]
]
]
]
];
```

@@ -121,17 +121,17 @@ If you don't want to use the dot notation, you can customize the character(s) us

```php
<?php return [
'components' => [
'i18n' => [
'translations' => [
'app*' => [
'class' => 'yii\i18n\YamlMessageSource',
'enableNesting' => true,
'nestingSeparator' => '/'
]
]
]
]
"components" => [
"i18n" => [
"translations" => [
"app*" => [
"class" => "yii\\i18n\\YamlMessageSource",
"enableNesting" => true,
"nestingSeparator" => "/"
]
]
]
]
];
```

@@ -140,14 +140,14 @@ You can then access a translation by using the customized notation:
```php
<?php
function main(): void {
// Using the slash character.
echo \Yii::t('app', 'foo/bar/baz');
// Using the slash character.
echo \Yii::t("app", "foo/bar/baz");

// Using the "->" string.
echo \Yii::t('app', 'foo->bar->baz');
// Using the "->" string.
echo \Yii::t("app", "foo->bar->baz");
}
```

!!! tip
This package also provides the `yii\i18n\ExtendedPhpMessageSource` class.
This class adds nested objects support to the [`yii\i18n\PhpMessageSource`](https://www.yiiframework.com/doc/api/2.0/yii-i18n-phpmessagesource) class.
This package also provides the `yii\i18n\ExtendedPhpMessageSource` class.
This class adds nested objects support to the [`yii\i18n\PhpMessageSource`](https://www.yiiframework.com/doc/api/2.0/yii-i18n-phpmessagesource) class.

+ 9
- 5
etc/mkdocs.yaml View File

@@ -8,19 +8,23 @@ site_dir: ../www

repo_name: git.belin.io
repo_url: https://git.belin.io/cedx/yii2-json-messages
edit_uri: ''
edit_uri: ""

copyright: Copyright &copy; 2014 - 2020 Cédric Belin
extra:
social:
- icon: fontawesome/solid/globe
link: 'https://belin.io'
link: "https://belin.io"
name: Belin.io
- icon: fontawesome/brands/github
link: 'https://github.com/cedx'
link: "https://github.com/cedx"
name: GitHub
- icon: fontawesome/brands/twitter
link: 'https://twitter.com/cedxbelin'
link: "https://twitter.com/cedxbelin"
name: Twitter
- icon: fontawesome/brands/linkedin
link: 'https://linkedin.com/in/cedxbelin'
link: "https://linkedin.com/in/cedxbelin"
name: LinkedIn

markdown_extensions:
- admonition


+ 22
- 22
etc/phpdoc.xml View File

@@ -1,25 +1,25 @@
<?xml version="1.0"?>
<phpdocumentor
configVersion="3"
xmlns="http://www.phpdoc.org"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="http://docs.phpdoc.org/latest/phpdoc.xsd">
<title>JSON &amp; YAML Messages for Yii</title>
<paths>
<cache>../var/phpdoc</cache>
<output>../doc/api</output>
</paths>
<version number="6.2.0">
<api>
<markers>
<marker>TODO</marker>
</markers>
<source dsn="..">
<path>src</path>
</source>
<visibility>protected</visibility>
<visibility>public</visibility>
</api>
</version>
configVersion="3"
xmlns="http://www.phpdoc.org"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="http://docs.phpdoc.org/latest/phpdoc.xsd">
<title>JSON &amp; YAML Messages for Yii</title>
<paths>
<cache>../var/phpdoc</cache>
<output>../doc/api</output>
</paths>
<version number="6.2.0">
<api>
<markers>
<marker>TODO</marker>
</markers>
<source dsn="..">
<path>src</path>
</source>
<visibility>protected</visibility>
<visibility>public</visibility>
</api>
</version>
</phpdocumentor>

+ 4
- 4
etc/phpstan.neon View File

@@ -1,5 +1,5 @@
parameters:
autoload_files: [../vendor/yiisoft/yii2/Yii.php]
excludes_analyse: [../test/fixtures]
level: max
paths: [../src, ../test]
autoload_files: [../vendor/yiisoft/yii2/Yii.php]
excludes_analyse: [../test/fixtures]
level: max
paths: [../src, ../test]

+ 13
- 13
etc/phpunit.xml View File

@@ -1,18 +1,18 @@
<?xml version="1.0"?>
<phpunit bootstrap="../test/index.php" cacheResult="false" testdox="true">
<filter>
<whitelist processUncoveredFilesFromWhitelist="true">
<directory suffix=".php">../src</directory>
</whitelist>
</filter>
<filter>
<whitelist processUncoveredFilesFromWhitelist="true">
<directory suffix=".php">../src</directory>
</whitelist>
</filter>

<logging>
<log type="coverage-clover" target="../var/coverage.xml"/>
</logging>
<logging>
<log type="coverage-clover" target="../var/coverage.xml"/>
</logging>

<testsuites>
<testsuite name="all">
<directory suffix="Test.php">../test</directory>
</testsuite>
</testsuites>
<testsuites>
<testsuite name="all">
<directory suffix="Test.php">../test</directory>
</testsuite>
</testsuites>
</phpunit>

+ 7
- 7
example/main.php View File

@@ -3,13 +3,13 @@ use yii\i18n\{JsonMessageSource};

/** Translates a message. */
function main(): void {
$i18n = Yii::$app->getI18n();
$i18n = Yii::$app->getI18n();

// Using flat mapping.
$i18n->translations['app*'] = new JsonMessageSource;
echo Yii::t('app', 'FooBarBaz');
// Using flat mapping.
$i18n->translations["app*"] = new JsonMessageSource;
echo Yii::t("app", "FooBarBaz");

// Using nested objects.
$i18n->translations['app*'] = new JsonMessageSource(['enableNesting' => true]);
echo Yii::t('app', 'foo.bar.baz');
// Using nested objects.
$i18n->translations["app*"] = new JsonMessageSource(["enableNesting" => true]);
echo Yii::t("app", "foo.bar.baz");
}

+ 11
- 11
src/ExtendedPhpMessageSource.php View File

@@ -6,16 +6,16 @@ use yii\helpers\{ArrayHelper};
/** Represents a message source that stores translated messages in PHP files. */
class ExtendedPhpMessageSource extends FileMessageSource {

/** @var string The extension of the PHP files. */
public string $fileExtension = 'php';
/** @var string The extension of the PHP files. */
public string $fileExtension = "php";

/**
* Parses the translations contained in the specified input data.
* @param string $messageData The input data.
* @return array<string, array|string> The translations contained in the specified input data.
*/
protected function parseMessages(string $messageData): array {
assert(mb_substr($messageData, 0, 5) == '<?php');
return ArrayHelper::isAssociative($messages = eval("?>$messageData")) ? $messages : [];
}
/**
* Parses the translations contained in the specified input data.
* @param string $messageData The input data.
* @return array<string, array|string> The translations contained in the specified input data.
*/
protected function parseMessages(string $messageData): array {
assert(mb_substr($messageData, 0, 5) == "<?php");
return ArrayHelper::isAssociative($messages = eval("?>$messageData")) ? $messages : [];
}
}

+ 58
- 58
src/FileMessageSource.php View File

@@ -6,72 +6,72 @@ use yii\helpers\{FileHelper};
/** Provides the base class for a message source that stores translated messages in files. */
abstract class FileMessageSource extends PhpMessageSource {

/** @var bool Value indicating whether nested objects are enabled. */
public bool $enableNesting = false;
/** @var bool Value indicating whether nested objects are enabled. */
public bool $enableNesting = false;

/** @var string The extension of the message files. */
public string $fileExtension = '';
/** @var string The extension of the message files. */
public string $fileExtension = "";

/** @var string The string used to delimit properties of nested objects. */
public string $nestingSeparator = '.';
/** @var string The string used to delimit properties of nested objects. */
public string $nestingSeparator = ".";

/** Initializes this object. */
function init(): void {
parent::init();
if ($this->enableNesting) $this->forceTranslation = true;
}
/** Initializes this object. */
function init(): void {
parent::init();
if ($this->enableNesting) $this->forceTranslation = true;
}

/**
* Returns message file path for the specified language and category.
* @param string $category The message category.
* @param string $language The target language.
* @return string The path to message file.
*/
protected function getMessageFilePath($category, $language): string {
assert(is_string($category) && mb_strlen($category) > 0);
assert(is_string($language) && mb_strlen($language) > 0);
$path = parent::getMessageFilePath($category, $language);
return FileHelper::normalizePath((string) preg_replace('/\.php$/i', ".{$this->fileExtension}", $path));
}
/**
* Returns message file path for the specified language and category.
* @param string $category The message category.
* @param string $language The target language.
* @return string The path to message file.
*/
protected function getMessageFilePath($category, $language): string {
assert(is_string($category) && mb_strlen($category) > 0);
assert(is_string($language) && mb_strlen($language) > 0);
$path = parent::getMessageFilePath($category, $language);
return FileHelper::normalizePath((string) preg_replace('/\.php$/i', ".{$this->fileExtension}", $path));
}

/**
* Loads the message translation for the specified language and category.
* @param string $messageFile string The path to message file.
* @return array<string, string>|null The message array, or a `null` reference if the file is not found.
*/
protected function loadMessagesFromFile($messageFile): ?array {
assert(is_string($messageFile) && mb_strlen($messageFile) > 0);
/**
* Loads the message translation for the specified language and category.
* @param string $messageFile string The path to message file.
* @return array<string, string>|null The message array, or a `null` reference if the file is not found.
*/
protected function loadMessagesFromFile($messageFile): ?array {
assert(is_string($messageFile) && mb_strlen($messageFile) > 0);

$file = new \SplFileObject($messageFile);
if (!$file->isReadable()) return null;
$messages = $this->parseMessages((string) $file->fread($file->getSize()));
return $this->enableNesting ? $this->flatten($messages) : $messages; // @phpstan-ignore-line
}
$file = new \SplFileObject($messageFile);
if (!$file->isReadable()) return null;
$messages = $this->parseMessages((string) $file->fread($file->getSize()));
return $this->enableNesting ? $this->flatten($messages) : $messages; // @phpstan-ignore-line
}

/**
* Parses the translations contained in the specified input data.
* @param string $messageData The input data.
* @return array<string, array|string> The translations contained in the specified input data.
*/
abstract protected function parseMessages(string $messageData): array;
/**
* Parses the translations contained in the specified input data.
* @param string $messageData The input data.
* @return array<string, array|string> The translations contained in the specified input data.
*/
abstract protected function parseMessages(string $messageData): array;

/**
* Flattens a multidimensional array into a single array where the keys are property paths to the contained scalar values.
* @param array<string, array|string> $array The input array.
* @return array<string, string> The flattened array.
*/
protected function flatten(array $array): array {
$flatMap = [];
/**
* Flattens a multidimensional array into a single array where the keys are property paths to the contained scalar values.
* @param array<string, array|string> $array The input array.
* @return array<string, string> The flattened array.
*/
protected function flatten(array $array): array {
$flatMap = [];

$iterator = new \RecursiveIteratorIterator(new \RecursiveArrayIterator($array), \RecursiveIteratorIterator::SELF_FIRST);
foreach ($iterator as $key => $value) {
if (!$iterator->callHasChildren()) {
$path = [];
for ($i = 0, $length = $iterator->getDepth(); $i <= $length; $i++) $path[] = $iterator->getSubIterator($i)->key();
$flatMap[implode($this->nestingSeparator, $path)] = $value;
}
}
$iterator = new \RecursiveIteratorIterator(new \RecursiveArrayIterator($array), \RecursiveIteratorIterator::SELF_FIRST);
foreach ($iterator as $key => $value) {
if (!$iterator->callHasChildren()) {
$path = [];
for ($i = 0, $length = $iterator->getDepth(); $i <= $length; $i++) $path[] = $iterator->getSubIterator($i)->key();
$flatMap[implode($this->nestingSeparator, $path)] = $value;
}
}

return $flatMap;
}
return $flatMap;
}
}

+ 11
- 11
src/JsonMessageSource.php View File

@@ -6,16 +6,16 @@ use yii\helpers\{ArrayHelper, Json};
/** Represents a message source that stores translated messages in JSON files. */
class JsonMessageSource extends FileMessageSource {

/** @var string The extension of the JSON files. */
public string $fileExtension = 'json';
/** @var string The extension of the JSON files. */
public string $fileExtension = "json";

/**
* Parses the translations contained in the specified input data.
* @param string $messageData The input data.
* @return array<string, array|string> The translations contained in the specified input data.
*/
protected function parseMessages(string $messageData): array {
assert(mb_strlen($messageData) > 0);
return ArrayHelper::isAssociative($messages = Json::decode($messageData)) ? $messages : [];
}
/**
* Parses the translations contained in the specified input data.
* @param string $messageData The input data.
* @return array<string, array|string> The translations contained in the specified input data.
*/
protected function parseMessages(string $messageData): array {
assert(mb_strlen($messageData) > 0);
return ArrayHelper::isAssociative($messages = Json::decode($messageData)) ? $messages : [];
}
}

+ 11
- 11
src/YamlMessageSource.php View File

@@ -7,16 +7,16 @@ use yii\helpers\{ArrayHelper};
/** Represents a message source that stores translated messages in YAML files. */
class YamlMessageSource extends FileMessageSource {

/** @var string The extension of the YAML files. */
public string $fileExtension = 'yaml';
/** @var string The extension of the YAML files. */
public string $fileExtension = "yaml";

/**
* Parses the translations contained in the specified input data.
* @param string $messageData The input data.
* @return array<string, array|string> The translations contained in the specified input data.
*/
protected function parseMessages(string $messageData): array {
assert(mb_strlen($messageData) > 0);
return ArrayHelper::isAssociative($messages = Yaml::parse($messageData)) ? $messages : [];
}
/**
* Parses the translations contained in the specified input data.
* @param string $messageData The input data.
* @return array<string, array|string> The translations contained in the specified input data.
*/
protected function parseMessages(string $messageData): array {
assert(mb_strlen($messageData) > 0);
return ArrayHelper::isAssociative($messages = Yaml::parse($messageData)) ? $messages : [];
}
}

+ 117
- 117
test/ExtendedPhpMessageSourceTest.php View File

@@ -7,121 +7,121 @@ use function PHPUnit\Framework\{assertThat, equalTo, isEmpty};
/** @testdox yii\i18n\ExtendedPhpMessageSource */
class ExtendedPhpMessageSourceTest extends TestCase {

/** @var \ReflectionClass<ExtendedPhpMessageSource> The object used to change the visibility of inaccessible class members. */
private static \ReflectionClass $reflection;
/** @beforeClass This method is called before the first test of this test class is run. */
static function setUpBeforeClass(): void {
self::$reflection = new \ReflectionClass(ExtendedPhpMessageSource::class);
}
/** @testdox ->flatten() */
function testFlatten(): void {
$method = self::$reflection->getMethod('flatten');
$method->setAccessible(true);
// It should merge the keys of a multidimensional array.
$model = new ExtendedPhpMessageSource;
assertThat($method->invoke($model, []), equalTo([]));
assertThat($method->invoke($model, ['foo' => 'bar', 'baz' => 'qux']), equalTo(['foo' => 'bar', 'baz' => 'qux']));
assertThat($method->invoke($model, ['foo' => ['bar' => 'baz']]), equalTo(['foo.bar' => 'baz']));
$source = [
'foo' => 'bar',
'bar' => ['baz' => 'qux'],
'baz' => ['qux' => [
'foo' => 'bar',
'bar' => 'baz'
]]
];
assertThat($method->invoke($model, $source), equalTo([
'foo' => 'bar',
'bar.baz' => 'qux',
'baz.qux.foo' => 'bar',
'baz.qux.bar' => 'baz'
]));
// It should allow different nesting separators.
$source = [
'foo' => 'bar',
'bar' => ['baz' => 'qux'],
'baz' => ['qux' => [
'foo' => 'bar',
'bar' => 'baz'
]]
];
$model = new ExtendedPhpMessageSource(['nestingSeparator' => '/']);
assertThat($method->invoke($model, $source), equalTo([
'foo' => 'bar',
'bar/baz' => 'qux',
'baz/qux/foo' => 'bar',
'baz/qux/bar' => 'baz'
]));
$model = new ExtendedPhpMessageSource(['nestingSeparator' => '->']);
assertThat($method->invoke($model, $source), equalTo([
'foo' => 'bar',
'bar->baz' => 'qux',
'baz->qux->foo' => 'bar',
'baz->qux->bar' => 'baz'
]));
}
/** @testdox ->getMessageFilePath() */
function testGetMessageFilePath(): void {
$method = self::$reflection->getMethod('getMessageFilePath');
$method->setAccessible(true);
// It should return the proper path to the message file.
$model = new ExtendedPhpMessageSource(['basePath' => '@root/test/fixtures']);
$messageFile = str_replace('/', DIRECTORY_SEPARATOR, __DIR__.'/fixtures/fr/messages.php');
assertThat($method->invoke($model, 'messages', 'fr'), equalTo($messageFile));
// It should should support different file extensions.
$model = new ExtendedPhpMessageSource(['basePath' => '@root/test/fixtures', 'fileExtension' => 'php7']);
$messageFile = str_replace('/', DIRECTORY_SEPARATOR, __DIR__.'/fixtures/fr/messages');
assertThat($method->invoke($model, 'messages', 'fr'), equalTo("$messageFile.php7"));
}
/** @testdox ->loadMessagesFromFile() */
function testLoadMessagesFromFile(): void {
$method = self::$reflection->getMethod('loadMessagesFromFile');
$method->setAccessible(true);
// It should properly load the JSON source and parse it as array.
$model = new ExtendedPhpMessageSource(['basePath' => '@root/test/fixtures', 'enableNesting' => true]);
$messageFile = \Yii::getAlias("{$model->basePath}/fr/messages.php");
assertThat($method->invoke($model, $messageFile), equalTo([
'Hello World!' => 'Bonjour le monde !',
'foo.bar.baz' => 'FooBarBaz'
]));
// It should enable proper translation of source strings.
$model = new ExtendedPhpMessageSource(['basePath' => '@root/test/fixtures', 'enableNesting' => true]);
assertThat($model->translate('messages', 'Hello World!', 'fr'), equalTo('Bonjour le monde !'));
assertThat($model->translate('messages', 'foo.bar.baz', 'fr'), equalTo('FooBarBaz'));
$model = new ExtendedPhpMessageSource(['basePath' => '@root/test/fixtures', 'enableNesting' => true, 'nestingSeparator' => '/']);
assertThat($model->translate('messages', 'foo/bar/baz', 'fr'), equalTo('FooBarBaz'));
}
/** @testdox ->parseMessages() */
function testParseMessages(): void {
$method = self::$reflection->getMethod('parseMessages');
$method->setAccessible(true);
// It should parse a PHP file as a hierarchical array.
$model = new ExtendedPhpMessageSource(['basePath' => '@root/test/fixtures', 'enableNesting' => true]);
$file = new \SplFileObject((string) \Yii::getAlias("{$model->basePath}/fr/messages.php"));
assertThat($method->invoke($model, (string) $file->fread($file->getSize())), equalTo([
'Hello World!' => 'Bonjour le monde !',
'foo' => ['bar' => ['baz' => 'FooBarBaz']]
]));
// It should parse an invalid PHP file as an empty array.
$model = new ExtendedPhpMessageSource(['basePath' => '@root/test/fixtures']);
assertThat($method->invoke($model, '<?php return ["foo", "bar"];'), isEmpty());
}
/** @var \ReflectionClass<ExtendedPhpMessageSource> The object used to change the visibility of inaccessible class members. */
private static \ReflectionClass $reflection;
/** @beforeClass This method is called before the first test of this test class is run. */
static function setUpBeforeClass(): void {
self::$reflection = new \ReflectionClass(ExtendedPhpMessageSource::class);
}
/** @testdox ->flatten() */
function testFlatten(): void {
$method = self::$reflection->getMethod("flatten");
$method->setAccessible(true);
// It should merge the keys of a multidimensional array.
$model = new ExtendedPhpMessageSource;
assertThat($method->invoke($model, []), equalTo([]));
assertThat($method->invoke($model, ["foo" => "bar", "baz" => "qux"]), equalTo(["foo" => "bar", "baz" => "qux"]));
assertThat($method->invoke($model, ["foo" => ["bar" => "baz"]]), equalTo(["foo.bar" => "baz"]));
$source = [
"foo" => "bar",
"bar" => ["baz" => "qux"],
"baz" => ["qux" => [
"foo" => "bar",
"bar" => "baz"
]]
];
assertThat($method->invoke($model, $source), equalTo([
"foo" => "bar",
"bar.baz" => "qux",
"baz.qux.foo" => "bar",
"baz.qux.bar" => "baz"
]));
// It should allow different nesting separators.
$source = [
"foo" => "bar",
"bar" => ["baz" => "qux"],
"baz" => ["qux" => [
"foo" => "bar",
"bar" => "baz"
]]
];
$model = new ExtendedPhpMessageSource(["nestingSeparator" => "/"]);
assertThat($method->invoke($model, $source), equalTo([
"foo" => "bar",
"bar/baz" => "qux",
"baz/qux/foo" => "bar",
"baz/qux/bar" => "baz"
]));
$model = new ExtendedPhpMessageSource(["nestingSeparator" => "->"]);
assertThat($method->invoke($model, $source), equalTo([
"foo" => "bar",
"bar->baz" => "qux",
"baz->qux->foo" => "bar",
"baz->qux->bar" => "baz"
]));
}
/** @testdox ->getMessageFilePath() */
function testGetMessageFilePath(): void {
$method = self::$reflection->getMethod("getMessageFilePath");
$method->setAccessible(true);
// It should return the proper path to the message file.
$model = new ExtendedPhpMessageSource(["basePath" => "@root/test/fixtures"]);
$messageFile = str_replace("/", DIRECTORY_SEPARATOR, __DIR__."/fixtures/fr/messages.php");
assertThat($method->invoke($model, "messages", "fr"), equalTo($messageFile));
// It should should support different file extensions.
$model = new ExtendedPhpMessageSource(["basePath" => "@root/test/fixtures", "fileExtension" => "php7"]);
$messageFile = str_replace("/", DIRECTORY_SEPARATOR, __DIR__."/fixtures/fr/messages");
assertThat($method->invoke($model, "messages", "fr"), equalTo("$messageFile.php7"));
}
/** @testdox ->loadMessagesFromFile() */
function testLoadMessagesFromFile(): void {
$method = self::$reflection->getMethod("loadMessagesFromFile");
$method->setAccessible(true);
// It should properly load the JSON source and parse it as array.
$model = new ExtendedPhpMessageSource(["basePath" => "@root/test/fixtures", "enableNesting" => true]);
$messageFile = \Yii::getAlias("{$model->basePath}/fr/messages.php");
assertThat($method->invoke($model, $messageFile), equalTo([
"Hello World!" => "Bonjour le monde !",
"foo.bar.baz" => "FooBarBaz"
]));
// It should enable proper translation of source strings.
$model = new ExtendedPhpMessageSource(["basePath" => "@root/test/fixtures", "enableNesting" => true]);
assertThat($model->translate("messages", "Hello World!", "fr"), equalTo("Bonjour le monde !"));
assertThat($model->translate("messages", "foo.bar.baz", "fr"), equalTo("FooBarBaz"));
$model = new ExtendedPhpMessageSource(["basePath" => "@root/test/fixtures", "enableNesting" => true, "nestingSeparator" => "/"]);
assertThat($model->translate("messages", "foo/bar/baz", "fr"), equalTo("FooBarBaz"));
}
/** @testdox ->parseMessages() */
function testParseMessages(): void {
$method = self::$reflection->getMethod("parseMessages");
$method->setAccessible(true);
// It should parse a PHP file as a hierarchical array.
$model = new ExtendedPhpMessageSource(["basePath" => "@root/test/fixtures", "enableNesting" => true]);
$file = new \SplFileObject((string) \Yii::getAlias("{$model->basePath}/fr/messages.php"));
assertThat($method->invoke($model, (string) $file->fread($file->getSize())), equalTo([
"Hello World!" => "Bonjour le monde !",
"foo" => ["bar" => ["baz" => "FooBarBaz"]]
]));
// It should parse an invalid PHP file as an empty array.
$model = new ExtendedPhpMessageSource(["basePath" => "@root/test/fixtures"]);
assertThat($method->invoke($model, '<?php return ["foo", "bar"];'), isEmpty());
}
}

+ 117
- 117
test/JsonMessageSourceTest.php View File

@@ -7,121 +7,121 @@ use function PHPUnit\Framework\{assertThat, equalTo, isEmpty};
/** @testdox yii\i18n\JsonMessageSource */
class JsonMessageSourceTest extends TestCase {

/** @var \ReflectionClass<JsonMessageSource> The object used to change the visibility of inaccessible class members. */
private static \ReflectionClass $reflection;
/** @beforeClass This method is called before the first test of this test class is run. */
static function setUpBeforeClass(): void {
self::$reflection = new \ReflectionClass(JsonMessageSource::class);
}
/** @testdox ->flatten() */
function testFlatten(): void {
$method = self::$reflection->getMethod('flatten');
$method->setAccessible(true);
// It should merge the keys of a multidimensional array.
$model = new JsonMessageSource;
assertThat($method->invoke($model, []), equalTo([]));
assertThat($method->invoke($model, ['foo' => 'bar', 'baz' => 'qux']), equalTo(['foo' => 'bar', 'baz' => 'qux']));
assertThat($method->invoke($model, ['foo' => ['bar' => 'baz']]), equalTo(['foo.bar' => 'baz']));
$source = [
'foo' => 'bar',
'bar' => ['baz' => 'qux'],
'baz' => ['qux' => [
'foo' => 'bar',
'bar' => 'baz'
]]
];
assertThat($method->invoke($model, $source), equalTo([
'foo' => 'bar',
'bar.baz' => 'qux',
'baz.qux.foo' => 'bar',
'baz.qux.bar' => 'baz'
]));
// It should allow different nesting separators.
$source = [
'foo' => 'bar',
'bar' => ['baz' => 'qux'],
'baz' => ['qux' => [
'foo' => 'bar',
'bar' => 'baz'
]]
];
$model = new JsonMessageSource(['nestingSeparator' => '/']);
assertThat($method->invoke($model, $source), equalTo([
'foo' => 'bar',
'bar/baz' => 'qux',
'baz/qux/foo' => 'bar',
'baz/qux/bar' => 'baz'
]));
$model = new JsonMessageSource(['nestingSeparator' => '->']);
assertThat($method->invoke($model, $source), equalTo([
'foo' => 'bar',
'bar->baz' => 'qux',
'baz->qux->foo' => 'bar',
'baz->qux->bar' => 'baz'
]));
}
/** @testdox ->getMessageFilePath() */
function testGetMessageFilePath(): void {
$method = self::$reflection->getMethod('getMessageFilePath');
$method->setAccessible(true);
// It should return the proper path to the message file.
$model = new JsonMessageSource(['basePath' => '@root/test/fixtures']);
$messageFile = str_replace('/', DIRECTORY_SEPARATOR, __DIR__.'/fixtures/fr/messages.json');
assertThat($method->invoke($model, 'messages', 'fr'), equalTo($messageFile));
// It should should support different file extensions.
$model = new JsonMessageSource(['basePath' => '@root/test/fixtures', 'fileExtension' => 'json5']);
$messageFile = str_replace('/', DIRECTORY_SEPARATOR, __DIR__.'/fixtures/fr/messages');
assertThat($method->invoke($model, 'messages', 'fr'), equalTo("$messageFile.json5"));
}
/** @testdox ->loadMessagesFromFile() */
function testLoadMessagesFromFile(): void {
$method = self::$reflection->getMethod('loadMessagesFromFile');
$method->setAccessible(true);
// It should properly load the JSON source and parse it as array.
$model = new JsonMessageSource(['basePath' => '@root/test/fixtures', 'enableNesting' => true]);
$messageFile = \Yii::getAlias("{$model->basePath}/fr/messages.json");
assertThat($method->invoke($model, $messageFile), equalTo([
'Hello World!' => 'Bonjour le monde !',
'foo.bar.baz' => 'FooBarBaz'
]));
// It should enable proper translation of source strings.
$model = new JsonMessageSource(['basePath' => '@root/test/fixtures', 'enableNesting' => true]);
assertThat($model->translate('messages', 'Hello World!', 'fr'), equalTo('Bonjour le monde !'));
assertThat($model->translate('messages', 'foo.bar.baz', 'fr'), equalTo('FooBarBaz'));
$model = new JsonMessageSource(['basePath' => '@root/test/fixtures', 'enableNesting' => true, 'nestingSeparator' => '/']);
assertThat($model->translate('messages', 'foo/bar/baz', 'fr'), equalTo('FooBarBaz'));
}
/** @testdox ->parseMessages() */
function testParseMessages(): void {
$method = self::$reflection->getMethod('parseMessages');
$method->setAccessible(true);
// It should parse a JSON file as a hierarchical array.
$model = new JsonMessageSource(['basePath' => '@root/test/fixtures', 'enableNesting' => true]);
$file = new \SplFileObject((string) \Yii::getAlias("{$model->basePath}/fr/messages.json"));
assertThat($method->invoke($model, (string) $file->fread($file->getSize())), equalTo([
'Hello World!' => 'Bonjour le monde !',
'foo' => ['bar' => ['baz' => 'FooBarBaz']]
]));
// It should parse an invalid JSON file as an empty array.
$model = new JsonMessageSource(['basePath' => '@root/test/fixtures']);
assertThat($method->invoke($model, '["foo", "bar"]'), isEmpty());
}
/** @var \ReflectionClass<JsonMessageSource> The object used to change the visibility of inaccessible class members. */
private static \ReflectionClass $reflection;
/** @beforeClass This method is called before the first test of this test class is run. */
static function setUpBeforeClass(): void {
self::$reflection = new \ReflectionClass(JsonMessageSource::class);
}
/** @testdox ->flatten() */
function testFlatten(): void {
$method = self::$reflection->getMethod("flatten");
$method->setAccessible(true);
// It should merge the keys of a multidimensional array.
$model = new JsonMessageSource;
assertThat($method->invoke($model, []), equalTo([]));
assertThat($method->invoke($model, ["foo" => "bar", "baz" => "qux"]), equalTo(["foo" => "bar", "baz" => "qux"]));
assertThat($method->invoke($model, ["foo" => ["bar" => "baz"]]), equalTo(["foo.bar" => "baz"]));
$source = [
"foo" => "bar",
"bar" => ["baz" => "qux"],
"baz" => ["qux" => [
"foo" => "bar",
"bar" => "baz"
]]
];
assertThat($method->invoke($model, $source), equalTo([
"foo" => "bar",
"bar.baz" => "qux",
"baz.qux.foo" => "bar",
"baz.qux.bar" => "baz"
]));
// It should allow different nesting separators.
$source = [
"foo" => "bar",
"bar" => ["baz" => "qux"],
"baz" => ["qux" => [
"foo" => "bar",
"bar" => "baz"
]]
];
$model = new JsonMessageSource(["nestingSeparator" => "/"]);
assertThat($method->invoke($model, $source), equalTo([
"foo" => "bar",
"bar/baz" => "qux",
"baz/qux/foo" => "bar",
"baz/qux/bar" => "baz"
]));
$model = new JsonMessageSource(["nestingSeparator" => "->"]);
assertThat($method->invoke($model, $source), equalTo([
"foo" => "bar",
"bar->baz" => "qux",
"baz->qux->foo" => "bar",
"baz->qux->bar" => "baz"
]));
}
/** @testdox ->getMessageFilePath() */
function testGetMessageFilePath(): void {
$method = self::$reflection->getMethod("getMessageFilePath");
$method->setAccessible(true);
// It should return the proper path to the message file.
$model = new JsonMessageSource(["basePath" => "@root/test/fixtures"]);
$messageFile = str_replace("/", DIRECTORY_SEPARATOR, __DIR__."/fixtures/fr/messages.json");
assertThat($method->invoke($model, "messages", "fr"), equalTo($messageFile));
// It should should support different file extensions.
$model = new JsonMessageSource(["basePath" => "@root/test/fixtures", "fileExtension" => "json5"]);
$messageFile = str_replace("/", DIRECTORY_SEPARATOR, __DIR__."/fixtures/fr/messages");
assertThat($method->invoke($model, "messages", "fr"), equalTo("$messageFile.json5"));
}
/** @testdox ->loadMessagesFromFile() */
function testLoadMessagesFromFile(): void {
$method = self::$reflection->getMethod("loadMessagesFromFile");
$method->setAccessible(true);
// It should properly load the JSON source and parse it as array.
$model = new JsonMessageSource(["basePath" => "@root/test/fixtures", "enableNesting" => true]);
$messageFile = \Yii::getAlias("{$model->basePath}/fr/messages.json");
assertThat($method->invoke($model, $messageFile), equalTo([
"Hello World!" => "Bonjour le monde !",
"foo.bar.baz" => "FooBarBaz"
]));
// It should enable proper translation of source strings.
$model = new JsonMessageSource(["basePath" => "@root/test/fixtures", "enableNesting" => true]);
assertThat($model->translate("messages", "Hello World!", "fr"), equalTo("Bonjour le monde !"));
assertThat($model->translate("messages", "foo.bar.baz", "fr"), equalTo("FooBarBaz"));
$model = new JsonMessageSource(["basePath" => "@root/test/fixtures", "enableNesting" => true, "nestingSeparator" => "/"]);
assertThat($model->translate("messages", "foo/bar/baz", "fr"), equalTo("FooBarBaz"));
}
/** @testdox ->parseMessages() */
function testParseMessages(): void {
$method = self::$reflection->getMethod("parseMessages");
$method->setAccessible(true);
// It should parse a JSON file as a hierarchical array.
$model = new JsonMessageSource(["basePath" => "@root/test/fixtures", "enableNesting" => true]);
$file = new \SplFileObject((string) \Yii::getAlias("{$model->basePath}/fr/messages.json"));
assertThat($method->invoke($model, (string) $file->fread($file->getSize())), equalTo([
"Hello World!" => "Bonjour le monde !",
"foo" => ["bar" => ["baz" => "FooBarBaz"]]
]));
// It should parse an invalid JSON file as an empty array.
$model = new JsonMessageSource(["basePath" => "@root/test/fixtures"]);
assertThat($method->invoke($model, '["foo", "bar"]'), isEmpty());
}
}

+ 117
- 117
test/YamlMessageSourceTest.php View File

@@ -7,121 +7,121 @@ use function PHPUnit\Framework\{assertThat, equalTo, isEmpty};
/** @testdox yii\i18n\YamlMessageSource */
class YamlMessageSourceTest extends TestCase {

/** @var \ReflectionClass<YamlMessageSource> The object used to change the visibility of inaccessible class members. */
private static \ReflectionClass $reflection;
/** @beforeClass This method is called before the first test of this test class is run. */
static function setUpBeforeClass(): void {
self::$reflection = new \ReflectionClass(YamlMessageSource::class);
}
/** @testdox ->flatten() */
function testFlatten(): void {
$method = self::$reflection->getMethod('flatten');
$method->setAccessible(true);
// It should merge the keys of a multidimensional array.
$model = new YamlMessageSource;
assertThat($method->invoke($model, []), equalTo([]));
assertThat($method->invoke($model, ['foo' => 'bar', 'baz' => 'qux']), equalTo(['foo' => 'bar', 'baz' => 'qux']));
assertThat($method->invoke($model, ['foo' => ['bar' => 'baz']]), equalTo(['foo.bar' => 'baz']));
$source = [
'foo' => 'bar',
'bar' => ['baz' => 'qux'],
'baz' => ['qux' => [
'foo' => 'bar',
'bar' => 'baz'
]]
];
assertThat($method->invoke($model, $source), equalTo([
'foo' => 'bar',
'bar.baz' => 'qux',
'baz.qux.foo' => 'bar',
'baz.qux.bar' => 'baz'
]));
// It should allow different nesting separators.
$source = [
'foo' => 'bar',
'bar' => ['baz' => 'qux'],
'baz' => ['qux' => [
'foo' => 'bar',
'bar' => 'baz'
]]
];
$model = new YamlMessageSource(['nestingSeparator' => '/']);
assertThat($method->invoke($model, $source), equalTo([
'foo' => 'bar',
'bar/baz' => 'qux',
'baz/qux/foo' => 'bar',
'baz/qux/bar' => 'baz'
]));
$model = new YamlMessageSource(['nestingSeparator' => '->']);
assertThat($method->invoke($model, $source), equalTo([
'foo' => 'bar',
'bar->baz' => 'qux',
'baz->qux->foo' => 'bar',
'baz->qux->bar' => 'baz'
]));
}
/** @testdox ->getMessageFilePath() */
function testGetMessageFilePath(): void {
$method = self::$reflection->getMethod('getMessageFilePath');
$method->setAccessible(true);
// It should return the proper path to the message file.
$model = new YamlMessageSource(['basePath' => '@root/test/fixtures']);
$messageFile = str_replace('/', DIRECTORY_SEPARATOR, __DIR__.'/fixtures/fr/messages.yaml');
assertThat($method->invoke($model, 'messages', 'fr'), equalTo($messageFile));
// It should should support different file extensions.
$model = new YamlMessageSource(['basePath' => '@root/test/fixtures', 'fileExtension' => 'yml']);
$messageFile = str_replace('/', DIRECTORY_SEPARATOR, __DIR__.'/fixtures/fr/messages');
assertThat($method->invoke($model, 'messages', 'fr'), equalTo("$messageFile.yml"));
}
/** @testdox ->loadMessagesFromFile() */
function testLoadMessagesFromFile(): void {
$method = self::$reflection->getMethod('loadMessagesFromFile');
$method->setAccessible(true);
// It should properly load the JSON source and parse it as array.
$model = new YamlMessageSource(['basePath' => '@root/test/fixtures', 'enableNesting' => true]);
$messageFile = \Yii::getAlias("{$model->basePath}/fr/messages.yaml");
assertThat($method->invoke($model, $messageFile), equalTo([
'Hello World!' => 'Bonjour le monde !',
'foo.bar.baz' => 'FooBarBaz'
]));
// It should enable proper translation of source strings.
$model = new YamlMessageSource(['basePath' => '@root/test/fixtures', 'enableNesting' => true]);
assertThat($model->translate('messages', 'Hello World!', 'fr'), equalTo('Bonjour le monde !'));
assertThat($model->translate('messages', 'foo.bar.baz', 'fr'), equalTo('FooBarBaz'));
$model = new YamlMessageSource(['basePath' => '@root/test/fixtures', 'enableNesting' => true, 'nestingSeparator' => '/']);
assertThat($model->translate('messages', 'foo/bar/baz', 'fr'), equalTo('FooBarBaz'));
}
/** @testdox ->parseMessages() */
function testParseMessages(): void {
$method = self::$reflection->getMethod('parseMessages');
$method->setAccessible(true);
// It should parse a YAML file as a hierarchical array.
$model = new YamlMessageSource(['basePath' => '@root/test/fixtures', 'enableNesting' => true]);
$file = new \SplFileObject((string) \Yii::getAlias("{$model->basePath}/fr/messages.yaml"));
assertThat($method->invoke($model, (string) $file->fread($file->getSize())), equalTo([
'Hello World!' => 'Bonjour le monde !',
'foo' => ['bar' => ['baz' => 'FooBarBaz']]
]));
// It should parse an invalid YAML file as an empty array.
$model = new YamlMessageSource(['basePath' => '@root/test/fixtures']);
assertThat($method->invoke($model, '[foo, bar]'), isEmpty());
}
/** @var \ReflectionClass<YamlMessageSource> The object used to change the visibility of inaccessible class members. */
private static \ReflectionClass $reflection;
/** @beforeClass This method is called before the first test of this test class is run. */
static function setUpBeforeClass(): void {
self::$reflection = new \ReflectionClass(YamlMessageSource::class);
}
/** @testdox ->flatten() */
function testFlatten(): void {
$method = self::$reflection->getMethod("flatten");
$method->setAccessible(true);
// It should merge the keys of a multidimensional array.
$model = new YamlMessageSource;
assertThat($method->invoke($model, []), equalTo([]));
assertThat($method->invoke($model, ["foo" => "bar", "baz" => "qux"]), equalTo(["foo" => "bar", "baz" => "qux"]));
assertThat($method->invoke($model, ["foo" => ["bar" => "baz"]]), equalTo(["foo.bar" => "baz"]));
$source = [
"foo" => "bar",
"bar" => ["baz" => "qux"],
"baz" => ["qux" => [
"foo" => "bar",
"bar" => "baz"
]]
];
assertThat($method->invoke($model, $source), equalTo([
"foo" => "bar",
"bar.baz" => "qux",
"baz.qux.foo" => "bar",
"baz.qux.bar" => "baz"
]));
// It should allow different nesting separators.
$source = [
"foo" => "bar",
"bar" => ["baz" => "qux"],
"baz" => ["qux" => [
"foo" => "bar",
"bar" => "baz"
]]
];
$model = new YamlMessageSource(["nestingSeparator" => "/"]);
assertThat($method->invoke($model, $source), equalTo([
"foo" => "bar",
"bar/baz" => "qux",
"baz/qux/foo" => "bar",
"baz/qux/bar" => "baz"
]));
$model = new YamlMessageSource(["nestingSeparator" => "->"]);
assertThat($method->invoke($model, $source), equalTo([
"foo" => "bar",
"bar->baz" => "qux",
"baz->qux->foo" => "bar",
"baz->qux->bar" => "baz"
]));
}
/** @testdox ->getMessageFilePath() */
function testGetMessageFilePath(): void {
$method = self::$reflection->getMethod("getMessageFilePath");
$method->setAccessible(true);
// It should return the proper path to the message file.
$model = new YamlMessageSource(["basePath" => "@root/test/fixtures"]);
$messageFile = str_replace("/", DIRECTORY_SEPARATOR, __DIR__."/fixtures/fr/messages.yaml");
assertThat($method->invoke($model, "messages", "fr"), equalTo($messageFile));
// It should should support different file extensions.
$model = new YamlMessageSource(["basePath" => "@root/test/fixtures", "fileExtension" => "yml"]);
$messageFile = str_replace("/", DIRECTORY_SEPARATOR, __DIR__."/fixtures/fr/messages");
assertThat($method->invoke($model, "messages", "fr"), equalTo("$messageFile.yml"));
}
/** @testdox ->loadMessagesFromFile() */
function testLoadMessagesFromFile(): void {
$method = self::$reflection->getMethod("loadMessagesFromFile");
$method->setAccessible(true);
// It should properly load the JSON source and parse it as array.
$model = new YamlMessageSource(["basePath" => "@root/test/fixtures", "enableNesting" => true]);
$messageFile = \Yii::getAlias("{$model->basePath}/fr/messages.yaml");
assertThat($method->invoke($model, $messageFile), equalTo([
"Hello World!" => "Bonjour le monde !",
"foo.bar.baz" => "FooBarBaz"
]));
// It should enable proper translation of source strings.
$model = new YamlMessageSource(["basePath" => "@root/test/fixtures", "enableNesting" => true]);
assertThat($model->translate("messages", "Hello World!", "fr"), equalTo("Bonjour le monde !"));
assertThat($model->translate("messages", "foo.bar.baz", "fr"), equalTo("FooBarBaz"));
$model = new YamlMessageSource(["basePath" => "@root/test/fixtures", "enableNesting" => true, "nestingSeparator" => "/"]);
assertThat($model->translate("messages", "foo/bar/baz", "fr"), equalTo("FooBarBaz"));
}
/** @testdox ->parseMessages() */
function testParseMessages(): void {
$method = self::$reflection->getMethod("parseMessages");
$method->setAccessible(true);
// It should parse a YAML file as a hierarchical array.
$model = new YamlMessageSource(["basePath" => "@root/test/fixtures", "enableNesting" => true]);
$file = new \SplFileObject((string) \Yii::getAlias("{$model->basePath}/fr/messages.yaml"));
assertThat($method->invoke($model, (string) $file->fread($file->getSize())), equalTo([
"Hello World!" => "Bonjour le monde !",
"foo" => ["bar" => ["baz" => "FooBarBaz"]]
]));
// It should parse an invalid YAML file as an empty array.
$model = new YamlMessageSource(["basePath" => "@root/test/fixtures"]);
assertThat($method->invoke($model, "[foo, bar]"), isEmpty());
}
}

+ 6
- 6
test/fixtures/fr/messages.json View File

@@ -1,8 +1,8 @@
{
"Hello World!": "Bonjour le monde !",
"foo": {
"bar": {
"baz": "FooBarBaz"
}
}
"Hello World!": "Bonjour le monde !",
"foo": {
"bar": {
"baz": "FooBarBaz"
}
}
}

+ 6
- 6
test/fixtures/fr/messages.php View File

@@ -1,8 +1,8 @@
<?php return [
'Hello World!' => 'Bonjour le monde !',
'foo' => [
'bar' => [
'baz' => 'FooBarBaz'
]
]
"Hello World!" => "Bonjour le monde !",
"foo" => [
"bar" => [
"baz" => "FooBarBaz"
]
]
];

+ 5
- 5
test/index.php View File

@@ -2,15 +2,15 @@
use yii\console\{Application};

// Set the environment.
define('YII_DEBUG', true);
define('YII_ENV', 'test');
define("YII_DEBUG", true);
define("YII_ENV", "test");

// Load the class library.
$rootPath = (new SplFileInfo(__DIR__))->getPath();
require_once "$rootPath/vendor/autoload.php";
require_once "$rootPath/vendor/yiisoft/yii2/Yii.php";
Yii::setAlias('@root', $rootPath);
Yii::setAlias('@yii/i18n', "$rootPath/src");
Yii::setAlias("@root", $rootPath);
Yii::setAlias("@yii/i18n", "$rootPath/src");

// Start the application.
new Application(['id' => 'yii2-json-messages', 'basePath' => '@root/src']);
new Application(["id" => "yii2-json-messages", "basePath" => "@root/src"]);

+ 3
- 3
tool/clean.ps1 View File

@@ -2,10 +2,10 @@
Set-StrictMode -Version Latest
Set-Location (Split-Path $PSScriptRoot)

foreach ($item in 'build', 'doc/api', 'www') {
if (Test-Path $item) { Remove-Item $item -Recurse }
foreach ($item in "build", "doc/api", "www") {
if (Test-Path $item) { Remove-Item $item -Recurse }
}

foreach ($item in Get-ChildItem var -Exclude .gitkeep) {
Remove-Item $item -Recurse
Remove-Item $item -Recurse
}

+ 1
- 1
tool/doc.ps1 View File

@@ -2,7 +2,7 @@
Set-StrictMode -Version Latest
Set-Location (Split-Path $PSScriptRoot)

$phpdoc = $IsWindows ? 'php "C:/Program Files/PHP/share/phpDocumentor.phar"' : 'phpdoc';
$phpdoc = $IsWindows ? 'php "C:/Program Files/PHP/share/phpDocumentor.phar"' : "phpdoc";
Invoke-Expression "$phpdoc --config=etc/phpdoc.xml"

if (-not (Test-Path doc/api/images)) { New-Item doc/api/images -ItemType Directory | Out-Null }


+ 1
- 1
tool/upgrade.ps1 View File

@@ -6,5 +6,5 @@ git reset --hard
git fetch --all --prune
git pull --rebase

$composer = $IsWindows ? 'php "C:/Program Files/PHP/share/composer.phar"' : 'composer'
$composer = $IsWindows ? 'php "C:/Program Files/PHP/share/composer.phar"' : "composer"
Invoke-Expression "$composer update --no-interaction"

Loading…
Cancel
Save