Load files and classes as lazy collections in Laravel.

Related tags

Laravel lody
Overview

🗄 Lody

Latest Version on Packagist GitHub Tests Action Status Total Downloads

Load files and classes as lazy collections in Laravel.

Installation

composer require lorisleiva/lody

Usage

Lody enables you to fetch all existing PHP classes of a provided path (or array of paths) that are relative to your application's base path. It returns a custom LazyCollection with helpful methods so that you can filter classes even further based on your own requirement. For example, the code below will fetch all non-abstract instances of Node within the given path recursively and register each of them.

use Lorisleiva\Lody\Lody;

Lody::classes('app/Workflow/Nodes')
    ->isNotAbstract()
    ->isInstanceOf(Node::class)
    ->each(fn (string $classname) => $this->register($classname));

If you want all files instead of existing PHP classes, you may use Lody::files instead.

use Lorisleiva\Lody\Lody;

Lody::files('app/Workflow/Nodes')
    ->each(fn (SplFileInfo $file) => $this->register($file));

Configuration

Resolving paths

When providing paths to the Lody::files or Lody::classes methods, Lody will automatically assume these paths are within the root of your application unless they start with a slash in which case they are left untouched.

You may configure this logic by calling the Lody::resolvePathUsing method on one of your service providers. The example below provides the default logic.

Lody::resolvePathUsing(function (string $path) {
    return Str::startsWith($path, DIRECTORY_SEPARATOR) ? $path : base_path($path);
});

Resolving classnames

When using the Lody::classes method, Lody will transform your filenames into classnames by following the PSR-4 conventions. That is, it will start with your App namespace and chain the rest of the filename with backslashes instead of forward slashes. E.g. app/Models/User will become App\Models\User.

You may configure this logic by calling the Lody::resolveClassnameUsing method on one of your service providers. The example below provides the default logic.

Lody::resolveClassnameUsing(function (SplFileInfo $file) {
    $classnameFromAppPath = str_replace(
        ['/', '.php'],
        ['\\', ''],
        Str::after($file->getRealPath(), realpath(app_path()).DIRECTORY_SEPARATOR)
    );

    return app()->getNamespace() . $classnameFromAppPath;
});

References

Lody

// All return an instance of FileLazyCollection (see below).
Lody::files('app/Actions');
Lody::files(['app/Auth/Actions', 'app/Billing/Actions']);
Lody::files('app/Actions', recursive: false); // Non-recursively.
Lody::files('app/Actions', hidden: true); // Includes dot files.
Lody::filesFromFinder(Finder::create()->files()->in(app_path('Actions'))->depth(1)); // With custom finder.

// All return an instance of ClassnameLazyCollection (see below).
Lody::classes('app/Actions');
Lody::classes(['app/Auth/Actions', 'app/Billing/Actions']);
Lody::classes('app/Actions', recursive: false); // Non-recursively.
Lody::classesFromFinder(Finder::create()->files()->in(app_path('Actions'))->depth(1)); // With custom finder.

// Registering custom resolvers.
Lody::resolvePathUsing(fn(string $path) => ...);
Lody::resolveClassnameUsing(fn(SplFileInfo $file) => ...);

FileLazyCollection

// Transforms files into classnames and returns a `ClassnameLazyCollection`.
// Note that these can still be invalid classes. See `classExists` below.
Lody::files('...')->getClassnames();

ClassnameLazyCollection

// The `classExists` rejects all classnames that do not reference a valid PHP class.
Lody::files('...')->getClassnames()->classExists();

// Note that this is equivalent to the line above.
Lody::classes('...');

// Filter abstract classes.
Lody::classes('...')->isAbstract();
Lody::classes('...')->isNotAbstract();

// Filter classes based on inheritance.
Lody::classes('...')->isInstanceOf(SomeClassOrInterface::class);
Lody::classes('...')->isNotInstanceOf(SomeClassOrInterface::class);

// Filter classes based on traits.
Lody::classes('...')->hasTrait(SomeTrait::class);
Lody::classes('...')->hasTrait(SomeTrait::class, recursive: false); // Don't include recursive traits.
Lody::classes('...')->doesNotHaveTrait(SomeTrait::class);
Lody::classes('...')->doesNotHaveTrait(SomeTrait::class, recursive: false); // Don't include recursive traits.

