0
I’m creating a routine using the Symfony console
to create new controllers from a pre-existing template file, but when searching for pattern
defined in this template, the class SplFileObject
jumps and sometimes skips a few lines;
public function writeWithTemplate($template)
{
try {
$this->template = new \SplFileObject(__DIR__ . "/templates/{$template}", "r");
$pattern = '@' . strtoupper($template) . '@';
while (!$this->template->eof()) {
$this->file->fwrite($this->template->fgets());
}
return true;
} catch(\Exception $error) {
return false;
}
}
the $this->file
is also an open file using the SplFileObject
, in this way that this function the same works perfectly, however if I make some comparisons within the while
the write
is not applied correctly.
the template file is:
<?php
namespace App\Controller;
use App\Controller\Controller;
use Psr\Http\Message\ServerRequestInterface as Request;
use Psr\Http\Message\ResponseInterface as Response;
class @CONTROLLER@ extends Controller
{
public function main(Request $request, Response $response)
{
}
}
Note that there is a tag @CONTROLLER@
which is where I wish to do the substitution, if I do a check inside the while;
...
while (!$this->template->eof()) {
if (strpos($this->template->fgets(), $pattern) !== false) {
$line = str_replace($pattern, $this->fileName, $this->template->fgets());
}
$line = empty($line) ? $this->template->fgets() : $line;
$this->file->fwrite($line);
}
Sometimes the generated file comes out only with }
(1 or more) and several other meaningless combinations.
Got it right! Thanks! , the only thing I found strange is the question of
fgets()
, if I use 3x$this->template->fgets();
even inside the while I’ll pick up 3 lines at once? I thought catching the line was conditional oneof()
and that it would be he who would determine on which line the pointer would be.– RFL
eof
(Andnd Thef File) is used inwhile
to know if you have reached the end of the file. Who picks up the line is thefgets
. It is right that the staff will release the withdrawal of "fgets" in February, but it is not good to abuse the code :P– Bacco
http://php.net/manual/en/splfileobject.fgets.php
– Bacco
Yes Bacco, I know what is eof, what I had in mind is that eof would work together with fgets to know on which line to put the pointer.
– RFL