Commit 900f9f1e authored by Akex's avatar Akex
Browse files

add func to read by line | add test data

parent 2a7f91b8
Loading
Loading
Loading
Loading
+29 −0
Original line number Diff line number Diff line
<?php

namespace App\Actions;

use Generator;

class ReadFileLineByLineAction
{
    /**
     * Принимает путь до файла,
     * проверяет, что файл существует и выводит пользователю построчный вывод используя yield
     * (файл можешь создать любой)
     *
     * @param string $filePath путь до файла
     * @return string|Generator  */
    public static function read(string $filePath): Generator
    {
        if (!file_exists($filePath)) {
            throw new Exception("неверный путь");
        }

        $file = fopen($filePath, 'r');
        while (!feof($file)) {
            yield fgets($file);
        }

        fclose($file);
    }
}
+11 −0
Original line number Diff line number Diff line
h
e
l
l
o

w
o
r
l
d
 No newline at end of file
+1 −1
Original line number Diff line number Diff line
@@ -8,5 +8,5 @@ namespace App\TestData;

class TestData
{

    public const FILE_PATH = "TestData/FileToRead.txt";
}
+8 −1
Original line number Diff line number Diff line
@@ -2,6 +2,13 @@

require_once __DIR__ . '/../vendor/autoload.php';

use App\Actions /*placeholder for a class */;
use App\Actions\ReadFileLineByLineAction;
use App\TestData\TestData;

try {
    foreach (ReadFileLineByLineAction::read(TestData::FILE_PATH) as $line) {
        echo $line;
    }
} catch (Exception $ex) {
    echo $ex->getMessage();
}