// Filter classes based on method it contains or not.
Lody::classes('...')->hasMethod('someMethod');
Lody::classes('...')->hasStaticMethod('someMethod'); // Ensures the method is static.
Lody::classes('...')->hasNonStaticMethod('someMethod'); // Ensures the method is non-static.
Lody::classes('...')->doesNotHaveMethod('someMethod');
You might also like...
A Laravel package that allows you to use multiple
A Laravel package that allows you to use multiple ".env" files in a precedent manner. Use ".env" files per domain (multi-tentant)!

Laravel Multi ENVs Use multiple .envs files and have a chain of precedence for the environment variables in these different .envs files. Use the .env

A light weight laravel package that facilitates dealing with arabic concepts using a set of classes and methods to make laravel speaks arabic

A light weight laravel package that facilitates dealing with arabic concepts using a set of classes and methods to make laravel speaks arabic! concepts like , Hijri Dates & Arabic strings and so on ..

Package with small support traits and classes for the Laravel Eloquent models

Contains a set of traits for the eloquent model. In future can contain more set of classes/traits for the eloquent database.

A university system that creates a timetable programm for subjects,classes and teachers which is used to create a programm for each semester. All this served as a website.

Timetable-System-Generator A university system that creates a timetable programm for subjects,classes and teachers which is used to create a programm

Collection of the Laravel/Eloquent Model classes that allows you to get data directly from a Magento 2 database.

Laragento LAravel MAgento Micro services Magento 2 has legacy code based on abandoned Zend Framework 1 with really ugly ORM on top of outdated Zend_DB

A laravel package to attach uuid to model classes

Laravel Model UUID A simple package to generate model uuid for laravel models Installation Require the package using composer: composer require touhid

An opinioned approach to extend the laravel seed classes.

Laravel Seed Extender A highly opinioned way to work with the laravel seeder. Installation Require the package using composer: composer require touhid

Use Laravel's built-in ORM classes to query cloud resources with Steampipe.
Use Laravel's built-in ORM classes to query cloud resources with Steampipe.

Laravel Steampipe Use Laravel's built-in ORM classes to query cloud resources with Steampipe, an open source CLI to instantly query cloud APIs using S

Collection of classes you can use to standardize data formats in your Laravel application.
Collection of classes you can use to standardize data formats in your Laravel application.

Laravel Formatters This package is a collection of classes you can use to standardize data formats in your Laravel application. It uses the Service Co

Comments
  • Psr4Resolver issue on Windows

    Psr4Resolver issue on Windows

    Hello,

    I'm trying to automatically register commands on laravel-actions, but found that this isn't working on windows.

    I've tracked it down to vendor\lorisleiva\lody\src\Psr4Resolver.php, on method findPrefixes you have:

    public function findPrefixes(string $filename): array
    {
        $directory = $this->getPsr4Dictionary();
        $fragments = array_reverse(explode(DIRECTORY_SEPARATOR, $filename));
        $accumulator = $filename;
    
        foreach ($fragments as $fragment) {
            $accumulator = Str::beforeLast($accumulator, DIRECTORY_SEPARATOR.$fragment);
    
            if ($classPrefix = ($directory[$accumulator] ?? false)) {
                return [realpath($accumulator).DIRECTORY_SEPARATOR, $classPrefix];
            }
        }
    
        return ['', ''];
    }
    

    I see two issues related with windows paths:

    First, getPsr4Dictionary method returns an array of paths, but on windows they have a mixed directory separators:

    array:201 [
      "D:\desarrollos\enertrade.es\api.enertrade.es\vendor/voku/portable-ascii/src/voku" => "voku\"
      "D:\desarrollos\enertrade.es\api.enertrade.es\vendor/phpdocumentor/reflection-common/src" => "phpDocumentor\Reflection\"
      "D:\desarrollos\enertrade.es\api.enertrade.es\vendor/phpdocumentor/reflection-docblock/src" => "phpDocumentor\Reflection\"
      "D:\desarrollos\enertrade.es\api.enertrade.es\vendor/phpdocumentor/type-resolver/src" => "phpDocumentor\Reflection\"
      "D:\desarrollos\enertrade.es\api.enertrade.es\vendor/hisorange/browser-detect/src" => "hisorange\BrowserDetect\"
      "D:\desarrollos\enertrade.es\api.enertrade.es\vendor/maennchen/zipstream-php/src" => "ZipStream\"
    ...
    ]
    

    Then $fragments on linux is an array:

    array:9 [
      0 => "ActualizaConfiguracionesCamposPortugal.php"
      1 => "Configuradores"
      2 => "Actions"
      3 => "app"
      4 => "intranet"
      5 => "enertrade"
      6 => "vagrant"
      7 => "home"
      8 => ""
    ]
    

    But on windows you have the drive letter

    array:8 [
      0 => "ActualizaConfiguracionesCamposPortugal.php"
      1 => "Configuradores"
      2 => "Actions"
      3 => "app"
      4 => "api.enertrade.es"
      5 => "enertrade.es"
      6 => "desarrollos"
      7 => "D:"
    ]
    

    As you prepend DIRECTORY_SEPARATOR to each fragment, to search for $classPrefix and they're mixed, but also there's no leading DIRECTORY_SEPARATOR on windows but a drive letter, it fails to find the any $classPrefix.

    I'm sorry I'm not sure I understand how the whole thing works and how you would like this to be solved, I cannot send a PR for this.

    opened by underdpt 3
