diff --git a/composer.json b/composer.json index b7577bff..2825524b 100644 --- a/composer.json +++ b/composer.json @@ -20,6 +20,7 @@ "phpmd/phpmd": "^2.15", "phpro/grumphp": "^2.15", "phpunit/phpunit": "^9.6", + "rector/rector": "^2.2", "rregeer/phpunit-coverage-check": "^0.3.1", "squizlabs/php_codesniffer": "^3.9.2", "symfony/css-selector": "^7.3", @@ -81,4 +82,4 @@ "wp:i18n:make-mo": "wp i18n make-mo ./languages", "wp:i18n:make-pot": "wp i18n make-pot ./ languages/speechkit.pot --slug=speechkit" } -} \ No newline at end of file +} diff --git a/composer.lock b/composer.lock index 0e32fc78..752be330 100644 --- a/composer.lock +++ b/composer.lock @@ -4,7 +4,7 @@ "Read more about it at https://getcomposer.org/doc/01-basic-usage.md#installing-dependencies", "This file is @generated automatically" ], - "content-hash": "218cc1115d43a60c248505663765c82e", + "content-hash": "acced7288af5194b2da21da88ba1f362", "packages": [ { "name": "psr/container", @@ -5405,6 +5405,59 @@ }, "time": "2025-08-28T11:50:51+00:00" }, + { + "name": "phpstan/phpstan", + "version": "2.1.31", + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/phpstan/phpstan/zipball/ead89849d879fe203ce9292c6ef5e7e76f867b96", + "reference": "ead89849d879fe203ce9292c6ef5e7e76f867b96", + "shasum": "" + }, + "require": { + "php": "^7.4|^8.0" + }, + "conflict": { + "phpstan/phpstan-shim": "*" + }, + "bin": [ + "phpstan", + "phpstan.phar" + ], + "type": "library", + "autoload": { + "files": [ + "bootstrap.php" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "description": "PHPStan - PHP Static Analysis Tool", + "keywords": [ + "dev", + "static analysis" + ], + "support": { + "docs": "https://phpstan.org/user-guide/getting-started", + "forum": "https://github.com/phpstan/phpstan/discussions", + "issues": "https://github.com/phpstan/phpstan/issues", + "security": "https://github.com/phpstan/phpstan/security/policy", + "source": "https://github.com/phpstan/phpstan-src" + }, + "funding": [ + { + "url": "https://github.com/ondrejmirtes", + "type": "github" + }, + { + "url": "https://github.com/phpstan", + "type": "github" + } + ], + "time": "2025-10-10T14:14:11+00:00" + }, { "name": "phpunit/php-code-coverage", "version": "9.2.32", @@ -6165,6 +6218,66 @@ ], "time": "2025-08-19T18:57:03+00:00" }, + { + "name": "rector/rector", + "version": "2.2.3", + "source": { + "type": "git", + "url": "https://github.com/rectorphp/rector.git", + "reference": "d27f976a332a87b5d03553c2e6f04adbe5da034f" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/rectorphp/rector/zipball/d27f976a332a87b5d03553c2e6f04adbe5da034f", + "reference": "d27f976a332a87b5d03553c2e6f04adbe5da034f", + "shasum": "" + }, + "require": { + "php": "^7.4|^8.0", + "phpstan/phpstan": "^2.1.26" + }, + "conflict": { + "rector/rector-doctrine": "*", + "rector/rector-downgrade-php": "*", + "rector/rector-phpunit": "*", + "rector/rector-symfony": "*" + }, + "suggest": { + "ext-dom": "To manipulate phpunit.xml via the custom-rule command" + }, + "bin": [ + "bin/rector" + ], + "type": "library", + "autoload": { + "files": [ + "bootstrap.php" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "description": "Instant Upgrade and Automated Refactoring of any PHP code", + "homepage": "https://getrector.com/", + "keywords": [ + "automation", + "dev", + "migration", + "refactoring" + ], + "support": { + "issues": "https://github.com/rectorphp/rector/issues", + "source": "https://github.com/rectorphp/rector/tree/2.2.3" + }, + "funding": [ + { + "url": "https://github.com/tomasvotruba", + "type": "github" + } + ], + "time": "2025-10-11T21:50:23+00:00" + }, { "name": "revolt/event-loop", "version": "v1.0.7", diff --git a/doc/code-quality-checks.md b/doc/code-quality-checks.md index 284fc2ca..08445c9d 100644 --- a/doc/code-quality-checks.md +++ b/doc/code-quality-checks.md @@ -18,6 +18,7 @@ The checks are: using the config at `phpcs.xml`, to *PSR-12* and *WordPress VIP* standards. - `phplint`: Check source files for syntax errors - `phpmd`: Check source files for bad coding standards +- `rector`: Check source files for refactoring opportunities - `test_phpunit`: PHPUnit tests - `coverage_check`: PHPUnit code coverage diff --git a/grumphp.yml b/grumphp.yml index 535eb104..88f9ec7b 100644 --- a/grumphp.yml +++ b/grumphp.yml @@ -55,6 +55,17 @@ grumphp: - vendor metadata: priority: 10 + rector: + config: rector.php + triggered_by: + - php + ignore_patterns: + - /tests/* + - /vendor/* + clear_cache: false + no_diffs: false + metadata: + priority: 10 test_phpunit: script: test:phpunit metadata: @@ -77,6 +88,7 @@ grumphp: - phpcs - phplint - phpmd + - rector code_quality: tasks: - composer @@ -84,3 +96,4 @@ grumphp: - phpcs - phplint - phpmd + - rector diff --git a/package.json b/package.json index 9dda72ce..4d3005ed 100644 --- a/package.json +++ b/package.json @@ -44,6 +44,9 @@ "lint:pkg-json": "wp-scripts lint-pkg-json", "mockoon:start": "mockoon-cli start --data ./.mockoon/beyondwords-api.json --port 3000", "packages-update": "wp-scripts packages-update", + "rector": "wp-env run cli --env-cwd=/var/www/html/wp-content/plugins/speechkit ./vendor/bin/rector process --dry-run", + "rector:fix": "wp-env run cli --env-cwd=/var/www/html/wp-content/plugins/speechkit ./vendor/bin/rector process", + "rector:fix:diff": "wp-env run cli --env-cwd=/var/www/html/wp-content/plugins/speechkit ./vendor/bin/rector process --debug", "start": "wp-scripts start", "test:e2e": "wp-scripts test-e2e", "test:unit": "wp-scripts test-unit-js", diff --git a/rector.php b/rector.php new file mode 100644 index 00000000..98b8b795 --- /dev/null +++ b/rector.php @@ -0,0 +1,31 @@ +withPaths([ + __DIR__ . '/src', + __DIR__ . '/index.php', + __DIR__ . '/speechkit.php', + __DIR__ . '/uninstall.php', + ]) + ->withSkip([ + __DIR__ . '/tests', + __DIR__ . '/vendor', + ]) + ->withRules([ + // Add any additional rules here. + ]) + ->withPreparedSets( + deadCode: true, // Remove dead code + codeQuality: false, // Don't auto-refactor code quality (too aggressive for WordPress) + ) + ->withPhpSets( + php80: true // Use PHP 8.0 features + ) + ->withTypeCoverageLevel(0); // Don't enforce type coverage (just clean up) diff --git a/src/Compatibility/WPGraphQL/WPGraphQL.php b/src/Compatibility/WPGraphQL/WPGraphQL.php index 1d67fae0..267c6069 100644 --- a/src/Compatibility/WPGraphQL/WPGraphQL.php +++ b/src/Compatibility/WPGraphQL/WPGraphQL.php @@ -25,7 +25,7 @@ class WPGraphQL public static function init() { // Actions for WPGraphQL - add_action('graphql_register_types', array(__CLASS__, 'graphqlRegisterTypes')); + add_action('graphql_register_types', [self::class, 'graphqlRegisterTypes']); } /** diff --git a/src/Component/Post/AddPlayer/AddPlayer.php b/src/Component/Post/AddPlayer/AddPlayer.php index a8ebda15..a4df5ce7 100644 --- a/src/Component/Post/AddPlayer/AddPlayer.php +++ b/src/Component/Post/AddPlayer/AddPlayer.php @@ -32,15 +32,15 @@ class AddPlayer */ public static function init() { - add_action('init', array(__CLASS__, 'registerBlock')); - add_action('enqueue_block_editor_assets', array(__CLASS__, 'addBlockEditorStylesheet')); + add_action('init', [self::class, 'registerBlock']); + add_action('enqueue_block_editor_assets', [self::class, 'addBlockEditorStylesheet']); - add_action('admin_head', array(__CLASS__, 'addEditorStyles')); - add_filter('tiny_mce_before_init', array(__CLASS__, 'filterTinyMceSettings')); + add_action('admin_head', [self::class, 'addEditorStyles']); + add_filter('tiny_mce_before_init', [self::class, 'filterTinyMceSettings']); - add_filter('mce_external_plugins', array(__CLASS__, 'addPlugin')); - add_filter('mce_buttons', array(__CLASS__, 'addButton')); - add_filter('mce_css', array(__CLASS__, 'addStylesheet')); + add_filter('mce_external_plugins', [self::class, 'addPlugin']); + add_filter('mce_buttons', [self::class, 'addButton']); + add_filter('mce_css', [self::class, 'addStylesheet']); } /** @@ -60,10 +60,8 @@ public static function registerBlock() * @since 6.0.0 Make static. * * @param array TinyMCE plugin array - * - * @return array */ - public static function addPlugin($plugin_array) + public static function addPlugin(array $plugin_array): array { $plugin_array['beyondwords_player'] = BEYONDWORDS__PLUGIN_URI . 'src/Component/Post/AddPlayer/tinymce.js'; return $plugin_array; @@ -75,10 +73,8 @@ public static function addPlugin($plugin_array) * @since 6.0.0 Make static. * * @param array TinyMCE buttons array - * - * @return array */ - public static function addButton($buttons) + public static function addButton(array $buttons): array { $advIndex = array_search('wp_adv', $buttons); @@ -100,7 +96,7 @@ public static function addButton($buttons) * * @return string Comma-delimited list of stylesheets with the "Add Player" CSS appended. */ - public static function addStylesheet($stylesheets) + public static function addStylesheet(string $stylesheets): string { return $stylesheets . ',' . BEYONDWORDS__PLUGIN_URI . 'src/Component/Post/AddPlayer/AddPlayer.css'; } @@ -135,7 +131,7 @@ public static function playerPreviewI18nStyles() * * @return mixed[] An array with TinyMCE config. */ - public static function filterTinyMceSettings($settings) + public static function filterTinyMceSettings(array $settings): array { if (isset($settings['content_style'])) { $settings['content_style'] .= ' ' . self::playerPreviewI18nStyles() . ' '; @@ -156,9 +152,9 @@ public static function filterTinyMceSettings($settings) */ public static function addEditorStyles() { - $allowed_html = array( - 'style' => array(), - ); + $allowed_html = [ + 'style' => [], + ]; echo wp_kses( sprintf('', self::playerPreviewI18nStyles()), @@ -171,7 +167,7 @@ public static function addEditorStyles() * * @since 6.0.0 Make static. */ - public static function addBlockEditorStylesheet($hook) + public static function addBlockEditorStylesheet(string $hook): void { // Only enqueue for Gutenberg/Post screens if (CoreUtils::isGutenbergPage() || $hook === 'post.php' || $hook === 'post-new.php') { @@ -179,7 +175,7 @@ public static function addBlockEditorStylesheet($hook) wp_enqueue_style( 'beyondwords-AddPlayer', BEYONDWORDS__PLUGIN_URI . 'src/Component/Post/AddPlayer/AddPlayer.css', - array(), + [], BEYONDWORDS__PLUGIN_VERSION ); } diff --git a/src/Component/Post/BlockAttributes/BlockAttributes.php b/src/Component/Post/BlockAttributes/BlockAttributes.php index 7f8b9a5d..079b8db4 100644 --- a/src/Component/Post/BlockAttributes/BlockAttributes.php +++ b/src/Component/Post/BlockAttributes/BlockAttributes.php @@ -33,9 +33,9 @@ class BlockAttributes */ public static function init() { - add_filter('register_block_type_args', array(__CLASS__, 'registerAudioAttribute')); - add_filter('register_block_type_args', array(__CLASS__, 'registerMarkerAttribute')); - add_filter('render_block', array(__CLASS__, 'renderBlock'), 10, 2); + add_filter('register_block_type_args', [self::class, 'registerAudioAttribute']); + add_filter('register_block_type_args', [self::class, 'registerMarkerAttribute']); + add_filter('render_block', [self::class, 'renderBlock'], 10, 2); } /** @@ -47,14 +47,14 @@ public static function registerAudioAttribute($args) { // Setup attributes if needed. if (! isset($args['attributes'])) { - $args['attributes'] = array(); + $args['attributes'] = []; } if (! array_key_exists('beyondwordsAudio', $args['attributes'])) { - $args['attributes']['beyondwordsAudio'] = array( + $args['attributes']['beyondwordsAudio'] = [ 'type' => 'boolean', 'default' => true, - ); + ]; } return $args; @@ -69,14 +69,14 @@ public static function registerMarkerAttribute($args) { // Setup attributes if needed. if (! isset($args['attributes'])) { - $args['attributes'] = array(); + $args['attributes'] = []; } if (! array_key_exists('beyondwordsMarker', $args['attributes'])) { - $args['attributes']['beyondwordsMarker'] = array( + $args['attributes']['beyondwordsMarker'] = [ 'type' => 'string', 'default' => '', - ); + ]; } return $args; diff --git a/src/Component/Post/DisplayPlayer/DisplayPlayer.php b/src/Component/Post/DisplayPlayer/DisplayPlayer.php index 61f7119c..56589960 100644 --- a/src/Component/Post/DisplayPlayer/DisplayPlayer.php +++ b/src/Component/Post/DisplayPlayer/DisplayPlayer.php @@ -30,12 +30,12 @@ class DisplayPlayer */ public static function init() { - add_action('wp_loaded', function () { + add_action('wp_loaded', function (): void { $postTypes = SettingsUtils::getCompatiblePostTypes(); if (is_array($postTypes)) { foreach ($postTypes as $postType) { - add_action("save_post_{$postType}", array(__CLASS__, 'save'), 20); + add_action("save_post_{$postType}", [self::class, 'save'], 20); } } }); diff --git a/src/Component/Post/ErrorNotice/ErrorNotice.php b/src/Component/Post/ErrorNotice/ErrorNotice.php index 052b381c..cdfdc4a1 100644 --- a/src/Component/Post/ErrorNotice/ErrorNotice.php +++ b/src/Component/Post/ErrorNotice/ErrorNotice.php @@ -29,7 +29,7 @@ class ErrorNotice */ public static function init() { - add_action('enqueue_block_assets', array(__CLASS__, 'enqueueBlockAssets')); + add_action('enqueue_block_assets', [self::class, 'enqueueBlockAssets']); } /** @@ -45,7 +45,7 @@ public static function enqueueBlockAssets() wp_enqueue_style( 'beyondwords-ErrorNotice', BEYONDWORDS__PLUGIN_URI . 'src/Component/Post/ErrorNotice/error-notice.css', - array(), + [], BEYONDWORDS__PLUGIN_VERSION ); } diff --git a/src/Component/Post/GenerateAudio/GenerateAudio.php b/src/Component/Post/GenerateAudio/GenerateAudio.php index dee180a2..f19bc03a 100644 --- a/src/Component/Post/GenerateAudio/GenerateAudio.php +++ b/src/Component/Post/GenerateAudio/GenerateAudio.php @@ -30,12 +30,12 @@ class GenerateAudio */ public static function init() { - add_action('wp_loaded', function () { + add_action('wp_loaded', function (): void { $postTypes = SettingsUtils::getCompatiblePostTypes(); if (is_array($postTypes)) { foreach ($postTypes as $postType) { - add_action("save_post_{$postType}", array(__CLASS__, 'save'), 10); + add_action("save_post_{$postType}", [self::class, 'save'], 10); } } }); diff --git a/src/Component/Post/Metabox/Metabox.php b/src/Component/Post/Metabox/Metabox.php index ef43c7c3..7a02e51b 100644 --- a/src/Component/Post/Metabox/Metabox.php +++ b/src/Component/Post/Metabox/Metabox.php @@ -36,8 +36,8 @@ class Metabox */ public static function init() { - add_action('admin_enqueue_scripts', array(__CLASS__, 'adminEnqueueScripts')); - add_action("add_meta_boxes", array(__CLASS__, 'addMetaBox')); + add_action('admin_enqueue_scripts', [self::class, 'adminEnqueueScripts']); + add_action("add_meta_boxes", [self::class, 'addMetaBox']); } /** @@ -70,14 +70,14 @@ public static function addMetaBox($postType) { $postTypes = SettingsUtils::getCompatiblePostTypes(); - if (is_array($postTypes) && ! in_array($postType, $postTypes)) { + if (! in_array($postType, $postTypes)) { return; } add_meta_box( 'beyondwords', __('BeyondWords', 'speechkit'), - array(__CLASS__, 'renderMetaBoxContent'), + [self::class, 'renderMetaBoxContent'], $postType, 'side', 'default', diff --git a/src/Component/Post/Panel/Inspect/Inspect.php b/src/Component/Post/Panel/Inspect/Inspect.php index aced6188..812e0165 100644 --- a/src/Component/Post/Panel/Inspect/Inspect.php +++ b/src/Component/Post/Panel/Inspect/Inspect.php @@ -30,18 +30,18 @@ class Inspect */ public static function init() { - add_action('admin_enqueue_scripts', array(__CLASS__, 'adminEnqueueScripts')); - add_action('add_meta_boxes', array(__CLASS__, 'addMetaBox')); - add_action('rest_api_init', array(__CLASS__, 'restApiInit')); + add_action('admin_enqueue_scripts', [self::class, 'adminEnqueueScripts']); + add_action('add_meta_boxes', [self::class, 'addMetaBox']); + add_action('rest_api_init', [self::class, 'restApiInit']); - add_filter('default_hidden_meta_boxes', array(__CLASS__, 'hideMetaBox')); + add_filter('default_hidden_meta_boxes', [self::class, 'hideMetaBox']); - add_action('wp_loaded', function () { + add_action('wp_loaded', function (): void { $postTypes = SettingsUtils::getCompatiblePostTypes(); if (is_array($postTypes)) { foreach ($postTypes as $postType) { - add_action("save_post_{$postType}", array(__CLASS__, 'save'), 5); + add_action("save_post_{$postType}", [self::class, 'save'], 5); } } }); @@ -59,7 +59,7 @@ public static function adminEnqueueScripts($hook) wp_enqueue_script( 'beyondwords-inspect', BEYONDWORDS__PLUGIN_URI . 'src/Component/Post/Panel/Inspect/js/inspect.js', - array('jquery'), + ['jquery'], BEYONDWORDS__PLUGIN_VERSION, true ); @@ -92,14 +92,14 @@ public static function addMetaBox($postType) { $postTypes = SettingsUtils::getCompatiblePostTypes(); - if (is_array($postTypes) && ! in_array($postType, $postTypes)) { + if (! in_array($postType, $postTypes)) { return; } add_meta_box( 'beyondwords__inspect', __('BeyondWords', 'speechkit') . ': ' . __('Inspect', 'speechkit'), - array(__CLASS__, 'renderMetaBoxContent'), + [self::class, 'renderMetaBoxContent'], $postType, 'advanced', 'low', @@ -189,7 +189,7 @@ public static function postMetaTable($metadata) continue; } - $metaId = $item['meta_id'] ? $item['meta_id'] : $item['meta_key']; + $metaId = $item['meta_id'] ?: $item['meta_key']; $metaKey = $item['meta_key']; $metaValue = self::formatPostMetaValue($item['meta_value']); ?> @@ -337,13 +337,11 @@ public static function save($postId) **/ public static function restApiInit() { - register_rest_route('beyondwords/v1', '/projects/(?P[0-9]+)/content/(?P[a-zA-Z0-9\-]+)', array( // phpcs:ignore Generic.Files.LineLength.TooLong + register_rest_route('beyondwords/v1', '/projects/(?P[0-9]+)/content/(?P[a-zA-Z0-9\-]+)', [ // phpcs:ignore Generic.Files.LineLength.TooLong 'methods' => \WP_REST_Server::READABLE, - 'callback' => array(__CLASS__, 'restApiResponse'), - 'permission_callback' => function () { - return current_user_can('edit_posts'); - }, - )); + 'callback' => [self::class, 'restApiResponse'], + 'permission_callback' => fn() => current_user_can('edit_posts'), + ]); } /** diff --git a/src/Component/Post/PlayerContent/PlayerContent.php b/src/Component/Post/PlayerContent/PlayerContent.php index 2e0d5c34..3979ff85 100644 --- a/src/Component/Post/PlayerContent/PlayerContent.php +++ b/src/Component/Post/PlayerContent/PlayerContent.php @@ -47,12 +47,12 @@ class PlayerContent */ public static function init() { - add_action('wp_loaded', function () { + add_action('wp_loaded', function (): void { $postTypes = SettingsUtils::getCompatiblePostTypes(); if (is_array($postTypes)) { foreach ($postTypes as $postType) { - add_action("save_post_{$postType}", array(__CLASS__, 'save'), 10); + add_action("save_post_{$postType}", [self::class, 'save'], 10); } } }); diff --git a/src/Component/Post/PlayerStyle/PlayerStyle.php b/src/Component/Post/PlayerStyle/PlayerStyle.php index 61d807b5..4a9fd05f 100644 --- a/src/Component/Post/PlayerStyle/PlayerStyle.php +++ b/src/Component/Post/PlayerStyle/PlayerStyle.php @@ -43,14 +43,14 @@ class PlayerStyle */ public static function init() { - add_action('rest_api_init', array(__CLASS__, 'restApiInit')); + add_action('rest_api_init', [self::class, 'restApiInit']); - add_action('wp_loaded', function () { + add_action('wp_loaded', function (): void { $postTypes = SettingsUtils::getCompatiblePostTypes(); if (is_array($postTypes)) { foreach ($postTypes as $postType) { - add_action("save_post_{$postType}", array(__CLASS__, 'save'), 10); + add_action("save_post_{$postType}", [self::class, 'save'], 10); } } }); @@ -150,13 +150,11 @@ public static function save($postId) public static function restApiInit() { // Player styles endpoint - register_rest_route('beyondwords/v1', '/projects/(?P[0-9]+)/player-styles', array( + register_rest_route('beyondwords/v1', '/projects/(?P[0-9]+)/player-styles', [ 'methods' => \WP_REST_Server::READABLE, - 'callback' => array(__CLASS__, 'playerStylesRestApiResponse'), - 'permission_callback' => function () { - return current_user_can('edit_posts'); - }, - )); + 'callback' => [self::class, 'playerStylesRestApiResponse'], + 'permission_callback' => fn() => current_user_can('edit_posts'), + ]); } /** diff --git a/src/Component/Post/Post.php b/src/Component/Post/Post.php index 02781936..dbc78d5b 100755 --- a/src/Component/Post/Post.php +++ b/src/Component/Post/Post.php @@ -21,7 +21,7 @@ class Post */ public static function init() { - add_action('wp_head', array(__CLASS__, 'addMetaTags')); + add_action('wp_head', [self::class, 'addMetaTags']); } /** diff --git a/src/Component/Post/PostContentUtils.php b/src/Component/Post/PostContentUtils.php index d56a8cfc..26074503 100755 --- a/src/Component/Post/PostContentUtils.php +++ b/src/Component/Post/PostContentUtils.php @@ -23,13 +23,13 @@ class PostContentUtils * From API version 1.1 the "summary" param is going to be used differently, * so for WordPress we now prepend the WordPress excerpt to the "body" param. * - * @param int|WP_Post $post The WordPress post ID, or post object. + * @param int|\WP_Post $post The WordPress post ID, or post object. * * @since 4.6.0 * * @return string The content body param. */ - public static function getContentBody($post) + public static function getContentBody(int|\WP_Post $post): string|null { $post = get_post($post); @@ -61,11 +61,11 @@ public static function getContentBody($post) * @since 5.0.0 Remove SpeechKit-Start shortcode. * @since 5.0.0 Remove beyondwords_content filter. * - * @param int|WP_Post $post The WordPress post ID, or post object. + * @param int|\WP_Post $post The WordPress post ID, or post object. * * @return string The body (the processed $post->post_content). */ - public static function getPostBody($post) + public static function getPostBody(int|\WP_Post $post): string|null { $post = get_post($post); @@ -96,13 +96,13 @@ public static function getPostBody($post) * This is a
with optional attributes depending on the BeyondWords * data of the post. * - * @param int|WP_Post $post The WordPress post ID, or post object. + * @param int|\WP_Post $post The WordPress post ID, or post object. * * @since 4.6.0 * * @return string The summary wrapper
. */ - public static function getPostSummaryWrapperFormat($post) + public static function getPostSummaryWrapperFormat(int|\WP_Post $post): string { $post = get_post($post); @@ -122,14 +122,14 @@ public static function getPostSummaryWrapperFormat($post) /** * Get the post summary for the audio content. * - * @param int|WP_Post $post The WordPress post ID, or post object. + * @param int|\WP_Post $post The WordPress post ID, or post object. * * @since 4.0.0 * @since 4.6.0 Renamed from PostContentUtils::getSummary() to PostContentUtils::getPostSummary() * * @return string The summary. */ - public static function getPostSummary($post) + public static function getPostSummary(int|\WP_Post $post): string|null { $post = get_post($post); @@ -162,16 +162,14 @@ public static function getPostSummary($post) * formatting tags such as and so we do not pass segments, we pass * a HTML string as the body param instead. * - * @param int|WP_Post $post The WordPress post ID, or post object. + * @param int|\WP_Post $post The WordPress post ID, or post object. * * @since 4.0.0 - * - * @return array|null The segments. */ - public static function getSegments($post) + public static function getSegments(int|\WP_Post $post): array { if (! has_blocks($post)) { - return null; + return []; } $titleSegment = (object) [ @@ -204,9 +202,7 @@ public static function getSegments($post) $segments = array_values(array_merge([$titleSegment], [$summarySegment], $bodySegments)); // Remove any segments with empty text - $segments = array_values(array_filter($segments, function ($segment) { - return (! empty($segment::text)); - })); + $segments = array_values(array_filter($segments, fn($segment) => ! empty($segment::text))); return $segments; } @@ -219,14 +215,14 @@ public static function getSegments($post) * * This method filters all blocks, removing any which have been excluded. * - * @param int|WP_Post $post The WordPress post ID, or post object. + * @param int|\WP_Post $post The WordPress post ID, or post object. * * @since 3.8.0 * @since 4.0.0 Replace for loop with array_reduce * * @return string The post body without excluded blocks. */ - public static function getContentWithoutExcludedBlocks($post) + public static function getContentWithoutExcludedBlocks(int|\WP_Post $post): string { if (! has_blocks($post)) { return trim($post->post_content); @@ -252,14 +248,14 @@ public static function getContentWithoutExcludedBlocks($post) /** * Get audio-enabled blocks. * - * @param int|WP_Post $post The WordPress post ID, or post object. + * @param int|\WP_Post $post The WordPress post ID, or post object. * * @since 4.0.0 * @since 5.0.0 Remove beyondwords_post_audio_enabled_blocks filter. * * @return array The blocks. */ - public static function getAudioEnabledBlocks($post) + public static function getAudioEnabledBlocks(int|\WP_Post $post): array { $post = get_post($post); @@ -273,7 +269,7 @@ public static function getAudioEnabledBlocks($post) $allBlocks = parse_blocks($post->post_content); - $blocks = array_filter($allBlocks, function ($block) { + return array_filter($allBlocks, function ($block) { $enabled = true; if (is_array($block['attrs']) && isset($block['attrs']['beyondwordsAudio'])) { @@ -282,8 +278,6 @@ public static function getAudioEnabledBlocks($post) return $enabled; }); - - return $blocks; } /** @@ -305,7 +299,7 @@ public static function getAudioEnabledBlocks($post) * * @return string JSON endoded params. **/ - public static function getContentParams($postId) + public static function getContentParams(int $postId): array|string { $body = [ 'type' => 'auto_segment', @@ -394,7 +388,7 @@ public static function getContentParams($postId) * * @return object The metadata object (empty if no metadata). */ - public static function getMetadata($postId) + public static function getMetadata(int $postId): array|object { $metadata = new \stdClass(); @@ -426,7 +420,7 @@ public static function getMetadata($postId) * * @return object The taxonomies object (empty if no taxonomies). */ - public static function getAllTaxonomiesAndTerms($postId) + public static function getAllTaxonomiesAndTerms(int $postId): array|object { $postType = get_post_type($postId); @@ -451,10 +445,8 @@ public static function getAllTaxonomiesAndTerms($postId) * @since 3.10.4 * * @param int $postId Post ID. - * - * @return string */ - public static function getAuthorName($postId) + public static function getAuthorName(int $postId): string { $authorId = get_post_field('post_author', $postId); @@ -475,7 +467,7 @@ public static function getAuthorName($postId) * * @return string HTML. */ - public static function addMarkerAttribute($html, $marker) + public static function addMarkerAttribute(string $html, string $marker): string { if (! $marker) { return $html; @@ -503,7 +495,7 @@ public static function addMarkerAttribute($html, $marker) * * @return string HTML. */ - public static function addMarkerAttributeWithHTMLTagProcessor($html, $marker) + public static function addMarkerAttributeWithHTMLTagProcessor(string $html, string $marker): string { if (! $marker) { return $html; @@ -545,7 +537,7 @@ public static function addMarkerAttributeWithHTMLTagProcessor($html, $marker) * * @return string HTML. */ - public static function addMarkerAttributeWithDOMDocument($html, $marker) + public static function addMarkerAttributeWithDOMDocument(string $html, string $marker): string { if (! $marker) { return $html; diff --git a/src/Component/Post/PostMetaUtils.php b/src/Component/Post/PostMetaUtils.php index d7a7b6cd..c52185a2 100755 --- a/src/Component/Post/PostMetaUtils.php +++ b/src/Component/Post/PostMetaUtils.php @@ -36,7 +36,7 @@ class PostMetaUtils * * @return string */ - public static function getRenamedPostMeta($postId, $name) + public static function getRenamedPostMeta(int $postId, string $name): mixed { if (metadata_exists('post', $postId, 'beyondwords_' . $name)) { return get_post_meta($postId, 'beyondwords_' . $name, true); @@ -59,7 +59,7 @@ public static function getRenamedPostMeta($postId, $name) * * @since 4.1.0 Append 'beyondwords_version' and 'wordpress_version'. */ - public static function getAllBeyondwordsMetadata($postId) + public static function getAllBeyondwordsMetadata(int $postId): array { global $wp_version; @@ -67,9 +67,7 @@ public static function getAllBeyondwordsMetadata($postId) $metadata = has_meta($postId); - $metadata = array_filter($metadata, function ($item) use ($keysToCheck) { - return in_array($item['meta_key'], $keysToCheck); - }); + $metadata = array_filter($metadata, fn($item) => in_array($item['meta_key'], $keysToCheck)); // Prepend the WordPress Post ID to the meta data // phpcs:disable WordPress.DB.SlowDBQuery @@ -99,7 +97,7 @@ public static function getAllBeyondwordsMetadata($postId) /** * Remove the BeyondWords metadata for a Post. */ - public static function removeAllBeyondwordsMetadata($postId) + public static function removeAllBeyondwordsMetadata(int $postId): void { $keysToCheck = [ 'beyondwords_generate_audio', @@ -136,8 +134,6 @@ public static function removeAllBeyondwordsMetadata($postId) foreach ($keysToCheck as $key) { delete_post_meta($postId, $key, null); } - - return true; } /** @@ -149,7 +145,7 @@ public static function removeAllBeyondwordsMetadata($postId) * * @return bool True if the post should have BeyondWords content, false otherwise. */ - public static function hasContent($postId) + public static function hasContent(int $postId): bool { $contentId = PostMetaUtils::getContentId($postId); $integrationMethod = get_post_meta($postId, 'beyondwords_integration_method', true); @@ -190,7 +186,7 @@ public static function hasContent($postId) * * @return string|false Content ID, or false */ - public static function getContentId($postId, $fallback = false) + public static function getContentId(int $postId, bool $fallback = false): string|int|false { $contentId = get_post_meta($postId, 'beyondwords_content_id', true); if (! empty($contentId)) { @@ -223,7 +219,7 @@ public static function getContentId($postId, $fallback = false) * * @return int|false Podcast ID, or false */ - public static function getPodcastId($postId) + public static function getPodcastId(int $postId): string|int|false { // Check for "Podcast ID" custom field (number, or string for > 4.x) $podcastId = PostMetaUtils::getRenamedPostMeta($postId, 'podcast_id'); @@ -294,11 +290,11 @@ public static function getPodcastId($postId) * * @return string Preview token */ - public static function getPreviewToken($postId) + public static function getPreviewToken(int $postId): string|false { $previewToken = get_post_meta($postId, 'beyondwords_preview_token', true); - return $previewToken; + return $previewToken ?: false; } /** @@ -309,10 +305,8 @@ public static function getPreviewToken($postId) * @since 6.0.0 Add Magic Embed support. * * @param int $postId Post ID. - * - * @return bool */ - public static function hasGenerateAudio($postId) + public static function hasGenerateAudio(int $postId): bool { $generateAudio = PostMetaUtils::getRenamedPostMeta($postId, 'generate_audio'); @@ -348,7 +342,7 @@ public static function hasGenerateAudio($postId) * * @return int|false Project ID, or false */ - public static function getProjectId($postId, $strict = false) + public static function getProjectId(int $postId, bool $strict = false): int|string|false { // If strict is true, we only check the custom field and do not fall back to the plugin setting. if ($strict) { @@ -396,11 +390,11 @@ public static function getProjectId($postId, $strict = false) * * @return int|false Body Voice ID, or false */ - public static function getBodyVoiceId($postId) + public static function getBodyVoiceId(int $postId): int|string|false { $voiceId = get_post_meta($postId, 'beyondwords_body_voice_id', true); - return $voiceId; + return $voiceId ?: false; } /** @@ -415,11 +409,11 @@ public static function getBodyVoiceId($postId) * * @return int|false Title Voice ID, or false */ - public static function getTitleVoiceId($postId) + public static function getTitleVoiceId(int $postId): int|string|false { $voiceId = get_post_meta($postId, 'beyondwords_title_voice_id', true); - return $voiceId; + return $voiceId ?: false; } /** @@ -434,11 +428,11 @@ public static function getTitleVoiceId($postId) * * @return int|false Summary Voice ID, or false */ - public static function getSummaryVoiceId($postId) + public static function getSummaryVoiceId(int $postId): int|string|false { $voiceId = get_post_meta($postId, 'beyondwords_summary_voice_id', true); - return $voiceId; + return $voiceId ?: false; } /** @@ -452,7 +446,7 @@ public static function getSummaryVoiceId($postId) * * @return string Player style. */ - public static function getPlayerStyle($postId) + public static function getPlayerStyle(int $postId): string { $playerStyle = get_post_meta($postId, 'beyondwords_player_style', true); @@ -476,7 +470,7 @@ public static function getPlayerStyle($postId) * * @return string */ - public static function getErrorMessage($postId) + public static function getErrorMessage(int $postId): string|false { return PostMetaUtils::getRenamedPostMeta($postId, 'error_message'); } @@ -489,12 +483,10 @@ public static function getErrorMessage($postId) * @since 3.7.0 * * @param int $postId Post ID. - * - * @return string */ - public static function getDisabled($postId) + public static function getDisabled(int $postId): bool { - return PostMetaUtils::getRenamedPostMeta($postId, 'disabled'); + return (bool) PostMetaUtils::getRenamedPostMeta($postId, 'disabled'); } /** @@ -515,7 +507,7 @@ public static function getDisabled($postId) * * @return string */ - public static function getHttpResponseBodyFromPostMeta($postId, $metaName) + public static function getHttpResponseBodyFromPostMeta(int $postId, string $metaName): array|string|false { $postMeta = get_post_meta($postId, $metaName, true); diff --git a/src/Component/Post/SelectVoice/SelectVoice.php b/src/Component/Post/SelectVoice/SelectVoice.php index 38aa530b..729a8f3c 100644 --- a/src/Component/Post/SelectVoice/SelectVoice.php +++ b/src/Component/Post/SelectVoice/SelectVoice.php @@ -31,15 +31,15 @@ class SelectVoice */ public static function init() { - add_action('rest_api_init', array(__CLASS__, 'restApiInit')); - add_action('admin_enqueue_scripts', array(__CLASS__, 'adminEnqueueScripts')); + add_action('rest_api_init', [self::class, 'restApiInit']); + add_action('admin_enqueue_scripts', [self::class, 'adminEnqueueScripts']); - add_action('wp_loaded', function () { + add_action('wp_loaded', function (): void { $postTypes = SettingsUtils::getCompatiblePostTypes(); if (is_array($postTypes)) { foreach ($postTypes as $postType) { - add_action("save_post_{$postType}", array(__CLASS__, 'save'), 10); + add_action("save_post_{$postType}", [self::class, 'save'], 10); } } }); @@ -199,22 +199,18 @@ public static function save($postId) public static function restApiInit() { // Languages endpoint - register_rest_route('beyondwords/v1', '/languages', array( + register_rest_route('beyondwords/v1', '/languages', [ 'methods' => \WP_REST_Server::READABLE, - 'callback' => array(__CLASS__, 'languagesRestApiResponse'), - 'permission_callback' => function () { - return current_user_can('edit_posts'); - }, - )); + 'callback' => [self::class, 'languagesRestApiResponse'], + 'permission_callback' => fn() => current_user_can('edit_posts'), + ]); // Voices endpoint - register_rest_route('beyondwords/v1', '/languages/(?P[a-zA-Z0-9-_]+)/voices', array( + register_rest_route('beyondwords/v1', '/languages/(?P[a-zA-Z0-9-_]+)/voices', [ 'methods' => \WP_REST_Server::READABLE, - 'callback' => array(__CLASS__, 'voicesRestApiResponse'), - 'permission_callback' => function () { - return current_user_can('edit_posts'); - }, - )); + 'callback' => [self::class, 'voicesRestApiResponse'], + 'permission_callback' => fn() => current_user_can('edit_posts'), + ]); } /** @@ -278,10 +274,10 @@ public static function adminEnqueueScripts($hook) wp_localize_script( 'beyondwords-metabox--select-voice', 'beyondwordsData', - array( + [ 'nonce' => wp_create_nonce('wp_rest'), 'root' => esc_url_raw(rest_url()), - ) + ] ); wp_enqueue_script('beyondwords-metabox--select-voice'); diff --git a/src/Component/Post/Sidebar/Sidebar.php b/src/Component/Post/Sidebar/Sidebar.php index 693f5b73..214071a3 100644 --- a/src/Component/Post/Sidebar/Sidebar.php +++ b/src/Component/Post/Sidebar/Sidebar.php @@ -32,7 +32,7 @@ class Sidebar */ public static function init() { - add_action('enqueue_block_assets', array(__CLASS__, 'enqueueBlockAssets')); + add_action('enqueue_block_assets', [self::class, 'enqueueBlockAssets']); } /** @@ -52,7 +52,7 @@ public static function enqueueBlockAssets() wp_enqueue_style( 'beyondwords-Sidebar', BEYONDWORDS__PLUGIN_URI . 'src/Component/Post/Sidebar/PostSidebar.css', - array(), + [], BEYONDWORDS__PLUGIN_VERSION ); } diff --git a/src/Component/Posts/BulkEdit/BulkEdit.php b/src/Component/Posts/BulkEdit/BulkEdit.php index ebbf161e..ae1eafbf 100644 --- a/src/Component/Posts/BulkEdit/BulkEdit.php +++ b/src/Component/Posts/BulkEdit/BulkEdit.php @@ -34,17 +34,17 @@ class BulkEdit */ public static function init() { - add_action('bulk_edit_custom_box', array(__CLASS__, 'bulkEditCustomBox'), 10, 2); - add_action('wp_ajax_save_bulk_edit_beyondwords', array(__CLASS__, 'saveBulkEdit')); + add_action('bulk_edit_custom_box', [self::class, 'bulkEditCustomBox'], 10, 2); + add_action('wp_ajax_save_bulk_edit_beyondwords', [self::class, 'saveBulkEdit']); - add_action('wp_loaded', function () { + add_action('wp_loaded', function (): void { $postTypes = SettingsUtils::getCompatiblePostTypes(); if (is_array($postTypes)) { foreach ($postTypes as $postType) { - add_filter("bulk_actions-edit-{$postType}", array(__CLASS__, 'bulkActionsEdit'), 10, 1); - add_filter("handle_bulk_actions-edit-{$postType}", array(__CLASS__, 'handleBulkDeleteAction'), 10, 3); // phpcs:ignore Generic.Files.LineLength.TooLong - add_filter("handle_bulk_actions-edit-{$postType}", array(__CLASS__, 'handleBulkGenerateAction'), 10, 3); // phpcs:ignore Generic.Files.LineLength.TooLong + add_filter("bulk_actions-edit-{$postType}", [self::class, 'bulkActionsEdit'], 10, 1); + add_filter("handle_bulk_actions-edit-{$postType}", [self::class, 'handleBulkDeleteAction'], 10, 3); // phpcs:ignore Generic.Files.LineLength.TooLong + add_filter("handle_bulk_actions-edit-{$postType}", [self::class, 'handleBulkGenerateAction'], 10, 3); // phpcs:ignore Generic.Files.LineLength.TooLong } } }); @@ -55,7 +55,7 @@ public static function init() * * @since 6.0.0 Make static. */ - public static function bulkEditCustomBox($columnName, $postType) + public static function bulkEditCustomBox(string $columnName, string $postType): void { if ($columnName !== 'beyondwords') { return; @@ -118,10 +118,8 @@ public static function saveBulkEdit() switch ($_POST['beyondwords_bulk_edit']) { case 'generate': return self::generateAudioForPosts($postIds); - break; case 'delete': return self::deleteAudioForPosts($postIds); - break; } } @@ -133,10 +131,10 @@ public static function saveBulkEdit() * * @since 6.0.0 Make static. */ - public static function generateAudioForPosts($postIds) + public static function generateAudioForPosts(array|null $postIds): array { if (! is_array($postIds)) { - return false; + return []; } $updatedPostIds = []; @@ -156,10 +154,10 @@ public static function generateAudioForPosts($postIds) * * @since 6.0.0 Make static. */ - public static function deleteAudioForPosts($postIds) + public static function deleteAudioForPosts(array|null $postIds): array { if (! is_array($postIds)) { - return false; + return []; } $updatedPostIds = []; @@ -188,7 +186,7 @@ public static function deleteAudioForPosts($postIds) * * @since 6.0.0 Make static. */ - public static function bulkActionsEdit($bulk_array) + public static function bulkActionsEdit(array $bulk_array): array { $bulk_array['beyondwords_generate_audio'] = __('Generate audio', 'speechkit'); $bulk_array['beyondwords_delete_audio'] = __('Delete audio', 'speechkit'); @@ -201,7 +199,7 @@ public static function bulkActionsEdit($bulk_array) * * @since 6.0.0 Make static. */ - public static function handleBulkGenerateAction($redirect, $doaction, $objectIds) + public static function handleBulkGenerateAction(string $redirect, string $doaction, array $objectIds): string { if ($doaction !== 'beyondwords_generate_audio') { return $redirect; @@ -249,9 +247,8 @@ public static function handleBulkGenerateAction($redirect, $doaction, $objectIds // Add nonce to redirect url $nonce = wp_create_nonce('beyondwords_bulk_edit_result'); - $redirect = add_query_arg('beyondwords_bulk_edit_result_nonce', $nonce, $redirect); - return $redirect; + return add_query_arg('beyondwords_bulk_edit_result_nonce', $nonce, $redirect); } /** @@ -259,7 +256,7 @@ public static function handleBulkGenerateAction($redirect, $doaction, $objectIds * * @since 6.0.0 Make static. */ - public static function handleBulkDeleteAction($redirect, $doaction, $objectIds) + public static function handleBulkDeleteAction(string $redirect, string $doaction, array $objectIds): string { if ($doaction !== 'beyondwords_delete_audio') { return $redirect; @@ -294,8 +291,7 @@ public static function handleBulkDeleteAction($redirect, $doaction, $objectIds) // Add $nonce query arg into redirect $nonce = wp_create_nonce('beyondwords_bulk_edit_result'); - $redirect = add_query_arg('beyondwords_bulk_edit_result_nonce', $nonce, $redirect); - return $redirect; + return add_query_arg('beyondwords_bulk_edit_result_nonce', $nonce, $redirect); } } diff --git a/src/Component/Posts/BulkEdit/Notices.php b/src/Component/Posts/BulkEdit/Notices.php index 9e6dc748..71be8145 100644 --- a/src/Component/Posts/BulkEdit/Notices.php +++ b/src/Component/Posts/BulkEdit/Notices.php @@ -28,10 +28,10 @@ class Notices */ public static function init() { - add_action('admin_notices', array(__CLASS__, 'generatedNotice')); - add_action('admin_notices', array(__CLASS__, 'deletedNotice')); - add_action('admin_notices', array(__CLASS__, 'failedNotice')); - add_action('admin_notices', array(__CLASS__, 'errorNotice')); + add_action('admin_notices', [self::class, 'generatedNotice']); + add_action('admin_notices', [self::class, 'deletedNotice']); + add_action('admin_notices', [self::class, 'failedNotice']); + add_action('admin_notices', [self::class, 'errorNotice']); } /** diff --git a/src/Component/Posts/Column/Column.php b/src/Component/Posts/Column/Column.php index 1e47e817..02a1e238 100644 --- a/src/Component/Posts/Column/Column.php +++ b/src/Component/Posts/Column/Column.php @@ -23,11 +23,11 @@ */ class Column { - public const ALLOWED_HTML = array( - 'span' => array( - 'class' => array(), - ), - ); + public const ALLOWED_HTML = [ + 'span' => [ + 'class' => [], + ], + ]; public const OUTPUT_YES = ' '; @@ -46,20 +46,20 @@ class Column */ public static function init() { - add_action('wp_loaded', function () { + add_action('wp_loaded', function (): void { $postTypes = SettingsUtils::getCompatiblePostTypes(); if (is_array($postTypes)) { foreach ($postTypes as $postType) { - add_filter("manage_{$postType}_posts_columns", array(__CLASS__, 'renderColumnsHead')); - add_action("manage_{$postType}_posts_custom_column", array(__CLASS__, 'renderColumnsContent'), 10, 2); // phpcs:ignore Generic.Files.LineLength.TooLong - add_filter("manage_edit-{$postType}_sortable_columns", array(__CLASS__, 'makeColumnSortable')); + add_filter("manage_{$postType}_posts_columns", [self::class, 'renderColumnsHead']); + add_action("manage_{$postType}_posts_custom_column", [self::class, 'renderColumnsContent'], 10, 2); // phpcs:ignore Generic.Files.LineLength.TooLong + add_filter("manage_edit-{$postType}_sortable_columns", [self::class, 'makeColumnSortable']); } } }); if (CoreUtils::isEditScreen()) { - add_action('pre_get_posts', array(__CLASS__, 'setSortQuery')); + add_action('pre_get_posts', [self::class, 'setSortQuery']); } } @@ -75,9 +75,9 @@ public static function init() **/ public static function renderColumnsHead($columns) { - return array_merge($columns, array( + return array_merge($columns, [ 'beyondwords' => __('BeyondWords', 'speechkit'), - )); + ]); } /** diff --git a/src/Component/Settings/Fields/ApiKey/ApiKey.php b/src/Component/Settings/Fields/ApiKey/ApiKey.php index 4c627766..b39c5187 100644 --- a/src/Component/Settings/Fields/ApiKey/ApiKey.php +++ b/src/Component/Settings/Fields/ApiKey/ApiKey.php @@ -36,7 +36,7 @@ class ApiKey */ public static function init() { - add_action('admin_init', array(__CLASS__, 'addSetting')); + add_action('admin_init', [self::class, 'addSetting']); } /** @@ -54,14 +54,14 @@ public static function addSetting() self::OPTION_NAME, [ 'default' => '', - 'sanitize_callback' => array(__CLASS__, 'sanitize'), + 'sanitize_callback' => [self::class, 'sanitize'], ] ); add_settings_field( 'beyondwords-api-key', __('API key', 'speechkit'), - array(__CLASS__, 'render'), + [self::class, 'render'], 'beyondwords_credentials', 'credentials' ); diff --git a/src/Component/Settings/Fields/AutoPublish/AutoPublish.php b/src/Component/Settings/Fields/AutoPublish/AutoPublish.php index 4df5e260..1c5566b2 100644 --- a/src/Component/Settings/Fields/AutoPublish/AutoPublish.php +++ b/src/Component/Settings/Fields/AutoPublish/AutoPublish.php @@ -43,7 +43,7 @@ class AutoPublish */ public static function init() { - add_action('admin_init', array(__CLASS__, 'addSetting')); + add_action('admin_init', [self::class, 'addSetting']); add_action('pre_update_option_' . self::OPTION_NAME, function ($value) { Sync::syncOptionToDashboard(self::OPTION_NAME); return $value; @@ -74,7 +74,7 @@ public static function addSetting() add_settings_field( 'beyondwords-auto-publish', __('Auto-publish', 'speechkit'), - array(__CLASS__, 'render'), + [self::class, 'render'], 'beyondwords_content', 'content' ); diff --git a/src/Component/Settings/Fields/CallToAction/CallToAction.php b/src/Component/Settings/Fields/CallToAction/CallToAction.php index fe6a88f7..4abf00f7 100644 --- a/src/Component/Settings/Fields/CallToAction/CallToAction.php +++ b/src/Component/Settings/Fields/CallToAction/CallToAction.php @@ -36,7 +36,7 @@ class CallToAction */ public static function init() { - add_action('admin_init', array(__CLASS__, 'addSetting')); + add_action('admin_init', [self::class, 'addSetting']); add_action('pre_update_option_' . self::OPTION_NAME, function ($value) { Sync::syncOptionToDashboard(self::OPTION_NAME); return $value; @@ -64,7 +64,7 @@ public static function addSetting() add_settings_field( 'beyondwords-player-call-to-action', __('Call-to-action', 'speechkit'), - array(__CLASS__, 'render'), + [self::class, 'render'], 'beyondwords_player', 'styling' ); diff --git a/src/Component/Settings/Fields/IncludeExcerpt/IncludeExcerpt.php b/src/Component/Settings/Fields/IncludeExcerpt/IncludeExcerpt.php index b9bd0859..55d92a92 100644 --- a/src/Component/Settings/Fields/IncludeExcerpt/IncludeExcerpt.php +++ b/src/Component/Settings/Fields/IncludeExcerpt/IncludeExcerpt.php @@ -42,7 +42,7 @@ class IncludeExcerpt */ public static function init() { - add_action('admin_init', array(__CLASS__, 'addSetting')); + add_action('admin_init', [self::class, 'addSetting']); add_filter('option_' . self::OPTION_NAME, 'rest_sanitize_boolean'); } @@ -70,7 +70,7 @@ public static function addSetting() add_settings_field( 'beyondwords-include-excerpt', __('Excerpt', 'speechkit'), - array(__CLASS__, 'render'), + [self::class, 'render'], 'beyondwords_content', 'content' ); diff --git a/src/Component/Settings/Fields/IncludeTitle/IncludeTitle.php b/src/Component/Settings/Fields/IncludeTitle/IncludeTitle.php index 10b0186c..ec14be1d 100644 --- a/src/Component/Settings/Fields/IncludeTitle/IncludeTitle.php +++ b/src/Component/Settings/Fields/IncludeTitle/IncludeTitle.php @@ -43,7 +43,7 @@ class IncludeTitle */ public static function init() { - add_action('admin_init', array(__CLASS__, 'addSetting')); + add_action('admin_init', [self::class, 'addSetting']); add_action('pre_update_option_' . self::OPTION_NAME, function ($value) { Sync::syncOptionToDashboard(self::OPTION_NAME); return $value; @@ -74,7 +74,7 @@ public static function addSetting() add_settings_field( 'beyondwords-include-title', __('Title', 'speechkit'), - array(__CLASS__, 'render'), + [self::class, 'render'], 'beyondwords_content', 'content' ); diff --git a/src/Component/Settings/Fields/IntegrationMethod/IntegrationMethod.php b/src/Component/Settings/Fields/IntegrationMethod/IntegrationMethod.php index 321e2723..9bc1ceab 100644 --- a/src/Component/Settings/Fields/IntegrationMethod/IntegrationMethod.php +++ b/src/Component/Settings/Fields/IntegrationMethod/IntegrationMethod.php @@ -63,7 +63,7 @@ class IntegrationMethod */ public static function init() { - add_action('admin_init', array(__CLASS__, 'addSetting')); + add_action('admin_init', [self::class, 'addSetting']); } /** @@ -87,7 +87,7 @@ public static function addSetting() add_settings_field( 'beyondwords-integration-method', __('Integration method', 'speechkit'), - array(__CLASS__, 'render'), + [self::class, 'render'], 'beyondwords_content', 'content' ); diff --git a/src/Component/Settings/Fields/Language/Language.php b/src/Component/Settings/Fields/Language/Language.php index 758b85ae..b9424175 100644 --- a/src/Component/Settings/Fields/Language/Language.php +++ b/src/Component/Settings/Fields/Language/Language.php @@ -35,7 +35,7 @@ class Language */ public static function init() { - add_action('admin_init', array(__CLASS__, 'addSetting')); + add_action('admin_init', [self::class, 'addSetting']); add_action('pre_update_option_' . self::OPTION_NAME_CODE, function ($value) { Sync::syncOptionToDashboard(self::OPTION_NAME_CODE); return $value; @@ -55,7 +55,7 @@ public static function addSetting() add_settings_field( 'beyondwords-default-language', __('Language', 'speechkit'), - array(__CLASS__, 'render'), + [self::class, 'render'], 'beyondwords_voices', 'voices' ); @@ -123,7 +123,7 @@ public static function getOptions() $languages = []; } - $options = array_map(function ($language) { + return array_map(function ($language) { $label = $language['name']; if (isset($language['accent'])) { @@ -136,7 +136,5 @@ public static function getOptions() 'voices' => wp_json_encode($language['default_voices']), ]; }, $languages); - - return $options; } } diff --git a/src/Component/Settings/Fields/PlaybackControls/PlaybackControls.php b/src/Component/Settings/Fields/PlaybackControls/PlaybackControls.php index 40ca2df9..8cc56f36 100644 --- a/src/Component/Settings/Fields/PlaybackControls/PlaybackControls.php +++ b/src/Component/Settings/Fields/PlaybackControls/PlaybackControls.php @@ -41,7 +41,7 @@ class PlaybackControls */ public static function init() { - add_action('admin_init', array(__CLASS__, 'addSetting')); + add_action('admin_init', [self::class, 'addSetting']); add_action('pre_update_option_' . self::OPTION_NAME, function ($value) { Sync::syncOptionToDashboard(self::OPTION_NAME); return $value; @@ -69,7 +69,7 @@ public static function addSetting() add_settings_field( 'beyondwords-player-skip-button-style', __('Skip button style', 'speechkit'), - array(__CLASS__, 'render'), + [self::class, 'render'], 'beyondwords_player', 'playback-controls' ); diff --git a/src/Component/Settings/Fields/PlaybackFromSegments/PlaybackFromSegments.php b/src/Component/Settings/Fields/PlaybackFromSegments/PlaybackFromSegments.php index ffb60a19..2c9f36d5 100644 --- a/src/Component/Settings/Fields/PlaybackFromSegments/PlaybackFromSegments.php +++ b/src/Component/Settings/Fields/PlaybackFromSegments/PlaybackFromSegments.php @@ -43,7 +43,7 @@ class PlaybackFromSegments */ public static function init() { - add_action('admin_init', array(__CLASS__, 'addSetting')); + add_action('admin_init', [self::class, 'addSetting']); add_action('pre_update_option_' . self::OPTION_NAME, function ($value) { Sync::syncOptionToDashboard(self::OPTION_NAME); return $value; @@ -74,7 +74,7 @@ public static function addSetting() add_settings_field( 'beyondwords-playback-from-segments', __('Playback from segments', 'speechkit'), - array(__CLASS__, 'render'), + [self::class, 'render'], 'beyondwords_player', 'styling' ); diff --git a/src/Component/Settings/Fields/PlayerColors/PlayerColors.php b/src/Component/Settings/Fields/PlayerColors/PlayerColors.php index 792cbc55..981e421a 100644 --- a/src/Component/Settings/Fields/PlayerColors/PlayerColors.php +++ b/src/Component/Settings/Fields/PlayerColors/PlayerColors.php @@ -50,8 +50,8 @@ class PlayerColors */ public static function init() { - add_action('admin_init', array(__CLASS__, 'addPlayerThemeSetting')); - add_action('admin_init', array(__CLASS__, 'addPlayerColorsSetting')); + add_action('admin_init', [self::class, 'addPlayerThemeSetting']); + add_action('admin_init', [self::class, 'addPlayerColorsSetting']); add_action('pre_update_option_' . self::OPTION_NAME_THEME, function ($value) { Sync::syncOptionToDashboard(self::OPTION_NAME_THEME); return $value; @@ -91,7 +91,7 @@ public static function addPlayerThemeSetting() add_settings_field( 'beyondwords-player-theme', __('Player theme', 'speechkit'), - array(__CLASS__, 'renderPlayerThemeSetting'), + [self::class, 'renderPlayerThemeSetting'], 'beyondwords_player', 'styling' ); @@ -117,7 +117,7 @@ public static function addPlayerColorsSetting() 'text_color' => '#111', 'highlight_color' => '#eee', ], - 'sanitize_callback' => array(__CLASS__, 'sanitizeColorsArray'), + 'sanitize_callback' => [self::class, 'sanitizeColorsArray'], ] ); @@ -131,7 +131,7 @@ public static function addPlayerColorsSetting() 'text_color' => '#111', 'highlight_color' => '#eee', ], - 'sanitize_callback' => array(__CLASS__, 'sanitizeColorsArray'), + 'sanitize_callback' => [self::class, 'sanitizeColorsArray'], ] ); @@ -144,14 +144,14 @@ public static function addPlayerColorsSetting() 'icon_color' => '#fff', 'text_color' => '#fff', ], - 'sanitize_callback' => array(__CLASS__, 'sanitizeColorsArray'), + 'sanitize_callback' => [self::class, 'sanitizeColorsArray'], ] ); add_settings_field( 'beyondwords-player-colors', __('Player colors', 'speechkit'), - array(__CLASS__, 'renderPlayerColorsSetting'), + [self::class, 'renderPlayerColorsSetting'], 'beyondwords_player', 'styling' ); @@ -247,7 +247,7 @@ public static function sanitizeColor($value) **/ public static function getPlayerThemeOptions() { - $themeOptions = [ + return [ [ 'value' => 'light', 'label' => 'Light (default)', @@ -261,8 +261,6 @@ public static function getPlayerThemeOptions() 'label' => 'Auto', ], ]; - - return $themeOptions; } /** diff --git a/src/Component/Settings/Fields/PlayerStyle/PlayerStyle.php b/src/Component/Settings/Fields/PlayerStyle/PlayerStyle.php index fbd408bc..f8c992f3 100644 --- a/src/Component/Settings/Fields/PlayerStyle/PlayerStyle.php +++ b/src/Component/Settings/Fields/PlayerStyle/PlayerStyle.php @@ -41,7 +41,7 @@ class PlayerStyle */ public static function init() { - add_action('admin_init', array(__CLASS__, 'addSetting')); + add_action('admin_init', [self::class, 'addSetting']); add_action('pre_update_option_' . self::OPTION_NAME, function ($value) { Sync::syncOptionToDashboard(self::OPTION_NAME); return $value; @@ -69,7 +69,7 @@ public static function addSetting() add_settings_field( 'beyondwords-player-style', __('Player style', 'speechkit'), - array(__CLASS__, 'render'), + [self::class, 'render'], 'beyondwords_player', 'styling' ); @@ -99,7 +99,7 @@ public static function render() ` * @param string $value `value` attribute for the `` - * - * @return string */ - public static function colorInput($label, $name, $value) + public static function colorInput(string $label, string $name, string $value): void { ?>
@@ -270,10 +262,8 @@ class="small-text" * * @param string $message The error message. * @param string $errorId The error ID. - * - * @return void **/ - public static function addSettingsErrorMessage($message, $errorId = '') + public static function addSettingsErrorMessage(string $message, string $errorId = ''): void { $errors = wp_cache_get('beyondwords_settings_errors', 'beyondwords'); diff --git a/src/Component/Settings/Sync.php b/src/Component/Settings/Sync.php index 26c893fe..64e73938 100644 --- a/src/Component/Settings/Sync.php +++ b/src/Component/Settings/Sync.php @@ -64,11 +64,11 @@ class Sync */ public static function init() { - add_action('load-settings_page_beyondwords', array(__CLASS__, 'syncToWordPress'), 30); + add_action('load-settings_page_beyondwords', [self::class, 'syncToWordPress'], 30); if (Environment::hasAutoSyncSettings()) { - add_action('load-settings_page_beyondwords', array(__CLASS__, 'scheduleSyncs'), 20); - add_action('shutdown', array(__CLASS__, 'syncToDashboard')); + add_action('load-settings_page_beyondwords', [self::class, 'scheduleSyncs'], 20); + add_action('shutdown', [self::class, 'syncToDashboard']); } } @@ -88,8 +88,6 @@ public static function scheduleSyncs() switch ($tab) { case 'content': - $endpoints = ['project']; - break; case 'voices': $endpoints = ['project']; break; diff --git a/src/Component/Settings/Tabs/Content/Content.php b/src/Component/Settings/Tabs/Content/Content.php index 01e7942a..35208691 100644 --- a/src/Component/Settings/Tabs/Content/Content.php +++ b/src/Component/Settings/Tabs/Content/Content.php @@ -41,7 +41,7 @@ public static function init() (new IncludeExcerpt())::init(); (new PreselectGenerateAudio())::init(); - add_action('admin_init', array(__CLASS__, 'addSettingsSection'), 5); + add_action('admin_init', [self::class, 'addSettingsSection'], 5); } /** @@ -55,7 +55,7 @@ public static function addSettingsSection() add_settings_section( 'content', __('Content', 'speechkit'), - array(__CLASS__, 'sectionCallback'), + [self::class, 'sectionCallback'], 'beyondwords_content', ); } diff --git a/src/Component/Settings/Tabs/Credentials/Credentials.php b/src/Component/Settings/Tabs/Credentials/Credentials.php index f2137e47..38c66972 100644 --- a/src/Component/Settings/Tabs/Credentials/Credentials.php +++ b/src/Component/Settings/Tabs/Credentials/Credentials.php @@ -35,7 +35,7 @@ public static function init() (new ApiKey())::init(); (new ProjectId())::init(); - add_action('admin_init', array(__CLASS__, 'addSettingsSection'), 5); + add_action('admin_init', [self::class, 'addSettingsSection'], 5); } /** @@ -49,7 +49,7 @@ public static function addSettingsSection() add_settings_section( 'credentials', __('Credentials', 'speechkit'), - array(__CLASS__, 'sectionCallback'), + [self::class, 'sectionCallback'], 'beyondwords_credentials', ); } diff --git a/src/Component/Settings/Tabs/Player/Player.php b/src/Component/Settings/Tabs/Player/Player.php index 43170365..874e07d5 100644 --- a/src/Component/Settings/Tabs/Player/Player.php +++ b/src/Component/Settings/Tabs/Player/Player.php @@ -49,7 +49,7 @@ public static function init() (new PlaybackFromSegments())::init(); (new PlaybackControls())::init(); - add_action('admin_init', array(__CLASS__, 'addSettingsSection'), 5); + add_action('admin_init', [self::class, 'addSettingsSection'], 5); } /** @@ -63,7 +63,7 @@ public static function addSettingsSection() add_settings_section( 'player', __('Player', 'speechkit'), - array(__CLASS__, 'sectionCallback'), + [self::class, 'sectionCallback'], 'beyondwords_player', ); diff --git a/src/Component/Settings/Tabs/Pronunciations/Pronunciations.php b/src/Component/Settings/Tabs/Pronunciations/Pronunciations.php index 8842c996..ec6e4db7 100644 --- a/src/Component/Settings/Tabs/Pronunciations/Pronunciations.php +++ b/src/Component/Settings/Tabs/Pronunciations/Pronunciations.php @@ -31,7 +31,7 @@ class Pronunciations */ public static function init() { - add_action('admin_init', array(__CLASS__, 'addSettingsSection'), 5); + add_action('admin_init', [self::class, 'addSettingsSection'], 5); } /** @@ -45,7 +45,7 @@ public static function addSettingsSection() add_settings_section( 'pronunciations', __('Pronunciations', 'speechkit'), - array(__CLASS__, 'sectionCallback'), + [self::class, 'sectionCallback'], 'beyondwords_pronunciations', ); } diff --git a/src/Component/Settings/Tabs/Summarization/Summarization.php b/src/Component/Settings/Tabs/Summarization/Summarization.php index 22b960d3..fc7c213d 100644 --- a/src/Component/Settings/Tabs/Summarization/Summarization.php +++ b/src/Component/Settings/Tabs/Summarization/Summarization.php @@ -31,7 +31,7 @@ class Summarization */ public static function init() { - add_action('admin_init', array(__CLASS__, 'addSettingsSection'), 5); + add_action('admin_init', [self::class, 'addSettingsSection'], 5); } /** @@ -45,7 +45,7 @@ public static function addSettingsSection() add_settings_section( 'summarization', __('Summarization', 'speechkit'), - array(__CLASS__, 'sectionCallback'), + [self::class, 'sectionCallback'], 'beyondwords_summarization', ); } diff --git a/src/Component/Settings/Tabs/Voices/Voices.php b/src/Component/Settings/Tabs/Voices/Voices.php index 0d5767ff..434a1301 100644 --- a/src/Component/Settings/Tabs/Voices/Voices.php +++ b/src/Component/Settings/Tabs/Voices/Voices.php @@ -41,7 +41,7 @@ public static function init() BodyVoice::init(); BodyVoiceSpeakingRate::init(); - add_action('admin_init', array(__CLASS__, 'addSettingsSection'), 5); + add_action('admin_init', [self::class, 'addSettingsSection'], 5); } /** @@ -55,7 +55,7 @@ public static function addSettingsSection() add_settings_section( 'voices', __('Voices', 'speechkit'), - [__CLASS__, 'sectionCallback'], + [self::class, 'sectionCallback'], 'beyondwords_voices', ); } diff --git a/src/Component/SiteHealth/SiteHealth.php b/src/Component/SiteHealth/SiteHealth.php index abc178ad..dff2f69f 100644 --- a/src/Component/SiteHealth/SiteHealth.php +++ b/src/Component/SiteHealth/SiteHealth.php @@ -79,7 +79,7 @@ class SiteHealth */ public static function init() { - add_filter('debug_information', array(__CLASS__, 'debugInformation')); + add_filter('debug_information', [self::class, 'debugInformation']); } /** @@ -88,11 +88,9 @@ public static function init() * @since 3.7.0 * @since 6.0.0 Make static. * - * @param array $info * - * @return array */ - public static function debugInformation($info) + public static function debugInformation(array $info): array { $info['beyondwords']['label'] = __('BeyondWords - Text-to-Speech', 'speechkit'); @@ -143,10 +141,8 @@ public static function debugInformation($info) * @since 6.0.0 Make static. * * @param array $info Debugging info array - * - * @return array */ - public static function addContentSettings(&$info) + public static function addContentSettings(array &$info): void { $info['beyondwords']['fields']['beyondwords_project_title_enabled'] = [ 'label' => __('Include title in audio', 'speechkit'), @@ -179,10 +175,8 @@ public static function addContentSettings(&$info) * @since 6.0.0 Make static. * * @param array $info Debugging info array - * - * @return array */ - public static function addProjectSettings(&$info) + public static function addProjectSettings(array &$info): void { $info['beyondwords']['fields']['beyondwords_project_language_code'] = [ 'label' => __('Default language code', 'speechkit'), @@ -222,10 +216,8 @@ public static function addProjectSettings(&$info) * @since 6.0.0 Make static. * * @param array $info Debugging info array - * - * @return array */ - public static function addPlayerSettings(&$info) + public static function addPlayerSettings(array &$info): void { $info['beyondwords']['fields']['beyondwords_player_ui'] = [ 'label' => __('Player UI', 'speechkit'), @@ -351,13 +343,13 @@ public static function addRestApiConnection(&$info) ]); if (! is_wp_error($response)) { - $info['beyondwords']['fields']['api-communication'] = array( + $info['beyondwords']['fields']['api-communication'] = [ 'label' => __('Communication with REST API', 'speechkit'), 'value' => __('BeyondWords API is reachable', 'speechkit'), 'debug' => 'true', - ); + ]; } else { - $info['beyondwords']['fields']['api-communication'] = array( + $info['beyondwords']['fields']['api-communication'] = [ 'label' => __('Communication with REST API', 'speechkit'), 'value' => sprintf( /* translators: 1: The IP address the REST API resolves to. 2: The error returned by the lookup. */ @@ -366,7 +358,7 @@ public static function addRestApiConnection(&$info) $response->get_error_message() ), 'debug' => $response->get_error_message(), - ); + ]; } } @@ -377,10 +369,8 @@ public static function addRestApiConnection(&$info) * @since 6.0.0 Make static. * * @param array $info Debugging info array - * - * @return array */ - public static function addFilters(&$info) + public static function addFilters(array &$info): void { $registered = array_values(array_filter(SiteHealth::FILTERS, 'has_filter')); @@ -406,10 +396,8 @@ public static function addFilters(&$info) * @since 6.0.0 Make static. * * @param array $info Debugging info array - * - * @return array */ - public static function addNoticeSettings(&$info) + public static function addNoticeSettings(array &$info): void { $info['beyondwords']['fields']['beyondwords_date_activated'] = [ 'label' => __('Date Activated', 'speechkit'), @@ -431,10 +419,8 @@ public static function addNoticeSettings(&$info) * * @param array $info Debugging info array * @param string $name Constant name - * - * @return array */ - public static function addConstant(&$info, $name) + public static function addConstant(array &$info, string $name): void { $value = __('Undefined', 'speechkit'); @@ -461,12 +447,9 @@ public static function addConstant(&$info, $name) * @static * * @param string $string - * @param int $count - * @param string $char * - * @return string */ - public static function maskString($string, $count = 4, $char = 'X') + public static function maskString(string|false $string, int $count = 4, string $char = 'X'): string { if (! is_string($string)) { return ''; @@ -475,7 +458,7 @@ public static function maskString($string, $count = 4, $char = 'X') if (strlen($string) < 8) { return str_repeat($char, strlen($string)); } else { - return str_repeat($char, strlen($string) - $count) . substr($string, (0 - $count)); + return str_repeat($char, strlen($string) - $count) . substr($string, (-$count)); } } } diff --git a/src/Core/ApiClient.php b/src/Core/ApiClient.php index efb0f5a7..750d8990 100644 --- a/src/Core/ApiClient.php +++ b/src/Core/ApiClient.php @@ -32,10 +32,10 @@ class ApiClient * * @return WP_Response|false **/ - public static function getContent($contentId, $projectId = null) + public static function getContent(int|string $contentId, int|string|null $projectId = null): array|false { if (! $projectId) { - $projectId = PostMetaUtils::getProjectId($contentId); + $projectId = get_option('beyondwords_project_id'); } if (! $projectId || ! $contentId) { @@ -59,7 +59,7 @@ public static function getContent($contentId, $projectId = null) * * @return mixed JSON-decoded response body **/ - public static function createAudio($postId) + public static function createAudio(int $postId): array|null|false { $projectId = PostMetaUtils::getProjectId($postId); @@ -88,7 +88,7 @@ public static function createAudio($postId) * * @return mixed JSON-decoded response body **/ - public static function updateAudio($postId) + public static function updateAudio(int $postId): array|null|false { $projectId = PostMetaUtils::getProjectId($postId); $contentId = PostMetaUtils::getContentId($postId, true); // fallback to Post ID @@ -118,7 +118,7 @@ public static function updateAudio($postId) * * @return mixed JSON-decoded response body **/ - public static function deleteAudio($postId) + public static function deleteAudio(int $postId): array|null|false { $projectId = PostMetaUtils::getProjectId($postId); $contentId = PostMetaUtils::getContentId($postId, true); // fallback to Post ID @@ -153,7 +153,7 @@ public static function deleteAudio($postId) * @throws \Exception * @return mixed JSON-decoded response body **/ - public static function batchDeleteAudio($postIds) + public static function batchDeleteAudio(array $postIds): array|false { $contentIds = []; $updatedPostIds = []; @@ -191,13 +191,13 @@ public static function batchDeleteAudio($postIds) $request = new Request('POST', $url, $body); - $args = array( + $args = [ 'blocking' => true, 'body' => $request->getBody(), 'headers' => $request->getHeaders(), 'method' => $request->getMethod(), 'timeout' => 30, // phpcs:ignore WordPressVIPMinimum.Performance.RemoteRequestTimeout.timeout_timeout - ); + ]; $response = wp_remote_request($request->getUrl(), $args); @@ -231,7 +231,7 @@ public static function batchDeleteAudio($postIds) * * @return mixed JSON-decoded response body, or false on failure. **/ - public static function getPlayerBySourceId($postId) + public static function getPlayerBySourceId(int $postId): array|null|false { $projectId = PostMetaUtils::getProjectId($postId); @@ -262,7 +262,7 @@ public static function getPlayerBySourceId($postId) * * @return mixed JSON-decoded response body **/ - public static function getLanguages() + public static function getLanguages(): array|null|false { $url = sprintf('%s/organization/languages', Environment::getApiUrl()); @@ -285,7 +285,7 @@ public static function getLanguages() * * @return mixed JSON-decoded response body **/ - public static function getVoices($languageCode) + public static function getVoices(int|string $languageCode): array|null|false { $url = sprintf( '%s/organization/voices?filter[language.code]=%s&filter[scopes][]=primary&filter[scopes][]=secondary', @@ -310,7 +310,7 @@ public static function getVoices($languageCode) * * @return object|false Voice, or false if not found. **/ - public static function getVoice($voiceId, $languageCode = false) + public static function getVoice(int $voiceId, int|string|false $languageCode = false): object|array|false { if (! $languageCode) { $languageCode = get_option('beyondwords_project_language_code'); @@ -336,7 +336,7 @@ public static function getVoice($voiceId, $languageCode = false) * * @return mixed JSON-decoded response body **/ - public static function updateVoice($voiceId, $settings) + public static function updateVoice(int $voiceId, array $settings): array|null|false { if (empty($voiceId)) { return false; @@ -361,7 +361,7 @@ public static function updateVoice($voiceId, $settings) * * @return mixed JSON-decoded response body **/ - public static function getProject() + public static function getProject(): array|null|false { $projectId = get_option('beyondwords_project_id'); @@ -388,7 +388,7 @@ public static function getProject() * * @return mixed JSON-decoded response body **/ - public static function updateProject($settings) + public static function updateProject(array $settings): array|null|false { $projectId = get_option('beyondwords_project_id'); @@ -414,7 +414,7 @@ public static function updateProject($settings) * * @return mixed JSON-decoded response body **/ - public static function getPlayerSettings() + public static function getPlayerSettings(): array|null|false { $projectId = get_option('beyondwords_project_id'); @@ -441,7 +441,7 @@ public static function getPlayerSettings() * * @return mixed JSON-decoded response body **/ - public static function updatePlayerSettings($settings) + public static function updatePlayerSettings(array $settings): array|null|false { $projectId = get_option('beyondwords_project_id'); @@ -470,7 +470,7 @@ public static function updatePlayerSettings($settings) * * @return mixed JSON-decoded response body **/ - public static function getVideoSettings($projectId = null) + public static function getVideoSettings(int|null $projectId = null): array|null|false { if (! $projectId) { $projectId = get_option('beyondwords_project_id'); @@ -506,7 +506,7 @@ public static function getVideoSettings($projectId = null) * @return array|WP_Error The response array or a WP_Error on failure. See WP_Http::request() for * information on return value. **/ - public static function callApi($request, $postId = false) + public static function callApi(Request $request, int|false $postId = false): array|\WP_Error { $post = get_post($postId); @@ -552,7 +552,7 @@ public static function callApi($request, $postId = false) * * @return array WordPress HTTP Request arguments. */ - public static function buildRequestArgs($request) + public static function buildRequestArgs(Request $request): array { return [ 'blocking' => true, @@ -573,7 +573,7 @@ public static function buildRequestArgs($request) * * @return string Error message. */ - public static function errorMessageFromResponse($response) + public static function errorMessageFromResponse(array|\WP_Error $response): string { $body = wp_remote_retrieve_body($response); $body = json_decode($body, true); @@ -604,10 +604,8 @@ public static function errorMessageFromResponse($response) * @since 5.2.0 Make static. * * @param int $postId WordPress post ID. - * - * @return void */ - public static function deleteErrors($postId) + public static function deleteErrors(int|false $postId): void { if (! $postId) { return; @@ -632,10 +630,8 @@ public static function deleteErrors($postId) * @param int $postId WordPress post ID. * @param string $message Error message. * @param int $code Error code. - * - * @return void */ - public static function saveErrorMessage($postId, $message = '', $code = 500) + public static function saveErrorMessage(int|false $postId, string $message = '', int|string $code = 500): void { if (! $postId) { return; diff --git a/src/Core/Core.php b/src/Core/Core.php index 2eeddffb..2094bb40 100644 --- a/src/Core/Core.php +++ b/src/Core/Core.php @@ -20,23 +20,23 @@ class Core * @since 4.0.0 * @since 6.0.0 Make static and stop loading plugin text domain on init. */ - public static function init() + public static function init(): void { // Actions - add_action('enqueue_block_editor_assets', array(__CLASS__, 'enqueueBlockEditorAssets'), 1, 0); - add_action('init', array(__CLASS__, 'registerMeta'), 99, 3); + add_action('enqueue_block_editor_assets', [self::class, 'enqueueBlockEditorAssets'], 1, 0); + add_action('init', [self::class, 'registerMeta'], 99, 3); // Actions for adding/updating posts - add_action('wp_after_insert_post', array(__CLASS__, 'onAddOrUpdatePost'), 99); + add_action('wp_after_insert_post', [self::class, 'onAddOrUpdatePost'], 99); // Actions for trashing/deleting posts - add_action('wp_trash_post', array(__CLASS__, 'onTrashPost')); - add_action('before_delete_post', array(__CLASS__, 'onDeletePost')); + add_action('wp_trash_post', [self::class, 'onTrashPost']); + add_action('before_delete_post', [self::class, 'onDeletePost']); - add_filter('is_protected_meta', array(__CLASS__, 'isProtectedMeta'), 10, 2); + add_filter('is_protected_meta', [self::class, 'isProtectedMeta'], 10, 2); // Older posts may be missing beyondwords_language_code, so we'll try to set it. - add_filter('get_post_metadata', array(__CLASS__, 'getLangCodeFromJsonIfEmpty'), 10, 3); + add_filter('get_post_metadata', [self::class, 'getLangCodeFromJsonIfEmpty'], 10, 3); } /** @@ -48,10 +48,8 @@ public static function init() * @since 6.0.0 Make static. * * @param string $status WordPress post status (e.g. 'pending', 'publish', 'private', 'future', etc). - * - * @return boolean */ - public static function shouldProcessPostStatus($status) + public static function shouldProcessPostStatus(string $status): bool { $statuses = ['pending', 'publish', 'private', 'future']; @@ -89,10 +87,8 @@ public static function shouldProcessPostStatus($status) * checks, and add support Magic Embed support. * * @param int $postId WordPress Post ID. - * - * @return boolean */ - public static function shouldGenerateAudioForPost($postId) + public static function shouldGenerateAudioForPost(int $postId): bool { // Ignore autosaves and revisions if (wp_is_post_autosave($postId) || wp_is_post_revision($postId)) { @@ -125,9 +121,9 @@ public static function shouldGenerateAudioForPost($postId) * * @param int $postId WordPress Post ID. * - * @return array|false Response from API, or false if audio was not generated. + * @return array|false|null Response from API, or false if audio was not generated. */ - public static function generateAudioForPost($postId) + public static function generateAudioForPost(int $postId): array|false|null { // Perform checks to see if this post should be processed if (! self::shouldGenerateAudioForPost($postId)) { @@ -182,9 +178,9 @@ public static function generateAudioForPost($postId) * * @param int $postId WordPress Post ID. * - * @return array|false Response from API, or false if audio was not generated. + * @return array|false|null Response from API, or false if audio was not generated. */ - public static function deleteAudioForPost($postId) + public static function deleteAudioForPost(int $postId): array|false|null { return ApiClient::deleteAudio($postId); } @@ -199,7 +195,7 @@ public static function deleteAudioForPost($postId) * * @return array|false Response from API, or false if audio was not generated. */ - public static function batchDeleteAudioForPosts($postIds) + public static function batchDeleteAudioForPosts(array $postIds): array|false|null { return ApiClient::batchDeleteAudio($postIds); } @@ -214,7 +210,7 @@ public static function batchDeleteAudioForPosts($postIds) * @since 5.0.0 Stop saving `beyondwords_podcast_id`. * @since 6.0.0 Make static. */ - public static function processResponse($response, $projectId, $postId) + public static function processResponse(mixed $response, int|string|false $projectId, int $postId): mixed { if (! is_array($response)) { return $response; @@ -255,7 +251,7 @@ public static function processResponse($response, $projectId, $postId) * @since 4.5.1 Disable plugin features if we don't have valid API settings. * @since 6.0.0 Make static. */ - public static function enqueueBlockEditorAssets() + public static function enqueueBlockEditorAssets(): void { if (! SettingsUtils::hasValidApiConnection()) { return; @@ -288,10 +284,8 @@ public static function enqueueBlockEditorAssets() * @since 2.5.0 * @since 3.9.0 Don't register speechkit_status - downgrades to plugin v2.x are no longer expected. * @since 6.0.0 Make static. - * - * @return void **/ - public static function registerMeta() + public static function registerMeta(): void { $postTypes = SettingsUtils::getCompatiblePostTypes(); @@ -299,7 +293,7 @@ public static function registerMeta() $keys = CoreUtils::getPostMetaKeys('all'); foreach ($postTypes as $postType) { - $options = array( + $options = [ 'show_in_rest' => true, 'single' => true, 'type' => 'string', @@ -307,10 +301,8 @@ public static function registerMeta() 'object_subtype' => $postType, 'prepare_callback' => 'sanitize_text_field', 'sanitize_callback' => 'sanitize_text_field', - 'auth_callback' => function () { - return current_user_can('edit_posts'); - }, - ); + 'auth_callback' => fn(): bool => current_user_can('edit_posts'), + ]; foreach ($keys as $key) { register_meta('post', $key, $options); @@ -328,7 +320,7 @@ public static function registerMeta() * @since 4.0.0 * @since 6.0.0 Make static. */ - public static function isProtectedMeta($protected, $metaKey) + public static function isProtectedMeta(bool $protected, string $metaKey): bool { $keysToProtect = CoreUtils::getPostMetaKeys('all'); @@ -351,10 +343,8 @@ public static function isProtectedMeta($protected, $metaKey) * @since 6.0.0 Make static. * * @param int $postId Post ID. - * - * @return bool **/ - public static function onTrashPost($postId) + public static function onTrashPost(int $postId): void { ApiClient::deleteAudio($postId); PostMetaUtils::removeAllBeyondwordsMetadata($postId); @@ -370,10 +360,8 @@ public static function onTrashPost($postId) * @since 6.0.0 Make static. * * @param int $postId Post ID. - * - * @return bool **/ - public static function onDeletePost($postId) + public static function onDeletePost(int $postId): void { ApiClient::deleteAudio($postId); } @@ -394,8 +382,6 @@ public static function onDeletePost($postId) * @since 6.0.0 Make static and refactor for Magic Embed updates. * * @param int $postId Post ID. - * - * @return bool **/ public static function onAddOrUpdatePost(int $postId): bool { @@ -423,10 +409,8 @@ public static function onAddOrUpdatePost(int $postId): bool * @param int $object_id The ID of the object metadata is for. * @param string $meta_key The key of the metadata. * @param bool $single Whether to return a single value. - * - * @return mixed */ - public static function getLangCodeFromJsonIfEmpty($value, $object_id, $meta_key) + public static function getLangCodeFromJsonIfEmpty(mixed $value, int $object_id, string $meta_key): mixed { if ('beyondwords_language_code' === $meta_key && empty($value)) { $languageId = get_post_meta($object_id, 'beyondwords_language_id', true); diff --git a/src/Core/CoreUtils.php b/src/Core/CoreUtils.php index f178b4b3..eb8ced80 100755 --- a/src/Core/CoreUtils.php +++ b/src/Core/CoreUtils.php @@ -22,7 +22,7 @@ class CoreUtils * @since 3.0.0 * @since 3.5.0 Moved from Core\Utils to Core\CoreUtils */ - public static function isGutenbergPage() + public static function isGutenbergPage(): bool { if (function_exists('is_gutenberg_page') && is_gutenberg_page()) { // The Gutenberg plugin is on. @@ -54,7 +54,7 @@ public static function isGutenbergPage() * @since 4.0.0 * @since 4.0.5 Ensure is_admin() and $screen */ - public static function isEditScreen() + public static function isEditScreen(): bool { if (! is_admin()) { return false; @@ -102,7 +102,7 @@ public static function isAmp(): bool * * @return string[] Post meta keys. **/ - public static function getPostMetaKeys($type = 'current') + public static function getPostMetaKeys(string $type = 'current'): array { $current = [ 'beyondwords_generate_audio', @@ -143,24 +143,12 @@ public static function getPostMetaKeys($type = 'current') '_speechkit_text', ]; - $keys = []; - - switch ($type) { - case 'current': - $keys = $current; - break; - case 'deprecated': - $keys = $deprecated; - break; - case 'all': - $keys = array_merge($current, $deprecated); - break; - default: - throw new \Exception('Unexpected $type param for CoreUtils::getPostMetaKeys()'); - break; - } - - return $keys; + return match ($type) { + 'current' => $current, + 'deprecated' => $deprecated, + 'all' => array_merge($current, $deprecated), + default => throw new \Exception('Unexpected $type param for CoreUtils::getPostMetaKeys()'), + }; } /** @@ -174,7 +162,7 @@ public static function getPostMetaKeys($type = 'current') * * @return string[] Post meta keys. **/ - public static function getOptions($type = 'current') + public static function getOptions(string $type = 'current'): array { $current = [ // v6.x @@ -238,23 +226,11 @@ public static function getOptions($type = 'current') 'speechkit_wordpress_cron', ]; - $keys = []; - - switch ($type) { - case 'current': - $keys = $current; - break; - case 'deprecated': - $keys = $deprecated; - break; - case 'all': - $keys = array_merge($current, $deprecated); - break; - default: - throw new \Exception('Unexpected $type param for CoreUtils::getOptions()'); - break; - } - - return $keys; + return match ($type) { + 'current' => $current, + 'deprecated' => $deprecated, + 'all' => array_merge($current, $deprecated), + default => throw new \Exception('Unexpected $type param for CoreUtils::getOptions()'), + }; } } diff --git a/src/Core/Environment.php b/src/Core/Environment.php index 02550b6e..0b7c92c6 100644 --- a/src/Core/Environment.php +++ b/src/Core/Environment.php @@ -88,10 +88,7 @@ class Environment */ public const BEYONDWORDS_AUTO_SYNC_SETTINGS = true; - /** - * @return string - */ - public static function getApiUrl() + public static function getApiUrl(): string { if (defined('BEYONDWORDS_API_URL') && strlen(BEYONDWORDS_API_URL)) { return BEYONDWORDS_API_URL; @@ -100,10 +97,7 @@ public static function getApiUrl() return static::BEYONDWORDS_API_URL; } - /** - * @return string - */ - public static function getBackendUrl() + public static function getBackendUrl(): string { if (defined('BEYONDWORDS_BACKEND_URL') && strlen(BEYONDWORDS_BACKEND_URL)) { return BEYONDWORDS_BACKEND_URL; @@ -112,10 +106,7 @@ public static function getBackendUrl() return static::BEYONDWORDS_BACKEND_URL; } - /** - * @return string - */ - public static function getJsSdkUrl() + public static function getJsSdkUrl(): string { if (defined('BEYONDWORDS_JS_SDK_URL') && strlen(BEYONDWORDS_JS_SDK_URL)) { return BEYONDWORDS_JS_SDK_URL; @@ -124,10 +115,7 @@ public static function getJsSdkUrl() return static::BEYONDWORDS_JS_SDK_URL; } - /** - * @return string - */ - public static function getAmpPlayerUrl() + public static function getAmpPlayerUrl(): string { if (defined('BEYONDWORDS_AMP_PLAYER_URL') && strlen(BEYONDWORDS_AMP_PLAYER_URL)) { return BEYONDWORDS_AMP_PLAYER_URL; @@ -136,10 +124,7 @@ public static function getAmpPlayerUrl() return static::BEYONDWORDS_AMP_PLAYER_URL; } - /** - * @return string - */ - public static function getAmpImgUrl() + public static function getAmpImgUrl(): string { if (defined('BEYONDWORDS_AMP_IMG_URL') && strlen(BEYONDWORDS_AMP_IMG_URL)) { return BEYONDWORDS_AMP_IMG_URL; @@ -148,10 +133,7 @@ public static function getAmpImgUrl() return static::BEYONDWORDS_AMP_IMG_URL; } - /** - * @return string - */ - public static function getDashboardUrl() + public static function getDashboardUrl(): string { if (defined('BEYONDWORDS_DASHBOARD_URL') && strlen(BEYONDWORDS_DASHBOARD_URL)) { return BEYONDWORDS_DASHBOARD_URL; @@ -160,10 +142,7 @@ public static function getDashboardUrl() return static::BEYONDWORDS_DASHBOARD_URL; } - /** - * @return bool - */ - public static function hasAutoSyncSettings() + public static function hasAutoSyncSettings(): bool { $value = static::BEYONDWORDS_AUTO_SYNC_SETTINGS; diff --git a/src/Core/Player/ConfigBuilder.php b/src/Core/Player/ConfigBuilder.php index 9b8bb061..caef6611 100644 --- a/src/Core/Player/ConfigBuilder.php +++ b/src/Core/Player/ConfigBuilder.php @@ -1,5 +1,7 @@ setHeaders(array_merge( - (array) $this->getHeaders(), + $this->getHeaders(), $headers )); } diff --git a/src/Core/Response.php b/src/Core/Response.php index 928b0d85..8d6cc9c2 100644 --- a/src/Core/Response.php +++ b/src/Core/Response.php @@ -12,10 +12,7 @@ class Response private $cookies; private $filename; - /** - * @param array $response - */ - public function __construct($response = array()) + public function __construct(array $response = []) { if (array_key_exists('headers', $response)) { $this->headers = $response['headers']; @@ -38,82 +35,52 @@ public function __construct($response = array()) } } - /** - * @return mixed - */ - public function getHeaders() + public function getHeaders(): mixed { return $this->headers; } - /** - * @param mixed $headers - */ - public function setHeaders($headers) + public function setHeaders(mixed $headers): void { $this->headers = $headers; } - /** - * @return mixed - */ - public function getBody() + public function getBody(): mixed { return $this->body; } - /** - * @param mixed $body - */ - public function setBody($body) + public function setBody(mixed $body): void { $this->body = $body; } - /** - * @return mixed - */ - public function getResponse() + public function getResponse(): mixed { return $this->response; } - /** - * @param mixed $response - */ - public function setResponse($response) + public function setResponse(mixed $response): void { $this->response = $response; } - /** - * @return mixed - */ - public function getCookies() + public function getCookies(): mixed { return $this->cookies; } - /** - * @param mixed $cookies - */ - public function setCookies($cookies) + public function setCookies(mixed $cookies): void { $this->cookies = $cookies; } - /** - * @return mixed - */ - public function getFilename() + public function getFilename(): mixed { return $this->filename; } - /** - * @param mixed $filename - */ - public function setFilename($filename) + public function setFilename(mixed $filename): void { $this->filename = $filename; } diff --git a/tests/phpunit/Component/Posts/BulkEdit/BulkEditTest.php b/tests/phpunit/Component/Posts/BulkEdit/BulkEditTest.php index b28e2538..ab0d311e 100644 --- a/tests/phpunit/Component/Posts/BulkEdit/BulkEditTest.php +++ b/tests/phpunit/Component/Posts/BulkEdit/BulkEditTest.php @@ -233,7 +233,7 @@ public function generateAudioForPosts() { $updatedPostIds = BulkEdit::generateAudioForPosts(null); - $this->assertFalse($updatedPostIds); + $this->assertSame([], $updatedPostIds); $postIds = [ self::factory()->post->create([ diff --git a/uninstall.php b/uninstall.php index b3dc54c1..b83a8a06 100644 --- a/uninstall.php +++ b/uninstall.php @@ -1,5 +1,7 @@