LaravelPackages.net
Acme Inc.
Toggle sidebar
laragear/meta

A Laravel Package helper for Laravel Packages

1.056.646
7
v5.2.0
About laragear/meta

laragear/meta is a Laravel package for a laravel package helper for laravel packages. It currently has 7 GitHub stars and 1.056.646 downloads on Packagist (latest version v5.2.0). Install it with composer require laragear/meta. Discover more Laravel packages by laragear or browse all Laravel packages to compare alternatives.

Last updated

Meta

Latest Version on Packagist Latest stable test run Codecov coverage Maintainability Sonarcloud Status Laravel Octane Compatibility

A Laravel Package helper for Laravel Packages.

public function boot()
{
    $this->publishMigrations(__DIR__.'/../migrations');
    
    $this->withSchedule(fn($schedule) => $schedule->command('inspire')->hourly());
}

Keep this package free

Your support allows me to keep this package free, up-to-date and maintainable. Alternatively, you can spread the word!

Requirements

  • PHP 8.0 or later.
  • Laravel 9.x or later.

Installation

Require this package into your project using Composer:

composer require laragear/meta

Usage

This package contains traits and classes to ease package development and package testing.

All classes and traits have been marked with the @internal PHPDoc tag. This will avoid some IDE to take into account these structural files into autocompletion / intellisense.

Discoverer

The Discoverer class is a builder that allows discovering classes under a given path. It contains various fluent methods to filter the classes to discover, like methods, properties, interfaces and traits, among others.

use Laragear\Meta\Discover;
use Vendor\Package\Facades\MyMutator;

$files = Discover::in('Events')->withMethod('handle*')->all();

MyMutator::add($files);

It returns a Collection instance with instances of ReflectionClass to further filter the list.

use Laragear\Meta\Discover;
use ReflectionClass;

Discover::in('Events')->all()->filter(function (ReflectionClass $class) {
    // ...
});

Boot Helpers

The BootHelpers trait adds some convenient Service Provider methods at boot time to add rules, middleware, listeners, and subscribers.

// Extends a service manager after it resolves
$this->withExtending('cache', 'nfs', fn () => new NfsCacheDriver());

// Registers a validation rule.
$this->withValidationRule('age', fn($attribute, $value) => $value > 18, 'You are too young!', true);

// Registers a middleware using fluent methods.
$this->withMiddleware(OnlyAdults::class)->as('adults');

// Registers a listener for a given event.
$this->withListener('birthday', GreetOnBirthday::class);

// Registers a subscriber for many events.
$this->withSubscriber(BirthdaySubscriber::class);

// Registers one or many scheduled jobs using a callback.
$this->withSchedule(function ($schedule) {
    $schedule->command('package:something')->everyFifteenMinutes();
}) 

Middleware declaration

When using withMiddleware() you will receive a MiddlewareDeclaration object with convenient methods to register the middleware globally or inside a group, set it as first/last in the stack, and register an alias for it.

$declaration = $this->withMiddleware(OnlyAdults::class);

// Make it a shared instance.
$declaration->shared();

// Set an alias
$declaration->as('adults');

// Puts it inside a middleware group.
$declaration->inGroup('web');

// Sets the middleware in the global stack.
$declaration->globally();

// Makes the middleware run first or last in the priority stack.
$declaration->first();
$declaration->last();

Testing

Testing the Service Provider

The InteractsWithServiceProvider allows to quickly test if the Service Provider of your package has registered all the needed bits of code into the Service Container.

use Orchestra\Testbench\TestCase
use Laragear\Meta\Tests\InteractsWithServiceProvider;

class ServiceProviderTest extends TestCase
{
    use InteractsWithServiceProvider
    
    public function test_is_registered_as_singleton(): void
    {
        $this->assertSingletons(\Vendor\Package\MyService::class);
    }
}

The available assertions are in this table:

| Methods | | | |------------------------|---------------------------|-------------------------------| | assertServices() | assertViews() | assertGlobalMiddleware() | | assertSingletons() | assertBladeComponent() | assertMiddlewareInGroup() | | assertConfigMerged() | assertBladeDirectives() | assertScheduledTask() | | assertPublishes() | assertValidationRules() | assertScheduledTaskRunsAt() | | assertTranslations() | assertMiddlewareAlias() | assertMacro() |

Service Helpers

The InteractsWithServices trait includes helpers to retrieve services from the Service Container and do quick things.

// Get a service from the Service Container, optionally run over a callback.
$this->service('cache', fn ($cache) => $cache->set('foo', 'bar', 30))

// Run a service once and forgets it, while running a callback over it.
$this->serviceOnce('blade.compiler', fn($compiler) => $compiler->check('cool'));

// Executes a callback over a REAL service when already mocked.
$this->unmock('files', function ($files): void {
    $files->copyDirectory('foo', 'bar');
})

Validation

This meta package includes a InteractsWithValidation trait, that assert if a rule passes or fails using minimal data. This is useful when creating validation rules and testing them without too much boilerplate.

// Assert the validation rule passes.
$this->assertValidationPasses(['test' => 'foo'],['test' => 'my_rule']);

// Assert the validation rule fails.
$this->assertValidationFails(['test' => 'bar'],['test' => 'my_rule']);

Middleware

The InteractsWithMiddleware trait allows to quickly test a middleware with a temporal random route using testMiddleware(). It returns an instance of PendingRequest, which you can build with additional data to test a middleware thoughtfully.

$this->testMiddleware('my-middleware')
    ->inWebGroup()
    ->withCookie('foo', 'bar')
    ->get();

Builder extender

The ExtendsBuilder trait allows a scope to extend the instance of the Eloquent Builder with new methods. Simply add public static methods in the scope that receive a Builder instance, and optional parameters if you deem so.

use Illuminate\Database\Eloquent\Scope;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Model;
use Laragear\Meta\Database\Eloquent\ExtendsBuilder;

class Cars implements Scope
{
    use ExtendsBuilder;
    
    public function apply(Builder $builder, Model $model)
    {
        // ...
    }
    
    public static function whereAvailable(Builder $builder)
    {
        return $builder->where('available_at', '>', now());
    }
    
    public static function whereColor(Builder $builder, string $color)
    {
        return $builder->where('base_color', $color);
    }
}

Command Helpers

This meta package includes command helpers for modifying the environment file, other files, confirm on production, and operate with stub files.

  • WithEnvironmentFile trait allows checking and replace environment file keys.
  • WithFileComparison trait allows checking files existence and equality (hash).
  • WithProductionConfirmation trait allows to confirm an action on production environments.
  • WithStubs trait allows copying custom stubs to a destination, while replacing custom strings.

Laravel Octane compatibility

  • There are no singletons using a stale application instance.
  • There are no singletons using a stale config instance.
  • There are no singletons using a stale request instance.
  • There are no static properties being overwritten constantly.

There should be no problems using this package with Laravel Octane.

Security

If you discover any security related issues, please email [email protected] instead of using the issue tracker.

License

This specific package version is licensed under the terms of the MIT License, at time of publishing.

Laravel is a Trademark of Taylor Otwell. Copyright © 2011-2022 Laravel LLC.

Comments