| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081 |
- <?php
-
- namespace App\Storefront;
-
- use App\Models\Store;
- use Illuminate\Http\Request;
-
- /**
- * One visit to a store's pages, in one of two ways:
- *
- * - Live: a shopper on the store's own address (such as sambal-nenek.localhost). No login.
- * Shows the published copy of the design. Only published stores can be opened.
- * - Preview: the owner, logged in, inside the dashboard address. Shows the working design.
- *
- * The same controllers and pages serve both. This class is the only place that knows the difference.
- */
- final readonly class Storefront
- {
- /**
- * @param array<string, mixed> $plan The design to draw.
- * @param string $baseUrl Path of the store's home page. Every other store address is built on it.
- */
- public function __construct(
- public Store $store,
- public array $plan,
- public string $baseUrl,
- public bool $preview,
- private string $origin,
- ) {}
-
- /**
- * Work out which store this request is for. Gives "not found" when the visitor may not see it.
- */
- public static function fromRequest(Request $request): self
- {
- $liveSlug = $request->route('storeSlug');
-
- if (is_string($liveSlug)) {
- $store = Store::query()->published()->where('slug', $liveSlug)->firstOrFail();
-
- // A store is only live while its owner has a plan: a paid one, or a free trial that has not ended.
- abort_if($store->user->currentPlan() === null, 404);
-
- return new self($store, $store->published_plan ?? [], '', false, $request->getSchemeAndHttpHost());
- }
-
- $store = $request->user()?->stores()->where('slug', (string) $request->route('slug'))->first();
-
- abort_if($store === null || $store->plan === null, 404);
-
- return new self($store, $store->plan, route('stores.preview', $store->slug, false), true, $request->getSchemeAndHttpHost());
- }
-
- /**
- * A path inside this store, such as "/cart".
- */
- public function path(string $path = ''): string
- {
- return $this->baseUrl.$path ?: '/';
- }
-
- /**
- * A full web address inside this store, for places outside our pages (the payment provider, emails).
- */
- public function url(string $path = ''): string
- {
- return $this->origin.$this->path($path);
- }
-
- /**
- * The address shoppers open a published store at, built from the address the app itself is on.
- * "http://localhost:8000" and store "luna-skin" give "http://luna-skin.localhost:8000".
- */
- public static function liveUrl(Store $store, Request $request): string
- {
- $port = $request->getPort();
- $standard = ($request->getScheme() === 'https' && $port === 443) || ($request->getScheme() === 'http' && $port === 80);
-
- return $request->getScheme().'://'.$store->slug.'.'.config('storefront.domain').($standard || $port === null ? '' : ':'.$port);
- }
- }
|