Skip to content

Commit

Permalink
Plugin: Fix fatal error for older WP/PHP versions (#40538)
Browse files Browse the repository at this point in the history
  • Loading branch information
Mamaduka authored Apr 22, 2022
1 parent 54fd3bf commit 0bb230c
Show file tree
Hide file tree
Showing 2 changed files with 71 additions and 0 deletions.
70 changes: 70 additions & 0 deletions lib/compat/wordpress-5.9/polyfills.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
<?php
/**
* Polyfills for functions missing from older WP versions.
*
* This file should be removed when WordPress 5.9.0 becomes the lowest
* supported version by this plugin.
*
* @package gutenberg
*/

if ( ! function_exists( 'str_contains' ) ) {
/**
* Polyfill for `str_contains()` function added in PHP 8.0.
*
* Performs a case-sensitive check indicating if needle is
* contained in haystack.
*
* @since 5.9.0
*
* @param string $haystack The string to search in.
* @param string $needle The substring to search for in the haystack.
* @return bool True if `$needle` is in `$haystack`, otherwise false.
*/
function str_contains( $haystack, $needle ) {
return ( '' === $needle || false !== strpos( $haystack, $needle ) );
}
}

if ( ! function_exists( 'str_starts_with' ) ) {
/**
* Polyfill for `str_starts_with()` function added in PHP 8.0.
*
* Performs a case-sensitive check indicating if
* the haystack begins with needle.
*
* @since 5.9.0
*
* @param string $haystack The string to search in.
* @param string $needle The substring to search for in the `$haystack`.
* @return bool True if `$haystack` starts with `$needle`, otherwise false.
*/
function str_starts_with( $haystack, $needle ) {
if ( '' === $needle ) {
return true;
}
return 0 === strpos( $haystack, $needle );
}
}

if ( ! function_exists( 'str_ends_with' ) ) {
/**
* Polyfill for `str_ends_with()` function added in PHP 8.0.
*
* Performs a case-sensitive check indicating if
* the haystack ends with needle.
*
* @since 5.9.0
*
* @param string $haystack The string to search in.
* @param string $needle The substring to search for in the `$haystack`.
* @return bool True if `$haystack` ends with `$needle`, otherwise false.
*/
function str_ends_with( $haystack, $needle ) {
if ( '' === $haystack && '' !== $needle ) {
return false;
}
$len = strlen( $needle );
return 0 === substr_compare( $haystack, $needle, -$len, $len );
}
}
1 change: 1 addition & 0 deletions lib/load.php
Original file line number Diff line number Diff line change
Expand Up @@ -77,6 +77,7 @@ function gutenberg_is_experiment_enabled( $name ) {
require __DIR__ . '/experimental/editor-settings.php';

// WordPress 5.9 compat.
require __DIR__ . '/compat/wordpress-5.9/polyfills.php';
require __DIR__ . '/compat/wordpress-5.9/block-gallery.php';
require __DIR__ . '/compat/wordpress-5.9/widget-render-api-endpoint/index.php';
require __DIR__ . '/compat/wordpress-5.9/blocks.php';
Expand Down

0 comments on commit 0bb230c

Please sign in to comment.