Skip to content

Commit

Permalink
Merge pull request #8 from cooperaj/docs_update
Browse files Browse the repository at this point in the history
Update with v3 upgrade instructions and script
  • Loading branch information
cooperaj authored Jul 19, 2023
2 parents 1db25d3 + f1f38a8 commit 3d95d36
Show file tree
Hide file tree
Showing 2 changed files with 71 additions and 2 deletions.
19 changes: 17 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -94,10 +94,25 @@ msgstr[0] ""
// This will
$value = $translator->translate('I have an apple');
```



## Usage

> See [extract.php](example/extract.php) and [index.php](example/index.php) for example usage.

## Upgrading

### Upgrading to v3.0.0 from prior versions

v3 introduces a new method of extracting keys that removes whitespace of more than 2 characters from the primary
language keys ([see the release notes for more information](https://github.com/cooperaj/better-twig-i18n/releases/tag/v3.0.0))

There is a [script](./scripts/v3_po_update.php) available in the [scripts folder](./scripts) that will help to migrate
any existing PO files you have to the newer keys and minimise the pain of poedit deciding everything is new rather than
different. It will likely need editing to your requirements but is usage is simple.

```shell
$ cp scripts/v3_po_update.php folder/containing/po.files
$ cd folder/containing/po.files
# edit script as appropriate for your translation domains
$ php v3_po_update.php
```
54 changes: 54 additions & 0 deletions scripts/v3_po_update.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
<?php

declare(strict_types=1);

const START_TOKEN = "/^msgid \"\"\n/";
const END_TOKEN = "/^msgstr \"/";

function correctBuffer(string $buffer): string
{
$lines = explode("\n", $buffer);

$rebuilt = '';
foreach ($lines as $line) {
$line = trim(trim($line), '"');
$rebuilt .= $line;
}

$rebuilt = preg_replace('/\\\\n/', ' ', $rebuilt);

return sprintf("msgid \"%s\"\n", trim(preg_replace('/\s{2,}/', ' ', $rebuilt)));
}

try {
$file_in = fopen('messages.po', 'r');
$file_out = fopen('messages_fixed.po', 'w');

$in_block = false;
$correction_buffer = '';

while (($buffer = fgets($file_in)) !== false) {
if (preg_match(START_TOKEN, $buffer)) {
$in_block = true;
$correction_buffer = '';
continue;
}

if (!$in_block) {
fputs($file_out, $buffer);
} elseif (preg_match(END_TOKEN, $buffer)) {
fputs($file_out, correctBuffer($correction_buffer));
fputs($file_out, $buffer);

$in_block = false;
$correction_buffer = '';
} else {
$correction_buffer .= $buffer;
}
}
} catch (Exception $ex) {
print $ex;
} finally {
fclose($file_in);
fclose($file_out);
}

0 comments on commit 3d95d36

Please sign in to comment.