| 1 |
<?php |
| 2 |
/** |
| 3 |
* Registry of follow-up adapters. |
| 4 |
* |
| 5 |
* @package Forge12\DoubleOptIn\FollowUp |
| 6 |
* @since 5.6.0 |
| 7 |
*/ |
| 8 |
|
| 9 |
declare( strict_types=1 ); |
| 10 |
|
| 11 |
namespace Forge12\DoubleOptIn\FollowUp; |
| 12 |
|
| 13 |
use forge12\contactform7\CF7DoubleOptIn\OptIn; |
| 14 |
|
| 15 |
if ( ! defined( 'ABSPATH' ) ) { |
| 16 |
exit; |
| 17 |
} |
| 18 |
|
| 19 |
/** |
| 20 |
* Maps an integration identifier to its adapter. |
| 21 |
* |
| 22 |
* Core and the form addons register directly (container lookup in |
| 23 |
* `boot()`). Third parties can use the `f12_doi_register_follow_up_adapters` |
| 24 |
* action, which fires once, lazily, on first lookup. |
| 25 |
*/ |
| 26 |
final class FollowUpAdapterRegistry { |
| 27 |
|
| 28 |
/** @var array<string, FollowUpAdapterInterface> */ |
| 29 |
private $adapters = array(); |
| 30 |
|
| 31 |
/** @var bool */ |
| 32 |
private $hookFired = false; |
| 33 |
|
| 34 |
public function register( FollowUpAdapterInterface $adapter ): void { |
| 35 |
$this->adapters[ $adapter->getIntegration() ] = $adapter; |
| 36 |
} |
| 37 |
|
| 38 |
public function get( string $integration ): ?FollowUpAdapterInterface { |
| 39 |
$this->fireHookOnce(); |
| 40 |
return $this->adapters[ $integration ] ?? null; |
| 41 |
} |
| 42 |
|
| 43 |
/** |
| 44 |
* Find the adapter responsible for an opt-in. |
| 45 |
* |
| 46 |
* `OptIn::isType()` is a lookup per call (post type / post meta), so |
| 47 |
* each registered integration is asked at most once. |
| 48 |
*/ |
| 49 |
public function forOptIn( OptIn $optIn ): ?FollowUpAdapterInterface { |
| 50 |
$this->fireHookOnce(); |
| 51 |
foreach ( $this->adapters as $integration => $adapter ) { |
| 52 |
if ( $optIn->isType( $integration ) ) { |
| 53 |
return $adapter; |
| 54 |
} |
| 55 |
} |
| 56 |
return null; |
| 57 |
} |
| 58 |
|
| 59 |
/** |
| 60 |
* @return string[] |
| 61 |
*/ |
| 62 |
public function integrations(): array { |
| 63 |
$this->fireHookOnce(); |
| 64 |
return array_keys( $this->adapters ); |
| 65 |
} |
| 66 |
|
| 67 |
private function fireHookOnce(): void { |
| 68 |
if ( $this->hookFired ) { |
| 69 |
return; |
| 70 |
} |
| 71 |
$this->hookFired = true; |
| 72 |
|
| 73 |
if ( function_exists( 'do_action' ) ) { |
| 74 |
/** |
| 75 |
* Register additional follow-up adapters. |
| 76 |
* |
| 77 |
* @param FollowUpAdapterRegistry $registry |
| 78 |
* |
| 79 |
* @since 5.6.0 |
| 80 |
*/ |
| 81 |
do_action( 'f12_doi_register_follow_up_adapters', $this ); |
| 82 |
} |
| 83 |
} |
| 84 |
} |
| 85 |
|