| @@ -1,0 +1,55 @@ | ||
| 1 | +<?php | |
| 2 | + | |
| 3 | +declare(strict_types=1); | |
| 4 | + | |
| 5 | +namespace Metricool\Controllers; | |
| 6 | + | |
| 7 | +if (!defined('ABSPATH')) { | |
| 8 | + exit; | |
| 9 | +} | |
| 10 | + | |
| 11 | +use Metricool\Interfaces\ControllerInterface; | |
| 12 | +use Metricool\Services\CapabilityService; | |
| 13 | + | |
| 14 | +class CapabilityController implements ControllerInterface | |
| 15 | +{ | |
| 16 | + private CapabilityService $service; | |
| 17 | + | |
| 18 | + public function __construct(CapabilityService $service) | |
| 19 | + { | |
| 20 | + $this->service = $service; | |
| 21 | + } | |
| 22 | + | |
| 23 | + public function register(): void | |
| 24 | + { | |
| 25 | + add_action('metricool_activation', [$this, 'handlePluginActivation']); | |
| 26 | + add_action('metricool_plugin_version_upgrade', [$this, 'handlePluginUpgrade'], 10, 2); | |
| 27 | + add_action('wp_initialize_site', [$this, 'addCapabilityToNewSubsite'], 10, 2); | |
| 28 | + } | |
| 29 | + | |
| 30 | + public function handlePluginActivation(): void | |
| 31 | + { | |
| 32 | + $this->service->addSiteCapability('metricool_manage'); | |
| 33 | + } | |
| 34 | + | |
| 35 | + /** | |
| 36 | + * Handle plugin upgrades | |
| 37 | + */ | |
| 38 | + public function handlePluginUpgrade(string $previousVersion, string $newVersion): void | |
| 39 | + { | |
| 40 | + // If someone upgrades from legacy version we need to add the capability | |
| 41 | + if ($previousVersion && version_compare($previousVersion, '2.0', '<')) { | |
| 42 | + $this->service->addSiteCapability('metricool_manage'); | |
| 43 | + } | |
| 44 | + } | |
| 45 | + | |
| 46 | + /** | |
| 47 | + * When a new site is added, add our custom capability | |
| 48 | + */ | |
| 49 | + public function addCapabilityToNewSubsite(\WP_Site $newSite, array $args): void | |
| 50 | + { | |
| 51 | + switch_to_blog((int) $newSite->blog_id); | |
| 52 | + $this->service->addSiteCapability('metricool_manage', false); | |
| 53 | + restore_current_blog(); | |
| 54 | + } | |
| 55 | +} | |