Created
December 27, 2023 05:46
-
-
Save pryley/e7050d6d759e706d07b20517dc830605 to your computer and use it in GitHub Desktop.
LocalValetDriver which supports WordPress Multisite
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
use Valet\Drivers\Specific\WordPressValetDriver; | |
class LocalValetDriver 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, $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 true; | |
} | |
/** | |
* 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(dirname(__FILE__).'/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 (!$this->isMultisite($sitePath)) { | |
return $uri; | |
} | |
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