Skip to content

Instantly share code, notes, and snippets.

@librevlad
Created February 5, 2020 15:10
Show Gist options
  • Save librevlad/6da52d095f7ba3c9f9a9359ea420d800 to your computer and use it in GitHub Desktop.
Save librevlad/6da52d095f7ba3c9f9a9359ea420d800 to your computer and use it in GitHub Desktop.
Magic dates PoC
<?php
namespace Librevlad\MagicDates;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Support\ServiceProvider;
class MagicDatesServiceProvider extends ServiceProvider {
/**
* Bootstrap the application services.
*/
public function boot() {
if ( $this->app->runningInConsole() ) {
$this->publishes( [
__DIR__ . '/../config/config.php' => config_path( 'magic-dates.php' ),
], 'config' );
$this->loadMigrationsFrom( [
__DIR__ . '/../database/migrations',
] );
}
$magicDates = [];
\Event::listen( 'eloquent.booted*', function ( $obj ) use ( &$magicDates ) {
$class = str_replace( 'eloquent.booted: ', '', $obj );
$modelObject = app( $class );
$dates = $modelObject->getDates();
foreach ( $dates as $date ) {
$magicDates[ $date ] = $magicDates[ $date ] ?? [];
$magicDates[ $date ] = array_merge( $magicDates[ $date ], [ $class ] );
}
foreach ( $magicDates as $date => $models ) {
$word = $date;
if ( ends_with( $word, '_at' ) ) {
$word = substr( $word, 0, - 3 );
}
$methodName = lcfirst( camel_case( $word ) ) . 'Since';
Builder::macro( $methodName, function ( $d ) use ( $methodName, $date ) {
if ( method_exists( $this->model, $methodName ) || method_exists( $this->model, 'scope' . ucfirst( $methodName ) ) ) {
return $this;
}
return $this->where( $date, '>', $d );
} );
$methodName = lcfirst( camel_case( $word ) ) . 'Before';
Builder::macro( $methodName, function ( $d ) use ( $methodName, $date ) {
if ( method_exists( $this->model, $methodName ) || method_exists( $this->model, 'scope' . ucfirst( $methodName ) ) ) {
return $this;
}
return $this->where( $date, '<', $d );
} );
$methodName = lcfirst( camel_case( $word ) ) . 'Within';
Builder::macro( $methodName, function ( $d ) use ( $methodName, $date ) {
if ( method_exists( $this->model, $methodName ) || method_exists( $this->model, 'scope' . ucfirst( $methodName ) ) ) {
return $this;
}
return $this->whereBetween( $date, $d );
} );
}
} );
}
/**
* Register the application services.
*/
public function register() {
$this->app->bind( 'magic-dates', MagicDatesClass::class );
$this->mergeConfigFrom( __DIR__ . '/../config/config.php', 'magic-dates' );
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment