Skip to content

Instantly share code, notes, and snippets.

@chrisvanpatten
Last active February 3, 2021 19:05
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save chrisvanpatten/ef608a325180c44d30c71fef77b92fb6 to your computer and use it in GitHub Desktop.
Save chrisvanpatten/ef608a325180c44d30c71fef77b92fb6 to your computer and use it in GitHub Desktop.
Automatically symlink `object-cache.php` after installing `wp-redis`.
...
"scripts": {
"post-package-install": [
"Namespace\\Scripts\\Composer::addObjectCacheSymlink"
],
"post-package-update": [
"Namespace\\Scripts\\Composer::addObjectCacheSymlink"
],
"pre-package-uninstall": [
"Namespace\\Scripts\\Composer::removeObjectCacheSymlink"
],
},
...
<?php
declare(strict_types=1);
namespace Namespace\Scripts;
use Composer\Installer\PackageEvent;
class Composer
{
/**
* Location of the object cache file.
*
* @param string
*/
protected static $objectCacheFilePath = './web/wp-content/object-cache.php';
/**
* Create the symlink for object-cache.php when wp-redis is installed or
* updated.
*
* @param PackageEvent $event The event being executed.
* @return void
*/
public static function addObjectCacheSymlink(PackageEvent $event): void
{
$operation = $event->getOperation();
if (!method_exists($operation, 'getPackage')) {
return;
}
$installedPackage = $operation->getPackage();
if ($installedPackage->getName() !== 'wpackagist-plugin/wp-redis') {
return;
}
$io = $event->getIO();
if (is_link(static::$objectCacheFilePath)) {
$io->write('Symlink for object-cache.php already exists.');
return;
}
try {
$result = symlink(
'./plugins/wp-redis/object-cache.php',
static::$objectCacheFilePath,
);
if (!$result) {
throw new Exception();
}
} catch (\Exception $e) {
$io->writeError('Could not create object-cache.php symlink.');
return;
}
$io->write('Created object-cache.php symlink for wp-redis.');
}
/**
* Remove the object-cache.php symlink when wp-redis is uninstalled.
*
* @param PackageEvent $event The event being executed.
* @return void
*/
public static function removeObjectCacheSymlink(PackageEvent $event): void
{
$installedPackage = $event->getOperation()->getPackage();
if ($installedPackage->getName() !== 'wpackagist-plugin/wp-redis') {
return;
}
$io = $event->getIO();
try {
$result = unlink(static::$objectCacheFilePath);
if (!$result) {
throw new \Exception();
}
} catch (\Exception $e) {
$io->writeError('Failed to remove object-cache.php symlink. It may have already been removed.');
return;
}
$io->write('Created object-cache.php symlink for wp-redis.');
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment