Ellrion
10/21/2016 - 9:40 AM

Laravel tinker helper include file

Laravel tinker helper include file

<?php

/*
|--------------------------------------------------------------------------
| Tinker configs and helpers
|--------------------------------------------------------------------------
|
| Possible run with this include `php artisan tinker .tinker`
| Or see http://psysh.org/#configure (~/.config/psysh/config.php)
| `'defaultIncludes' => [ getcwd() . '/.tinker', ]`
|
*/

_Tinker::register(app_path('Models'), 'm');
_Tinker::register(app_path('Services/Domain'), 's');
_Tinker::alias(Carbon\Carbon::class, 'Carbon');

if (!function_exists('now')) {
    function now($timezone = null) {
        return Carbon\Carbon::now($timezone);
    }
}
if (!function_exists('cq')) {
    function cq($query) {
        return _Tinker::castQuery($query);
    }
}

/**
 * Class _Tinker
 * Helper class
 */
class _Tinker
{
    public static function castQuery($query)
    {
        if ($query instanceof \Illuminate\Database\Eloquent\Builder) {
            $query = $query->getQuery();
        }
        $sql = $query->toSql();
        $bindings = array_map(function ($binding) {
            return is_int($binding) || is_float($binding) ? $binding : "'{$binding}'";
        }, $query->getBindings());
        $raw = vsprintf(str_replace('?', "%s", $sql), $bindings);

        return compact('sql', 'bindings', 'raw');
    }

    public static function register($path, $base = null)
    {
        foreach (glob($path.'/*.php') as $file) {
            $class = trim(app()->getNamespace(), '\\') . str_replace([app_path(), '/', '.php'], ['', '\\', ''], $file);
            $alias = ($base ? $base . '\\' : '') . class_basename($class);
            self::alias($class, $alias);
        }
    }

    public static function alias($class, $alias = null)
    {
        if (!class_exists($alias = $alias ?: class_basename($class)) && class_exists($class)) {
            class_alias($class, $alias);
        }
    }
}

if ( ! function_exists('glob_recursive'))
{
    /**
     * Find pathnames matching a pattern recursive.
     *
     * Recursive analog glob function.
     * Does not support flag GLOB_BRACE.
     * Possible should move to helpers file.
     *
     * @param $pattern
     * @param int $flags
     * @return array
     */
    function glob_recursive($pattern, $flags = 0)
    {
        $files = glob($pattern, $flags);

        foreach (glob(dirname($pattern) . '/*', GLOB_ONLYDIR|GLOB_NOSORT) as $dir) {
            $files = array_merge($files, glob_recursive($dir.'/'.basename($pattern), $flags));
        }

        return $files;
    }
}