|
| 1 | +<?php |
| 2 | +/** |
| 3 | + * Composer Autoloader |
| 4 | + * |
| 5 | + * Load's Composer's autoloader if it exists and prompts the user to install it |
| 6 | + * if it doesn't. |
| 7 | + * |
| 8 | + * phpcs:disable WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedVariableFound |
| 9 | + * |
| 10 | + * @package example-project |
| 11 | + */ |
| 12 | + |
| 13 | +$composer_autoloader_path = dirname( __DIR__ ) . '/vendor/autoload.php'; |
| 14 | + |
| 15 | +// Display a friendly error message if Composer is not installed locally. |
| 16 | +if ( 'local' === wp_get_environment_type() ) { |
| 17 | + if ( ! file_exists( $composer_autoloader_path ) ) { |
| 18 | + wp_die( |
| 19 | + 'Composer is not installed. Please run <code>composer install</code> locally in the <code>wp-content</code> folder for this project.' |
| 20 | + ); |
| 21 | + } |
| 22 | + |
| 23 | + /** @var array{ |
| 24 | + * config?: array{ |
| 25 | + * platform?: array{ |
| 26 | + * php?: string, |
| 27 | + * } |
| 28 | + * } |
| 29 | + * } $composer Composer configuration from composer.json, which may specify the platform PHP version. |
| 30 | + */ |
| 31 | + $composer = json_decode( file_get_contents( dirname( __DIR__ ) . '/composer.json' ) ?: '', true ); |
| 32 | + $required_version = $composer['config']['platform']['php'] ?? '8.0.0'; |
| 33 | + |
| 34 | + // Display a friendly error message if the wrong PHP version is used locally. |
| 35 | + if ( version_compare( PHP_VERSION, $required_version, '<' ) ) { |
| 36 | + wp_die( |
| 37 | + sprintf( |
| 38 | + 'This site requires a PHP version >= %s. You are running %s. Please switch to <code>%s</code> on your machine.', |
| 39 | + esc_html( $required_version ), |
| 40 | + PHP_VERSION, |
| 41 | + esc_html( $required_version ), |
| 42 | + ), |
| 43 | + ); |
| 44 | + } |
| 45 | + |
| 46 | + // Unset all variables to prevent any external usage. |
| 47 | + unset( $composer, $required_version ); |
| 48 | +} |
| 49 | + |
| 50 | +// Load the Composer autoloader or add a notice if it doesn't exist. |
| 51 | +if ( file_exists( $composer_autoloader_path ) ) { |
| 52 | + require_once $composer_autoloader_path; |
| 53 | +} else { |
| 54 | + // Include an error notice. |
| 55 | + add_action( |
| 56 | + 'admin_notices', |
| 57 | + function() { |
| 58 | + if ( 'local' === wp_get_environment_type() ) { |
| 59 | + printf( |
| 60 | + '<div class="notice notice-error"><p>%s</p></div>', |
| 61 | + esc_html( 'Composer needs to be installed for the site.' ) |
| 62 | + ); |
| 63 | + } else { |
| 64 | + printf( |
| 65 | + '<div class="notice notice-error"><p>%s</p></div>', |
| 66 | + esc_html( 'Composer is not installed on the site! Please contact the site administrator.' ) |
| 67 | + ); |
| 68 | + } |
| 69 | + } |
| 70 | + ); |
| 71 | +} |
| 72 | + |
| 73 | +// Don't pollute global scope. |
| 74 | +unset( $composer_autoloader_path ); |
0 commit comments