statamic / ssg

The official Statamic Static Site Generator
229 stars 23 forks source link

Exception when using `request()` #134

Closed aerni closed 1 month ago

aerni commented 1 year ago

An issue was brought to my attention when using statamic/ssg and aerni/advanced-seo. It might be related to https://github.com/statamic/ssg/issues/99 as it's the same exception.

The following exception happens whenever you run php please ssg:generate:

[2023-06-07 14:13:12] local.ERROR: Call to a member function url() on null {"exception":"[object] (Error(code: 0): Call to a member function url() on null at /Users/michael/Code/ssg-advanced/vendor/statamic/ssg/src/Request.php:51)
[stacktrace]
#0 /Users/michael/Code/ssg-advanced/vendor/statamic/ssg/src/Request.php(56): Statamic\\StaticSite\\Request->getPathInfo()
#1 /Users/michael/Code/ssg-advanced/vendor/aerni/advanced-seo/src/Support/Helpers.php(23): Statamic\\StaticSite\\Request->path()
#2 /Users/michael/Code/ssg-advanced/vendor/aerni/advanced-seo/src/Subscribers/OnPageSeoBlueprintSubscriber.php(167): Aerni\\AdvancedSeo\\Support\\Helpers::isBlueprintCpRoute()
#3 /Users/michael/Code/ssg-advanced/vendor/aerni/advanced-seo/src/Subscribers/OnPageSeoBlueprintSubscriber.php(36): Aerni\\AdvancedSeo\\Subscribers\\OnPageSeoBlueprintSubscriber->shouldExtendBlueprint(Object(Statamic\\Events\\EntryBlueprintFound))
#4 /Users/michael/Code/ssg-advanced/vendor/laravel/framework/src/Illuminate/Events/Dispatcher.php(441): Aerni\\AdvancedSeo\\Subscribers\\OnPageSeoBlueprintSubscriber->extendBlueprint(Object(Statamic\\Events\\EntryBlueprintFound))
...

The exception is triggered by request()->path() in this helper method:

public static function isBlueprintCpRoute(): bool
{
    return Str::containsAll(request()->path(), [config('statamic.cp.route', 'cp'), 'blueprints']);
}

This can easily be reproduced by following these steps:

How to reproduce

Add this listener:

<?php

namespace App\Listeners;

class ExtendBlueprint
{
    public function handle(object $event): void
    {
        request()->path();
    }
}

Register the listener in the EventServiceProvider:

protected $listen = [
    EntryBlueprintFound::class => [
        ExtendBlueprint::class,
    ],
];

Run php please ssg:generate.

globalexport commented 7 months ago

I can add to this that the same breaking problem occurs when using the aardvark-seo package.

jasonvarga commented 7 months ago

This is probably fixable if we bind our custom Request into 'request'.