Releases(v0.3.0)
  • v0.3.0(Jan 25, 2022)

    What's Changed

    • Add Windows support and tests by @lorisleiva in https://github.com/lorisleiva/lody/pull/3
    • Add support for Laravel 9 and PHP 8.1 by @lorisleiva in https://github.com/lorisleiva/lody/pull/4

    Full Changelog: https://github.com/lorisleiva/lody/compare/v0.2.0...v0.3.0

    Source code(tar.gz)
    Source code(zip)
  • v0.2.0(Nov 11, 2021)

    Resolve class names from filenames using PSR-4. It uses the vendor/composer/autoload_psr4.php file to generate a dictionary of all namespaces from their paths. This means, Lody now properly resolve classes even in the vendor directory. See the readme for me details.

    Full Changelog: https://github.com/lorisleiva/lody/compare/v0.1.0...v0.2.0

    Source code(tar.gz)
    Source code(zip)
  • v0.1.0(Jul 4, 2021)

Owner
Loris Leiva
Hi there my geeky friends! 👋🦄
Loris Leiva
These are simple array and object collections that provide convinient methods to manipulate them.

Simple Collections These are simple array and object collections that provide convinient methods to manipulate collections; To install this package ty

Artem 4 Nov 19, 2021
Source code behind the Laracasts Larabit: My Favorite Laravel Collections Methods

My Favorite Laravel Collections Methods This is the source code behind the Laracasts Larabit: My Favorite Laravel Collections Methods, and features al

Andrew Schmelyun 2 Dec 2, 2021
A Collections-only split from Laravel's Illuminate Support

Collect - Illuminate Collections Deprecated: With the separation of Illuminate's Collections package, Collect is no longer necessary ?? . We will main

Tighten 1.5k Dec 28, 2022
A Collections-only split from Laravel's Illuminate Support

Collect - Illuminate Collections Deprecated: With the separation of Illuminate's Collections package, Collect is no longer necessary ?? . We will main

Tighten 1.5k Dec 30, 2022
Laravel Proxy Package for handling sessions when behind load balancers or other intermediaries.

Laravel Trusted Proxies Setting a trusted proxy allows for correct URL generation, redirecting, session handling and logging in Laravel when behind a

Chris Fidao 7.3k Jan 4, 2023
Automatically load your helpers in your laravel application.

Laravel AutoHelpers Automatically load your helpers in your laravel application. Installation You can install the package via composer: composer requi

Florian Wartner 6 Jul 26, 2021
Load Laravel service providers based on your application's environment.

Laravel EnvProviders A more finetuned way of managing your service providers in Laravel. This package allows you to configure the environment certain

Sven Luijten 79 Dec 29, 2022
Load head metadata from a manifest file which can be shared with a SPA project

Laravel Head Manifest Installation Step 1: Add Laravel Head Manifest to your laravel project composer require critiq/laravel-head-manifest Step 2: Add

Critiq 1 Nov 17, 2021
With dadjokes every time you load your control panel you'll be greeted by an epic dad joke on the dashboard.

Filament Dad Jokes Widget With DadJokes every time you load your control panel you'll be greeted by an epic dad joke on the dashboard. Installation Yo

Craig Smith 15 Jan 7, 2023
A laravel package to generate class files from stub files.

Laravel Stub Generator A php laravel package to generate useable php files from given stub files . Installation Require the package using composer: co

Touhidur Rahman 31 Dec 29, 2022