Completed
Push — add/cli ( 74cf7f...2842da )
by
unknown
10:13
created

Autoloader::activate()   A

Complexity

Conditions 4
Paths 4

Size

Total Lines 26

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 4
nc 4
nop 1
dl 0
loc 26
rs 9.504
c 0
b 0
f 0
1
<?php
2
/* HEADER */ // phpcs:ignore
3
4
/**
5
 * This class handles management of the actual PHP autoloader.
6
 */
7
class Autoloader {
8
9
	/**
10
	 * Checks to see whether or not the autoloader should be initialized and then initializes it if so.
11
	 *
12
	 * @param Container|null $container The container we want to use for autoloader initialization. If none is given
13
	 *                                  then a container will be created automatically.
14
	 */
15
	public static function init( $container = null ) {
16
		// The container holds and manages the lifecycle of our dependencies
17
		// to make them easier to work with and increase flexibility.
18
		if ( ! isset( $container ) ) {
19
			require_once __DIR__ . '/class-container.php';
20
			$container = new Container();
21
		}
22
23
		// phpcs:disable Generic.Commenting.DocComment.MissingShort
24
25
		/** @var Plugin_Locator $plugin_locator */
26
		$plugin_locator = $container->get( Plugin_Locator::class );
27
28
		/** @var Plugins_Handler $plugins_handler */
29
		$plugins_handler = $container->get( Plugins_Handler::class );
30
31
		// The current plugin is the one that we are attempting to initialize here.
32
		$current_plugin = $plugin_locator->find_current_plugin();
33
34
		// The cached plugins are all of those that were active or discovered by the autoloader during a previous request.
35
		// Note that it's possible this list will include plugins that have since been deactivated, but after a request
36
		// the cache should be updated and the deactivated plugins will be removed.
37
		$cached_plugins = $plugins_handler->get_cached_plugins();
38
39
		// The active plugins are those that we were able to discover in on the site. This list will not include
40
		// mu-plugins, those activated by code, or those who are hidden by filtering.
41
		// By combining these lists we can preemptively load classes for plugins that are activated via another method.
42
		// While this may result in us considering packages in deactivated plugins the request after they're removed,
43
		// there shouldn't be any problems as a result and the eventual consistency is reliable enough.
44
		$all_plugins = array_values( array_unique( array_merge( $plugins_handler->get_active_plugins(), $cached_plugins ) ) );
45
46
		/** @var Latest_Autoloader_Guard $guard */
47
		$guard = $container->get( Latest_Autoloader_Guard::class );
48
		if ( $guard->should_stop_init( $current_plugin, $all_plugins ) ) {
49
			return;
50
		}
51
52
		/** @var Autoloader_Handler $autoloader_handler */
53
		$autoloader_handler = $container->get( Autoloader_Handler::class );
54
55
		// Initialize the autoloader using the handler now that we're ready.
56
		$autoloader_handler->create_autoloader( $all_plugins );
57
58
		/** @var Hook_Manager $hook_manager */
59
		$hook_manager = $container->get( Hook_Manager::class );
60
61
		// When the active and cached plugin lists do not match we should
62
		// update the cache. This will prevent plugins that have been
63
		// deactivated from being considered in other requests.
64
		$hook_manager->add_action(
65
			'shutdown',
66
			function () use ( $plugins_handler, $cached_plugins ) {
67
				// Don't save a broken cache if an error happens during some plugin's initialization.
68
				if ( ! did_action( 'plugins_loaded' ) ) {
69
					// Ensure that the cache is emptied to prevent consecutive failures if the cache is to blame.
70
					if ( ! empty( $cached_plugins ) ) {
71
						$plugins_handler->cache_plugins( array() );
72
					}
73
74
					return;
75
				}
76
77
				// Load the active plugins fresh since the list we pulled earlier might not contain
78
				// plugins that were activated but did not reset the autoloader. This happens
79
				// when a plugin is in the cache but not "active" when the autoloader loads.
80
				// We also want to make sure that plugins which are deactivating are not
81
				// considered "active" so that they will be removed from the cache now.
82
				$active_plugins = $plugins_handler->get_active_plugins( false );
83
84
				// The paths should be sorted for easy comparisons with those loaded from the cache.
85
				// Note we don't need to sort the cached entries because they're already sorted.
86
				sort( $active_plugins );
87
88
				// We don't want to waste time saving a cache that hasn't changed.
89
				if ( $cached_plugins === $active_plugins ) {
90
					return;
91
				}
92
93
				$plugins_handler->cache_plugins( $active_plugins );
94
			}
95
		);
96
97
		// phpcs:enable Generic.Commenting.DocComment.MissingShort
98
	}
99
100
	/**
101
	 * Loads a class file if one could be found.
102
	 *
103
	 * @param string $class_name The name of the class to autoload.
104
	 *
105
	 * @return bool Indicates whether or not a class file was loaded.
106
	 */
107
	public static function load_class( $class_name ) {
108
		global $jetpack_autoloader_loader;
109
		if ( ! isset( $jetpack_autoloader_loader ) ) {
110
			return;
111
		}
112
113
		$file = $jetpack_autoloader_loader->find_class_file( $class_name );
114
		if ( ! isset( $file ) ) {
115
			return false;
116
		}
117
118
		require $file;
119
		return true;
120
	}
121
122
	/**
123
	 * Activates this autoloader and deactivates any other v2 autoloaders that may be present.
124
	 *
125
	 * @param Version_Loader $version_loader The version loader for our autoloader.
126
	 */
127
	public static function activate( $version_loader ) {
128
		// Set the global autoloader to indicate that we've activated this autoloader.
129
		global $jetpack_autoloader_loader;
130
		$jetpack_autoloader_loader = $version_loader;
131
132
		// Remove any v2 autoloader that we've already registered.
133
		$autoload_chain = spl_autoload_functions();
134
		foreach ( $autoload_chain as $autoloader ) {
135
			// Jetpack autoloaders are always strings.
136
			if ( ! is_string( $autoloader ) ) {
137
				continue;
138
			}
139
140
			// We can identify a v2 autoloader using the namespace prefix without the unique suffix.
141
			if ( 'Automattic\\Jetpack\\Autoloader\\jp' === substr( $autoloader, 0, 32 ) ) {
142
				spl_autoload_unregister( $autoloader );
143
				continue;
144
			}
145
		}
146
147
		// Ensure that the autoloader is first to avoid contention with others.
148
		spl_autoload_register( self::class . '::load_class', true, true );
149
150
		// Now that we've activated the autoloader we should load the filemap.
151
		$jetpack_autoloader_loader->load_filemap();
152
	}
153
}
154