Skip to content

Instantly share code, notes, and snippets.

@pryley
Last active December 27, 2023 05:25
Show Gist options
  • Save pryley/b42af19c70dee7c22e51f4ab9c834ea9 to your computer and use it in GitHub Desktop.
Save pryley/b42af19c70dee7c22e51f4ab9c834ea9 to your computer and use it in GitHub Desktop.
File goes here: ~/Library/Application Support/Herd/config/valet/Drivers/MultisiteValetDriver.php
<?php
namespace Valet\Drivers\Custom;
use Valet\Drivers\Specific\WordPressValetDriver;
class MultisiteValetDriver extends WordPressValetDriver
{
/**
* Get the fully resolved path to the application's front controller.
*/
public function frontControllerPath(string $sitePath, string $siteName, string $uri): ?string
{
$uri = $this->rewriteMultisite($sitePath, $uri);
return parent::frontControllerPath(
$sitePath,
$siteName,
$this->forceTrailingSlash($uri)
);
}
/**
* Determine if the incoming request is for a static file.
*/
public function isStaticFile(string $sitePath, string $siteName, string $uri)/*: string|false */
{
$uri = $this->rewriteMultisite($sitePath, $uri);
return parent::isStaticFile($sitePath, $siteName, $uri);
}
/**
* Determine if the driver serves the request.
*/
public function serves(string $sitePath, string $siteName, string $uri): bool
{
return $this->isMultisite($sitePath) && parent::serves($sitePath, $siteName, $uri);
}
/**
* Redirect to uri with trailing slash.
*/
private function forceTrailingSlash($uri): ?string
{
if (substr($uri, -1 * strlen('/wp-admin')) === '/wp-admin') {
header('Location: '.$uri.'/');
exit;
}
return $uri;
}
/**
* Determine if the application is Multisite.
*/
private function isMultisite(string $sitePath): bool
{
$config = file_get_contents($sitePath.'/wp-config.php');
return (bool) preg_match("/define\(\s*('|\")MULTISITE\\1\s*,\s*true\s*\)/mi", $config);
}
/**
* Imitate the rewrite rules for a multisite .htaccess.
*/
private function rewriteMultisite(string $sitePath, string $uri): string
{
if (preg_match('#^(/[^/]+)?(?!/wp-json)(/wp-.*)#', $uri, $matches) || preg_match('#^(/[^/]+)?(/.*\.php)#', $uri, $matches)) {
return $matches[2];
}
return $uri;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment