Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[8.x] Add File::lines($path) method #34187

Merged
merged 1 commit into from
Sep 8, 2020

Conversation

JosephSilber
Copy link
Member

@JosephSilber JosephSilber commented Sep 7, 2020

Many of the most useful scenarios for using lazy collections involves reading files line by line (see here for more details).

This PR adds a lines method to the Filesystem class, to lazily read the lines of a file:

$collection = File::lines($path);

Example

With this in place, you can easily read Laravel's logs lazily (using the new chunkWhile method):

$pattern = '/^[\d\d\d\d-\d\d-\d\d \d\d:\d\d:\d\d]/'; // starts with e.g. [2020-09-07 00:24:11]

$logs = File::lines(storage_path('logs/laravel.log'))
    ->chunkWhile(fn ($line) => ! preg_match($pattern, $line));

The $logs variable will now be a lazy collection, from which we can pull out a single log entry at a time.

@JosephSilber JosephSilber force-pushed the files-lines branch 2 times, most recently from 37da74d to d7b139c Compare September 7, 2020 17:27
@GrahamCampbell
Copy link
Member

GrahamCampbell commented Sep 7, 2020

Lazy collections could be quite appropriate for paginating eloquent queries tbh. Currently there's an each method, but we could "go native" as it were, and have a way to do getLazy() or something.

@taylorotwell taylorotwell merged commit 154fef3 into laravel:8.x Sep 8, 2020
@JosephSilber JosephSilber deleted the files-lines branch September 8, 2020 13:55
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

5 participants