Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
0.00% covered (danger)
0.00%
0 / 9
0.00% covered (danger)
0.00%
0 / 4
CRAP
0.00% covered (danger)
0.00%
0 / 1
OptionListener
0.00% covered (danger)
0.00%
0 / 9
0.00% covered (danger)
0.00%
0 / 4
30
0.00% covered (danger)
0.00%
0 / 1
 __construct
0.00% covered (danger)
0.00%
0 / 5
0.00% covered (danger)
0.00%
0 / 1
2
 onAdd
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 onUpdate
0.00% covered (danger)
0.00%
0 / 2
0.00% covered (danger)
0.00%
0 / 1
6
 onDelete
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
1<?php
2
3namespace NewfoldLabs\WP\Module\Performance;
4
5/**
6 * Class to monitor changes to an option.
7 */
8class OptionListener {
9
10    /**
11     * Callback function to be called on change.
12     *
13     * @var callable
14     */
15    protected $callable;
16
17    /**
18     * Name of the option to monitor.
19     *
20     * @var string
21     */
22    protected $option;
23
24    /**
25     * Constructor
26     *
27     * @param string   $option_name The name of the option to monitor.
28     * @param callable $callback    The callback function to be called on change.
29     */
30    public function __construct( string $option_name, callable $callback ) {
31
32        $this->callable = $callback;
33        $this->option   = $option_name;
34
35        add_action( "add_option_{$option_name}", array( $this, 'onAdd' ), 10, 2 );
36        add_action( "update_option_{$option_name}", array( $this, 'onUpdate' ), 10, 2 );
37        add_action( "delete_option_{$option_name}", array( $this, 'onDelete' ) );
38    }
39
40    /**
41     * Call function when a new option value is added.
42     *
43     * @param string $option The option name.
44     * @param mixed  $value  The option value.
45     */
46    public function onAdd( $option, $value ) {
47        call_user_func( $this->callable, $value, $option );
48    }
49
50    /**
51     * Call function when an option value is updated.
52     *
53     * @param mixed $old_value The old option value.
54     * @param mixed $new_value The new option value.
55     */
56    public function onUpdate( $old_value, $new_value ) {
57        if ( $old_value !== $new_value ) {
58            call_user_func( $this->callable, $new_value, $this->option );
59        }
60    }
61
62    /**
63     * Call function when an option is deleted.
64     */
65    public function onDelete() {
66        call_user_func( $this->callable, null, $this->option );
67    }
68}