Completed
Push — add/premium-content-block ( 0777f3...9c4eb6 )
by Jeremy
55:22 queued 45:30
created

fix-monorepo-plugins-url.php ➔ jetpack_docker_plugins_url()   B

Complexity

Conditions 7
Paths 8

Size

Total Lines 25

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 7
nc 8
nop 3
dl 0
loc 25
rs 8.5866
c 0
b 0
f 0
1
<?php
2
/**
3
 * Plugin Name: Fix monorepo plugins_url
4
 * Description: In the Jetpack Docker dev environment, plugins_url fails for packages becuase the symlinks from vendor cause it to be unable to find the "plugin" that the URL is supposed to be relative to.
5
 * Version: 1.0
6
 * Author: Automattic
7
 * Author URI: https://automattic.com/
8
 * Text Domain: jetpack
9
 *
10
 * @package Jetpack.
11
 */
12
13
namespace Jetpack\Docker\MuPlugin\FixMonorepoPluginsUrl;
14
15
use Automattic\Jetpack\Constants as Jetpack_Constants;
16
17
/**
18
 * Fix the plugins_url in the Docker dev environment.
19
 *
20
 * @param string $url    The complete URL to the plugins directory including scheme and path.
21
 * @param string $path   Path relative to the URL to the plugins directory. Blank string
22
 *                       if no path is specified.
23
 * @param string $plugin The plugin file path to be relative to. Blank string if no plugin
24
 *                       is specified.
25
 * @return string Filtered URL
26
 */
27
function jetpack_docker_plugins_url( $url, $path, $plugin ) {
28
	global $wp_plugin_paths;
29
	static $monorepo, $packages;
30
31
	if ( ! isset( $monorepo ) ) {
32
		// Determine the path to the monorepo based on the path to Jetpack.
33
		$monorepo = dirname( dirname( dirname( Jetpack_Constants::get_constant( 'JETPACK__PLUGIN_DIR' ) ) ) ) . '/';
34
		$packages = $monorepo . 'projects/packages/';
35
	}
36
37
	if ( strpos( $url, $packages ) !== false && strpos( $plugin, $packages ) === 0 ) {
38
		// Look through available monorepo plugins until we find one with the plugin symlink.
39
		$suffix      = '/vendor/automattic/jetpack-' . substr( $plugin, strlen( $packages ) );
40
		$real_plugin = realpath( $plugin );
41
		if ( false !== $real_plugin ) {
42
			foreach ( $wp_plugin_paths as $dir ) {
43
				if ( realpath( $dir . $suffix ) === $real_plugin ) {
44
					return plugins_url( $path, $dir . $suffix );
45
				}
46
			}
47
		}
48
	}
49
50
	return $url;
51
}
52
add_filter( 'plugins_url', __NAMESPACE__ . '\jetpack_docker_plugins_url', 1, 3 );
53