Skip to content

Commit

Permalink
Merge pull request #16367 from craftcms/feature/ability-to-set-reques…
Browse files Browse the repository at this point in the history
…t-site

Ability to specify the site for a request
  • Loading branch information
brandonkelly authored Jan 2, 2025
2 parents 92cdb09 + 6c260ef commit 3db93e8
Show file tree
Hide file tree
Showing 3 changed files with 16 additions and 1 deletion.
1 change: 1 addition & 0 deletions CHANGELOG-WIP.md
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
## Development
- Added the `primarySite` global Twig variable. ([#16370](https://github.com/craftcms/cms/discussions/16370))
- The `duration` Twig filter now has a `language` argument. ([#16332](https://github.com/craftcms/cms/pull/16332))
- Added support for specifying the current site via an `X-Craft-Site` header set to a site ID or handle. ([#16367](https://github.com/craftcms/cms/pull/16367))
- Deprecated the `ucfirst` Twig filter. `capitalize` should be used instead.

## Extensibility
Expand Down
1 change: 0 additions & 1 deletion src/config/app.php
Original file line number Diff line number Diff line change
Expand Up @@ -183,7 +183,6 @@
],
'sites' => [
'class' => craft\services\Sites::class,
'currentSite' => craft\helpers\App::env('CRAFT_SITE'),
],
'i18n' => [
'class' => craft\i18n\I18N::class,
Expand Down
15 changes: 15 additions & 0 deletions src/web/Request.php
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@
use craft\helpers\StringHelper;
use craft\models\Site;
use craft\services\Sites;
use yii\base\InvalidArgumentException;
use yii\base\InvalidConfigException;
use yii\db\Exception as DbException;
use yii\di\Instance;
Expand Down Expand Up @@ -1516,6 +1517,20 @@ private function _requestedSite(?int &$siteScore = null): Site
return $site;
}

// Is CRAFT_SITE or X-Craft-Site present?
$siteId = App::env('CRAFT_SITE') ?? $this->getHeaders()->get('X-Craft-Site');
if ($siteId !== null) {
if (is_numeric($siteId)) {
$site = $this->sites->getSiteById($siteId, false);
} else {
$site = $this->sites->getSiteByHandle($siteId, false);
}
if (!$site && Craft::$app->getIsInstalled() && !Craft::$app->getUpdates()->getIsCraftUpdatePending()) {
throw new InvalidArgumentException("Invalid site: $siteId");
}
return $site;
}

$sites = $this->sites->getAllSites(false);

if (empty($sites)) {
Expand Down

0 comments on commit 3db93e8

Please sign in to comment.