PHP code example of theflowbyte / laravel-macro-attribute
1. Go to this page and download the library: Download theflowbyte/laravel-macro-attribute library. Choose the download type require.
2. Extract the ZIP file and open the index.php.
3. Add this code to the index.php.
<?php
require_once('vendor/autoload.php');
/* Start to develop here. Best regards https://php-download.com/ */
theflowbyte / laravel-macro-attribute example snippets
namespace App\Helpers;
use TheFlowByte\MacroAttribute\Attributes\Macro;
use Illuminate\Http\Request;
class CrawlerHelper
{
#[Macro(targetClass: Request::class)]
public static function isCrawler(Request $request): bool
{
$userAgent = strtolower($request->header('User-Agent', ''));
return str_contains($userAgent, 'bot');
}
#[Macro(targetClass: Request::class, macroName: 'denyCrawlerAccess')]
public static function shouldBlockCrawler(Request $request): bool
{
$userAgent = strtolower($request->header('User-Agent', ''));
$blockedBots = config('bots.blacklist', []);
foreach ($blockedBots as $bot) {
if (str_contains($userAgent, $bot)) {
return true;
}
}
return false;
}
}
namespace App\Providers;
use Illuminate\Support\ServiceProvider;
use TheFlowByte\MacroAttribute\Loaders\MacroAttributeLoader;
use App\Helpers\CrawlerHelper;
class AppServiceProvider extends ServiceProvider
{
public function boot()
{
// Register the macros from the specified class
MacroAttributeLoader::register([
CrawlerHelper::class,
// ...
]);
}
}
namespace App\Http\Middleware;
use Closure;
use Illuminate\Http\Request;
class BlockCrawlers
{
public function handle(Request $request, Closure $next)
{
if ($request->isCrawler()) {
logger()->debug('Request identified as coming from a crawler.');
}
if ($request->denyCrawlerAccess()) {
return response('Access Denied for Crawlers.', 403);
}
return $next($request);
}
}
use TheFlowByte\MacroAttribute\Attributes\Macro;
use App\Models\Order;
use App\Models\Invoice;
class FinancialMacros
{
#[Macro(targetClass: [Order::class, Invoice::class])]
public static function calculateTotalWithTax(HasSubtotal $model, float $taxRate = 0.2): float
{
return $model->subtotal + ($model->subtotal * $taxRate);
}
}
Loading please wait ...
Before you can download the PHP files, the dependencies should be resolved. This can take some minutes. Please be patient.