|
| 1 | +<?php |
| 2 | +/** |
| 3 | + * GitHub Plugin Updater |
| 4 | + * |
| 5 | + * Minimal wrapper around yahnis-elsts/plugin-update-checker for GitHub-hosted |
| 6 | + * WordPress plugins. Defers the actual update-checker setup to the `init` action |
| 7 | + * so it works regardless of when the calling plugin loads the file. |
| 8 | + * |
| 9 | + * @package Soderlind\WordPress |
| 10 | + * @version 1.0.0 |
| 11 | + * @author Per Soderlind |
| 12 | + * @license GPL-2.0-or-later |
| 13 | + * @link https://github.com/soderlind/wordpress-plugin-github-updater |
| 14 | + */ |
| 15 | + |
| 16 | +namespace Soderlind\WordPress; |
| 17 | + |
| 18 | +use YahnisElsts\PluginUpdateChecker\v5\PucFactory; |
| 19 | + |
| 20 | +// Prevent direct access. |
| 21 | +defined( 'ABSPATH' ) || exit; |
| 22 | + |
| 23 | +/** |
| 24 | + * Sets up automatic plugin updates from a GitHub repository. |
| 25 | + */ |
| 26 | +final class GitHubUpdater { |
| 27 | + |
| 28 | + /** |
| 29 | + * Initialize the GitHub update checker. |
| 30 | + * |
| 31 | + * @param string $github_url Full GitHub repository URL (e.g. 'https://github.com/owner/repo'). |
| 32 | + * @param string $plugin_file Absolute path to the main plugin file (__FILE__). |
| 33 | + * @param string $plugin_slug Plugin slug used by WordPress (e.g. 'my-plugin'). |
| 34 | + * @param string $name_regex Optional regex to filter release assets (e.g. '/my-plugin\.zip/'). |
| 35 | + * @param string $branch Branch to track (default 'main'). |
| 36 | + */ |
| 37 | + public static function init( |
| 38 | + string $github_url, |
| 39 | + string $plugin_file, |
| 40 | + string $plugin_slug, |
| 41 | + string $name_regex = '', |
| 42 | + string $branch = 'main', |
| 43 | + ): void { |
| 44 | + add_action( 'init', static function () use ( $github_url, $plugin_file, $plugin_slug, $name_regex, $branch ): void { |
| 45 | + try { |
| 46 | + $checker = PucFactory::buildUpdateChecker( $github_url, $plugin_file, $plugin_slug ); |
| 47 | + $checker->setBranch( $branch ); |
| 48 | + |
| 49 | + if ( '' !== $name_regex ) { |
| 50 | + $checker->getVcsApi()->enableReleaseAssets( $name_regex ); |
| 51 | + } |
| 52 | + } catch ( \Exception $e ) { |
| 53 | + if ( defined( 'WP_DEBUG' ) && WP_DEBUG ) { |
| 54 | + // phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_error_log |
| 55 | + error_log( 'GitHubUpdater (' . $plugin_slug . '): ' . $e->getMessage() ); |
| 56 | + } |
| 57 | + } |
| 58 | + } ); |
| 59 | + } |
| 60 | +} |
0 commit comments