| 1 |
<?php |
| 2 |
|
| 3 |
namespace Elementor\Modules\ElementorCounter; |
| 4 |
|
| 5 |
use Elementor\Core\Isolation\Elementor_Counter_Adapter_Interface; |
| 6 |
use Elementor\Core\Isolation\Wordpress_Adapter; |
| 7 |
use Elementor\Core\Isolation\Wordpress_Adapter_Interface; |
| 8 |
use Elementor\Core\Base\Module as BaseModule; |
| 9 |
|
| 10 |
if ( ! defined( 'ABSPATH' ) ) { |
| 11 |
exit; |
| 12 |
} |
| 13 |
|
| 14 |
class Module extends BaseModule implements Elementor_Counter_Adapter_Interface { |
| 15 |
const EDITOR_COUNTER_KEY = 'e_editor_counter'; |
| 16 |
|
| 17 |
private ?Wordpress_Adapter_Interface $wordpress_adapter = null; |
| 18 |
private static $should_count_editor = true; |
| 19 |
|
| 20 |
public function get_name() { |
| 21 |
return 'elementor-counter'; |
| 22 |
} |
| 23 |
|
| 24 |
public function __construct( ?Wordpress_Adapter_Interface $wordpress_adapter = null ) { |
| 25 |
parent::__construct(); |
| 26 |
$this->wordpress_adapter = $wordpress_adapter ?? new Wordpress_Adapter(); |
| 27 |
|
| 28 |
if ( self::$should_count_editor ) { |
| 29 |
add_action( 'elementor/editor/init', function () { |
| 30 |
$this->increment( self::EDITOR_COUNTER_KEY ); |
| 31 |
}, 10 ); |
| 32 |
|
| 33 |
self::$should_count_editor = false; |
| 34 |
} |
| 35 |
} |
| 36 |
|
| 37 |
/** |
| 38 |
* @param self::EDITOR_COUNTER_KEY $key |
| 39 |
* |
| 40 |
* @return int | null |
| 41 |
*/ |
| 42 |
public function get_count( $key ): ?int { |
| 43 |
return $this->is_key_allowed( $key ) |
| 44 |
? (int) $this->wordpress_adapter->get_option( $key, 0 ) |
| 45 |
: null; |
| 46 |
} |
| 47 |
|
| 48 |
/** |
| 49 |
* @param self::EDITOR_COUNTER_KEY $key |
| 50 |
* @param int $count |
| 51 |
*/ |
| 52 |
public function set_count( $key, $count = 0 ): void { |
| 53 |
if ( ! $this->is_key_allowed( $key ) || ! is_int( $count ) ) { |
| 54 |
return; |
| 55 |
} |
| 56 |
|
| 57 |
$this->wordpress_adapter->update_option( $key, $count ); |
| 58 |
} |
| 59 |
|
| 60 |
/** |
| 61 |
* @param self::EDITOR_COUNTER_KEY $key |
| 62 |
*/ |
| 63 |
public function increment( $key ): void { |
| 64 |
if ( ! $this->is_key_allowed( $key ) ) { |
| 65 |
return; |
| 66 |
} |
| 67 |
|
| 68 |
$count = $this->get_count( $key ); |
| 69 |
|
| 70 |
$this->set_count( $key, $count + 1 ); |
| 71 |
} |
| 72 |
|
| 73 |
public function is_key_allowed( $key ): bool { |
| 74 |
return in_array( $key, [ self::EDITOR_COUNTER_KEY ] ); |
| 75 |
} |
| 76 |
} |
| 77 |
|