php-gettext / Gettext

PHP library to collect and manipulate gettext (.po, .mo, .php, .json, etc)
MIT License
687 stars 132 forks source link

Subsequent loadFile fails #257

Closed vielhuber closed 2 years ago

vielhuber commented 4 years ago
<?php
require_once(__DIR__ . '/vendor/autoload.php');
use Gettext\Loader\PoLoader;
use Gettext\Generator\PoGenerator;
use Gettext\Generator\MoGenerator;
use Gettext\Translation;
use Gettext\Translations;

// setup
$poLoader = new PoLoader();
$poGenerator = new PoGenerator();
file_put_contents('test.po', '');
$translations = $poLoader->loadFile('test.po');
$translation = Translation::create('foo', 'bar');
$translations->add($translation);
$poGenerator->generateFile($translations, 'test.po');

// load again
$poLoader = new PoLoader();
$poGenerator = new PoGenerator();
$translations = $poLoader->loadFile('test.po');
var_dump(count($translations->getTranslations())); // this returns "0"

Fix (Generator.php):

    public function generateFile(Translations $translations, string $filename): bool
    {
        $content = $this->generateString($translations);

        $res = file_put_contents($filename, $content) !== false;
        clearstatcache();
        return $res;
    }

Reason: https://www.php.net/manual/de/function.filesize.php#101996

vielhuber commented 4 years ago

The fix above is not sufficient: This has to be done inside loadFile.

ideag commented 2 years ago

Hi @oscarotero, I'd like to help fixing this, as we seem to have issues when we try to modify the same PO file several times. Is there any specific reason for using fopen/fread in the readFile method instead of file_get_contents? In our experience using file_get_contents solves the issues for us, but maybe I'm not aware of something?

oscarotero commented 2 years ago

Hi @ideag Sorry, I missed this. Yes, you can use file_get_contents, I don't remember any special reason to use fopen. Thanks for your contribution!

ideag commented 2 years ago

I'll make a PR 👍