Completed
Branch master (87d3f3)
by
unknown
03:30
created
core/domain/entities/routing/handlers/admin/EspressoEventEditor.php 1 patch
Indentation   +114 added lines, -114 removed lines patch added patch discarded remove patch
@@ -17,125 +17,125 @@
 block discarded – undo
17 17
  */
18 18
 class EspressoEventEditor extends EspressoEventsAdmin
19 19
 {
20
-    /**
21
-     * returns true if the current request matches this route
22
-     *
23
-     * @return bool
24
-     * @since   $VID:$
25
-     */
26
-    public function matchesCurrentRequest(): bool
27
-    {
28
-        return parent::matchesCurrentRequest()
29
-               && $this->admin_config->useAdvancedEditor()
30
-               && (
31
-                   $this->request->getRequestParam('action') === 'create_new'
32
-                || $this->request->getRequestParam('action') === 'edit'
33
-               );
34
-    }
20
+	/**
21
+	 * returns true if the current request matches this route
22
+	 *
23
+	 * @return bool
24
+	 * @since   $VID:$
25
+	 */
26
+	public function matchesCurrentRequest(): bool
27
+	{
28
+		return parent::matchesCurrentRequest()
29
+			   && $this->admin_config->useAdvancedEditor()
30
+			   && (
31
+				   $this->request->getRequestParam('action') === 'create_new'
32
+				|| $this->request->getRequestParam('action') === 'edit'
33
+			   );
34
+	}
35 35
 
36 36
 
37
-    /**
38
-     * @since $VID:$
39
-     */
40
-    protected function registerDependencies()
41
-    {
42
-        $editor_dependencies = [
43
-            'EventEspresso\core\domain\services\admin\events\editor\EventEditorGraphQLData' => [
44
-                'EventEspresso\core\domain\entities\admin\GraphQLData\Datetimes'                 => EE_Dependency_Map::load_from_cache,
45
-                'EventEspresso\core\domain\entities\admin\GraphQLData\Event'                     => EE_Dependency_Map::load_from_cache,
46
-                'EventEspresso\core\domain\entities\admin\GraphQLData\Prices'                    => EE_Dependency_Map::load_from_cache,
47
-                'EventEspresso\core\domain\entities\admin\GraphQLData\PriceTypes'                => EE_Dependency_Map::load_from_cache,
48
-                'EventEspresso\core\domain\entities\admin\GraphQLData\Tickets'                   => EE_Dependency_Map::load_from_cache,
49
-                'EventEspresso\core\domain\services\admin\events\editor\NewEventDefaultEntities' => EE_Dependency_Map::load_from_cache,
50
-                '\EventEspresso\core\domain\services\admin\events\editor\EventManagerData'       => EE_Dependency_Map::load_from_cache,
51
-                'EventEspresso\core\domain\services\admin\events\editor\EventEntityRelations'    => EE_Dependency_Map::load_from_cache,
52
-                'EventEspresso\core\domain\services\admin\events\editor\TicketMeta'              => EE_Dependency_Map::load_from_cache,
53
-                'EventEspresso\core\domain\services\admin\events\editor\FormBuilder'             => EE_Dependency_Map::load_from_cache,
54
-                'EventEspresso\core\domain\entities\admin\GraphQLData\Venues'                   => EE_Dependency_Map::load_from_cache,
55
-            ],
56
-            'EventEspresso\core\domain\services\admin\events\editor\EventEntityRelations' => [
57
-                'EEM_Datetime'                                         => EE_Dependency_Map::load_from_cache,
58
-                'EEM_Event'                                            => EE_Dependency_Map::load_from_cache,
59
-                'EEM_Price'                                            => EE_Dependency_Map::load_from_cache,
60
-                'EEM_Price_Type'                                       => EE_Dependency_Map::load_from_cache,
61
-                'EEM_Ticket'                                           => EE_Dependency_Map::load_from_cache,
62
-                'EventEspresso\core\domain\services\graphql\Utilities' => EE_Dependency_Map::load_from_cache,
63
-            ],
64
-            'EventEspresso\core\domain\services\admin\events\editor\NewEventDefaultEntities' => [
65
-                'EventEspresso\core\domain\services\admin\entities\DefaultDatetimes'    => EE_Dependency_Map::load_from_cache,
66
-                'EventEspresso\core\domain\services\admin\entities\DefaultFormSections' => EE_Dependency_Map::load_from_cache,
67
-                'EEM_Datetime'                                                          => EE_Dependency_Map::load_from_cache,
68
-                'EEM_Event'                                                             => EE_Dependency_Map::load_from_cache,
69
-                'EEM_Price'                                                             => EE_Dependency_Map::load_from_cache,
70
-                'EEM_Price_Type'                                                        => EE_Dependency_Map::load_from_cache,
71
-                'EEM_Ticket'                                                            => EE_Dependency_Map::load_from_cache,
72
-                'EventEspresso\core\domain\services\graphql\Utilities'                  => EE_Dependency_Map::load_from_cache,
73
-            ],
74
-            'EventEspresso\core\domain\services\admin\events\editor\TicketMeta' => [
75
-                'EEM_Ticket' => EE_Dependency_Map::load_from_cache,
76
-            ],
77
-            'EventEspresso\core\domain\services\admin\entities\DefaultDatetimes' => [
78
-                'EventEspresso\core\domain\services\admin\entities\DefaultTickets' => EE_Dependency_Map::load_from_cache,
79
-                'EEM_Datetime'                                                     => EE_Dependency_Map::load_from_cache,
80
-            ],
81
-            'EventEspresso\core\domain\services\admin\entities\DefaultTickets' => [
82
-                'EventEspresso\core\domain\services\admin\entities\DefaultPrices' => EE_Dependency_Map::load_from_cache,
83
-                'EEM_Ticket'                                                      => EE_Dependency_Map::load_from_cache,
84
-            ],
85
-            'EventEspresso\core\domain\services\admin\entities\DefaultPrices' => [
86
-                'EEM_Price'      => EE_Dependency_Map::load_from_cache,
87
-                'EEM_Price_Type' => EE_Dependency_Map::load_from_cache,
88
-            ],
89
-            'EventEspresso\core\domain\services\admin\entities\DefaultFormSections' => [
90
-                'EEM_Form_Element' => EE_Dependency_Map::load_from_cache,
91
-                'EEM_Form_Section' => EE_Dependency_Map::load_from_cache,
92
-            ],
93
-            'EventEspresso\core\domain\entities\routing\data_nodes\domains\EventEditor' => [
94
-                'EventEspresso\core\domain\services\admin\events\editor\EventEditorGraphQLData' => EE_Dependency_Map::load_from_cache,
95
-                'EventEspresso\core\services\json\JsonDataNodeValidator'                        => EE_Dependency_Map::load_from_cache,
96
-            ],
97
-            'EventEspresso\core\domain\services\assets\EventEditorAssetManager' => [
98
-                'EventEspresso\core\domain\Domain'                   => EE_Dependency_Map::load_from_cache,
99
-                'EventEspresso\core\services\assets\AssetCollection' => EE_Dependency_Map::load_from_cache,
100
-                'EventEspresso\core\services\assets\Registry'        => EE_Dependency_Map::load_from_cache,
101
-            ],
102
-            'EventEspresso\core\domain\services\admin\events\editor\EventManagerData' => [
103
-                'EventEspresso\core\domain\entities\users\EventManagers' => EE_Dependency_Map::load_from_cache,
104
-                'EventEspresso\core\domain\services\graphql\Utilities'   => EE_Dependency_Map::load_from_cache,
105
-            ],
106
-        ];
107
-        foreach ($editor_dependencies as $dependency => $dependencies) {
108
-            $this->dependency_map->registerDependencies($dependency, $dependencies);
109
-        }
110
-    }
37
+	/**
38
+	 * @since $VID:$
39
+	 */
40
+	protected function registerDependencies()
41
+	{
42
+		$editor_dependencies = [
43
+			'EventEspresso\core\domain\services\admin\events\editor\EventEditorGraphQLData' => [
44
+				'EventEspresso\core\domain\entities\admin\GraphQLData\Datetimes'                 => EE_Dependency_Map::load_from_cache,
45
+				'EventEspresso\core\domain\entities\admin\GraphQLData\Event'                     => EE_Dependency_Map::load_from_cache,
46
+				'EventEspresso\core\domain\entities\admin\GraphQLData\Prices'                    => EE_Dependency_Map::load_from_cache,
47
+				'EventEspresso\core\domain\entities\admin\GraphQLData\PriceTypes'                => EE_Dependency_Map::load_from_cache,
48
+				'EventEspresso\core\domain\entities\admin\GraphQLData\Tickets'                   => EE_Dependency_Map::load_from_cache,
49
+				'EventEspresso\core\domain\services\admin\events\editor\NewEventDefaultEntities' => EE_Dependency_Map::load_from_cache,
50
+				'\EventEspresso\core\domain\services\admin\events\editor\EventManagerData'       => EE_Dependency_Map::load_from_cache,
51
+				'EventEspresso\core\domain\services\admin\events\editor\EventEntityRelations'    => EE_Dependency_Map::load_from_cache,
52
+				'EventEspresso\core\domain\services\admin\events\editor\TicketMeta'              => EE_Dependency_Map::load_from_cache,
53
+				'EventEspresso\core\domain\services\admin\events\editor\FormBuilder'             => EE_Dependency_Map::load_from_cache,
54
+				'EventEspresso\core\domain\entities\admin\GraphQLData\Venues'                   => EE_Dependency_Map::load_from_cache,
55
+			],
56
+			'EventEspresso\core\domain\services\admin\events\editor\EventEntityRelations' => [
57
+				'EEM_Datetime'                                         => EE_Dependency_Map::load_from_cache,
58
+				'EEM_Event'                                            => EE_Dependency_Map::load_from_cache,
59
+				'EEM_Price'                                            => EE_Dependency_Map::load_from_cache,
60
+				'EEM_Price_Type'                                       => EE_Dependency_Map::load_from_cache,
61
+				'EEM_Ticket'                                           => EE_Dependency_Map::load_from_cache,
62
+				'EventEspresso\core\domain\services\graphql\Utilities' => EE_Dependency_Map::load_from_cache,
63
+			],
64
+			'EventEspresso\core\domain\services\admin\events\editor\NewEventDefaultEntities' => [
65
+				'EventEspresso\core\domain\services\admin\entities\DefaultDatetimes'    => EE_Dependency_Map::load_from_cache,
66
+				'EventEspresso\core\domain\services\admin\entities\DefaultFormSections' => EE_Dependency_Map::load_from_cache,
67
+				'EEM_Datetime'                                                          => EE_Dependency_Map::load_from_cache,
68
+				'EEM_Event'                                                             => EE_Dependency_Map::load_from_cache,
69
+				'EEM_Price'                                                             => EE_Dependency_Map::load_from_cache,
70
+				'EEM_Price_Type'                                                        => EE_Dependency_Map::load_from_cache,
71
+				'EEM_Ticket'                                                            => EE_Dependency_Map::load_from_cache,
72
+				'EventEspresso\core\domain\services\graphql\Utilities'                  => EE_Dependency_Map::load_from_cache,
73
+			],
74
+			'EventEspresso\core\domain\services\admin\events\editor\TicketMeta' => [
75
+				'EEM_Ticket' => EE_Dependency_Map::load_from_cache,
76
+			],
77
+			'EventEspresso\core\domain\services\admin\entities\DefaultDatetimes' => [
78
+				'EventEspresso\core\domain\services\admin\entities\DefaultTickets' => EE_Dependency_Map::load_from_cache,
79
+				'EEM_Datetime'                                                     => EE_Dependency_Map::load_from_cache,
80
+			],
81
+			'EventEspresso\core\domain\services\admin\entities\DefaultTickets' => [
82
+				'EventEspresso\core\domain\services\admin\entities\DefaultPrices' => EE_Dependency_Map::load_from_cache,
83
+				'EEM_Ticket'                                                      => EE_Dependency_Map::load_from_cache,
84
+			],
85
+			'EventEspresso\core\domain\services\admin\entities\DefaultPrices' => [
86
+				'EEM_Price'      => EE_Dependency_Map::load_from_cache,
87
+				'EEM_Price_Type' => EE_Dependency_Map::load_from_cache,
88
+			],
89
+			'EventEspresso\core\domain\services\admin\entities\DefaultFormSections' => [
90
+				'EEM_Form_Element' => EE_Dependency_Map::load_from_cache,
91
+				'EEM_Form_Section' => EE_Dependency_Map::load_from_cache,
92
+			],
93
+			'EventEspresso\core\domain\entities\routing\data_nodes\domains\EventEditor' => [
94
+				'EventEspresso\core\domain\services\admin\events\editor\EventEditorGraphQLData' => EE_Dependency_Map::load_from_cache,
95
+				'EventEspresso\core\services\json\JsonDataNodeValidator'                        => EE_Dependency_Map::load_from_cache,
96
+			],
97
+			'EventEspresso\core\domain\services\assets\EventEditorAssetManager' => [
98
+				'EventEspresso\core\domain\Domain'                   => EE_Dependency_Map::load_from_cache,
99
+				'EventEspresso\core\services\assets\AssetCollection' => EE_Dependency_Map::load_from_cache,
100
+				'EventEspresso\core\services\assets\Registry'        => EE_Dependency_Map::load_from_cache,
101
+			],
102
+			'EventEspresso\core\domain\services\admin\events\editor\EventManagerData' => [
103
+				'EventEspresso\core\domain\entities\users\EventManagers' => EE_Dependency_Map::load_from_cache,
104
+				'EventEspresso\core\domain\services\graphql\Utilities'   => EE_Dependency_Map::load_from_cache,
105
+			],
106
+		];
107
+		foreach ($editor_dependencies as $dependency => $dependencies) {
108
+			$this->dependency_map->registerDependencies($dependency, $dependencies);
109
+		}
110
+	}
111 111
 
112 112
 
113
-    /**
114
-     * @return string
115
-     */
116
-    protected function dataNodeClass(): string
117
-    {
118
-        return EventEditor::class;
119
-    }
113
+	/**
114
+	 * @return string
115
+	 */
116
+	protected function dataNodeClass(): string
117
+	{
118
+		return EventEditor::class;
119
+	}
120 120
 
121 121
 
122
-    /**
123
-     * implements logic required to run during request
124
-     *
125
-     * @return bool
126
-     * @since   $VID:$
127
-     */
128
-    protected function requestHandler(): bool
129
-    {
130
-        /** @var GraphQLManager $graphQL_manager */
131
-        $graphQL_manager = $this->loader->getShared('EventEspresso\core\services\graphql\GraphQLManager');
132
-        $graphQL_manager->init();
122
+	/**
123
+	 * implements logic required to run during request
124
+	 *
125
+	 * @return bool
126
+	 * @since   $VID:$
127
+	 */
128
+	protected function requestHandler(): bool
129
+	{
130
+		/** @var GraphQLManager $graphQL_manager */
131
+		$graphQL_manager = $this->loader->getShared('EventEspresso\core\services\graphql\GraphQLManager');
132
+		$graphQL_manager->init();
133 133
 
134
-        /** @var EventEditorAssetManager $asset_manager */
135
-        $asset_manager = $this->loader->getShared(
136
-            'EventEspresso\core\domain\services\assets\EventEditorAssetManager'
137
-        );
138
-        add_action('admin_enqueue_scripts', [$asset_manager, 'enqueueEventEditor']);
139
-        return true;
140
-    }
134
+		/** @var EventEditorAssetManager $asset_manager */
135
+		$asset_manager = $this->loader->getShared(
136
+			'EventEspresso\core\domain\services\assets\EventEditorAssetManager'
137
+		);
138
+		add_action('admin_enqueue_scripts', [$asset_manager, 'enqueueEventEditor']);
139
+		return true;
140
+	}
141 141
 }
Please login to merge, or discard this patch.
core/domain/entities/shortcodes/EspressoTicketSelector.php 1 patch
Indentation   +92 added lines, -92 removed lines patch added patch discarded remove patch
@@ -22,104 +22,104 @@
 block discarded – undo
22 22
  */
23 23
 class EspressoTicketSelector extends EspressoShortcode
24 24
 {
25
-    /**
26
-     * the actual shortcode tag that gets registered with WordPress
27
-     *
28
-     * @return string
29
-     */
30
-    public function getTag()
31
-    {
32
-        return 'ESPRESSO_TICKET_SELECTOR';
33
-    }
25
+	/**
26
+	 * the actual shortcode tag that gets registered with WordPress
27
+	 *
28
+	 * @return string
29
+	 */
30
+	public function getTag()
31
+	{
32
+		return 'ESPRESSO_TICKET_SELECTOR';
33
+	}
34 34
 
35 35
 
36
-    /**
37
-     * the time in seconds to cache the results of the processShortcode() method
38
-     * 0 means the processShortcode() results will NOT be cached at all
39
-     *
40
-     * @return int
41
-     */
42
-    public function cacheExpiration()
43
-    {
44
-        return 0;
45
-    }
36
+	/**
37
+	 * the time in seconds to cache the results of the processShortcode() method
38
+	 * 0 means the processShortcode() results will NOT be cached at all
39
+	 *
40
+	 * @return int
41
+	 */
42
+	public function cacheExpiration()
43
+	{
44
+		return 0;
45
+	}
46 46
 
47 47
 
48
-    /**
49
-     * a place for adding any initialization code that needs to run prior to wp_header().
50
-     * this may be required for shortcodes that utilize a corresponding module,
51
-     * and need to enqueue assets for that module
52
-     *
53
-     * @return void
54
-     */
55
-    public function initializeShortcode()
56
-    {
57
-        add_filter('FHEE__EED_Ticket_Selector__load_tckt_slctr_assets', '__return_true');
58
-        $this->shortcodeHasBeenInitialized();
59
-    }
48
+	/**
49
+	 * a place for adding any initialization code that needs to run prior to wp_header().
50
+	 * this may be required for shortcodes that utilize a corresponding module,
51
+	 * and need to enqueue assets for that module
52
+	 *
53
+	 * @return void
54
+	 */
55
+	public function initializeShortcode()
56
+	{
57
+		add_filter('FHEE__EED_Ticket_Selector__load_tckt_slctr_assets', '__return_true');
58
+		$this->shortcodeHasBeenInitialized();
59
+	}
60 60
 
61 61
 
62
-    /**
63
-     * callback that runs when the shortcode is encountered in post content.
64
-     * IMPORTANT !!!
65
-     * remember that shortcode content should be RETURNED and NOT echoed out
66
-     *
67
-     * @param array|string $attributes
68
-     * @return string
69
-     * @throws InvalidArgumentException
70
-     * @throws EE_Error
71
-     * @throws InvalidDataTypeException
72
-     * @throws InvalidInterfaceException
73
-     * @throws ReflectionException
74
-     * @throws Exception
75
-     */
76
-    public function processShortcode($attributes = array())
77
-    {
78
-        extract((array) $attributes);
79
-        $event_id = $event_id ?? 0;
80
-        $event = EEM_Event::instance()->get_one_by_ID($event_id);
81
-        if (! $event instanceof EE_Event) {
82
-            return $this->processInvalidEvent($event_id);
83
-        }
84
-        ob_start();
85
-        do_action('AHEE_event_details_before_post', $event_id);
86
-        espresso_ticket_selector($event);
87
-        do_action('AHEE_event_details_after_post');
88
-        return ob_get_clean();
89
-    }
62
+	/**
63
+	 * callback that runs when the shortcode is encountered in post content.
64
+	 * IMPORTANT !!!
65
+	 * remember that shortcode content should be RETURNED and NOT echoed out
66
+	 *
67
+	 * @param array|string $attributes
68
+	 * @return string
69
+	 * @throws InvalidArgumentException
70
+	 * @throws EE_Error
71
+	 * @throws InvalidDataTypeException
72
+	 * @throws InvalidInterfaceException
73
+	 * @throws ReflectionException
74
+	 * @throws Exception
75
+	 */
76
+	public function processShortcode($attributes = array())
77
+	{
78
+		extract((array) $attributes);
79
+		$event_id = $event_id ?? 0;
80
+		$event = EEM_Event::instance()->get_one_by_ID($event_id);
81
+		if (! $event instanceof EE_Event) {
82
+			return $this->processInvalidEvent($event_id);
83
+		}
84
+		ob_start();
85
+		do_action('AHEE_event_details_before_post', $event_id);
86
+		espresso_ticket_selector($event);
87
+		do_action('AHEE_event_details_after_post');
88
+		return ob_get_clean();
89
+	}
90 90
 
91 91
 
92
-    /**
93
-     * @param string $event_id
94
-     * @return string
95
-     * @throws Exception
96
-     * @since $VID:$
97
-     */
98
-    private function processInvalidEvent(string $event_id): string
99
-    {
100
-        if (WP_DEBUG === true && current_user_can('edit_pages')) {
101
-            new ExceptionStackTraceDisplay(
102
-                new InvalidArgumentException(
103
-                    sprintf(
104
-                        esc_html__(
105
-                            'A valid Event ID is required to use the "%1$s" shortcode.%4$sAn Event with an ID of "%2$s" could not be found.%4$sPlease verify that the shortcode added to this post\'s content includes an "%3$s" argument and that its value corresponds to a valid Event ID.',
106
-                            'event_espresso'
107
-                        ),
108
-                        $this->getTag(),
109
-                        $event_id,
110
-                        'event_id',
111
-                        '<br />'
112
-                    )
113
-                )
114
-            );
115
-            return '';
116
-        }
117
-        return sprintf(
118
-            esc_html__(
119
-                'An Event with an ID of "%s" could not be found. Please contact the event administrator for assistance.',
120
-                'event_espresso'
121
-            ),
122
-            $event_id
123
-        );
124
-    }
92
+	/**
93
+	 * @param string $event_id
94
+	 * @return string
95
+	 * @throws Exception
96
+	 * @since $VID:$
97
+	 */
98
+	private function processInvalidEvent(string $event_id): string
99
+	{
100
+		if (WP_DEBUG === true && current_user_can('edit_pages')) {
101
+			new ExceptionStackTraceDisplay(
102
+				new InvalidArgumentException(
103
+					sprintf(
104
+						esc_html__(
105
+							'A valid Event ID is required to use the "%1$s" shortcode.%4$sAn Event with an ID of "%2$s" could not be found.%4$sPlease verify that the shortcode added to this post\'s content includes an "%3$s" argument and that its value corresponds to a valid Event ID.',
106
+							'event_espresso'
107
+						),
108
+						$this->getTag(),
109
+						$event_id,
110
+						'event_id',
111
+						'<br />'
112
+					)
113
+				)
114
+			);
115
+			return '';
116
+		}
117
+		return sprintf(
118
+			esc_html__(
119
+				'An Event with an ID of "%s" could not be found. Please contact the event administrator for assistance.',
120
+				'event_espresso'
121
+			),
122
+			$event_id
123
+		);
124
+	}
125 125
 }
Please login to merge, or discard this patch.
core/domain/services/admin/events/editor/NewEventDefaultEntities.php 1 patch
Indentation   +117 added lines, -117 removed lines patch added patch discarded remove patch
@@ -29,130 +29,130 @@
 block discarded – undo
29 29
  */
30 30
 class NewEventDefaultEntities extends EventEditorData
31 31
 {
32
-    /**
33
-     * @var DefaultDatetimes
34
-     */
35
-    protected $default_datetimes;
32
+	/**
33
+	 * @var DefaultDatetimes
34
+	 */
35
+	protected $default_datetimes;
36 36
 
37
-    /**
38
-     * @var   DefaultFormSections
39
-     */
40
-    protected $default_form_sections;
37
+	/**
38
+	 * @var   DefaultFormSections
39
+	 */
40
+	protected $default_form_sections;
41 41
 
42 42
 
43
-    /**
44
-     * NewEventDefaultEntities constructor.
45
-     *
46
-     * @param DefaultDatetimes    $default_datetimes
47
-     * @param DefaultFormSections $default_form_sections
48
-     * @param EEM_Datetime        $datetime_model
49
-     * @param EEM_Event           $event_model
50
-     * @param EEM_Price           $price_model
51
-     * @param EEM_Price_Type      $price_type_model
52
-     * @param EEM_Ticket          $ticket_model
53
-     * @param Utilities           $utilities
54
-     */
55
-    public function __construct(
56
-        DefaultDatetimes $default_datetimes,
57
-        DefaultFormSections $default_form_sections,
58
-        EEM_Datetime $datetime_model,
59
-        EEM_Event $event_model,
60
-        EEM_Price $price_model,
61
-        EEM_Price_Type $price_type_model,
62
-        EEM_Ticket $ticket_model,
63
-        Utilities $utilities
64
-    ) {
65
-        $this->default_datetimes     = $default_datetimes;
66
-        $this->default_form_sections = $default_form_sections;
67
-        parent::__construct(
68
-            $datetime_model,
69
-            $event_model,
70
-            $price_model,
71
-            $price_type_model,
72
-            $ticket_model,
73
-            $utilities
74
-        );
75
-    }
43
+	/**
44
+	 * NewEventDefaultEntities constructor.
45
+	 *
46
+	 * @param DefaultDatetimes    $default_datetimes
47
+	 * @param DefaultFormSections $default_form_sections
48
+	 * @param EEM_Datetime        $datetime_model
49
+	 * @param EEM_Event           $event_model
50
+	 * @param EEM_Price           $price_model
51
+	 * @param EEM_Price_Type      $price_type_model
52
+	 * @param EEM_Ticket          $ticket_model
53
+	 * @param Utilities           $utilities
54
+	 */
55
+	public function __construct(
56
+		DefaultDatetimes $default_datetimes,
57
+		DefaultFormSections $default_form_sections,
58
+		EEM_Datetime $datetime_model,
59
+		EEM_Event $event_model,
60
+		EEM_Price $price_model,
61
+		EEM_Price_Type $price_type_model,
62
+		EEM_Ticket $ticket_model,
63
+		Utilities $utilities
64
+	) {
65
+		$this->default_datetimes     = $default_datetimes;
66
+		$this->default_form_sections = $default_form_sections;
67
+		parent::__construct(
68
+			$datetime_model,
69
+			$event_model,
70
+			$price_model,
71
+			$price_type_model,
72
+			$ticket_model,
73
+			$utilities
74
+		);
75
+	}
76 76
 
77 77
 
78
-    /**
79
-     * @param int $eventId
80
-     * @return EE_Datetime[]
81
-     * @throws EE_Error
82
-     * @throws InvalidArgumentException
83
-     * @throws InvalidEntityException
84
-     * @throws ReflectionException
85
-     * @since $VID:$
86
-     */
87
-    public function getData(int $eventId): array
88
-    {
89
-        $EVT_ID = absint($eventId);
90
-        if ($EVT_ID < 1) {
91
-            throw new InvalidArgumentException(
92
-                esc_html__(
93
-                    'A missing or invalid event ID was received.',
94
-                    'event_espresso'
95
-                )
96
-            );
97
-        }
98
-        $event = $this->event_model->get_one_by_ID($EVT_ID);
99
-        if (! $event instanceof EE_Event) {
100
-            throw new InvalidEntityException($event, 'EE_Event');
101
-        }
102
-        $new_event = isset($_REQUEST['action']) && $_REQUEST['action'] === 'create_new';
103
-        return [
104
-            'datetimes'     => $this->createDefaultDatetimes($event, $new_event),
105
-            'form_sections' => $this->createDefaultFormSections($event, $new_event),
106
-        ];
107
-    }
78
+	/**
79
+	 * @param int $eventId
80
+	 * @return EE_Datetime[]
81
+	 * @throws EE_Error
82
+	 * @throws InvalidArgumentException
83
+	 * @throws InvalidEntityException
84
+	 * @throws ReflectionException
85
+	 * @since $VID:$
86
+	 */
87
+	public function getData(int $eventId): array
88
+	{
89
+		$EVT_ID = absint($eventId);
90
+		if ($EVT_ID < 1) {
91
+			throw new InvalidArgumentException(
92
+				esc_html__(
93
+					'A missing or invalid event ID was received.',
94
+					'event_espresso'
95
+				)
96
+			);
97
+		}
98
+		$event = $this->event_model->get_one_by_ID($EVT_ID);
99
+		if (! $event instanceof EE_Event) {
100
+			throw new InvalidEntityException($event, 'EE_Event');
101
+		}
102
+		$new_event = isset($_REQUEST['action']) && $_REQUEST['action'] === 'create_new';
103
+		return [
104
+			'datetimes'     => $this->createDefaultDatetimes($event, $new_event),
105
+			'form_sections' => $this->createDefaultFormSections($event, $new_event),
106
+		];
107
+	}
108 108
 
109 109
 
110
-    /**
111
-     * @param EE_Event $event
112
-     * @param bool     $new_event
113
-     * @return EE_Datetime[]
114
-     * @throws EE_Error
115
-     * @throws ReflectionException
116
-     */
117
-    private function createDefaultDatetimes(EE_Event $event, bool $new_event): array
118
-    {
119
-        if ($new_event) {
120
-            return $this->default_datetimes->create($event);
121
-        }
122
-        $datetime_count = $this->datetime_model->count(
123
-            [
124
-                [
125
-                    'EVT_ID'      => $event->ID(),
126
-                    'DTT_deleted' => ['IN', [true, false]],
127
-                ],
128
-                'default_where_conditions' => EEM_Base::default_where_conditions_none,
129
-            ],
130
-            'EVT_ID'
131
-        );
132
-        return $datetime_count === 0
133
-            ? $this->default_datetimes->create($event)
134
-            : [];
135
-    }
110
+	/**
111
+	 * @param EE_Event $event
112
+	 * @param bool     $new_event
113
+	 * @return EE_Datetime[]
114
+	 * @throws EE_Error
115
+	 * @throws ReflectionException
116
+	 */
117
+	private function createDefaultDatetimes(EE_Event $event, bool $new_event): array
118
+	{
119
+		if ($new_event) {
120
+			return $this->default_datetimes->create($event);
121
+		}
122
+		$datetime_count = $this->datetime_model->count(
123
+			[
124
+				[
125
+					'EVT_ID'      => $event->ID(),
126
+					'DTT_deleted' => ['IN', [true, false]],
127
+				],
128
+				'default_where_conditions' => EEM_Base::default_where_conditions_none,
129
+			],
130
+			'EVT_ID'
131
+		);
132
+		return $datetime_count === 0
133
+			? $this->default_datetimes->create($event)
134
+			: [];
135
+	}
136 136
 
137 137
 
138
-    /**
139
-     * if it's a new event and defaults have not been created yet, OR if there is no reg form at all...
140
-     *
141
-     * @param EE_Event $event
142
-     * @param bool     $new_event
143
-     * @return EE_Form_Section[]
144
-     * @throws EE_Error
145
-     * @throws ReflectionException
146
-     */
147
-    private function createDefaultFormSections(EE_Event $event, bool $new_event): array
148
-    {
149
-        if ($new_event) {
150
-            return $this->default_form_sections->create($event);
151
-        }
152
-        $reg_form_UUID = $event->registrationFormUuid();
153
-        // if it's a new event and defaults have not been created yet, OR if there is no reg form at all...
154
-        return ! $reg_form_UUID
155
-            ? $this->default_form_sections->create($event)
156
-            : [];
157
-    }
138
+	/**
139
+	 * if it's a new event and defaults have not been created yet, OR if there is no reg form at all...
140
+	 *
141
+	 * @param EE_Event $event
142
+	 * @param bool     $new_event
143
+	 * @return EE_Form_Section[]
144
+	 * @throws EE_Error
145
+	 * @throws ReflectionException
146
+	 */
147
+	private function createDefaultFormSections(EE_Event $event, bool $new_event): array
148
+	{
149
+		if ($new_event) {
150
+			return $this->default_form_sections->create($event);
151
+		}
152
+		$reg_form_UUID = $event->registrationFormUuid();
153
+		// if it's a new event and defaults have not been created yet, OR if there is no reg form at all...
154
+		return ! $reg_form_UUID
155
+			? $this->default_form_sections->create($event)
156
+			: [];
157
+	}
158 158
 }
Please login to merge, or discard this patch.
core/domain/services/admin/events/editor/EventEntityRelations.php 1 patch
Indentation   +136 added lines, -136 removed lines patch added patch discarded remove patch
@@ -14,151 +14,151 @@
 block discarded – undo
14 14
  */
15 15
 class EventEntityRelations extends EventEditorData
16 16
 {
17
-    /**
18
-     * @param array $data
19
-     */
20
-    private $data;
17
+	/**
18
+	 * @param array $data
19
+	 */
20
+	private $data;
21 21
 
22
-    /**
23
-     * @param int $eventId
24
-     * @return array
25
-     * @throws EE_Error
26
-     * @since $VID:$
27
-     */
28
-    public function getData(int $eventId): array
29
-    {
30
-        $this->data = [
31
-            'datetimes' => [],
32
-            'tickets'   => [],
33
-            'prices'    => [],
34
-        ];
22
+	/**
23
+	 * @param int $eventId
24
+	 * @return array
25
+	 * @throws EE_Error
26
+	 * @since $VID:$
27
+	 */
28
+	public function getData(int $eventId): array
29
+	{
30
+		$this->data = [
31
+			'datetimes' => [],
32
+			'tickets'   => [],
33
+			'prices'    => [],
34
+		];
35 35
 
36
-        $datetimeIds = $this->processDatetimes($eventId);
37
-        $ticketIds = $this->processTickets($datetimeIds);
38
-        $this->processPrices($ticketIds);
36
+		$datetimeIds = $this->processDatetimes($eventId);
37
+		$ticketIds = $this->processTickets($datetimeIds);
38
+		$this->processPrices($ticketIds);
39 39
 
40
-        return $this->data;
41
-    }
40
+		return $this->data;
41
+	}
42 42
 
43 43
 
44
-    /**
45
-     * @param int $eventId
46
-     * @return array
47
-     * @throws EE_Error
48
-     * @since $VID:$
49
-     */
50
-    private function processDatetimes(int $eventId): array
51
-    {
52
-        $related_models = [
53
-            'tickets' => $this->ticket_model,
54
-        ];
55
-        // Get the IDs of event datetimes.
56
-        // SELECT Datetime.DTT_ID FROM wp_esp_datetime AS Datetime WHERE Datetime.EVT_ID = ##
57
-        $datetimeIds = $this->datetime_model->get_col([
58
-            [ 'EVT_ID' => $eventId ],
59
-            'default_where_conditions' => 'minimum',
60
-        ]);
61
-        foreach ($datetimeIds as $datetimeId) {
62
-            $GID = $this->utilities->convertToGlobalId($this->datetime_model->item_name(), $datetimeId);
63
-            foreach ($related_models as $key => $model) {
64
-                // Get the IDs of related entities for the datetime ID.
65
-                // SELECT Ticket.TKT_ID FROM wp_esp_ticket AS Ticket
66
-                // LEFT JOIN wp_esp_datetime_ticket AS Datetime_Ticket ON Datetime_Ticket.TKT_ID=Ticket.TKT_ID
67
-                // LEFT JOIN wp_esp_datetime AS Datetime ON Datetime.DTT_ID=Datetime_Ticket.DTT_ID
68
-                // WHERE Datetime.DTT_ID = ##
69
-                $Ids = $model->get_col([
70
-                    [ 'Datetime.DTT_ID' => $datetimeId ],
71
-                    'default_where_conditions' => 'minimum',
72
-                ]);
73
-                $this->data['datetimes'][ $GID ][ $key ] = ! empty($Ids)
74
-                    ? $this->utilities->convertToGlobalId($model->item_name(), $Ids)
75
-                    : [];
76
-            }
77
-        }
78
-        return is_array($datetimeIds) ? $datetimeIds : [];
79
-    }
44
+	/**
45
+	 * @param int $eventId
46
+	 * @return array
47
+	 * @throws EE_Error
48
+	 * @since $VID:$
49
+	 */
50
+	private function processDatetimes(int $eventId): array
51
+	{
52
+		$related_models = [
53
+			'tickets' => $this->ticket_model,
54
+		];
55
+		// Get the IDs of event datetimes.
56
+		// SELECT Datetime.DTT_ID FROM wp_esp_datetime AS Datetime WHERE Datetime.EVT_ID = ##
57
+		$datetimeIds = $this->datetime_model->get_col([
58
+			[ 'EVT_ID' => $eventId ],
59
+			'default_where_conditions' => 'minimum',
60
+		]);
61
+		foreach ($datetimeIds as $datetimeId) {
62
+			$GID = $this->utilities->convertToGlobalId($this->datetime_model->item_name(), $datetimeId);
63
+			foreach ($related_models as $key => $model) {
64
+				// Get the IDs of related entities for the datetime ID.
65
+				// SELECT Ticket.TKT_ID FROM wp_esp_ticket AS Ticket
66
+				// LEFT JOIN wp_esp_datetime_ticket AS Datetime_Ticket ON Datetime_Ticket.TKT_ID=Ticket.TKT_ID
67
+				// LEFT JOIN wp_esp_datetime AS Datetime ON Datetime.DTT_ID=Datetime_Ticket.DTT_ID
68
+				// WHERE Datetime.DTT_ID = ##
69
+				$Ids = $model->get_col([
70
+					[ 'Datetime.DTT_ID' => $datetimeId ],
71
+					'default_where_conditions' => 'minimum',
72
+				]);
73
+				$this->data['datetimes'][ $GID ][ $key ] = ! empty($Ids)
74
+					? $this->utilities->convertToGlobalId($model->item_name(), $Ids)
75
+					: [];
76
+			}
77
+		}
78
+		return is_array($datetimeIds) ? $datetimeIds : [];
79
+	}
80 80
 
81 81
 
82
-    /**
83
-     * @param array $datetimeIds
84
-     * @return array
85
-     * @throws EE_Error
86
-     * @since $VID:$
87
-     */
88
-    private function processTickets(array $datetimeIds): array
89
-    {
90
-        $related_models = [
91
-            'datetimes' => $this->datetime_model,
92
-            'prices'    => $this->price_model,
93
-        ];
94
-        // Get the IDs of all datetime tickets.
95
-        $ticketIds = $this->ticket_model->get_col([
96
-            [
97
-                'OR' => [
98
-                    'Datetime.DTT_ID' => ['IN', $datetimeIds],
99
-                    'TKT_is_default' => 1,
100
-                ]
101
-            ],
102
-            'default_where_conditions' => 'minimum',
103
-        ]);
104
-        foreach ($ticketIds as $ticketId) {
105
-            $GID = $this->utilities->convertToGlobalId($this->ticket_model->item_name(), $ticketId);
82
+	/**
83
+	 * @param array $datetimeIds
84
+	 * @return array
85
+	 * @throws EE_Error
86
+	 * @since $VID:$
87
+	 */
88
+	private function processTickets(array $datetimeIds): array
89
+	{
90
+		$related_models = [
91
+			'datetimes' => $this->datetime_model,
92
+			'prices'    => $this->price_model,
93
+		];
94
+		// Get the IDs of all datetime tickets.
95
+		$ticketIds = $this->ticket_model->get_col([
96
+			[
97
+				'OR' => [
98
+					'Datetime.DTT_ID' => ['IN', $datetimeIds],
99
+					'TKT_is_default' => 1,
100
+				]
101
+			],
102
+			'default_where_conditions' => 'minimum',
103
+		]);
104
+		foreach ($ticketIds as $ticketId) {
105
+			$GID = $this->utilities->convertToGlobalId($this->ticket_model->item_name(), $ticketId);
106 106
 
107
-            foreach ($related_models as $key => $model) {
108
-                // Get the IDs of related entities for the ticket ID.
109
-                $Ids = $model->get_col([
110
-                    [ 'Ticket.TKT_ID' => $ticketId ],
111
-                    'default_where_conditions' => 'minimum',
112
-                ]);
113
-                $this->data['tickets'][ $GID ][ $key ] = ! empty($Ids)
114
-                    ? $this->utilities->convertToGlobalId($model->item_name(), $Ids)
115
-                    : [];
116
-            }
117
-        }
118
-        return is_array($ticketIds) ? $ticketIds : [];
119
-    }
107
+			foreach ($related_models as $key => $model) {
108
+				// Get the IDs of related entities for the ticket ID.
109
+				$Ids = $model->get_col([
110
+					[ 'Ticket.TKT_ID' => $ticketId ],
111
+					'default_where_conditions' => 'minimum',
112
+				]);
113
+				$this->data['tickets'][ $GID ][ $key ] = ! empty($Ids)
114
+					? $this->utilities->convertToGlobalId($model->item_name(), $Ids)
115
+					: [];
116
+			}
117
+		}
118
+		return is_array($ticketIds) ? $ticketIds : [];
119
+	}
120 120
 
121 121
 
122
-    /**
123
-     * @param array $ticketIds
124
-     * @throws EE_Error
125
-     * @since $VID:$
126
-     */
127
-    private function processPrices(array $ticketIds)
128
-    {
129
-        $related_models = [
130
-            'tickets'    => $this->ticket_model,
131
-            'priceTypes' => $this->price_type_model,
132
-        ];
133
-        // Get the IDs of all ticket prices and default prices
134
-        $priceIds = $this->price_model->get_col([
135
-            [
136
-                'OR' => [
137
-                    // either the price is related to any of these tickets
138
-                    'Ticket.TKT_ID' => ['IN', $ticketIds],
139
-                    // or it's a default price and not trashed
140
-                    'AND' => [
141
-                        'PRC_deleted'    => 0,
142
-                        'PRC_is_default' => 1,
143
-                    ],
144
-                ],
145
-            ],
146
-            'group_by'                 => 'PRC_ID',
147
-            'default_where_conditions' => 'minimum',
148
-        ]);
149
-        foreach ($priceIds as $priceId) {
150
-            $GID = $this->utilities->convertToGlobalId($this->price_model->item_name(), $priceId);
122
+	/**
123
+	 * @param array $ticketIds
124
+	 * @throws EE_Error
125
+	 * @since $VID:$
126
+	 */
127
+	private function processPrices(array $ticketIds)
128
+	{
129
+		$related_models = [
130
+			'tickets'    => $this->ticket_model,
131
+			'priceTypes' => $this->price_type_model,
132
+		];
133
+		// Get the IDs of all ticket prices and default prices
134
+		$priceIds = $this->price_model->get_col([
135
+			[
136
+				'OR' => [
137
+					// either the price is related to any of these tickets
138
+					'Ticket.TKT_ID' => ['IN', $ticketIds],
139
+					// or it's a default price and not trashed
140
+					'AND' => [
141
+						'PRC_deleted'    => 0,
142
+						'PRC_is_default' => 1,
143
+					],
144
+				],
145
+			],
146
+			'group_by'                 => 'PRC_ID',
147
+			'default_where_conditions' => 'minimum',
148
+		]);
149
+		foreach ($priceIds as $priceId) {
150
+			$GID = $this->utilities->convertToGlobalId($this->price_model->item_name(), $priceId);
151 151
 
152
-            foreach ($related_models as $key => $model) {
153
-                // Get the IDs of related entities for the price ID.
154
-                $Ids = $model->get_col([
155
-                    [ 'Price.PRC_ID' => $priceId ],
156
-                    'default_where_conditions' => 'minimum',
157
-                ]);
158
-                $this->data['prices'][ $GID ][ $key ] = ! empty($Ids)
159
-                    ? $this->utilities->convertToGlobalId($model->item_name(), $Ids)
160
-                    : [];
161
-            }
162
-        }
163
-    }
152
+			foreach ($related_models as $key => $model) {
153
+				// Get the IDs of related entities for the price ID.
154
+				$Ids = $model->get_col([
155
+					[ 'Price.PRC_ID' => $priceId ],
156
+					'default_where_conditions' => 'minimum',
157
+				]);
158
+				$this->data['prices'][ $GID ][ $key ] = ! empty($Ids)
159
+					? $this->utilities->convertToGlobalId($model->item_name(), $Ids)
160
+					: [];
161
+			}
162
+		}
163
+	}
164 164
 }
Please login to merge, or discard this patch.
core/domain/services/admin/entities/DefaultTickets.php 1 patch
Indentation   +55 added lines, -55 removed lines patch added patch discarded remove patch
@@ -21,64 +21,64 @@
 block discarded – undo
21 21
  */
22 22
 class DefaultTickets implements DefaultEntityGeneratorInterface
23 23
 {
24
-    /**
25
-     * @var DefaultPrices $default_prices
26
-     */
27
-    protected $default_prices;
24
+	/**
25
+	 * @var DefaultPrices $default_prices
26
+	 */
27
+	protected $default_prices;
28 28
 
29
-    /**
30
-     * @var EEM_Ticket $ticket_model
31
-     */
32
-    protected $ticket_model;
29
+	/**
30
+	 * @var EEM_Ticket $ticket_model
31
+	 */
32
+	protected $ticket_model;
33 33
 
34 34
 
35
-    /**
36
-     * @param DefaultPrices $default_prices
37
-     * @param EEM_Ticket    $ticket_model
38
-     */
39
-    public function __construct(DefaultPrices $default_prices, EEM_Ticket $ticket_model)
40
-    {
41
-        $this->default_prices = $default_prices;
42
-        $this->ticket_model   = $ticket_model;
43
-    }
35
+	/**
36
+	 * @param DefaultPrices $default_prices
37
+	 * @param EEM_Ticket    $ticket_model
38
+	 */
39
+	public function __construct(DefaultPrices $default_prices, EEM_Ticket $ticket_model)
40
+	{
41
+		$this->default_prices = $default_prices;
42
+		$this->ticket_model   = $ticket_model;
43
+	}
44 44
 
45 45
 
46
-    /**
47
-     * @param EE_Datetime|EE_Base_Class $entity
48
-     * @return EE_Ticket[]
49
-     * @throws EE_Error
50
-     * @throws InvalidEntityException
51
-     * @throws ReflectionException
52
-     * @since $VID:$
53
-     */
54
-    public function create(EE_Base_Class $entity): array
55
-    {
56
-        if (! $entity instanceof EE_Datetime) {
57
-            throw new InvalidEntityException($entity, 'EE_Datetime');
58
-        }
59
-        $new_tickets     = [];
60
-        $default_tickets = $this->ticket_model->get_all_default_tickets();
61
-        foreach ($default_tickets as $default_ticket) {
62
-            if (! $default_ticket instanceof EE_Ticket) {
63
-                throw new InvalidEntityException($default_ticket, 'EE_Ticket');
64
-            }
65
-            $existing_default_prices = $default_ticket->prices();
66
-            // clone ticket, strip out ID, then save to get a new ID
67
-            $default_ticket_clone = clone $default_ticket;
68
-            $default_ticket_clone->set('TKT_ID', null);
69
-            $default_ticket_clone->set('TKT_is_default', false);
70
-            $default_ticket_clone->save();
71
-            $default_ticket_clone->_add_relation_to($entity, 'Datetime');
72
-            // temporarily adding relations to existing prices, but these will be cloned and removed
73
-            // when passed to DefaultPrices::create() below so that they the clones can be freely mutated
74
-            foreach ($existing_default_prices as $existing_default_price) {
75
-                if ($existing_default_price instanceof EE_Price) {
76
-                    $existing_default_price->_add_relation_to($default_ticket_clone, 'Ticket');
77
-                }
78
-            }
79
-            $this->default_prices->create($default_ticket_clone);
80
-            $new_tickets[ $default_ticket_clone->ID() ] = $default_ticket_clone;
81
-        }
82
-        return $new_tickets;
83
-    }
46
+	/**
47
+	 * @param EE_Datetime|EE_Base_Class $entity
48
+	 * @return EE_Ticket[]
49
+	 * @throws EE_Error
50
+	 * @throws InvalidEntityException
51
+	 * @throws ReflectionException
52
+	 * @since $VID:$
53
+	 */
54
+	public function create(EE_Base_Class $entity): array
55
+	{
56
+		if (! $entity instanceof EE_Datetime) {
57
+			throw new InvalidEntityException($entity, 'EE_Datetime');
58
+		}
59
+		$new_tickets     = [];
60
+		$default_tickets = $this->ticket_model->get_all_default_tickets();
61
+		foreach ($default_tickets as $default_ticket) {
62
+			if (! $default_ticket instanceof EE_Ticket) {
63
+				throw new InvalidEntityException($default_ticket, 'EE_Ticket');
64
+			}
65
+			$existing_default_prices = $default_ticket->prices();
66
+			// clone ticket, strip out ID, then save to get a new ID
67
+			$default_ticket_clone = clone $default_ticket;
68
+			$default_ticket_clone->set('TKT_ID', null);
69
+			$default_ticket_clone->set('TKT_is_default', false);
70
+			$default_ticket_clone->save();
71
+			$default_ticket_clone->_add_relation_to($entity, 'Datetime');
72
+			// temporarily adding relations to existing prices, but these will be cloned and removed
73
+			// when passed to DefaultPrices::create() below so that they the clones can be freely mutated
74
+			foreach ($existing_default_prices as $existing_default_price) {
75
+				if ($existing_default_price instanceof EE_Price) {
76
+					$existing_default_price->_add_relation_to($default_ticket_clone, 'Ticket');
77
+				}
78
+			}
79
+			$this->default_prices->create($default_ticket_clone);
80
+			$new_tickets[ $default_ticket_clone->ID() ] = $default_ticket_clone;
81
+		}
82
+		return $new_tickets;
83
+	}
84 84
 }
Please login to merge, or discard this patch.
core/domain/services/assets/CoreAssetManager.php 1 patch
Indentation   +160 added lines, -160 removed lines patch added patch discarded remove patch
@@ -29,164 +29,164 @@
 block discarded – undo
29 29
 class CoreAssetManager extends AssetManager
30 30
 {
31 31
 
32
-    // WordPress core / Third party JS asset handles
33
-    const JS_HANDLE_JS_CORE = 'eejs-core';
34
-
35
-    const JS_HANDLE_CORE    = 'espresso_core';
36
-
37
-    const JS_HANDLE_I18N    = 'eei18n';
38
-
39
-    const JS_HANDLE_VENDOR  = 'eventespresso-vendor';
40
-
41
-    const JS_HANDLE_RAMDA  = 'ramda';
42
-
43
-    const RAMDA_VERSION = '0.27.1';
44
-
45
-    // EE CSS assets handles
46
-    const CSS_HANDLE_DEFAULT = 'espresso_default';
47
-
48
-    const CSS_HANDLE_CUSTOM  = 'espresso_custom_css';
49
-
50
-    /**
51
-     * @var EE_Currency_Config $currency_config
52
-     */
53
-    protected $currency_config;
54
-
55
-    /**
56
-     * @var EE_Template_Config $template_config
57
-     */
58
-    protected $template_config;
59
-
60
-
61
-    /**
62
-     * CoreAssetRegister constructor.
63
-     *
64
-     * @param AssetCollection    $assets
65
-     * @param EE_Currency_Config $currency_config
66
-     * @param EE_Template_Config $template_config
67
-     * @param DomainInterface    $domain
68
-     * @param Registry           $registry
69
-     */
70
-    public function __construct(
71
-        AssetCollection $assets,
72
-        EE_Currency_Config $currency_config,
73
-        EE_Template_Config $template_config,
74
-        DomainInterface $domain,
75
-        Registry $registry
76
-    ) {
77
-        $this->currency_config = $currency_config;
78
-        $this->template_config = $template_config;
79
-        parent::__construct($domain, $assets, $registry);
80
-    }
81
-
82
-
83
-    /**
84
-     * @throws DomainException
85
-     * @throws DuplicateCollectionIdentifierException
86
-     * @throws InvalidArgumentException
87
-     * @throws InvalidDataTypeException
88
-     * @throws InvalidEntityException
89
-     * @throws InvalidInterfaceException
90
-     * @since 4.9.62.p
91
-     */
92
-    public function addAssets()
93
-    {
94
-        $this->addJavascriptFiles();
95
-        $this->addStylesheetFiles();
96
-    }
97
-
98
-
99
-    /**
100
-     * @throws DomainException
101
-     * @throws DuplicateCollectionIdentifierException
102
-     * @throws InvalidArgumentException
103
-     * @throws InvalidDataTypeException
104
-     * @throws InvalidEntityException
105
-     * @throws InvalidInterfaceException
106
-     * @since 4.9.62.p
107
-     */
108
-    public function addJavascriptFiles()
109
-    {
110
-        $this->addJs(CoreAssetManager::JS_HANDLE_VENDOR);
111
-        $this->addJs(CoreAssetManager::JS_HANDLE_JS_CORE)->setHasInlineData();
112
-        $this->addJavascript(
113
-            CoreAssetManager::JS_HANDLE_CORE,
114
-            EE_GLOBAL_ASSETS_URL . 'scripts/espresso_core.js',
115
-            [JqueryAssetManager::JS_HANDLE_JQUERY]
116
-        )->setInlineDataCallback(
117
-            function () {
118
-                wp_localize_script(
119
-                    CoreAssetManager::JS_HANDLE_CORE,
120
-                    CoreAssetManager::JS_HANDLE_I18N,
121
-                    EE_Registry::$i18n_js_strings
122
-                );
123
-            }
124
-        );
125
-        $this->loadQtipJs();
126
-        $this->addVendorJavascript(
127
-            CoreAssetManager::JS_HANDLE_RAMDA,
128
-            [],
129
-            true,
130
-            CoreAssetManager::RAMDA_VERSION
131
-        );
132
-    }
133
-
134
-
135
-    /**
136
-     * @throws DuplicateCollectionIdentifierException
137
-     * @throws InvalidDataTypeException
138
-     * @throws InvalidEntityException
139
-     * @throws DomainException
140
-     * @since 4.9.62.p
141
-     */
142
-    public function addStylesheetFiles()
143
-    {
144
-        if (! is_admin()) {
145
-            $this->addStylesheet(
146
-                CoreAssetManager::CSS_HANDLE_DEFAULT,
147
-                is_readable(EVENT_ESPRESSO_UPLOAD_DIR . 'css/espresso_default.css')
148
-                    ? EVENT_ESPRESSO_UPLOAD_URL . 'css/espresso_default.css'
149
-                    : EE_GLOBAL_ASSETS_URL . 'css/espresso_default.css',
150
-                ['dashicons']
151
-            );
152
-        }
153
-    }
154
-
155
-
156
-    /**
157
-     * Returns configuration data for the js Currency VO.
158
-     *
159
-     * @return array
160
-     * @since 4.9.71.p
161
-     */
162
-    private function getCurrencySettings()
163
-    {
164
-        return [
165
-            'code'               => $this->currency_config->code,
166
-            'singularLabel'      => $this->currency_config->name,
167
-            'pluralLabel'        => $this->currency_config->plural,
168
-            'sign'               => $this->currency_config->sign,
169
-            'signB4'             => $this->currency_config->sign_b4,
170
-            'decimalPlaces'      => $this->currency_config->dec_plc,
171
-            'decimalMark'        => $this->currency_config->dec_mrk,
172
-            'thousandsSeparator' => $this->currency_config->thsnds,
173
-        ];
174
-    }
175
-
176
-
177
-    /**
178
-     * replacement:
179
-     * EventEspresso\core\domain\services\assets\EspressoLegacyAdminAssetManager::loadQtipJs()
180
-     *
181
-     * @param JavascriptAsset $script
182
-     * @deprecated $VID:$
183
-     */
184
-    public function loadQtipJs(JavascriptAsset $script = null)
185
-    {
186
-        // qtip is turned OFF by default, but prior to the wp_enqueue_scripts hook,
187
-        // can be turned back on again via: add_filter('FHEE_load_qtip', '__return_true' );
188
-        if (apply_filters('FHEE_load_qtip', false)) {
189
-            EEH_Qtip_Loader::instance()->register_and_enqueue();
190
-        }
191
-    }
32
+	// WordPress core / Third party JS asset handles
33
+	const JS_HANDLE_JS_CORE = 'eejs-core';
34
+
35
+	const JS_HANDLE_CORE    = 'espresso_core';
36
+
37
+	const JS_HANDLE_I18N    = 'eei18n';
38
+
39
+	const JS_HANDLE_VENDOR  = 'eventespresso-vendor';
40
+
41
+	const JS_HANDLE_RAMDA  = 'ramda';
42
+
43
+	const RAMDA_VERSION = '0.27.1';
44
+
45
+	// EE CSS assets handles
46
+	const CSS_HANDLE_DEFAULT = 'espresso_default';
47
+
48
+	const CSS_HANDLE_CUSTOM  = 'espresso_custom_css';
49
+
50
+	/**
51
+	 * @var EE_Currency_Config $currency_config
52
+	 */
53
+	protected $currency_config;
54
+
55
+	/**
56
+	 * @var EE_Template_Config $template_config
57
+	 */
58
+	protected $template_config;
59
+
60
+
61
+	/**
62
+	 * CoreAssetRegister constructor.
63
+	 *
64
+	 * @param AssetCollection    $assets
65
+	 * @param EE_Currency_Config $currency_config
66
+	 * @param EE_Template_Config $template_config
67
+	 * @param DomainInterface    $domain
68
+	 * @param Registry           $registry
69
+	 */
70
+	public function __construct(
71
+		AssetCollection $assets,
72
+		EE_Currency_Config $currency_config,
73
+		EE_Template_Config $template_config,
74
+		DomainInterface $domain,
75
+		Registry $registry
76
+	) {
77
+		$this->currency_config = $currency_config;
78
+		$this->template_config = $template_config;
79
+		parent::__construct($domain, $assets, $registry);
80
+	}
81
+
82
+
83
+	/**
84
+	 * @throws DomainException
85
+	 * @throws DuplicateCollectionIdentifierException
86
+	 * @throws InvalidArgumentException
87
+	 * @throws InvalidDataTypeException
88
+	 * @throws InvalidEntityException
89
+	 * @throws InvalidInterfaceException
90
+	 * @since 4.9.62.p
91
+	 */
92
+	public function addAssets()
93
+	{
94
+		$this->addJavascriptFiles();
95
+		$this->addStylesheetFiles();
96
+	}
97
+
98
+
99
+	/**
100
+	 * @throws DomainException
101
+	 * @throws DuplicateCollectionIdentifierException
102
+	 * @throws InvalidArgumentException
103
+	 * @throws InvalidDataTypeException
104
+	 * @throws InvalidEntityException
105
+	 * @throws InvalidInterfaceException
106
+	 * @since 4.9.62.p
107
+	 */
108
+	public function addJavascriptFiles()
109
+	{
110
+		$this->addJs(CoreAssetManager::JS_HANDLE_VENDOR);
111
+		$this->addJs(CoreAssetManager::JS_HANDLE_JS_CORE)->setHasInlineData();
112
+		$this->addJavascript(
113
+			CoreAssetManager::JS_HANDLE_CORE,
114
+			EE_GLOBAL_ASSETS_URL . 'scripts/espresso_core.js',
115
+			[JqueryAssetManager::JS_HANDLE_JQUERY]
116
+		)->setInlineDataCallback(
117
+			function () {
118
+				wp_localize_script(
119
+					CoreAssetManager::JS_HANDLE_CORE,
120
+					CoreAssetManager::JS_HANDLE_I18N,
121
+					EE_Registry::$i18n_js_strings
122
+				);
123
+			}
124
+		);
125
+		$this->loadQtipJs();
126
+		$this->addVendorJavascript(
127
+			CoreAssetManager::JS_HANDLE_RAMDA,
128
+			[],
129
+			true,
130
+			CoreAssetManager::RAMDA_VERSION
131
+		);
132
+	}
133
+
134
+
135
+	/**
136
+	 * @throws DuplicateCollectionIdentifierException
137
+	 * @throws InvalidDataTypeException
138
+	 * @throws InvalidEntityException
139
+	 * @throws DomainException
140
+	 * @since 4.9.62.p
141
+	 */
142
+	public function addStylesheetFiles()
143
+	{
144
+		if (! is_admin()) {
145
+			$this->addStylesheet(
146
+				CoreAssetManager::CSS_HANDLE_DEFAULT,
147
+				is_readable(EVENT_ESPRESSO_UPLOAD_DIR . 'css/espresso_default.css')
148
+					? EVENT_ESPRESSO_UPLOAD_URL . 'css/espresso_default.css'
149
+					: EE_GLOBAL_ASSETS_URL . 'css/espresso_default.css',
150
+				['dashicons']
151
+			);
152
+		}
153
+	}
154
+
155
+
156
+	/**
157
+	 * Returns configuration data for the js Currency VO.
158
+	 *
159
+	 * @return array
160
+	 * @since 4.9.71.p
161
+	 */
162
+	private function getCurrencySettings()
163
+	{
164
+		return [
165
+			'code'               => $this->currency_config->code,
166
+			'singularLabel'      => $this->currency_config->name,
167
+			'pluralLabel'        => $this->currency_config->plural,
168
+			'sign'               => $this->currency_config->sign,
169
+			'signB4'             => $this->currency_config->sign_b4,
170
+			'decimalPlaces'      => $this->currency_config->dec_plc,
171
+			'decimalMark'        => $this->currency_config->dec_mrk,
172
+			'thousandsSeparator' => $this->currency_config->thsnds,
173
+		];
174
+	}
175
+
176
+
177
+	/**
178
+	 * replacement:
179
+	 * EventEspresso\core\domain\services\assets\EspressoLegacyAdminAssetManager::loadQtipJs()
180
+	 *
181
+	 * @param JavascriptAsset $script
182
+	 * @deprecated $VID:$
183
+	 */
184
+	public function loadQtipJs(JavascriptAsset $script = null)
185
+	{
186
+		// qtip is turned OFF by default, but prior to the wp_enqueue_scripts hook,
187
+		// can be turned back on again via: add_filter('FHEE_load_qtip', '__return_true' );
188
+		if (apply_filters('FHEE_load_qtip', false)) {
189
+			EEH_Qtip_Loader::instance()->register_and_enqueue();
190
+		}
191
+	}
192 192
 }
Please login to merge, or discard this patch.
core/libraries/plugin_api/EE_Register_Addon.lib.php 1 patch
Indentation   +1201 added lines, -1201 removed lines patch added patch discarded remove patch
@@ -24,1205 +24,1205 @@
 block discarded – undo
24 24
  */
25 25
 class EE_Register_Addon implements EEI_Plugin_API
26 26
 {
27
-    /**
28
-     * possibly truncated version of the EE core version string
29
-     *
30
-     * @var string
31
-     */
32
-    protected static $_core_version = '';
33
-
34
-    /**
35
-     * Holds values for registered addons
36
-     *
37
-     * @var array
38
-     */
39
-    protected static $_settings = [];
40
-
41
-    /**
42
-     * @var  array $_incompatible_addons keys are addon SLUGS
43
-     * (first argument passed to EE_Register_Addon::register()), keys are
44
-     * their MINIMUM VERSION (with all 5 parts. Eg 1.2.3.rc.004).
45
-     * Generally this should be used sparingly, as we don't want to muddle up
46
-     * EE core with knowledge of ALL the addons out there.
47
-     * If you want NO versions of an addon to run with a certain version of core,
48
-     * it's usually best to define the addon's "min_core_version" as part of its call
49
-     * to EE_Register_Addon::register(), rather than using this array with a super high value for its
50
-     * minimum plugin version.
51
-     * @access    protected
52
-     */
53
-    protected static $_incompatible_addons = [
54
-        'Multi_Event_Registration' => '2.0.11.rc.002',
55
-        'Promotions'               => '1.0.0.rc.084',
56
-    ];
57
-
58
-    /**
59
-     * @var LoaderInterface
60
-     */
61
-    protected static $loader;
62
-
63
-
64
-    /**
65
-     * We should always be comparing core to a version like '4.3.0.rc.000',
66
-     * not just '4.3.0'.
67
-     * So if the addon developer doesn't provide that full version string,
68
-     * fill in the blanks for them
69
-     *
70
-     * @param string $min_core_version
71
-     * @return string always like '4.3.0.rc.000'
72
-     */
73
-    protected static function _effective_version(string $min_core_version): string
74
-    {
75
-        // versions: 4 . 3 . 1 . p . 123
76
-        // offsets:    0 . 1 . 2 . 3 . 4
77
-        $version_parts = explode('.', $min_core_version);
78
-        // check they specified the micro version (after 2nd period)
79
-        if (! isset($version_parts[2])) {
80
-            $version_parts[2] = '0';
81
-        }
82
-        // if they didn't specify the 'p', or 'rc' part. Just assume the lowest possible
83
-        // soon we can assume that's 'rc', but this current version is 'alpha'
84
-        if (! isset($version_parts[3])) {
85
-            $version_parts[3] = 'dev';
86
-        }
87
-        if (! isset($version_parts[4])) {
88
-            $version_parts[4] = '000';
89
-        }
90
-        return implode('.', $version_parts);
91
-    }
92
-
93
-
94
-    /**
95
-     * Returns whether or not the min core version requirement of the addon is met
96
-     *
97
-     * @param string $min_core_version    the minimum core version required by the addon
98
-     * @param string $actual_core_version the actual core version, optional
99
-     * @return bool
100
-     */
101
-    public static function _meets_min_core_version_requirement(
102
-        string $min_core_version,
103
-        string $actual_core_version = EVENT_ESPRESSO_VERSION
104
-    ): bool {
105
-        return version_compare(
106
-            self::_effective_version($actual_core_version),
107
-            self::_effective_version($min_core_version),
108
-            '>='
109
-        );
110
-    }
111
-
112
-
113
-    /**
114
-     * Method for registering new EE_Addons.
115
-     * Should be called AFTER AHEE__EE_System__load_espresso_addons but BEFORE
116
-     * AHEE__EE_System___detect_if_activation_or_upgrade__begin in order to register all its components. However, it
117
-     * may also be called after the 'activate_plugin' action (when an addon is activated), because an activating addon
118
-     * won't be loaded by WP until after AHEE__EE_System__load_espresso_addons has fired. If its called after
119
-     * 'activate_plugin', it registers the addon still, but its components are not registered
120
-     * (they shouldn't be needed anyways, because it's just an activation request and they won't have a chance to do
121
-     * anything anyways). Instead, it just sets the newly-activated addon's activation indicator wp option and returns
122
-     * (so that we can detect that the addon has activated on the subsequent request)
123
-     *
124
-     * @param string                  $addon_name                       [Required] the EE_Addon's name.
125
-     * @param array                   $setup_args                       {
126
-     *                                                                  An array of arguments provided for registering
127
-     *                                                                  the message type.
128
-     * @type  string                  $class_name                       the addon's main file name.
129
-     *                                                                  If left blank, generated from the addon name,
130
-     *                                                                  changes something like "calendar" to
131
-     *                                                                  "EE_Calendar"
132
-     * @type string                   $min_core_version                 the minimum version of EE Core that the
133
-     *                                                                  addon will work with. eg "4.8.1.rc.084"
134
-     * @type string                   $version                          the "software" version for the addon. eg
135
-     *                                                                  "1.0.0.p" for a first stable release, or
136
-     *                                                                  "1.0.0.rc.043" for a version in progress
137
-     * @type string                   $main_file_path                   the full server path to the main file
138
-     *                                                                  loaded directly by WP
139
-     * @type DomainInterface          $domain                           child class of
140
-     *                                                                  EventEspresso\core\domain\DomainBase
141
-     * @type string                   $domain_fqcn                      Fully Qualified Class Name
142
-     *                                                                  for the addon's Domain class
143
-     *                                                                  (see EventEspresso\core\domain\Domain)
144
-     * @type string                   $admin_path                       full server path to the folder where the
145
-     *                                                                  addon\'s admin files reside
146
-     * @type string                   $admin_callback                   a method to be called when the EE Admin is
147
-     *                                                                  first invoked, can be used for hooking into
148
-     *                                                                  any admin page
149
-     * @type string                   $config_section                   the section name for this addon's
150
-     *                                                                  configuration settings section
151
-     *                                                                  (defaults to "addons")
152
-     * @type string                   $config_class                     the class name for this addon's
153
-     *                                                                  configuration settings object
154
-     * @type string                   $config_name                      the class name for this addon's
155
-     *                                                                  configuration settings object
156
-     * @type string                   $autoloader_paths                 [Required] an array of class names and the full
157
-     *                                                                  server paths to those files.
158
-     * @type string                   $autoloader_folders               an array of  "full server paths" for any
159
-     *                                                                  folders containing classes that might be
160
-     *                                                                  invoked by the addon
161
-     * @type string                   $dms_paths                        [Required] an array of full server paths to
162
-     *                                                                  folders that contain data migration scripts.
163
-     *                                                                  The key should be the EE_Addon class name that
164
-     *                                                                  this set of data migration scripts belongs to.
165
-     *                                                                  If the EE_Addon class is namespaced, then this
166
-     *                                                                  needs to be the Fully Qualified Class Name
167
-     * @type string                   $module_paths                     an array of full server paths to any
168
-     *                                                                  EED_Modules used by the addon
169
-     * @type string                   $shortcode_paths                  an array of full server paths to folders
170
-     *                                                                  that contain EES_Shortcodes
171
-     * @type string                   $widget_paths                     an array of full server paths to folders
172
-     *                                                                  that contain WP_Widgets
173
-     * @type array                    $capabilities                     an array indexed by role name
174
-     *                                                                  (i.e administrator,author ) and the values
175
-     *                                                                  are an array of caps to add to the role.
176
-     *                                                                  'administrator' => array(
177
-     *                                                                  'read_addon',
178
-     *                                                                  'edit_addon',
179
-     *                                                                  etc.
180
-     *                                                                  ).
181
-     * @type EE_Meta_Capability_Map[] $capability_maps                  an array of EE_Meta_Capability_Map object
182
-     *                                                                  for any addons that need to register any
183
-     *                                                                  special meta mapped capabilities.  Should
184
-     *                                                                  be indexed where the key is the
185
-     *                                                                  EE_Meta_Capability_Map class name and the
186
-     *                                                                  values are the arguments sent to the class.
187
-     * @type array                    $model_paths                      array of folders containing DB models
188
-     * @return bool
189
-     * @throws DomainException
190
-     * @throws EE_Error
191
-     * @throws InvalidArgumentException
192
-     * @throws InvalidDataTypeException
193
-     * @throws InvalidInterfaceException
194
-     * @since                                                           4.3.0
195
-     * @see                                                             EE_Register_Model
196
-     * @type array                    $class_paths                      array of folders containing DB classes
197
-     * @see                                                             EE_Register_Model
198
-     * @type array                    $model_extension_paths            array of folders containing DB model
199
-     *                                                                  extensions
200
-     * @see                                                             EE_Register_Model_Extension
201
-     * @type array                    $class_extension_paths            array of folders containing DB class
202
-     *                                                                  extensions
203
-     * @see                                                             EE_Register_Model_Extension
204
-     * @type array message_types {
205
-     *                                                                  An array of message types with the key as
206
-     *                                                                  the message type name and the values as
207
-     *                                                                  below:
208
-     * @type string                   $mtfilename                       [Required] The filename of the message type
209
-     *                                                                  being registered. This will be the main
210
-     *                                                                  EE_{Message Type Name}_message_type class.
211
-     *                                                                  for example:
212
-     *                                                                  EE_Declined_Registration_message_type.class.php
213
-     * @type array                    $autoloadpaths                    [Required] An array of paths to add to the
214
-     *                                                                  messages autoloader for the new message type.
215
-     * @type array                    $messengers_to_activate_with      An array of messengers that this message
216
-     *                                                                  type should activate with. Each value in
217
-     *                                                                  the
218
-     *                                                                  array
219
-     *                                                                  should match the name property of a
220
-     *                                                                  EE_messenger. Optional.
221
-     * @type array                    $messengers_to_validate_with      An array of messengers that this message
222
-     *                                                                  type should validate with. Each value in
223
-     *                                                                  the
224
-     *                                                                  array
225
-     *                                                                  should match the name property of an
226
-     *                                                                  EE_messenger.
227
-     *                                                                  Optional.
228
-     *                                                                  }
229
-     * @type array                    $custom_post_types
230
-     * @type array                    $custom_taxonomies
231
-     * @type array                    $payment_method_paths             each element is the folder containing the
232
-     *                                                                  EE_PMT_Base child class
233
-     *                                                                  (eg,
234
-     *                                                                  '/wp-content/plugins/my_plugin/Payomatic/'
235
-     *                                                                  which contains the files
236
-     *                                                                  EE_PMT_Payomatic.pm.php)
237
-     * @type array                    $default_terms
238
-     * @type array                    $namespace                        {
239
-     *                                                                  An array with two items for registering the
240
-     *                                                                  addon's namespace. (If, for some reason, you
241
-     *                                                                  require additional namespaces,
242
-     *                                                                  use
243
-     *                                                                  EventEspresso\core\Psr4Autoloader::addNamespace()
244
-     *                                                                  directly)
245
-     * @see                                                             EventEspresso\core\Psr4Autoloader::addNamespace()
246
-     * @type string                   $FQNS                             the namespace prefix
247
-     * @type string                   $DIR                              a base directory for class files in the
248
-     *                                                                  namespace.
249
-     *                                                                  }
250
-     *                                                                  }
251
-     * @type string                   $privacy_policies                 FQNSs (namespaces, each of which contains only
252
-     *                                                                  privacy policy classes) or FQCNs (specific
253
-     *                                                                  classnames of privacy policy classes)
254
-     * @type string                   $personal_data_exporters          FQNSs (namespaces, each of which contains only
255
-     *                                                                  privacy policy classes) or FQCNs (specific
256
-     *                                                                  classnames of privacy policy classes)
257
-     * @type string                   $personal_data_erasers            FQNSs (namespaces, each of which contains only
258
-     *                                                                  privacy policy classes) or FQCNs (specific
259
-     *                                                                  classnames of privacy policy classes)
260
-     */
261
-    public static function register(string $addon_name = '', array $setup_args = []): bool
262
-    {
263
-        if (! self::$loader instanceof LoaderInterface) {
264
-            self::$loader = LoaderFactory::getLoader();
265
-        }
266
-        // make sure this was called in the right place!
267
-        if (
268
-            ! did_action('activate_plugin')
269
-            && (
270
-                ! did_action('AHEE__EE_System__load_espresso_addons')
271
-                || did_action('AHEE__EE_System___detect_if_activation_or_upgrade__begin')
272
-            )
273
-        ) {
274
-            EE_Error::doing_it_wrong(
275
-                __METHOD__,
276
-                sprintf(
277
-                    esc_html__(
278
-                        'An attempt to register an EE_Addon named "%s" has failed because it was not registered at the correct time.  Please use the "AHEE__EE_System__load_espresso_addons" hook to register addons.',
279
-                        'event_espresso'
280
-                    ),
281
-                    $addon_name
282
-                ),
283
-                '4.3.0'
284
-            );
285
-            return false;
286
-        }
287
-        // required fields MUST be present, so let's make sure they are.
288
-        EE_Register_Addon::_verify_parameters($addon_name, $setup_args);
289
-        // get class name for addon
290
-        $class_name = EE_Register_Addon::_parse_class_name($addon_name, $setup_args);
291
-        // setup $_settings array from incoming values.
292
-        $addon_settings = EE_Register_Addon::_get_addon_settings($class_name, $setup_args);
293
-        // allow early addon setup or modification of addon api settings
294
-        self::$_settings = (array) apply_filters(
295
-            'FHEE__EE_Register_Addon__register',
296
-            self::$_settings,
297
-            $addon_name,
298
-            $class_name,
299
-            $setup_args
300
-        );
301
-        // does this addon work with this version of core or WordPress ?
302
-        // does this addon work with this version of core or WordPress ?
303
-        if (! EE_Register_Addon::_addon_is_compatible($addon_name, $addon_settings)) {
304
-            return false;
305
-        }
306
-        // register namespaces
307
-        EE_Register_Addon::_setup_namespaces($addon_settings);
308
-        // check if this is an activation request
309
-        if (EE_Register_Addon::_addon_activation($addon_name, $addon_settings)) {
310
-            // dont bother setting up the rest of the addon atm
311
-            return false;
312
-        }
313
-        // we need cars
314
-        EE_Register_Addon::_setup_autoloaders($addon_name);
315
-        // register new models and extensions
316
-        EE_Register_Addon::_register_models_and_extensions($addon_name);
317
-        // setup DMS
318
-        EE_Register_Addon::_register_data_migration_scripts($addon_name);
319
-        // if config_class is present let's register config.
320
-        EE_Register_Addon::_register_config($addon_name);
321
-        // register admin pages
322
-        EE_Register_Addon::_register_admin_pages($addon_name);
323
-        // add to list of modules to be registered
324
-        EE_Register_Addon::_register_modules($addon_name);
325
-        // add to list of shortcodes to be registered
326
-        EE_Register_Addon::_register_shortcodes($addon_name);
327
-        // add to list of widgets to be registered
328
-        EE_Register_Addon::_register_widgets($addon_name);
329
-        // register capability related stuff.
330
-        EE_Register_Addon::_register_capabilities($addon_name);
331
-        // any message type to register?
332
-        EE_Register_Addon::_register_message_types($addon_name);
333
-        // any custom post type/ custom capabilities or default terms to register
334
-        EE_Register_Addon::_register_custom_post_types($addon_name);
335
-        // and any payment methods
336
-        EE_Register_Addon::_register_payment_methods($addon_name);
337
-        // and privacy policy generators
338
-        EE_Register_Addon::registerPrivacyPolicies($addon_name);
339
-        // and privacy policy generators
340
-        EE_Register_Addon::registerPersonalDataExporters($addon_name);
341
-        // and privacy policy generators
342
-        EE_Register_Addon::registerPersonalDataErasers($addon_name);
343
-        // load and instantiate main addon class
344
-        $addon = EE_Register_Addon::_load_and_init_addon_class($addon_name);
345
-        // delay calling after_registration hook on each addon until after all add-ons have been registered.
346
-        add_action('AHEE__EE_System__load_espresso_addons__complete', [$addon, 'after_registration'], 999);
347
-        return $addon instanceof EE_Addon;
348
-    }
349
-
350
-
351
-    /**
352
-     * @param string $addon_name
353
-     * @param array  $setup_args
354
-     * @return void
355
-     * @throws EE_Error
356
-     */
357
-    private static function _verify_parameters(string $addon_name, array $setup_args)
358
-    {
359
-        // required fields MUST be present, so let's make sure they are.
360
-        if (empty($addon_name) || empty($setup_args)) {
361
-            throw new EE_Error(
362
-                esc_html__(
363
-                    'In order to register an EE_Addon with EE_Register_Addon::register(), you must include the "addon_name" (the name of the addon), and an array of arguments.',
364
-                    'event_espresso'
365
-                )
366
-            );
367
-        }
368
-        if (empty($setup_args['main_file_path'])) {
369
-            throw new EE_Error(
370
-                sprintf(
371
-                    esc_html__(
372
-                        'When registering an addon, you didn\'t provide the "main_file_path", which is the full path to the main file loaded directly by Wordpress. You only provided %s',
373
-                        'event_espresso'
374
-                    ),
375
-                    implode(',', array_keys($setup_args))
376
-                )
377
-            );
378
-        }
379
-        // check that addon has not already been registered with that name
380
-        if (isset(self::$_settings[ $addon_name ]) && ! did_action('activate_plugin')) {
381
-            throw new EE_Error(
382
-                sprintf(
383
-                    esc_html__(
384
-                        'An EE_Addon with the name "%s" has already been registered and each EE_Addon requires a unique name.',
385
-                        'event_espresso'
386
-                    ),
387
-                    $addon_name
388
-                )
389
-            );
390
-        }
391
-    }
392
-
393
-
394
-    /**
395
-     * @param string $addon_name
396
-     * @param array  $setup_args
397
-     * @return string
398
-     */
399
-    private static function _parse_class_name(string $addon_name, array $setup_args): string
400
-    {
401
-        if (empty($setup_args['class_name'])) {
402
-            // generate one by first separating name with spaces
403
-            $class_name = str_replace(['-', '_'], ' ', trim($addon_name));
404
-            // capitalize, then replace spaces with underscores
405
-            $class_name = str_replace(' ', '_', ucwords($class_name));
406
-        } else {
407
-            $class_name = $setup_args['class_name'];
408
-        }
409
-        // check if classname is fully  qualified or is a legacy classname already prefixed with 'EE_'
410
-        return strpos($class_name, '\\') || strpos($class_name, 'EE_') === 0
411
-            ? $class_name
412
-            : 'EE_' . $class_name;
413
-    }
414
-
415
-
416
-    /**
417
-     * @param string $class_name
418
-     * @param array  $setup_args
419
-     * @return array
420
-     */
421
-    private static function _get_addon_settings(string $class_name, array $setup_args): array
422
-    {
423
-        // setup $_settings array from incoming values.
424
-        $addon_settings = [
425
-            // generated from the addon name, changes something like "calendar" to "EE_Calendar"
426
-            'class_name'            => $class_name,
427
-            // the addon slug for use in URLs, etc
428
-            'plugin_slug'           => isset($setup_args['plugin_slug'])
429
-                ? (string) $setup_args['plugin_slug']
430
-                : '',
431
-            // page slug to be used when generating the "Settings" link on the WP plugin page
432
-            'plugin_action_slug'    => isset($setup_args['plugin_action_slug'])
433
-                ? (string) $setup_args['plugin_action_slug']
434
-                : '',
435
-            // the "software" version for the addon
436
-            'version'               => isset($setup_args['version'])
437
-                ? (string) $setup_args['version']
438
-                : '',
439
-            // the minimum version of EE Core that the addon will work with
440
-            'min_core_version'      => isset($setup_args['min_core_version'])
441
-                ? (string) $setup_args['min_core_version']
442
-                : '',
443
-            // the minimum version of WordPress that the addon will work with
444
-            'min_wp_version'        => isset($setup_args['min_wp_version'])
445
-                ? (string) $setup_args['min_wp_version']
446
-                : EE_MIN_WP_VER_REQUIRED,
447
-            // full server path to main file (file loaded directly by WP)
448
-            'main_file_path'        => isset($setup_args['main_file_path'])
449
-                ? (string) $setup_args['main_file_path']
450
-                : '',
451
-            // instance of \EventEspresso\core\domain\DomainInterface
452
-            'domain'                => isset($setup_args['domain']) && $setup_args['domain'] instanceof DomainInterface
453
-                ? $setup_args['domain']
454
-                : null,
455
-            // Fully Qualified Class Name for the addon's Domain class
456
-            'domain_fqcn'           => isset($setup_args['domain_fqcn'])
457
-                ? (string) $setup_args['domain_fqcn']
458
-                : '',
459
-            // path to folder containing files for integrating with the EE core admin and/or setting up EE admin pages
460
-            'admin_path'            => isset($setup_args['admin_path'])
461
-                ? (string) $setup_args['admin_path'] : '',
462
-            // a method to be called when the EE Admin is first invoked, can be used for hooking into any admin page
463
-            'admin_callback'        => isset($setup_args['admin_callback'])
464
-                ? (string) $setup_args['admin_callback']
465
-                : '',
466
-            // the section name for this addon's configuration settings section (defaults to "addons")
467
-            'config_section'        => isset($setup_args['config_section'])
468
-                ? (string) $setup_args['config_section']
469
-                : 'addons',
470
-            // the class name for this addon's configuration settings object
471
-            'config_class'          => isset($setup_args['config_class'])
472
-                ? (string) $setup_args['config_class'] : '',
473
-            // the name given to the config for this addons' configuration settings object (optional)
474
-            'config_name'           => isset($setup_args['config_name'])
475
-                ? (string) $setup_args['config_name'] : '',
476
-            // an array of "class names" => "full server paths" for any classes that might be invoked by the addon
477
-            'autoloader_paths'      => isset($setup_args['autoloader_paths'])
478
-                ? (array) $setup_args['autoloader_paths']
479
-                : [],
480
-            // an array of  "full server paths" for any folders containing classes that might be invoked by the addon
481
-            'autoloader_folders'    => isset($setup_args['autoloader_folders'])
482
-                ? (array) $setup_args['autoloader_folders']
483
-                : [],
484
-            // array of full server paths to any EE_DMS data migration scripts used by the addon.
485
-            // The key should be the EE_Addon class name that this set of data migration scripts belongs to.
486
-            // If the EE_Addon class is namespaced, then this needs to be the Fully Qualified Class Name
487
-            'dms_paths'             => isset($setup_args['dms_paths'])
488
-                ? (array) $setup_args['dms_paths']
489
-                : [],
490
-            // array of full server paths to any EED_Modules used by the addon
491
-            'module_paths'          => isset($setup_args['module_paths'])
492
-                ? (array) $setup_args['module_paths']
493
-                : [],
494
-            // array of full server paths to any EES_Shortcodes used by the addon
495
-            'shortcode_paths'       => isset($setup_args['shortcode_paths'])
496
-                ? (array) $setup_args['shortcode_paths']
497
-                : [],
498
-            'shortcode_fqcns'       => isset($setup_args['shortcode_fqcns'])
499
-                ? (array) $setup_args['shortcode_fqcns']
500
-                : [],
501
-            // array of full server paths to any WP_Widgets used by the addon
502
-            'widget_paths'          => isset($setup_args['widget_paths'])
503
-                ? (array) $setup_args['widget_paths']
504
-                : [],
505
-            'message_types'         => isset($setup_args['message_types'])
506
-                ? (array) $setup_args['message_types']
507
-                : [],
508
-            'capabilities'          => isset($setup_args['capabilities'])
509
-                ? (array) $setup_args['capabilities']
510
-                : [],
511
-            'capability_maps'       => isset($setup_args['capability_maps'])
512
-                ? (array) $setup_args['capability_maps']
513
-                : [],
514
-            'model_paths'           => isset($setup_args['model_paths'])
515
-                ? (array) $setup_args['model_paths']
516
-                : [],
517
-            'class_paths'           => isset($setup_args['class_paths'])
518
-                ? (array) $setup_args['class_paths']
519
-                : [],
520
-            'model_extension_paths' => isset($setup_args['model_extension_paths'])
521
-                ? (array) $setup_args['model_extension_paths']
522
-                : [],
523
-            'class_extension_paths' => isset($setup_args['class_extension_paths'])
524
-                ? (array) $setup_args['class_extension_paths']
525
-                : [],
526
-            'custom_post_types'     => isset($setup_args['custom_post_types'])
527
-                ? (array) $setup_args['custom_post_types']
528
-                : [],
529
-            'custom_taxonomies'     => isset($setup_args['custom_taxonomies'])
530
-                ? (array) $setup_args['custom_taxonomies']
531
-                : [],
532
-            'payment_method_paths'  => isset($setup_args['payment_method_paths'])
533
-                ? (array) $setup_args['payment_method_paths']
534
-                : [],
535
-            'default_terms'         => isset($setup_args['default_terms'])
536
-                ? (array) $setup_args['default_terms']
537
-                : [],
538
-            // if not empty, inserts a new table row after this plugin's row on the WP Plugins page
539
-            // that can be used for adding upgrading/marketing info
540
-            'plugins_page_row'      => isset($setup_args['plugins_page_row'])
541
-                ? (array) $setup_args['plugins_page_row']
542
-                : [],
543
-            'namespace'             => isset(
544
-                $setup_args['namespace']['FQNS'],
545
-                $setup_args['namespace']['DIR']
546
-            )
547
-                ? (array) $setup_args['namespace']
548
-                : [],
549
-            'privacy_policies'      => isset($setup_args['privacy_policies'])
550
-                ? (array) $setup_args['privacy_policies']
551
-                : '',
552
-        ];
553
-        // if plugin_action_slug is NOT set, but an admin page path IS set,
554
-        // then let's just use the plugin_slug since that will be used for linking to the admin page
555
-        $addon_settings['plugin_action_slug'] = empty($addon_settings['plugin_action_slug'])
556
-                                                && ! empty($addon_settings['admin_path'])
557
-            ? $addon_settings['plugin_slug']
558
-            : $addon_settings['plugin_action_slug'];
559
-        // full server path to main file (file loaded directly by WP)
560
-        $addon_settings['plugin_basename'] = plugin_basename($addon_settings['main_file_path']);
561
-        return $addon_settings;
562
-    }
563
-
564
-
565
-    /**
566
-     * @param string $addon_name
567
-     * @param array  $addon_settings
568
-     * @return bool
569
-     */
570
-    private static function _addon_is_compatible(string $addon_name, array $addon_settings): bool
571
-    {
572
-        global $wp_version;
573
-        $incompatibility_message = '';
574
-        // check whether this addon version is compatible with EE core
575
-        if (
576
-            isset(EE_Register_Addon::$_incompatible_addons[ $addon_name ])
577
-            && ! self::_meets_min_core_version_requirement(
578
-                EE_Register_Addon::$_incompatible_addons[ $addon_name ],
579
-                $addon_settings['version']
580
-            )
581
-        ) {
582
-            $incompatibility_message = sprintf(
583
-                esc_html__(
584
-                    '%4$sIMPORTANT!%5$sThe Event Espresso "%1$s" addon is not compatible with this version of Event Espresso.%2$sPlease upgrade your "%1$s" addon to version %3$s or newer to resolve this issue.',
585
-                    'event_espresso'
586
-                ),
587
-                $addon_name,
588
-                '<br />',
589
-                EE_Register_Addon::$_incompatible_addons[ $addon_name ],
590
-                '<span style="font-weight: bold; color: #D54E21;">',
591
-                '</span><br />'
592
-            );
593
-        } elseif (
594
-            ! self::_meets_min_core_version_requirement($addon_settings['min_core_version'], espresso_version())
595
-        ) {
596
-            $incompatibility_message = sprintf(
597
-                esc_html__(
598
-                    '%5$sIMPORTANT!%6$sThe Event Espresso "%1$s" addon requires Event Espresso Core version "%2$s" or higher in order to run.%4$sYour version of Event Espresso Core is currently at "%3$s". Please upgrade Event Espresso Core first and then re-activate "%1$s".',
599
-                    'event_espresso'
600
-                ),
601
-                $addon_name,
602
-                self::_effective_version($addon_settings['min_core_version']),
603
-                self::_effective_version(espresso_version()),
604
-                '<br />',
605
-                '<span style="font-weight: bold; color: #D54E21;">',
606
-                '</span><br />'
607
-            );
608
-        } elseif (version_compare($wp_version, $addon_settings['min_wp_version'], '<')) {
609
-            $incompatibility_message = sprintf(
610
-                esc_html__(
611
-                    '%4$sIMPORTANT!%5$sThe Event Espresso "%1$s" addon requires WordPress version "%2$s" or greater.%3$sPlease update your version of WordPress to use the "%1$s" addon and to keep your site secure.',
612
-                    'event_espresso'
613
-                ),
614
-                $addon_name,
615
-                $addon_settings['min_wp_version'],
616
-                '<br />',
617
-                '<span style="font-weight: bold; color: #D54E21;">',
618
-                '</span><br />'
619
-            );
620
-        }
621
-        if (! empty($incompatibility_message)) {
622
-            // remove 'activate' from the REQUEST
623
-            // so WP doesn't erroneously tell the user the plugin activated fine when it didn't
624
-            /** @var RequestInterface $request */
625
-            $request = LoaderFactory::getLoader()->getShared(RequestInterface::class);
626
-            $request->unSetRequestParam('activate', true);
627
-            if (current_user_can('activate_plugins')) {
628
-                // show an error message indicating the plugin didn't activate properly
629
-                EE_Error::add_error($incompatibility_message, __FILE__, __FUNCTION__, __LINE__);
630
-            }
631
-            unset($_GET['activate'], $_REQUEST['activate']);
632
-            if (! function_exists('deactivate_plugins')) {
633
-                require_once ABSPATH . 'wp-admin/includes/plugin.php';
634
-            }
635
-            deactivate_plugins(plugin_basename($addon_settings['main_file_path']));
636
-            // BAIL FROM THE ADDON REGISTRATION PROCESS
637
-            return false;
638
-        }
639
-        // addon IS compatible
640
-        return true;
641
-    }
642
-
643
-
644
-    /**
645
-     * register namespaces right away before any other files or classes get loaded, but AFTER the version checks
646
-     *
647
-     * @param array $addon_settings
648
-     * @return void
649
-     */
650
-    private static function _setup_namespaces(array $addon_settings)
651
-    {
652
-        //
653
-        if (
654
-            isset(
655
-                $addon_settings['namespace']['FQNS'],
656
-                $addon_settings['namespace']['DIR']
657
-            )
658
-        ) {
659
-            EE_Psr4AutoloaderInit::psr4_loader()->addNamespace(
660
-                $addon_settings['namespace']['FQNS'],
661
-                $addon_settings['namespace']['DIR']
662
-            );
663
-        }
664
-    }
665
-
666
-
667
-    /**
668
-     * @param string $addon_name
669
-     * @param array  $addon_settings
670
-     * @return bool
671
-     * @throws InvalidArgumentException
672
-     * @throws InvalidDataTypeException
673
-     * @throws InvalidInterfaceException
674
-     */
675
-    private static function _addon_activation(string $addon_name, array $addon_settings): bool
676
-    {
677
-        // this is an activation request
678
-        if (did_action('activate_plugin')) {
679
-            // to find if THIS is the addon that was activated, just check if we have already registered it or not
680
-            // (as the newly-activated addon wasn't around the first time addons were registered).
681
-            // Note: the presence of pue_options in the addon registration options will initialize the $_settings
682
-            // property for the add-on, but the add-on is only partially initialized.  Hence, the additional check.
683
-            if (
684
-                ! isset(self::$_settings[ $addon_name ])
685
-                || (isset(self::$_settings[ $addon_name ])
686
-                    && ! isset(self::$_settings[ $addon_name ]['class_name'])
687
-                )
688
-            ) {
689
-                self::$_settings[ $addon_name ] = $addon_settings;
690
-                $addon                          = self::_load_and_init_addon_class($addon_name);
691
-                $addon->set_activation_indicator_option();
692
-                // dont bother setting up the rest of the addon.
693
-                // we know it was just activated and the request will end soon
694
-            }
695
-            return true;
696
-        }
697
-        // make sure addon settings are set correctly without overwriting anything existing
698
-        if (isset(self::$_settings[ $addon_name ])) {
699
-            self::$_settings[ $addon_name ] += $addon_settings;
700
-        } else {
701
-            self::$_settings[ $addon_name ] = $addon_settings;
702
-        }
703
-        return false;
704
-    }
705
-
706
-
707
-    /**
708
-     * @param string $addon_name
709
-     * @return void
710
-     * @throws EE_Error
711
-     */
712
-    private static function _setup_autoloaders(string $addon_name)
713
-    {
714
-        if (! empty(self::$_settings[ $addon_name ]['autoloader_paths'])) {
715
-            // setup autoloader for single file
716
-            EEH_Autoloader::instance()->register_autoloader(self::$_settings[ $addon_name ]['autoloader_paths']);
717
-        }
718
-        // setup autoloaders for folders
719
-        if (! empty(self::$_settings[ $addon_name ]['autoloader_folders'])) {
720
-            foreach ((array) self::$_settings[ $addon_name ]['autoloader_folders'] as $autoloader_folder) {
721
-                EEH_Autoloader::register_autoloaders_for_each_file_in_folder($autoloader_folder);
722
-            }
723
-        }
724
-    }
725
-
726
-
727
-    /**
728
-     * register new models and extensions
729
-     *
730
-     * @param string $addon_name
731
-     * @return void
732
-     * @throws EE_Error
733
-     */
734
-    private static function _register_models_and_extensions(string $addon_name)
735
-    {
736
-        // register new models
737
-        if (
738
-            ! empty(self::$_settings[ $addon_name ]['model_paths'])
739
-            || ! empty(self::$_settings[ $addon_name ]['class_paths'])
740
-        ) {
741
-            EE_Register_Model::register(
742
-                $addon_name,
743
-                [
744
-                    'model_paths' => self::$_settings[ $addon_name ]['model_paths'],
745
-                    'class_paths' => self::$_settings[ $addon_name ]['class_paths'],
746
-                ]
747
-            );
748
-        }
749
-        // register model extensions
750
-        if (
751
-            ! empty(self::$_settings[ $addon_name ]['model_extension_paths'])
752
-            || ! empty(self::$_settings[ $addon_name ]['class_extension_paths'])
753
-        ) {
754
-            EE_Register_Model_Extensions::register(
755
-                $addon_name,
756
-                [
757
-                    'model_extension_paths' => self::$_settings[ $addon_name ]['model_extension_paths'],
758
-                    'class_extension_paths' => self::$_settings[ $addon_name ]['class_extension_paths'],
759
-                ]
760
-            );
761
-        }
762
-    }
763
-
764
-
765
-    /**
766
-     * @param string $addon_name
767
-     * @return void
768
-     * @throws EE_Error
769
-     */
770
-    private static function _register_data_migration_scripts(string $addon_name)
771
-    {
772
-        // setup DMS
773
-        if (! empty(self::$_settings[ $addon_name ]['dms_paths'])) {
774
-            EE_Register_Data_Migration_Scripts::register(
775
-                $addon_name,
776
-                ['dms_paths' => self::$_settings[ $addon_name ]['dms_paths']]
777
-            );
778
-        }
779
-    }
780
-
781
-
782
-    /**
783
-     * @param string $addon_name
784
-     * @return void
785
-     * @throws EE_Error
786
-     */
787
-    private static function _register_config(string $addon_name)
788
-    {
789
-        // if config_class is present let's register config.
790
-        if (! empty(self::$_settings[ $addon_name ]['config_class'])) {
791
-            EE_Register_Config::register(
792
-                self::$_settings[ $addon_name ]['config_class'],
793
-                [
794
-                    'config_section' => self::$_settings[ $addon_name ]['config_section'],
795
-                    'config_name'    => self::$_settings[ $addon_name ]['config_name'],
796
-                ]
797
-            );
798
-        }
799
-    }
800
-
801
-
802
-    /**
803
-     * @param string $addon_name
804
-     * @return void
805
-     * @throws EE_Error
806
-     */
807
-    private static function _register_admin_pages(string $addon_name)
808
-    {
809
-        if (! empty(self::$_settings[ $addon_name ]['admin_path'])) {
810
-            EE_Register_Admin_Page::register(
811
-                $addon_name,
812
-                ['page_path' => self::$_settings[ $addon_name ]['admin_path']]
813
-            );
814
-        }
815
-    }
816
-
817
-
818
-    /**
819
-     * @param string $addon_name
820
-     * @return void
821
-     * @throws EE_Error
822
-     */
823
-    private static function _register_modules(string $addon_name)
824
-    {
825
-        if (! empty(self::$_settings[ $addon_name ]['module_paths'])) {
826
-            EE_Register_Module::register(
827
-                $addon_name,
828
-                ['module_paths' => self::$_settings[ $addon_name ]['module_paths']]
829
-            );
830
-        }
831
-    }
832
-
833
-
834
-    /**
835
-     * @param string $addon_name
836
-     * @return void
837
-     * @throws EE_Error
838
-     */
839
-    private static function _register_shortcodes(string $addon_name)
840
-    {
841
-        if (
842
-            ! empty(self::$_settings[ $addon_name ]['shortcode_paths'])
843
-            || ! empty(self::$_settings[ $addon_name ]['shortcode_fqcns'])
844
-        ) {
845
-            EE_Register_Shortcode::register(
846
-                $addon_name,
847
-                [
848
-                    'shortcode_paths' => self::$_settings[ $addon_name ]['shortcode_paths'] ?? [],
849
-                    'shortcode_fqcns' => self::$_settings[ $addon_name ]['shortcode_fqcns'] ?? [],
850
-                ]
851
-            );
852
-        }
853
-    }
854
-
855
-
856
-    /**
857
-     * @param string $addon_name
858
-     * @return void
859
-     * @throws EE_Error
860
-     */
861
-    private static function _register_widgets(string $addon_name)
862
-    {
863
-        if (! empty(self::$_settings[ $addon_name ]['widget_paths'])) {
864
-            EE_Register_Widget::register(
865
-                $addon_name,
866
-                ['widget_paths' => self::$_settings[ $addon_name ]['widget_paths']]
867
-            );
868
-        }
869
-    }
870
-
871
-
872
-    /**
873
-     * @param string $addon_name
874
-     * @return void
875
-     * @throws EE_Error
876
-     */
877
-    private static function _register_capabilities(string $addon_name)
878
-    {
879
-        if (! empty(self::$_settings[ $addon_name ]['capabilities'])) {
880
-            EE_Register_Capabilities::register(
881
-                $addon_name,
882
-                [
883
-                    'capabilities'    => self::$_settings[ $addon_name ]['capabilities'],
884
-                    'capability_maps' => self::$_settings[ $addon_name ]['capability_maps'],
885
-                ]
886
-            );
887
-        }
888
-    }
889
-
890
-
891
-    /**
892
-     * @param string $addon_name
893
-     * @return void
894
-     */
895
-    private static function _register_message_types(string $addon_name)
896
-    {
897
-        if (! empty(self::$_settings[ $addon_name ]['message_types'])) {
898
-            add_action(
899
-                'EE_Brewing_Regular___messages_caf',
900
-                ['EE_Register_Addon', 'register_message_types']
901
-            );
902
-        }
903
-    }
904
-
905
-
906
-    /**
907
-     * @param string $addon_name
908
-     * @return void
909
-     * @throws EE_Error
910
-     */
911
-    private static function _register_custom_post_types(string $addon_name)
912
-    {
913
-        if (
914
-            ! empty(self::$_settings[ $addon_name ]['custom_post_types'])
915
-            || ! empty(self::$_settings[ $addon_name ]['custom_taxonomies'])
916
-        ) {
917
-            EE_Register_CPT::register(
918
-                $addon_name,
919
-                [
920
-                    'cpts'          => self::$_settings[ $addon_name ]['custom_post_types'],
921
-                    'cts'           => self::$_settings[ $addon_name ]['custom_taxonomies'],
922
-                    'default_terms' => self::$_settings[ $addon_name ]['default_terms'],
923
-                ]
924
-            );
925
-        }
926
-    }
927
-
928
-
929
-    /**
930
-     * @param string $addon_name
931
-     * @return void
932
-     * @throws InvalidArgumentException
933
-     * @throws InvalidInterfaceException
934
-     * @throws InvalidDataTypeException
935
-     * @throws DomainException
936
-     * @throws EE_Error
937
-     */
938
-    private static function _register_payment_methods(string $addon_name)
939
-    {
940
-        if (! empty(self::$_settings[ $addon_name ]['payment_method_paths'])) {
941
-            EE_Register_Payment_Method::register(
942
-                $addon_name,
943
-                ['payment_method_paths' => self::$_settings[ $addon_name ]['payment_method_paths']]
944
-            );
945
-        }
946
-    }
947
-
948
-
949
-    /**
950
-     * @param string $addon_name
951
-     * @return void
952
-     * @throws InvalidArgumentException
953
-     * @throws InvalidInterfaceException
954
-     * @throws InvalidDataTypeException
955
-     * @throws DomainException
956
-     */
957
-    private static function registerPrivacyPolicies(string $addon_name)
958
-    {
959
-        if (! empty(self::$_settings[ $addon_name ]['privacy_policies'])) {
960
-            EE_Register_Privacy_Policy::register(
961
-                $addon_name,
962
-                self::$_settings[ $addon_name ]['privacy_policies']
963
-            );
964
-        }
965
-    }
966
-
967
-
968
-    /**
969
-     * @param string $addon_name
970
-     * @return void
971
-     */
972
-    private static function registerPersonalDataExporters(string $addon_name)
973
-    {
974
-        if (! empty(self::$_settings[ $addon_name ]['personal_data_exporters'])) {
975
-            EE_Register_Personal_Data_Eraser::register(
976
-                $addon_name,
977
-                self::$_settings[ $addon_name ]['personal_data_exporters']
978
-            );
979
-        }
980
-    }
981
-
982
-
983
-    /**
984
-     * @param string $addon_name
985
-     * @return void
986
-     */
987
-    private static function registerPersonalDataErasers(string $addon_name)
988
-    {
989
-        if (! empty(self::$_settings[ $addon_name ]['personal_data_erasers'])) {
990
-            EE_Register_Personal_Data_Eraser::register(
991
-                $addon_name,
992
-                self::$_settings[ $addon_name ]['personal_data_erasers']
993
-            );
994
-        }
995
-    }
996
-
997
-
998
-    /**
999
-     * Loads and instantiates the EE_Addon class and adds it onto the registry
1000
-     *
1001
-     * @param string $addon_name
1002
-     * @return EE_Addon
1003
-     * @throws InvalidArgumentException
1004
-     * @throws InvalidInterfaceException
1005
-     * @throws InvalidDataTypeException
1006
-     */
1007
-    private static function _load_and_init_addon_class(string $addon_name): EE_Addon
1008
-    {
1009
-        $addon = self::$loader->getShared(
1010
-            self::$_settings[ $addon_name ]['class_name'],
1011
-            ['EE_Registry::create(addon)' => true]
1012
-        );
1013
-        if (! $addon instanceof EE_Addon) {
1014
-            throw new DomainException(
1015
-                sprintf(
1016
-                    esc_html__('The "%1$s" EE_Addon class failed to instantiate!', 'event_espresso'),
1017
-                    self::$_settings[ $addon_name ]['class_name']
1018
-                )
1019
-            );
1020
-        }
1021
-        // setter inject dep map if required
1022
-        if ($addon->dependencyMap() === null) {
1023
-            $addon->setDependencyMap(self::$loader->getShared('EE_Dependency_Map'));
1024
-        }
1025
-        // setter inject domain if required
1026
-        EE_Register_Addon::injectAddonDomain($addon_name, $addon);
1027
-
1028
-        $addon->set_name($addon_name);
1029
-        $addon->set_plugin_slug(self::$_settings[ $addon_name ]['plugin_slug']);
1030
-        $addon->set_plugin_basename(self::$_settings[ $addon_name ]['plugin_basename']);
1031
-        $addon->set_main_plugin_file(self::$_settings[ $addon_name ]['main_file_path']);
1032
-        $addon->set_plugin_action_slug(self::$_settings[ $addon_name ]['plugin_action_slug']);
1033
-        $addon->set_plugins_page_row(self::$_settings[ $addon_name ]['plugins_page_row']);
1034
-        $addon->set_version(self::$_settings[ $addon_name ]['version']);
1035
-        $addon->set_min_core_version(self::_effective_version(self::$_settings[ $addon_name ]['min_core_version']));
1036
-        $addon->set_config_section(self::$_settings[ $addon_name ]['config_section']);
1037
-        $addon->set_config_class(self::$_settings[ $addon_name ]['config_class']);
1038
-        $addon->set_config_name(self::$_settings[ $addon_name ]['config_name']);
1039
-        do_action(
1040
-            'AHEE__EE_Register_Addon___load_and_init_addon_class',
1041
-            $addon,
1042
-            $addon_name,
1043
-            self::$_settings
1044
-        );
1045
-        // unfortunately this can't be hooked in upon construction,
1046
-        // because we don't have the plugin's mainfile path upon construction.
1047
-        register_deactivation_hook($addon->get_main_plugin_file(), [$addon, 'deactivation']);
1048
-        // call any additional admin_callback functions during load_admin_controller hook
1049
-        if (! empty(self::$_settings[ $addon_name ]['admin_callback'])) {
1050
-            add_action(
1051
-                'AHEE__EE_System__load_controllers__load_admin_controllers',
1052
-                [$addon, self::$_settings[ $addon_name ]['admin_callback']]
1053
-            );
1054
-        }
1055
-        return $addon;
1056
-    }
1057
-
1058
-
1059
-    /**
1060
-     * @param string   $addon_name
1061
-     * @param EE_Addon $addon
1062
-     * @since   4.10.13.p
1063
-     */
1064
-    private static function injectAddonDomain(string $addon_name, EE_Addon $addon)
1065
-    {
1066
-        if ($addon instanceof RequiresDomainInterface && $addon->domain() === null) {
1067
-            // using supplied Domain object
1068
-            $domain = self::$_settings[ $addon_name ]['domain'] instanceof DomainInterface
1069
-                ? self::$_settings[ $addon_name ]['domain']
1070
-                : null;
1071
-            // or construct one using Domain FQCN
1072
-            if ($domain === null && self::$_settings[ $addon_name ]['domain_fqcn'] !== '') {
1073
-                $domain = self::$loader->getShared(
1074
-                    self::$_settings[ $addon_name ]['domain_fqcn'],
1075
-                    [
1076
-                        new EventEspresso\core\domain\values\FilePath(
1077
-                            self::$_settings[ $addon_name ]['main_file_path']
1078
-                        ),
1079
-                        EventEspresso\core\domain\values\Version::fromString(
1080
-                            self::$_settings[ $addon_name ]['version']
1081
-                        ),
1082
-                    ]
1083
-                );
1084
-            }
1085
-            if ($domain instanceof DomainInterface) {
1086
-                $addon->setDomain($domain);
1087
-            }
1088
-        }
1089
-    }
1090
-
1091
-
1092
-    /**
1093
-     * @return void
1094
-     * @deprecated $VID:$
1095
-     */
1096
-    public static function load_pue_update()
1097
-    {
1098
-        RegisterAddonPUE::loadPueUpdate();
1099
-    }
1100
-
1101
-
1102
-    /**
1103
-     * Callback for EE_Brewing_Regular__messages_caf hook used to register message types.
1104
-     *
1105
-     * @return void
1106
-     * @throws EE_Error
1107
-     * @since 4.4.0
1108
-     */
1109
-    public static function register_message_types()
1110
-    {
1111
-        foreach (self::$_settings as $settings) {
1112
-            if (! empty($settings['message_types'])) {
1113
-                foreach ((array) $settings['message_types'] as $message_type => $message_type_settings) {
1114
-                    EE_Register_Message_Type::register($message_type, $message_type_settings);
1115
-                }
1116
-            }
1117
-        }
1118
-    }
1119
-
1120
-
1121
-    /**
1122
-     * This deregisters an addon that was previously registered with a specific addon_name.
1123
-     *
1124
-     * @param string $addon_name the name for the addon that was previously registered
1125
-     * @throws DomainException
1126
-     * @throws InvalidArgumentException
1127
-     * @throws InvalidDataTypeException
1128
-     * @throws InvalidInterfaceException
1129
-     * @since    4.3.0
1130
-     */
1131
-    public static function deregister(string $addon_name = '')
1132
-    {
1133
-        if (isset(self::$_settings[ $addon_name ]['class_name'])) {
1134
-            try {
1135
-                do_action('AHEE__EE_Register_Addon__deregister__before', $addon_name);
1136
-                $class_name = self::$_settings[ $addon_name ]['class_name'];
1137
-                if (! empty(self::$_settings[ $addon_name ]['dms_paths'])) {
1138
-                    // setup DMS
1139
-                    EE_Register_Data_Migration_Scripts::deregister($addon_name);
1140
-                }
1141
-                if (! empty(self::$_settings[ $addon_name ]['admin_path'])) {
1142
-                    // register admin page
1143
-                    EE_Register_Admin_Page::deregister($addon_name);
1144
-                }
1145
-                if (! empty(self::$_settings[ $addon_name ]['module_paths'])) {
1146
-                    // add to list of modules to be registered
1147
-                    EE_Register_Module::deregister($addon_name);
1148
-                }
1149
-                if (
1150
-                    ! empty(self::$_settings[ $addon_name ]['shortcode_paths'])
1151
-                    || ! empty(self::$_settings[ $addon_name ]['shortcode_fqcns'])
1152
-                ) {
1153
-                    // add to list of shortcodes to be registered
1154
-                    EE_Register_Shortcode::deregister($addon_name);
1155
-                }
1156
-                if (! empty(self::$_settings[ $addon_name ]['config_class'])) {
1157
-                    // if config_class present let's register config.
1158
-                    EE_Register_Config::deregister(self::$_settings[ $addon_name ]['config_class']);
1159
-                }
1160
-                if (! empty(self::$_settings[ $addon_name ]['widget_paths'])) {
1161
-                    // add to list of widgets to be registered
1162
-                    EE_Register_Widget::deregister($addon_name);
1163
-                }
1164
-                if (
1165
-                    ! empty(self::$_settings[ $addon_name ]['model_paths'])
1166
-                    || ! empty(self::$_settings[ $addon_name ]['class_paths'])
1167
-                ) {
1168
-                    // add to list of shortcodes to be registered
1169
-                    EE_Register_Model::deregister($addon_name);
1170
-                }
1171
-                if (
1172
-                    ! empty(self::$_settings[ $addon_name ]['model_extension_paths'])
1173
-                    || ! empty(self::$_settings[ $addon_name ]['class_extension_paths'])
1174
-                ) {
1175
-                    // add to list of shortcodes to be registered
1176
-                    EE_Register_Model_Extensions::deregister($addon_name);
1177
-                }
1178
-                if (! empty(self::$_settings[ $addon_name ]['message_types'])) {
1179
-                    foreach ((array) self::$_settings[ $addon_name ]['message_types'] as $message_type => $message_type_settings) {
1180
-                        EE_Register_Message_Type::deregister($message_type);
1181
-                    }
1182
-                }
1183
-                // deregister capabilities for addon
1184
-                if (
1185
-                    ! empty(self::$_settings[ $addon_name ]['capabilities'])
1186
-                    || ! empty(self::$_settings[ $addon_name ]['capability_maps'])
1187
-                ) {
1188
-                    EE_Register_Capabilities::deregister($addon_name);
1189
-                }
1190
-                // deregister custom_post_types for addon
1191
-                if (! empty(self::$_settings[ $addon_name ]['custom_post_types'])) {
1192
-                    EE_Register_CPT::deregister($addon_name);
1193
-                }
1194
-                if (! empty(self::$_settings[ $addon_name ]['payment_method_paths'])) {
1195
-                    EE_Register_Payment_Method::deregister($addon_name);
1196
-                }
1197
-                $addon = EE_Registry::instance()->getAddon($class_name);
1198
-                if ($addon instanceof EE_Addon) {
1199
-                    remove_action(
1200
-                        'deactivate_' . $addon->get_main_plugin_file_basename(),
1201
-                        [$addon, 'deactivation']
1202
-                    );
1203
-                    remove_action(
1204
-                        'AHEE__EE_System__perform_activations_upgrades_and_migrations',
1205
-                        [$addon, 'initialize_db_if_no_migrations_required']
1206
-                    );
1207
-                    // remove `after_registration` call
1208
-                    remove_action(
1209
-                        'AHEE__EE_System__load_espresso_addons__complete',
1210
-                        [$addon, 'after_registration'],
1211
-                        999
1212
-                    );
1213
-                }
1214
-                EE_Registry::instance()->removeAddon($class_name);
1215
-                LoaderFactory::getLoader()->remove($class_name);
1216
-            } catch (OutOfBoundsException $addon_not_yet_registered_exception) {
1217
-                // the add-on was not yet registered in the registry,
1218
-                // so RegistryContainer::__get() throws this exception.
1219
-                // also no need to worry about this or log it,
1220
-                // it's ok to deregister an add-on before its registered in the registry
1221
-            } catch (Exception $e) {
1222
-                new ExceptionLogger($e);
1223
-            }
1224
-            unset(self::$_settings[ $addon_name ]);
1225
-            do_action('AHEE__EE_Register_Addon__deregister__after', $addon_name);
1226
-        }
1227
-    }
27
+	/**
28
+	 * possibly truncated version of the EE core version string
29
+	 *
30
+	 * @var string
31
+	 */
32
+	protected static $_core_version = '';
33
+
34
+	/**
35
+	 * Holds values for registered addons
36
+	 *
37
+	 * @var array
38
+	 */
39
+	protected static $_settings = [];
40
+
41
+	/**
42
+	 * @var  array $_incompatible_addons keys are addon SLUGS
43
+	 * (first argument passed to EE_Register_Addon::register()), keys are
44
+	 * their MINIMUM VERSION (with all 5 parts. Eg 1.2.3.rc.004).
45
+	 * Generally this should be used sparingly, as we don't want to muddle up
46
+	 * EE core with knowledge of ALL the addons out there.
47
+	 * If you want NO versions of an addon to run with a certain version of core,
48
+	 * it's usually best to define the addon's "min_core_version" as part of its call
49
+	 * to EE_Register_Addon::register(), rather than using this array with a super high value for its
50
+	 * minimum plugin version.
51
+	 * @access    protected
52
+	 */
53
+	protected static $_incompatible_addons = [
54
+		'Multi_Event_Registration' => '2.0.11.rc.002',
55
+		'Promotions'               => '1.0.0.rc.084',
56
+	];
57
+
58
+	/**
59
+	 * @var LoaderInterface
60
+	 */
61
+	protected static $loader;
62
+
63
+
64
+	/**
65
+	 * We should always be comparing core to a version like '4.3.0.rc.000',
66
+	 * not just '4.3.0'.
67
+	 * So if the addon developer doesn't provide that full version string,
68
+	 * fill in the blanks for them
69
+	 *
70
+	 * @param string $min_core_version
71
+	 * @return string always like '4.3.0.rc.000'
72
+	 */
73
+	protected static function _effective_version(string $min_core_version): string
74
+	{
75
+		// versions: 4 . 3 . 1 . p . 123
76
+		// offsets:    0 . 1 . 2 . 3 . 4
77
+		$version_parts = explode('.', $min_core_version);
78
+		// check they specified the micro version (after 2nd period)
79
+		if (! isset($version_parts[2])) {
80
+			$version_parts[2] = '0';
81
+		}
82
+		// if they didn't specify the 'p', or 'rc' part. Just assume the lowest possible
83
+		// soon we can assume that's 'rc', but this current version is 'alpha'
84
+		if (! isset($version_parts[3])) {
85
+			$version_parts[3] = 'dev';
86
+		}
87
+		if (! isset($version_parts[4])) {
88
+			$version_parts[4] = '000';
89
+		}
90
+		return implode('.', $version_parts);
91
+	}
92
+
93
+
94
+	/**
95
+	 * Returns whether or not the min core version requirement of the addon is met
96
+	 *
97
+	 * @param string $min_core_version    the minimum core version required by the addon
98
+	 * @param string $actual_core_version the actual core version, optional
99
+	 * @return bool
100
+	 */
101
+	public static function _meets_min_core_version_requirement(
102
+		string $min_core_version,
103
+		string $actual_core_version = EVENT_ESPRESSO_VERSION
104
+	): bool {
105
+		return version_compare(
106
+			self::_effective_version($actual_core_version),
107
+			self::_effective_version($min_core_version),
108
+			'>='
109
+		);
110
+	}
111
+
112
+
113
+	/**
114
+	 * Method for registering new EE_Addons.
115
+	 * Should be called AFTER AHEE__EE_System__load_espresso_addons but BEFORE
116
+	 * AHEE__EE_System___detect_if_activation_or_upgrade__begin in order to register all its components. However, it
117
+	 * may also be called after the 'activate_plugin' action (when an addon is activated), because an activating addon
118
+	 * won't be loaded by WP until after AHEE__EE_System__load_espresso_addons has fired. If its called after
119
+	 * 'activate_plugin', it registers the addon still, but its components are not registered
120
+	 * (they shouldn't be needed anyways, because it's just an activation request and they won't have a chance to do
121
+	 * anything anyways). Instead, it just sets the newly-activated addon's activation indicator wp option and returns
122
+	 * (so that we can detect that the addon has activated on the subsequent request)
123
+	 *
124
+	 * @param string                  $addon_name                       [Required] the EE_Addon's name.
125
+	 * @param array                   $setup_args                       {
126
+	 *                                                                  An array of arguments provided for registering
127
+	 *                                                                  the message type.
128
+	 * @type  string                  $class_name                       the addon's main file name.
129
+	 *                                                                  If left blank, generated from the addon name,
130
+	 *                                                                  changes something like "calendar" to
131
+	 *                                                                  "EE_Calendar"
132
+	 * @type string                   $min_core_version                 the minimum version of EE Core that the
133
+	 *                                                                  addon will work with. eg "4.8.1.rc.084"
134
+	 * @type string                   $version                          the "software" version for the addon. eg
135
+	 *                                                                  "1.0.0.p" for a first stable release, or
136
+	 *                                                                  "1.0.0.rc.043" for a version in progress
137
+	 * @type string                   $main_file_path                   the full server path to the main file
138
+	 *                                                                  loaded directly by WP
139
+	 * @type DomainInterface          $domain                           child class of
140
+	 *                                                                  EventEspresso\core\domain\DomainBase
141
+	 * @type string                   $domain_fqcn                      Fully Qualified Class Name
142
+	 *                                                                  for the addon's Domain class
143
+	 *                                                                  (see EventEspresso\core\domain\Domain)
144
+	 * @type string                   $admin_path                       full server path to the folder where the
145
+	 *                                                                  addon\'s admin files reside
146
+	 * @type string                   $admin_callback                   a method to be called when the EE Admin is
147
+	 *                                                                  first invoked, can be used for hooking into
148
+	 *                                                                  any admin page
149
+	 * @type string                   $config_section                   the section name for this addon's
150
+	 *                                                                  configuration settings section
151
+	 *                                                                  (defaults to "addons")
152
+	 * @type string                   $config_class                     the class name for this addon's
153
+	 *                                                                  configuration settings object
154
+	 * @type string                   $config_name                      the class name for this addon's
155
+	 *                                                                  configuration settings object
156
+	 * @type string                   $autoloader_paths                 [Required] an array of class names and the full
157
+	 *                                                                  server paths to those files.
158
+	 * @type string                   $autoloader_folders               an array of  "full server paths" for any
159
+	 *                                                                  folders containing classes that might be
160
+	 *                                                                  invoked by the addon
161
+	 * @type string                   $dms_paths                        [Required] an array of full server paths to
162
+	 *                                                                  folders that contain data migration scripts.
163
+	 *                                                                  The key should be the EE_Addon class name that
164
+	 *                                                                  this set of data migration scripts belongs to.
165
+	 *                                                                  If the EE_Addon class is namespaced, then this
166
+	 *                                                                  needs to be the Fully Qualified Class Name
167
+	 * @type string                   $module_paths                     an array of full server paths to any
168
+	 *                                                                  EED_Modules used by the addon
169
+	 * @type string                   $shortcode_paths                  an array of full server paths to folders
170
+	 *                                                                  that contain EES_Shortcodes
171
+	 * @type string                   $widget_paths                     an array of full server paths to folders
172
+	 *                                                                  that contain WP_Widgets
173
+	 * @type array                    $capabilities                     an array indexed by role name
174
+	 *                                                                  (i.e administrator,author ) and the values
175
+	 *                                                                  are an array of caps to add to the role.
176
+	 *                                                                  'administrator' => array(
177
+	 *                                                                  'read_addon',
178
+	 *                                                                  'edit_addon',
179
+	 *                                                                  etc.
180
+	 *                                                                  ).
181
+	 * @type EE_Meta_Capability_Map[] $capability_maps                  an array of EE_Meta_Capability_Map object
182
+	 *                                                                  for any addons that need to register any
183
+	 *                                                                  special meta mapped capabilities.  Should
184
+	 *                                                                  be indexed where the key is the
185
+	 *                                                                  EE_Meta_Capability_Map class name and the
186
+	 *                                                                  values are the arguments sent to the class.
187
+	 * @type array                    $model_paths                      array of folders containing DB models
188
+	 * @return bool
189
+	 * @throws DomainException
190
+	 * @throws EE_Error
191
+	 * @throws InvalidArgumentException
192
+	 * @throws InvalidDataTypeException
193
+	 * @throws InvalidInterfaceException
194
+	 * @since                                                           4.3.0
195
+	 * @see                                                             EE_Register_Model
196
+	 * @type array                    $class_paths                      array of folders containing DB classes
197
+	 * @see                                                             EE_Register_Model
198
+	 * @type array                    $model_extension_paths            array of folders containing DB model
199
+	 *                                                                  extensions
200
+	 * @see                                                             EE_Register_Model_Extension
201
+	 * @type array                    $class_extension_paths            array of folders containing DB class
202
+	 *                                                                  extensions
203
+	 * @see                                                             EE_Register_Model_Extension
204
+	 * @type array message_types {
205
+	 *                                                                  An array of message types with the key as
206
+	 *                                                                  the message type name and the values as
207
+	 *                                                                  below:
208
+	 * @type string                   $mtfilename                       [Required] The filename of the message type
209
+	 *                                                                  being registered. This will be the main
210
+	 *                                                                  EE_{Message Type Name}_message_type class.
211
+	 *                                                                  for example:
212
+	 *                                                                  EE_Declined_Registration_message_type.class.php
213
+	 * @type array                    $autoloadpaths                    [Required] An array of paths to add to the
214
+	 *                                                                  messages autoloader for the new message type.
215
+	 * @type array                    $messengers_to_activate_with      An array of messengers that this message
216
+	 *                                                                  type should activate with. Each value in
217
+	 *                                                                  the
218
+	 *                                                                  array
219
+	 *                                                                  should match the name property of a
220
+	 *                                                                  EE_messenger. Optional.
221
+	 * @type array                    $messengers_to_validate_with      An array of messengers that this message
222
+	 *                                                                  type should validate with. Each value in
223
+	 *                                                                  the
224
+	 *                                                                  array
225
+	 *                                                                  should match the name property of an
226
+	 *                                                                  EE_messenger.
227
+	 *                                                                  Optional.
228
+	 *                                                                  }
229
+	 * @type array                    $custom_post_types
230
+	 * @type array                    $custom_taxonomies
231
+	 * @type array                    $payment_method_paths             each element is the folder containing the
232
+	 *                                                                  EE_PMT_Base child class
233
+	 *                                                                  (eg,
234
+	 *                                                                  '/wp-content/plugins/my_plugin/Payomatic/'
235
+	 *                                                                  which contains the files
236
+	 *                                                                  EE_PMT_Payomatic.pm.php)
237
+	 * @type array                    $default_terms
238
+	 * @type array                    $namespace                        {
239
+	 *                                                                  An array with two items for registering the
240
+	 *                                                                  addon's namespace. (If, for some reason, you
241
+	 *                                                                  require additional namespaces,
242
+	 *                                                                  use
243
+	 *                                                                  EventEspresso\core\Psr4Autoloader::addNamespace()
244
+	 *                                                                  directly)
245
+	 * @see                                                             EventEspresso\core\Psr4Autoloader::addNamespace()
246
+	 * @type string                   $FQNS                             the namespace prefix
247
+	 * @type string                   $DIR                              a base directory for class files in the
248
+	 *                                                                  namespace.
249
+	 *                                                                  }
250
+	 *                                                                  }
251
+	 * @type string                   $privacy_policies                 FQNSs (namespaces, each of which contains only
252
+	 *                                                                  privacy policy classes) or FQCNs (specific
253
+	 *                                                                  classnames of privacy policy classes)
254
+	 * @type string                   $personal_data_exporters          FQNSs (namespaces, each of which contains only
255
+	 *                                                                  privacy policy classes) or FQCNs (specific
256
+	 *                                                                  classnames of privacy policy classes)
257
+	 * @type string                   $personal_data_erasers            FQNSs (namespaces, each of which contains only
258
+	 *                                                                  privacy policy classes) or FQCNs (specific
259
+	 *                                                                  classnames of privacy policy classes)
260
+	 */
261
+	public static function register(string $addon_name = '', array $setup_args = []): bool
262
+	{
263
+		if (! self::$loader instanceof LoaderInterface) {
264
+			self::$loader = LoaderFactory::getLoader();
265
+		}
266
+		// make sure this was called in the right place!
267
+		if (
268
+			! did_action('activate_plugin')
269
+			&& (
270
+				! did_action('AHEE__EE_System__load_espresso_addons')
271
+				|| did_action('AHEE__EE_System___detect_if_activation_or_upgrade__begin')
272
+			)
273
+		) {
274
+			EE_Error::doing_it_wrong(
275
+				__METHOD__,
276
+				sprintf(
277
+					esc_html__(
278
+						'An attempt to register an EE_Addon named "%s" has failed because it was not registered at the correct time.  Please use the "AHEE__EE_System__load_espresso_addons" hook to register addons.',
279
+						'event_espresso'
280
+					),
281
+					$addon_name
282
+				),
283
+				'4.3.0'
284
+			);
285
+			return false;
286
+		}
287
+		// required fields MUST be present, so let's make sure they are.
288
+		EE_Register_Addon::_verify_parameters($addon_name, $setup_args);
289
+		// get class name for addon
290
+		$class_name = EE_Register_Addon::_parse_class_name($addon_name, $setup_args);
291
+		// setup $_settings array from incoming values.
292
+		$addon_settings = EE_Register_Addon::_get_addon_settings($class_name, $setup_args);
293
+		// allow early addon setup or modification of addon api settings
294
+		self::$_settings = (array) apply_filters(
295
+			'FHEE__EE_Register_Addon__register',
296
+			self::$_settings,
297
+			$addon_name,
298
+			$class_name,
299
+			$setup_args
300
+		);
301
+		// does this addon work with this version of core or WordPress ?
302
+		// does this addon work with this version of core or WordPress ?
303
+		if (! EE_Register_Addon::_addon_is_compatible($addon_name, $addon_settings)) {
304
+			return false;
305
+		}
306
+		// register namespaces
307
+		EE_Register_Addon::_setup_namespaces($addon_settings);
308
+		// check if this is an activation request
309
+		if (EE_Register_Addon::_addon_activation($addon_name, $addon_settings)) {
310
+			// dont bother setting up the rest of the addon atm
311
+			return false;
312
+		}
313
+		// we need cars
314
+		EE_Register_Addon::_setup_autoloaders($addon_name);
315
+		// register new models and extensions
316
+		EE_Register_Addon::_register_models_and_extensions($addon_name);
317
+		// setup DMS
318
+		EE_Register_Addon::_register_data_migration_scripts($addon_name);
319
+		// if config_class is present let's register config.
320
+		EE_Register_Addon::_register_config($addon_name);
321
+		// register admin pages
322
+		EE_Register_Addon::_register_admin_pages($addon_name);
323
+		// add to list of modules to be registered
324
+		EE_Register_Addon::_register_modules($addon_name);
325
+		// add to list of shortcodes to be registered
326
+		EE_Register_Addon::_register_shortcodes($addon_name);
327
+		// add to list of widgets to be registered
328
+		EE_Register_Addon::_register_widgets($addon_name);
329
+		// register capability related stuff.
330
+		EE_Register_Addon::_register_capabilities($addon_name);
331
+		// any message type to register?
332
+		EE_Register_Addon::_register_message_types($addon_name);
333
+		// any custom post type/ custom capabilities or default terms to register
334
+		EE_Register_Addon::_register_custom_post_types($addon_name);
335
+		// and any payment methods
336
+		EE_Register_Addon::_register_payment_methods($addon_name);
337
+		// and privacy policy generators
338
+		EE_Register_Addon::registerPrivacyPolicies($addon_name);
339
+		// and privacy policy generators
340
+		EE_Register_Addon::registerPersonalDataExporters($addon_name);
341
+		// and privacy policy generators
342
+		EE_Register_Addon::registerPersonalDataErasers($addon_name);
343
+		// load and instantiate main addon class
344
+		$addon = EE_Register_Addon::_load_and_init_addon_class($addon_name);
345
+		// delay calling after_registration hook on each addon until after all add-ons have been registered.
346
+		add_action('AHEE__EE_System__load_espresso_addons__complete', [$addon, 'after_registration'], 999);
347
+		return $addon instanceof EE_Addon;
348
+	}
349
+
350
+
351
+	/**
352
+	 * @param string $addon_name
353
+	 * @param array  $setup_args
354
+	 * @return void
355
+	 * @throws EE_Error
356
+	 */
357
+	private static function _verify_parameters(string $addon_name, array $setup_args)
358
+	{
359
+		// required fields MUST be present, so let's make sure they are.
360
+		if (empty($addon_name) || empty($setup_args)) {
361
+			throw new EE_Error(
362
+				esc_html__(
363
+					'In order to register an EE_Addon with EE_Register_Addon::register(), you must include the "addon_name" (the name of the addon), and an array of arguments.',
364
+					'event_espresso'
365
+				)
366
+			);
367
+		}
368
+		if (empty($setup_args['main_file_path'])) {
369
+			throw new EE_Error(
370
+				sprintf(
371
+					esc_html__(
372
+						'When registering an addon, you didn\'t provide the "main_file_path", which is the full path to the main file loaded directly by Wordpress. You only provided %s',
373
+						'event_espresso'
374
+					),
375
+					implode(',', array_keys($setup_args))
376
+				)
377
+			);
378
+		}
379
+		// check that addon has not already been registered with that name
380
+		if (isset(self::$_settings[ $addon_name ]) && ! did_action('activate_plugin')) {
381
+			throw new EE_Error(
382
+				sprintf(
383
+					esc_html__(
384
+						'An EE_Addon with the name "%s" has already been registered and each EE_Addon requires a unique name.',
385
+						'event_espresso'
386
+					),
387
+					$addon_name
388
+				)
389
+			);
390
+		}
391
+	}
392
+
393
+
394
+	/**
395
+	 * @param string $addon_name
396
+	 * @param array  $setup_args
397
+	 * @return string
398
+	 */
399
+	private static function _parse_class_name(string $addon_name, array $setup_args): string
400
+	{
401
+		if (empty($setup_args['class_name'])) {
402
+			// generate one by first separating name with spaces
403
+			$class_name = str_replace(['-', '_'], ' ', trim($addon_name));
404
+			// capitalize, then replace spaces with underscores
405
+			$class_name = str_replace(' ', '_', ucwords($class_name));
406
+		} else {
407
+			$class_name = $setup_args['class_name'];
408
+		}
409
+		// check if classname is fully  qualified or is a legacy classname already prefixed with 'EE_'
410
+		return strpos($class_name, '\\') || strpos($class_name, 'EE_') === 0
411
+			? $class_name
412
+			: 'EE_' . $class_name;
413
+	}
414
+
415
+
416
+	/**
417
+	 * @param string $class_name
418
+	 * @param array  $setup_args
419
+	 * @return array
420
+	 */
421
+	private static function _get_addon_settings(string $class_name, array $setup_args): array
422
+	{
423
+		// setup $_settings array from incoming values.
424
+		$addon_settings = [
425
+			// generated from the addon name, changes something like "calendar" to "EE_Calendar"
426
+			'class_name'            => $class_name,
427
+			// the addon slug for use in URLs, etc
428
+			'plugin_slug'           => isset($setup_args['plugin_slug'])
429
+				? (string) $setup_args['plugin_slug']
430
+				: '',
431
+			// page slug to be used when generating the "Settings" link on the WP plugin page
432
+			'plugin_action_slug'    => isset($setup_args['plugin_action_slug'])
433
+				? (string) $setup_args['plugin_action_slug']
434
+				: '',
435
+			// the "software" version for the addon
436
+			'version'               => isset($setup_args['version'])
437
+				? (string) $setup_args['version']
438
+				: '',
439
+			// the minimum version of EE Core that the addon will work with
440
+			'min_core_version'      => isset($setup_args['min_core_version'])
441
+				? (string) $setup_args['min_core_version']
442
+				: '',
443
+			// the minimum version of WordPress that the addon will work with
444
+			'min_wp_version'        => isset($setup_args['min_wp_version'])
445
+				? (string) $setup_args['min_wp_version']
446
+				: EE_MIN_WP_VER_REQUIRED,
447
+			// full server path to main file (file loaded directly by WP)
448
+			'main_file_path'        => isset($setup_args['main_file_path'])
449
+				? (string) $setup_args['main_file_path']
450
+				: '',
451
+			// instance of \EventEspresso\core\domain\DomainInterface
452
+			'domain'                => isset($setup_args['domain']) && $setup_args['domain'] instanceof DomainInterface
453
+				? $setup_args['domain']
454
+				: null,
455
+			// Fully Qualified Class Name for the addon's Domain class
456
+			'domain_fqcn'           => isset($setup_args['domain_fqcn'])
457
+				? (string) $setup_args['domain_fqcn']
458
+				: '',
459
+			// path to folder containing files for integrating with the EE core admin and/or setting up EE admin pages
460
+			'admin_path'            => isset($setup_args['admin_path'])
461
+				? (string) $setup_args['admin_path'] : '',
462
+			// a method to be called when the EE Admin is first invoked, can be used for hooking into any admin page
463
+			'admin_callback'        => isset($setup_args['admin_callback'])
464
+				? (string) $setup_args['admin_callback']
465
+				: '',
466
+			// the section name for this addon's configuration settings section (defaults to "addons")
467
+			'config_section'        => isset($setup_args['config_section'])
468
+				? (string) $setup_args['config_section']
469
+				: 'addons',
470
+			// the class name for this addon's configuration settings object
471
+			'config_class'          => isset($setup_args['config_class'])
472
+				? (string) $setup_args['config_class'] : '',
473
+			// the name given to the config for this addons' configuration settings object (optional)
474
+			'config_name'           => isset($setup_args['config_name'])
475
+				? (string) $setup_args['config_name'] : '',
476
+			// an array of "class names" => "full server paths" for any classes that might be invoked by the addon
477
+			'autoloader_paths'      => isset($setup_args['autoloader_paths'])
478
+				? (array) $setup_args['autoloader_paths']
479
+				: [],
480
+			// an array of  "full server paths" for any folders containing classes that might be invoked by the addon
481
+			'autoloader_folders'    => isset($setup_args['autoloader_folders'])
482
+				? (array) $setup_args['autoloader_folders']
483
+				: [],
484
+			// array of full server paths to any EE_DMS data migration scripts used by the addon.
485
+			// The key should be the EE_Addon class name that this set of data migration scripts belongs to.
486
+			// If the EE_Addon class is namespaced, then this needs to be the Fully Qualified Class Name
487
+			'dms_paths'             => isset($setup_args['dms_paths'])
488
+				? (array) $setup_args['dms_paths']
489
+				: [],
490
+			// array of full server paths to any EED_Modules used by the addon
491
+			'module_paths'          => isset($setup_args['module_paths'])
492
+				? (array) $setup_args['module_paths']
493
+				: [],
494
+			// array of full server paths to any EES_Shortcodes used by the addon
495
+			'shortcode_paths'       => isset($setup_args['shortcode_paths'])
496
+				? (array) $setup_args['shortcode_paths']
497
+				: [],
498
+			'shortcode_fqcns'       => isset($setup_args['shortcode_fqcns'])
499
+				? (array) $setup_args['shortcode_fqcns']
500
+				: [],
501
+			// array of full server paths to any WP_Widgets used by the addon
502
+			'widget_paths'          => isset($setup_args['widget_paths'])
503
+				? (array) $setup_args['widget_paths']
504
+				: [],
505
+			'message_types'         => isset($setup_args['message_types'])
506
+				? (array) $setup_args['message_types']
507
+				: [],
508
+			'capabilities'          => isset($setup_args['capabilities'])
509
+				? (array) $setup_args['capabilities']
510
+				: [],
511
+			'capability_maps'       => isset($setup_args['capability_maps'])
512
+				? (array) $setup_args['capability_maps']
513
+				: [],
514
+			'model_paths'           => isset($setup_args['model_paths'])
515
+				? (array) $setup_args['model_paths']
516
+				: [],
517
+			'class_paths'           => isset($setup_args['class_paths'])
518
+				? (array) $setup_args['class_paths']
519
+				: [],
520
+			'model_extension_paths' => isset($setup_args['model_extension_paths'])
521
+				? (array) $setup_args['model_extension_paths']
522
+				: [],
523
+			'class_extension_paths' => isset($setup_args['class_extension_paths'])
524
+				? (array) $setup_args['class_extension_paths']
525
+				: [],
526
+			'custom_post_types'     => isset($setup_args['custom_post_types'])
527
+				? (array) $setup_args['custom_post_types']
528
+				: [],
529
+			'custom_taxonomies'     => isset($setup_args['custom_taxonomies'])
530
+				? (array) $setup_args['custom_taxonomies']
531
+				: [],
532
+			'payment_method_paths'  => isset($setup_args['payment_method_paths'])
533
+				? (array) $setup_args['payment_method_paths']
534
+				: [],
535
+			'default_terms'         => isset($setup_args['default_terms'])
536
+				? (array) $setup_args['default_terms']
537
+				: [],
538
+			// if not empty, inserts a new table row after this plugin's row on the WP Plugins page
539
+			// that can be used for adding upgrading/marketing info
540
+			'plugins_page_row'      => isset($setup_args['plugins_page_row'])
541
+				? (array) $setup_args['plugins_page_row']
542
+				: [],
543
+			'namespace'             => isset(
544
+				$setup_args['namespace']['FQNS'],
545
+				$setup_args['namespace']['DIR']
546
+			)
547
+				? (array) $setup_args['namespace']
548
+				: [],
549
+			'privacy_policies'      => isset($setup_args['privacy_policies'])
550
+				? (array) $setup_args['privacy_policies']
551
+				: '',
552
+		];
553
+		// if plugin_action_slug is NOT set, but an admin page path IS set,
554
+		// then let's just use the plugin_slug since that will be used for linking to the admin page
555
+		$addon_settings['plugin_action_slug'] = empty($addon_settings['plugin_action_slug'])
556
+												&& ! empty($addon_settings['admin_path'])
557
+			? $addon_settings['plugin_slug']
558
+			: $addon_settings['plugin_action_slug'];
559
+		// full server path to main file (file loaded directly by WP)
560
+		$addon_settings['plugin_basename'] = plugin_basename($addon_settings['main_file_path']);
561
+		return $addon_settings;
562
+	}
563
+
564
+
565
+	/**
566
+	 * @param string $addon_name
567
+	 * @param array  $addon_settings
568
+	 * @return bool
569
+	 */
570
+	private static function _addon_is_compatible(string $addon_name, array $addon_settings): bool
571
+	{
572
+		global $wp_version;
573
+		$incompatibility_message = '';
574
+		// check whether this addon version is compatible with EE core
575
+		if (
576
+			isset(EE_Register_Addon::$_incompatible_addons[ $addon_name ])
577
+			&& ! self::_meets_min_core_version_requirement(
578
+				EE_Register_Addon::$_incompatible_addons[ $addon_name ],
579
+				$addon_settings['version']
580
+			)
581
+		) {
582
+			$incompatibility_message = sprintf(
583
+				esc_html__(
584
+					'%4$sIMPORTANT!%5$sThe Event Espresso "%1$s" addon is not compatible with this version of Event Espresso.%2$sPlease upgrade your "%1$s" addon to version %3$s or newer to resolve this issue.',
585
+					'event_espresso'
586
+				),
587
+				$addon_name,
588
+				'<br />',
589
+				EE_Register_Addon::$_incompatible_addons[ $addon_name ],
590
+				'<span style="font-weight: bold; color: #D54E21;">',
591
+				'</span><br />'
592
+			);
593
+		} elseif (
594
+			! self::_meets_min_core_version_requirement($addon_settings['min_core_version'], espresso_version())
595
+		) {
596
+			$incompatibility_message = sprintf(
597
+				esc_html__(
598
+					'%5$sIMPORTANT!%6$sThe Event Espresso "%1$s" addon requires Event Espresso Core version "%2$s" or higher in order to run.%4$sYour version of Event Espresso Core is currently at "%3$s". Please upgrade Event Espresso Core first and then re-activate "%1$s".',
599
+					'event_espresso'
600
+				),
601
+				$addon_name,
602
+				self::_effective_version($addon_settings['min_core_version']),
603
+				self::_effective_version(espresso_version()),
604
+				'<br />',
605
+				'<span style="font-weight: bold; color: #D54E21;">',
606
+				'</span><br />'
607
+			);
608
+		} elseif (version_compare($wp_version, $addon_settings['min_wp_version'], '<')) {
609
+			$incompatibility_message = sprintf(
610
+				esc_html__(
611
+					'%4$sIMPORTANT!%5$sThe Event Espresso "%1$s" addon requires WordPress version "%2$s" or greater.%3$sPlease update your version of WordPress to use the "%1$s" addon and to keep your site secure.',
612
+					'event_espresso'
613
+				),
614
+				$addon_name,
615
+				$addon_settings['min_wp_version'],
616
+				'<br />',
617
+				'<span style="font-weight: bold; color: #D54E21;">',
618
+				'</span><br />'
619
+			);
620
+		}
621
+		if (! empty($incompatibility_message)) {
622
+			// remove 'activate' from the REQUEST
623
+			// so WP doesn't erroneously tell the user the plugin activated fine when it didn't
624
+			/** @var RequestInterface $request */
625
+			$request = LoaderFactory::getLoader()->getShared(RequestInterface::class);
626
+			$request->unSetRequestParam('activate', true);
627
+			if (current_user_can('activate_plugins')) {
628
+				// show an error message indicating the plugin didn't activate properly
629
+				EE_Error::add_error($incompatibility_message, __FILE__, __FUNCTION__, __LINE__);
630
+			}
631
+			unset($_GET['activate'], $_REQUEST['activate']);
632
+			if (! function_exists('deactivate_plugins')) {
633
+				require_once ABSPATH . 'wp-admin/includes/plugin.php';
634
+			}
635
+			deactivate_plugins(plugin_basename($addon_settings['main_file_path']));
636
+			// BAIL FROM THE ADDON REGISTRATION PROCESS
637
+			return false;
638
+		}
639
+		// addon IS compatible
640
+		return true;
641
+	}
642
+
643
+
644
+	/**
645
+	 * register namespaces right away before any other files or classes get loaded, but AFTER the version checks
646
+	 *
647
+	 * @param array $addon_settings
648
+	 * @return void
649
+	 */
650
+	private static function _setup_namespaces(array $addon_settings)
651
+	{
652
+		//
653
+		if (
654
+			isset(
655
+				$addon_settings['namespace']['FQNS'],
656
+				$addon_settings['namespace']['DIR']
657
+			)
658
+		) {
659
+			EE_Psr4AutoloaderInit::psr4_loader()->addNamespace(
660
+				$addon_settings['namespace']['FQNS'],
661
+				$addon_settings['namespace']['DIR']
662
+			);
663
+		}
664
+	}
665
+
666
+
667
+	/**
668
+	 * @param string $addon_name
669
+	 * @param array  $addon_settings
670
+	 * @return bool
671
+	 * @throws InvalidArgumentException
672
+	 * @throws InvalidDataTypeException
673
+	 * @throws InvalidInterfaceException
674
+	 */
675
+	private static function _addon_activation(string $addon_name, array $addon_settings): bool
676
+	{
677
+		// this is an activation request
678
+		if (did_action('activate_plugin')) {
679
+			// to find if THIS is the addon that was activated, just check if we have already registered it or not
680
+			// (as the newly-activated addon wasn't around the first time addons were registered).
681
+			// Note: the presence of pue_options in the addon registration options will initialize the $_settings
682
+			// property for the add-on, but the add-on is only partially initialized.  Hence, the additional check.
683
+			if (
684
+				! isset(self::$_settings[ $addon_name ])
685
+				|| (isset(self::$_settings[ $addon_name ])
686
+					&& ! isset(self::$_settings[ $addon_name ]['class_name'])
687
+				)
688
+			) {
689
+				self::$_settings[ $addon_name ] = $addon_settings;
690
+				$addon                          = self::_load_and_init_addon_class($addon_name);
691
+				$addon->set_activation_indicator_option();
692
+				// dont bother setting up the rest of the addon.
693
+				// we know it was just activated and the request will end soon
694
+			}
695
+			return true;
696
+		}
697
+		// make sure addon settings are set correctly without overwriting anything existing
698
+		if (isset(self::$_settings[ $addon_name ])) {
699
+			self::$_settings[ $addon_name ] += $addon_settings;
700
+		} else {
701
+			self::$_settings[ $addon_name ] = $addon_settings;
702
+		}
703
+		return false;
704
+	}
705
+
706
+
707
+	/**
708
+	 * @param string $addon_name
709
+	 * @return void
710
+	 * @throws EE_Error
711
+	 */
712
+	private static function _setup_autoloaders(string $addon_name)
713
+	{
714
+		if (! empty(self::$_settings[ $addon_name ]['autoloader_paths'])) {
715
+			// setup autoloader for single file
716
+			EEH_Autoloader::instance()->register_autoloader(self::$_settings[ $addon_name ]['autoloader_paths']);
717
+		}
718
+		// setup autoloaders for folders
719
+		if (! empty(self::$_settings[ $addon_name ]['autoloader_folders'])) {
720
+			foreach ((array) self::$_settings[ $addon_name ]['autoloader_folders'] as $autoloader_folder) {
721
+				EEH_Autoloader::register_autoloaders_for_each_file_in_folder($autoloader_folder);
722
+			}
723
+		}
724
+	}
725
+
726
+
727
+	/**
728
+	 * register new models and extensions
729
+	 *
730
+	 * @param string $addon_name
731
+	 * @return void
732
+	 * @throws EE_Error
733
+	 */
734
+	private static function _register_models_and_extensions(string $addon_name)
735
+	{
736
+		// register new models
737
+		if (
738
+			! empty(self::$_settings[ $addon_name ]['model_paths'])
739
+			|| ! empty(self::$_settings[ $addon_name ]['class_paths'])
740
+		) {
741
+			EE_Register_Model::register(
742
+				$addon_name,
743
+				[
744
+					'model_paths' => self::$_settings[ $addon_name ]['model_paths'],
745
+					'class_paths' => self::$_settings[ $addon_name ]['class_paths'],
746
+				]
747
+			);
748
+		}
749
+		// register model extensions
750
+		if (
751
+			! empty(self::$_settings[ $addon_name ]['model_extension_paths'])
752
+			|| ! empty(self::$_settings[ $addon_name ]['class_extension_paths'])
753
+		) {
754
+			EE_Register_Model_Extensions::register(
755
+				$addon_name,
756
+				[
757
+					'model_extension_paths' => self::$_settings[ $addon_name ]['model_extension_paths'],
758
+					'class_extension_paths' => self::$_settings[ $addon_name ]['class_extension_paths'],
759
+				]
760
+			);
761
+		}
762
+	}
763
+
764
+
765
+	/**
766
+	 * @param string $addon_name
767
+	 * @return void
768
+	 * @throws EE_Error
769
+	 */
770
+	private static function _register_data_migration_scripts(string $addon_name)
771
+	{
772
+		// setup DMS
773
+		if (! empty(self::$_settings[ $addon_name ]['dms_paths'])) {
774
+			EE_Register_Data_Migration_Scripts::register(
775
+				$addon_name,
776
+				['dms_paths' => self::$_settings[ $addon_name ]['dms_paths']]
777
+			);
778
+		}
779
+	}
780
+
781
+
782
+	/**
783
+	 * @param string $addon_name
784
+	 * @return void
785
+	 * @throws EE_Error
786
+	 */
787
+	private static function _register_config(string $addon_name)
788
+	{
789
+		// if config_class is present let's register config.
790
+		if (! empty(self::$_settings[ $addon_name ]['config_class'])) {
791
+			EE_Register_Config::register(
792
+				self::$_settings[ $addon_name ]['config_class'],
793
+				[
794
+					'config_section' => self::$_settings[ $addon_name ]['config_section'],
795
+					'config_name'    => self::$_settings[ $addon_name ]['config_name'],
796
+				]
797
+			);
798
+		}
799
+	}
800
+
801
+
802
+	/**
803
+	 * @param string $addon_name
804
+	 * @return void
805
+	 * @throws EE_Error
806
+	 */
807
+	private static function _register_admin_pages(string $addon_name)
808
+	{
809
+		if (! empty(self::$_settings[ $addon_name ]['admin_path'])) {
810
+			EE_Register_Admin_Page::register(
811
+				$addon_name,
812
+				['page_path' => self::$_settings[ $addon_name ]['admin_path']]
813
+			);
814
+		}
815
+	}
816
+
817
+
818
+	/**
819
+	 * @param string $addon_name
820
+	 * @return void
821
+	 * @throws EE_Error
822
+	 */
823
+	private static function _register_modules(string $addon_name)
824
+	{
825
+		if (! empty(self::$_settings[ $addon_name ]['module_paths'])) {
826
+			EE_Register_Module::register(
827
+				$addon_name,
828
+				['module_paths' => self::$_settings[ $addon_name ]['module_paths']]
829
+			);
830
+		}
831
+	}
832
+
833
+
834
+	/**
835
+	 * @param string $addon_name
836
+	 * @return void
837
+	 * @throws EE_Error
838
+	 */
839
+	private static function _register_shortcodes(string $addon_name)
840
+	{
841
+		if (
842
+			! empty(self::$_settings[ $addon_name ]['shortcode_paths'])
843
+			|| ! empty(self::$_settings[ $addon_name ]['shortcode_fqcns'])
844
+		) {
845
+			EE_Register_Shortcode::register(
846
+				$addon_name,
847
+				[
848
+					'shortcode_paths' => self::$_settings[ $addon_name ]['shortcode_paths'] ?? [],
849
+					'shortcode_fqcns' => self::$_settings[ $addon_name ]['shortcode_fqcns'] ?? [],
850
+				]
851
+			);
852
+		}
853
+	}
854
+
855
+
856
+	/**
857
+	 * @param string $addon_name
858
+	 * @return void
859
+	 * @throws EE_Error
860
+	 */
861
+	private static function _register_widgets(string $addon_name)
862
+	{
863
+		if (! empty(self::$_settings[ $addon_name ]['widget_paths'])) {
864
+			EE_Register_Widget::register(
865
+				$addon_name,
866
+				['widget_paths' => self::$_settings[ $addon_name ]['widget_paths']]
867
+			);
868
+		}
869
+	}
870
+
871
+
872
+	/**
873
+	 * @param string $addon_name
874
+	 * @return void
875
+	 * @throws EE_Error
876
+	 */
877
+	private static function _register_capabilities(string $addon_name)
878
+	{
879
+		if (! empty(self::$_settings[ $addon_name ]['capabilities'])) {
880
+			EE_Register_Capabilities::register(
881
+				$addon_name,
882
+				[
883
+					'capabilities'    => self::$_settings[ $addon_name ]['capabilities'],
884
+					'capability_maps' => self::$_settings[ $addon_name ]['capability_maps'],
885
+				]
886
+			);
887
+		}
888
+	}
889
+
890
+
891
+	/**
892
+	 * @param string $addon_name
893
+	 * @return void
894
+	 */
895
+	private static function _register_message_types(string $addon_name)
896
+	{
897
+		if (! empty(self::$_settings[ $addon_name ]['message_types'])) {
898
+			add_action(
899
+				'EE_Brewing_Regular___messages_caf',
900
+				['EE_Register_Addon', 'register_message_types']
901
+			);
902
+		}
903
+	}
904
+
905
+
906
+	/**
907
+	 * @param string $addon_name
908
+	 * @return void
909
+	 * @throws EE_Error
910
+	 */
911
+	private static function _register_custom_post_types(string $addon_name)
912
+	{
913
+		if (
914
+			! empty(self::$_settings[ $addon_name ]['custom_post_types'])
915
+			|| ! empty(self::$_settings[ $addon_name ]['custom_taxonomies'])
916
+		) {
917
+			EE_Register_CPT::register(
918
+				$addon_name,
919
+				[
920
+					'cpts'          => self::$_settings[ $addon_name ]['custom_post_types'],
921
+					'cts'           => self::$_settings[ $addon_name ]['custom_taxonomies'],
922
+					'default_terms' => self::$_settings[ $addon_name ]['default_terms'],
923
+				]
924
+			);
925
+		}
926
+	}
927
+
928
+
929
+	/**
930
+	 * @param string $addon_name
931
+	 * @return void
932
+	 * @throws InvalidArgumentException
933
+	 * @throws InvalidInterfaceException
934
+	 * @throws InvalidDataTypeException
935
+	 * @throws DomainException
936
+	 * @throws EE_Error
937
+	 */
938
+	private static function _register_payment_methods(string $addon_name)
939
+	{
940
+		if (! empty(self::$_settings[ $addon_name ]['payment_method_paths'])) {
941
+			EE_Register_Payment_Method::register(
942
+				$addon_name,
943
+				['payment_method_paths' => self::$_settings[ $addon_name ]['payment_method_paths']]
944
+			);
945
+		}
946
+	}
947
+
948
+
949
+	/**
950
+	 * @param string $addon_name
951
+	 * @return void
952
+	 * @throws InvalidArgumentException
953
+	 * @throws InvalidInterfaceException
954
+	 * @throws InvalidDataTypeException
955
+	 * @throws DomainException
956
+	 */
957
+	private static function registerPrivacyPolicies(string $addon_name)
958
+	{
959
+		if (! empty(self::$_settings[ $addon_name ]['privacy_policies'])) {
960
+			EE_Register_Privacy_Policy::register(
961
+				$addon_name,
962
+				self::$_settings[ $addon_name ]['privacy_policies']
963
+			);
964
+		}
965
+	}
966
+
967
+
968
+	/**
969
+	 * @param string $addon_name
970
+	 * @return void
971
+	 */
972
+	private static function registerPersonalDataExporters(string $addon_name)
973
+	{
974
+		if (! empty(self::$_settings[ $addon_name ]['personal_data_exporters'])) {
975
+			EE_Register_Personal_Data_Eraser::register(
976
+				$addon_name,
977
+				self::$_settings[ $addon_name ]['personal_data_exporters']
978
+			);
979
+		}
980
+	}
981
+
982
+
983
+	/**
984
+	 * @param string $addon_name
985
+	 * @return void
986
+	 */
987
+	private static function registerPersonalDataErasers(string $addon_name)
988
+	{
989
+		if (! empty(self::$_settings[ $addon_name ]['personal_data_erasers'])) {
990
+			EE_Register_Personal_Data_Eraser::register(
991
+				$addon_name,
992
+				self::$_settings[ $addon_name ]['personal_data_erasers']
993
+			);
994
+		}
995
+	}
996
+
997
+
998
+	/**
999
+	 * Loads and instantiates the EE_Addon class and adds it onto the registry
1000
+	 *
1001
+	 * @param string $addon_name
1002
+	 * @return EE_Addon
1003
+	 * @throws InvalidArgumentException
1004
+	 * @throws InvalidInterfaceException
1005
+	 * @throws InvalidDataTypeException
1006
+	 */
1007
+	private static function _load_and_init_addon_class(string $addon_name): EE_Addon
1008
+	{
1009
+		$addon = self::$loader->getShared(
1010
+			self::$_settings[ $addon_name ]['class_name'],
1011
+			['EE_Registry::create(addon)' => true]
1012
+		);
1013
+		if (! $addon instanceof EE_Addon) {
1014
+			throw new DomainException(
1015
+				sprintf(
1016
+					esc_html__('The "%1$s" EE_Addon class failed to instantiate!', 'event_espresso'),
1017
+					self::$_settings[ $addon_name ]['class_name']
1018
+				)
1019
+			);
1020
+		}
1021
+		// setter inject dep map if required
1022
+		if ($addon->dependencyMap() === null) {
1023
+			$addon->setDependencyMap(self::$loader->getShared('EE_Dependency_Map'));
1024
+		}
1025
+		// setter inject domain if required
1026
+		EE_Register_Addon::injectAddonDomain($addon_name, $addon);
1027
+
1028
+		$addon->set_name($addon_name);
1029
+		$addon->set_plugin_slug(self::$_settings[ $addon_name ]['plugin_slug']);
1030
+		$addon->set_plugin_basename(self::$_settings[ $addon_name ]['plugin_basename']);
1031
+		$addon->set_main_plugin_file(self::$_settings[ $addon_name ]['main_file_path']);
1032
+		$addon->set_plugin_action_slug(self::$_settings[ $addon_name ]['plugin_action_slug']);
1033
+		$addon->set_plugins_page_row(self::$_settings[ $addon_name ]['plugins_page_row']);
1034
+		$addon->set_version(self::$_settings[ $addon_name ]['version']);
1035
+		$addon->set_min_core_version(self::_effective_version(self::$_settings[ $addon_name ]['min_core_version']));
1036
+		$addon->set_config_section(self::$_settings[ $addon_name ]['config_section']);
1037
+		$addon->set_config_class(self::$_settings[ $addon_name ]['config_class']);
1038
+		$addon->set_config_name(self::$_settings[ $addon_name ]['config_name']);
1039
+		do_action(
1040
+			'AHEE__EE_Register_Addon___load_and_init_addon_class',
1041
+			$addon,
1042
+			$addon_name,
1043
+			self::$_settings
1044
+		);
1045
+		// unfortunately this can't be hooked in upon construction,
1046
+		// because we don't have the plugin's mainfile path upon construction.
1047
+		register_deactivation_hook($addon->get_main_plugin_file(), [$addon, 'deactivation']);
1048
+		// call any additional admin_callback functions during load_admin_controller hook
1049
+		if (! empty(self::$_settings[ $addon_name ]['admin_callback'])) {
1050
+			add_action(
1051
+				'AHEE__EE_System__load_controllers__load_admin_controllers',
1052
+				[$addon, self::$_settings[ $addon_name ]['admin_callback']]
1053
+			);
1054
+		}
1055
+		return $addon;
1056
+	}
1057
+
1058
+
1059
+	/**
1060
+	 * @param string   $addon_name
1061
+	 * @param EE_Addon $addon
1062
+	 * @since   4.10.13.p
1063
+	 */
1064
+	private static function injectAddonDomain(string $addon_name, EE_Addon $addon)
1065
+	{
1066
+		if ($addon instanceof RequiresDomainInterface && $addon->domain() === null) {
1067
+			// using supplied Domain object
1068
+			$domain = self::$_settings[ $addon_name ]['domain'] instanceof DomainInterface
1069
+				? self::$_settings[ $addon_name ]['domain']
1070
+				: null;
1071
+			// or construct one using Domain FQCN
1072
+			if ($domain === null && self::$_settings[ $addon_name ]['domain_fqcn'] !== '') {
1073
+				$domain = self::$loader->getShared(
1074
+					self::$_settings[ $addon_name ]['domain_fqcn'],
1075
+					[
1076
+						new EventEspresso\core\domain\values\FilePath(
1077
+							self::$_settings[ $addon_name ]['main_file_path']
1078
+						),
1079
+						EventEspresso\core\domain\values\Version::fromString(
1080
+							self::$_settings[ $addon_name ]['version']
1081
+						),
1082
+					]
1083
+				);
1084
+			}
1085
+			if ($domain instanceof DomainInterface) {
1086
+				$addon->setDomain($domain);
1087
+			}
1088
+		}
1089
+	}
1090
+
1091
+
1092
+	/**
1093
+	 * @return void
1094
+	 * @deprecated $VID:$
1095
+	 */
1096
+	public static function load_pue_update()
1097
+	{
1098
+		RegisterAddonPUE::loadPueUpdate();
1099
+	}
1100
+
1101
+
1102
+	/**
1103
+	 * Callback for EE_Brewing_Regular__messages_caf hook used to register message types.
1104
+	 *
1105
+	 * @return void
1106
+	 * @throws EE_Error
1107
+	 * @since 4.4.0
1108
+	 */
1109
+	public static function register_message_types()
1110
+	{
1111
+		foreach (self::$_settings as $settings) {
1112
+			if (! empty($settings['message_types'])) {
1113
+				foreach ((array) $settings['message_types'] as $message_type => $message_type_settings) {
1114
+					EE_Register_Message_Type::register($message_type, $message_type_settings);
1115
+				}
1116
+			}
1117
+		}
1118
+	}
1119
+
1120
+
1121
+	/**
1122
+	 * This deregisters an addon that was previously registered with a specific addon_name.
1123
+	 *
1124
+	 * @param string $addon_name the name for the addon that was previously registered
1125
+	 * @throws DomainException
1126
+	 * @throws InvalidArgumentException
1127
+	 * @throws InvalidDataTypeException
1128
+	 * @throws InvalidInterfaceException
1129
+	 * @since    4.3.0
1130
+	 */
1131
+	public static function deregister(string $addon_name = '')
1132
+	{
1133
+		if (isset(self::$_settings[ $addon_name ]['class_name'])) {
1134
+			try {
1135
+				do_action('AHEE__EE_Register_Addon__deregister__before', $addon_name);
1136
+				$class_name = self::$_settings[ $addon_name ]['class_name'];
1137
+				if (! empty(self::$_settings[ $addon_name ]['dms_paths'])) {
1138
+					// setup DMS
1139
+					EE_Register_Data_Migration_Scripts::deregister($addon_name);
1140
+				}
1141
+				if (! empty(self::$_settings[ $addon_name ]['admin_path'])) {
1142
+					// register admin page
1143
+					EE_Register_Admin_Page::deregister($addon_name);
1144
+				}
1145
+				if (! empty(self::$_settings[ $addon_name ]['module_paths'])) {
1146
+					// add to list of modules to be registered
1147
+					EE_Register_Module::deregister($addon_name);
1148
+				}
1149
+				if (
1150
+					! empty(self::$_settings[ $addon_name ]['shortcode_paths'])
1151
+					|| ! empty(self::$_settings[ $addon_name ]['shortcode_fqcns'])
1152
+				) {
1153
+					// add to list of shortcodes to be registered
1154
+					EE_Register_Shortcode::deregister($addon_name);
1155
+				}
1156
+				if (! empty(self::$_settings[ $addon_name ]['config_class'])) {
1157
+					// if config_class present let's register config.
1158
+					EE_Register_Config::deregister(self::$_settings[ $addon_name ]['config_class']);
1159
+				}
1160
+				if (! empty(self::$_settings[ $addon_name ]['widget_paths'])) {
1161
+					// add to list of widgets to be registered
1162
+					EE_Register_Widget::deregister($addon_name);
1163
+				}
1164
+				if (
1165
+					! empty(self::$_settings[ $addon_name ]['model_paths'])
1166
+					|| ! empty(self::$_settings[ $addon_name ]['class_paths'])
1167
+				) {
1168
+					// add to list of shortcodes to be registered
1169
+					EE_Register_Model::deregister($addon_name);
1170
+				}
1171
+				if (
1172
+					! empty(self::$_settings[ $addon_name ]['model_extension_paths'])
1173
+					|| ! empty(self::$_settings[ $addon_name ]['class_extension_paths'])
1174
+				) {
1175
+					// add to list of shortcodes to be registered
1176
+					EE_Register_Model_Extensions::deregister($addon_name);
1177
+				}
1178
+				if (! empty(self::$_settings[ $addon_name ]['message_types'])) {
1179
+					foreach ((array) self::$_settings[ $addon_name ]['message_types'] as $message_type => $message_type_settings) {
1180
+						EE_Register_Message_Type::deregister($message_type);
1181
+					}
1182
+				}
1183
+				// deregister capabilities for addon
1184
+				if (
1185
+					! empty(self::$_settings[ $addon_name ]['capabilities'])
1186
+					|| ! empty(self::$_settings[ $addon_name ]['capability_maps'])
1187
+				) {
1188
+					EE_Register_Capabilities::deregister($addon_name);
1189
+				}
1190
+				// deregister custom_post_types for addon
1191
+				if (! empty(self::$_settings[ $addon_name ]['custom_post_types'])) {
1192
+					EE_Register_CPT::deregister($addon_name);
1193
+				}
1194
+				if (! empty(self::$_settings[ $addon_name ]['payment_method_paths'])) {
1195
+					EE_Register_Payment_Method::deregister($addon_name);
1196
+				}
1197
+				$addon = EE_Registry::instance()->getAddon($class_name);
1198
+				if ($addon instanceof EE_Addon) {
1199
+					remove_action(
1200
+						'deactivate_' . $addon->get_main_plugin_file_basename(),
1201
+						[$addon, 'deactivation']
1202
+					);
1203
+					remove_action(
1204
+						'AHEE__EE_System__perform_activations_upgrades_and_migrations',
1205
+						[$addon, 'initialize_db_if_no_migrations_required']
1206
+					);
1207
+					// remove `after_registration` call
1208
+					remove_action(
1209
+						'AHEE__EE_System__load_espresso_addons__complete',
1210
+						[$addon, 'after_registration'],
1211
+						999
1212
+					);
1213
+				}
1214
+				EE_Registry::instance()->removeAddon($class_name);
1215
+				LoaderFactory::getLoader()->remove($class_name);
1216
+			} catch (OutOfBoundsException $addon_not_yet_registered_exception) {
1217
+				// the add-on was not yet registered in the registry,
1218
+				// so RegistryContainer::__get() throws this exception.
1219
+				// also no need to worry about this or log it,
1220
+				// it's ok to deregister an add-on before its registered in the registry
1221
+			} catch (Exception $e) {
1222
+				new ExceptionLogger($e);
1223
+			}
1224
+			unset(self::$_settings[ $addon_name ]);
1225
+			do_action('AHEE__EE_Register_Addon__deregister__after', $addon_name);
1226
+		}
1227
+	}
1228 1228
 }
Please login to merge, or discard this patch.
core/libraries/batch/BatchRequestProcessor.php 1 patch
Indentation   +303 added lines, -303 removed lines patch added patch discarded remove patch
@@ -31,307 +31,307 @@
 block discarded – undo
31 31
  */
32 32
 class BatchRequestProcessor
33 33
 {
34
-    /**
35
-     * Current job's ID (if assigned)
36
-     *
37
-     * @var string|null
38
-     */
39
-    protected $_job_id = '';
40
-
41
-    /**
42
-     * Current job's parameters
43
-     *
44
-     * @var JobParameters|null
45
-     */
46
-    protected $_job_parameters = null;
47
-
48
-    /**
49
-     * @var LoaderInterface|null
50
-     */
51
-    private $loader;
52
-
53
-
54
-    /**
55
-     * @var RequestInterface|null
56
-     */
57
-    private $request;
58
-
59
-
60
-    /**
61
-     * BatchRequestProcessor constructor.
62
-     *
63
-     * @param LoaderInterface  $loader
64
-     * @param RequestInterface $request
65
-     */
66
-    public function __construct(LoaderInterface $loader, RequestInterface $request)
67
-    {
68
-        $this->loader  = $loader;
69
-        $this->request = $request;
70
-    }
71
-
72
-
73
-    /**
74
-     * @param string $job_id
75
-     * @param string $job_handler_class
76
-     * @param array  $request_data
77
-     * @return JobHandlerInterface
78
-     * @throws BatchRequestException
79
-     * @since   $VID:$
80
-     */
81
-    private function initializeJobHandler(
82
-        string $job_id,
83
-        string $job_handler_class = '',
84
-        array $request_data = []
85
-    ): JobHandlerInterface {
86
-        $this->_job_id         = $job_id;
87
-        $this->_job_parameters = ! empty($job_handler_class)
88
-            ? new JobParameters($this->_job_id, $job_handler_class, $request_data)
89
-            : JobParameters::load($this->_job_id);
90
-        $this->_job_parameters->save();
91
-        return $this->instantiateBatchJobHandlerFromJobParameters($this->_job_parameters);
92
-    }
93
-
94
-
95
-    /**
96
-     * Creates a job for the specified batch handler class (which should be autoloaded)
97
-     * and the specified request data
98
-     *
99
-     * @return JobStepResponse
100
-     */
101
-    public function createJob(): JobStepResponse
102
-    {
103
-        try {
104
-            $request_data = $this->request->requestParams();
105
-            $job_id       = $this->request->getRequestParam(
106
-                'job_code',
107
-                wp_generate_password(15, false)
108
-            );
109
-            $service      = $this->request->getRequestParam('job_handler', '', 'fqcn');
110
-            $assessment   = $this->request->getRequestParam('job_assessment', '', 'fqcn');
111
-            $job_class    = $assessment !== '' ? $assessment : $service;
112
-            // replace escaped escaped backslashes with escaped unescaped backslashes :lol:
113
-            $job_class    = str_replace('\\\\', '\\', urldecode($job_class));
114
-            $job_handler  = $this->initializeJobHandler($job_id, $job_class, $request_data);
115
-            $job_response = $job_handler->createJob($this->_job_parameters);
116
-            $this->validateResponse('createJob', $this->_job_id, $job_response);
117
-            $success = $this->_job_parameters->save();
118
-            if (! $success) {
119
-                throw new BatchRequestException(
120
-                    sprintf(
121
-                        esc_html__(
122
-                            'Could not save job %1$s to the Wordpress Options table. These were the arguments used: %2$s',
123
-                            'event_espresso'
124
-                        ),
125
-                        $this->_job_id,
126
-                        wp_json_encode($request_data)
127
-                    )
128
-                );
129
-            }
130
-        } catch (Exception $e) {
131
-            $job_response = $this->_get_error_response($e, 'createJob');
132
-        }
133
-        return $job_response;
134
-    }
135
-
136
-
137
-    /**
138
-     * Retrieves the job's arguments
139
-     *
140
-     * @param string $job_id
141
-     * @param int    $batch_size
142
-     * @return JobStepResponse
143
-     */
144
-    public function continueJob(string $job_id, int $batch_size = 50): JobStepResponse
145
-    {
146
-        try {
147
-            $batch_size   = defined('EE_BATCHRUNNER_BATCH_SIZE')
148
-                ? EE_BATCHRUNNER_BATCH_SIZE
149
-                : $batch_size;
150
-            $job_handler  = $this->initializeJobHandler($job_id);
151
-            $job_response = $job_handler->continueJob($this->_job_parameters, $batch_size);
152
-            $this->validateResponse('continueJob', $this->_job_id, $job_response);
153
-            $this->_job_parameters->save();
154
-        } catch (Exception $e) {
155
-            $job_response = $this->_get_error_response($e, 'continueJob');
156
-        }
157
-        return $job_response;
158
-    }
159
-
160
-
161
-    /**
162
-     * Retrieves the job's arguments
163
-     *
164
-     * @param string $job_id
165
-     * @return JobStepResponse
166
-     */
167
-    public function advanceJob(string $job_id): JobStepResponse
168
-    {
169
-        try {
170
-            $job_handler  = $this->initializeJobHandler($job_id);
171
-            $job_response = $job_handler->advanceJob($this->_job_parameters);
172
-            $this->validateResponse('advanceJob', $this->_job_id, $job_response);
173
-            $this->_job_parameters->save();
174
-        } catch (Exception $e) {
175
-            $job_response = $this->_get_error_response($e, 'advanceJob');
176
-        }
177
-        return $job_response;
178
-    }
179
-
180
-
181
-    /**
182
-     * Forces a job to be cleaned up
183
-     *
184
-     * @param string $job_id
185
-     * @return JobStepResponse
186
-     */
187
-    public function cleanupJob(string $job_id): JobStepResponse
188
-    {
189
-        try {
190
-            $job_handler  = $this->initializeJobHandler($job_id);
191
-            $job_response = $job_handler->cleanupJob($this->_job_parameters);
192
-            $this->validateResponse('cleanupJob', $this->_job_id, $job_response);
193
-            $this->_job_parameters->set_status(JobParameters::status_cleaned_up);
194
-            $this->_job_parameters->delete();
195
-        } catch (Exception $e) {
196
-            $job_response = $this->_get_error_response($e, 'cleanupJob');
197
-        }
198
-        return $job_response;
199
-    }
200
-
201
-
202
-    /**
203
-     * Instantiates an object of type $classname, which implements
204
-     * JobHandlerInterface
205
-     *
206
-     * @param JobParameters $job_parameters
207
-     * @return JobHandlerInterface
208
-     * @throws BatchRequestException
209
-     */
210
-    public function instantiateBatchJobHandlerFromJobParameters(JobParameters $job_parameters): JobHandlerInterface
211
-    {
212
-        $this->verifyJobHandlerClassExists($job_parameters);
213
-        $job_handler = $this->loader->getNew($job_parameters->classname());
214
-        $this->validateJobHandler($job_handler, $job_parameters);
215
-        $job_handler->setRequestData($job_parameters->request_data());
216
-        if ($job_handler instanceof DbServiceJobHandler) {
217
-            $job_handler->initialize($job_parameters);
218
-        }
219
-        return $job_handler;
220
-    }
221
-
222
-
223
-    /**
224
-     * Instantiates an object of type $classname, which implements
225
-     * JobHandlerInterface
226
-     *
227
-     * @param string $classname
228
-     * @param array  $request_data
229
-     * @return JobHandlerInterface
230
-     * @throws BatchRequestException
231
-     * @deprecatd $VID:$
232
-     */
233
-    public function instantiate_batch_job_handler_from_classname(
234
-        string $classname,
235
-        array $request_data = []
236
-    ): JobHandlerInterface {
237
-        return $this->instantiateBatchJobHandlerFromJobParameters($this->_job_parameters);
238
-    }
239
-
240
-
241
-    /**
242
-     * Creates a valid JobStepResponse object from an exception and method name.
243
-     *
244
-     * @param Exception $exception
245
-     * @param string    $method_name
246
-     * @return JobStepResponse
247
-     */
248
-    protected function _get_error_response(Exception $exception, string $method_name): JobStepResponse
249
-    {
250
-        if (! $this->_job_parameters instanceof JobParameters) {
251
-            $this->_job_parameters = new JobParameters($this->_job_id, esc_html__('__Unknown__', 'event_espresso'), []);
252
-        }
253
-        $this->_job_parameters->set_status(JobParameters::status_error);
254
-
255
-        $error_message = sprintf(
256
-            esc_html__(
257
-                '%1$sWhile running %3$s the following %2$s occurred: %4$s %5$s',
258
-                'event_espresso'
259
-            ),
260
-            '<h4>',
261
-            get_class($exception),
262
-            '<code>' . 'BatchRunner::' . $method_name . '()</code>',
263
-            '</h4><p>' . $exception->getMessage() . '</p>',
264
-            '<pre>' . $exception->getTraceAsString() . '</pre>'
265
-        );
266
-        return new JobStepResponse(
267
-            $this->_job_parameters,
268
-            "<div class='ee-batch-runner__error ee-status-outline ee-status-outline--error'>$error_message</div>"
269
-        );
270
-    }
271
-
272
-
273
-    /**
274
-     * @param string $function
275
-     * @param string $job_id
276
-     * @param        $job_response
277
-     * @throws BatchRequestException
278
-     * @since   $VID:$
279
-     */
280
-    private function validateResponse(string $function, string $job_id, $job_response)
281
-    {
282
-        if (! $job_response instanceof JobStepResponse) {
283
-            throw new BatchRequestException(
284
-                sprintf(
285
-                    esc_html__(
286
-                        'The class implementing JobHandlerInterface did not return a JobStepResponse when %1$s was called for job %2$s. It needs to return one or throw an Exception',
287
-                        'event_espresso'
288
-                    ),
289
-                    $function,
290
-                    $job_id
291
-                )
292
-            );
293
-        }
294
-    }
295
-
296
-
297
-    /**
298
-     * @param JobParameters $job_parameters
299
-     * @throws BatchRequestException
300
-     * @since   $VID:$
301
-     */
302
-    private function verifyJobHandlerClassExists(JobParameters $job_parameters)
303
-    {
304
-        if (! class_exists($job_parameters->classname())) {
305
-            throw new BatchRequestException(
306
-                sprintf(
307
-                    esc_html__(
308
-                        'The class %1$s does not exist, and so could not be used for running a job. It should implement JobHandlerInterface.',
309
-                        'event_espresso'
310
-                    ),
311
-                    $job_parameters->classname()
312
-                )
313
-            );
314
-        }
315
-    }
316
-
317
-    /**
318
-     * @param JobHandlerInterface|NULL $job_handler
319
-     * @param JobParameters $job_parameters
320
-     * @throws BatchRequestException
321
-     * @since   $VID:$
322
-     */
323
-    private function validateJobHandler(?JobHandlerInterface $job_handler, JobParameters $job_parameters)
324
-    {
325
-        if (! $job_handler instanceof JobHandlerInterface) {
326
-            throw new BatchRequestException(
327
-                sprintf(
328
-                    esc_html__(
329
-                        'The class %1$s does not implement JobHandlerInterface and so could not be used for running a job',
330
-                        'event_espresso'
331
-                    ),
332
-                    $job_parameters->classname()
333
-                )
334
-            );
335
-        }
336
-    }
34
+	/**
35
+	 * Current job's ID (if assigned)
36
+	 *
37
+	 * @var string|null
38
+	 */
39
+	protected $_job_id = '';
40
+
41
+	/**
42
+	 * Current job's parameters
43
+	 *
44
+	 * @var JobParameters|null
45
+	 */
46
+	protected $_job_parameters = null;
47
+
48
+	/**
49
+	 * @var LoaderInterface|null
50
+	 */
51
+	private $loader;
52
+
53
+
54
+	/**
55
+	 * @var RequestInterface|null
56
+	 */
57
+	private $request;
58
+
59
+
60
+	/**
61
+	 * BatchRequestProcessor constructor.
62
+	 *
63
+	 * @param LoaderInterface  $loader
64
+	 * @param RequestInterface $request
65
+	 */
66
+	public function __construct(LoaderInterface $loader, RequestInterface $request)
67
+	{
68
+		$this->loader  = $loader;
69
+		$this->request = $request;
70
+	}
71
+
72
+
73
+	/**
74
+	 * @param string $job_id
75
+	 * @param string $job_handler_class
76
+	 * @param array  $request_data
77
+	 * @return JobHandlerInterface
78
+	 * @throws BatchRequestException
79
+	 * @since   $VID:$
80
+	 */
81
+	private function initializeJobHandler(
82
+		string $job_id,
83
+		string $job_handler_class = '',
84
+		array $request_data = []
85
+	): JobHandlerInterface {
86
+		$this->_job_id         = $job_id;
87
+		$this->_job_parameters = ! empty($job_handler_class)
88
+			? new JobParameters($this->_job_id, $job_handler_class, $request_data)
89
+			: JobParameters::load($this->_job_id);
90
+		$this->_job_parameters->save();
91
+		return $this->instantiateBatchJobHandlerFromJobParameters($this->_job_parameters);
92
+	}
93
+
94
+
95
+	/**
96
+	 * Creates a job for the specified batch handler class (which should be autoloaded)
97
+	 * and the specified request data
98
+	 *
99
+	 * @return JobStepResponse
100
+	 */
101
+	public function createJob(): JobStepResponse
102
+	{
103
+		try {
104
+			$request_data = $this->request->requestParams();
105
+			$job_id       = $this->request->getRequestParam(
106
+				'job_code',
107
+				wp_generate_password(15, false)
108
+			);
109
+			$service      = $this->request->getRequestParam('job_handler', '', 'fqcn');
110
+			$assessment   = $this->request->getRequestParam('job_assessment', '', 'fqcn');
111
+			$job_class    = $assessment !== '' ? $assessment : $service;
112
+			// replace escaped escaped backslashes with escaped unescaped backslashes :lol:
113
+			$job_class    = str_replace('\\\\', '\\', urldecode($job_class));
114
+			$job_handler  = $this->initializeJobHandler($job_id, $job_class, $request_data);
115
+			$job_response = $job_handler->createJob($this->_job_parameters);
116
+			$this->validateResponse('createJob', $this->_job_id, $job_response);
117
+			$success = $this->_job_parameters->save();
118
+			if (! $success) {
119
+				throw new BatchRequestException(
120
+					sprintf(
121
+						esc_html__(
122
+							'Could not save job %1$s to the Wordpress Options table. These were the arguments used: %2$s',
123
+							'event_espresso'
124
+						),
125
+						$this->_job_id,
126
+						wp_json_encode($request_data)
127
+					)
128
+				);
129
+			}
130
+		} catch (Exception $e) {
131
+			$job_response = $this->_get_error_response($e, 'createJob');
132
+		}
133
+		return $job_response;
134
+	}
135
+
136
+
137
+	/**
138
+	 * Retrieves the job's arguments
139
+	 *
140
+	 * @param string $job_id
141
+	 * @param int    $batch_size
142
+	 * @return JobStepResponse
143
+	 */
144
+	public function continueJob(string $job_id, int $batch_size = 50): JobStepResponse
145
+	{
146
+		try {
147
+			$batch_size   = defined('EE_BATCHRUNNER_BATCH_SIZE')
148
+				? EE_BATCHRUNNER_BATCH_SIZE
149
+				: $batch_size;
150
+			$job_handler  = $this->initializeJobHandler($job_id);
151
+			$job_response = $job_handler->continueJob($this->_job_parameters, $batch_size);
152
+			$this->validateResponse('continueJob', $this->_job_id, $job_response);
153
+			$this->_job_parameters->save();
154
+		} catch (Exception $e) {
155
+			$job_response = $this->_get_error_response($e, 'continueJob');
156
+		}
157
+		return $job_response;
158
+	}
159
+
160
+
161
+	/**
162
+	 * Retrieves the job's arguments
163
+	 *
164
+	 * @param string $job_id
165
+	 * @return JobStepResponse
166
+	 */
167
+	public function advanceJob(string $job_id): JobStepResponse
168
+	{
169
+		try {
170
+			$job_handler  = $this->initializeJobHandler($job_id);
171
+			$job_response = $job_handler->advanceJob($this->_job_parameters);
172
+			$this->validateResponse('advanceJob', $this->_job_id, $job_response);
173
+			$this->_job_parameters->save();
174
+		} catch (Exception $e) {
175
+			$job_response = $this->_get_error_response($e, 'advanceJob');
176
+		}
177
+		return $job_response;
178
+	}
179
+
180
+
181
+	/**
182
+	 * Forces a job to be cleaned up
183
+	 *
184
+	 * @param string $job_id
185
+	 * @return JobStepResponse
186
+	 */
187
+	public function cleanupJob(string $job_id): JobStepResponse
188
+	{
189
+		try {
190
+			$job_handler  = $this->initializeJobHandler($job_id);
191
+			$job_response = $job_handler->cleanupJob($this->_job_parameters);
192
+			$this->validateResponse('cleanupJob', $this->_job_id, $job_response);
193
+			$this->_job_parameters->set_status(JobParameters::status_cleaned_up);
194
+			$this->_job_parameters->delete();
195
+		} catch (Exception $e) {
196
+			$job_response = $this->_get_error_response($e, 'cleanupJob');
197
+		}
198
+		return $job_response;
199
+	}
200
+
201
+
202
+	/**
203
+	 * Instantiates an object of type $classname, which implements
204
+	 * JobHandlerInterface
205
+	 *
206
+	 * @param JobParameters $job_parameters
207
+	 * @return JobHandlerInterface
208
+	 * @throws BatchRequestException
209
+	 */
210
+	public function instantiateBatchJobHandlerFromJobParameters(JobParameters $job_parameters): JobHandlerInterface
211
+	{
212
+		$this->verifyJobHandlerClassExists($job_parameters);
213
+		$job_handler = $this->loader->getNew($job_parameters->classname());
214
+		$this->validateJobHandler($job_handler, $job_parameters);
215
+		$job_handler->setRequestData($job_parameters->request_data());
216
+		if ($job_handler instanceof DbServiceJobHandler) {
217
+			$job_handler->initialize($job_parameters);
218
+		}
219
+		return $job_handler;
220
+	}
221
+
222
+
223
+	/**
224
+	 * Instantiates an object of type $classname, which implements
225
+	 * JobHandlerInterface
226
+	 *
227
+	 * @param string $classname
228
+	 * @param array  $request_data
229
+	 * @return JobHandlerInterface
230
+	 * @throws BatchRequestException
231
+	 * @deprecatd $VID:$
232
+	 */
233
+	public function instantiate_batch_job_handler_from_classname(
234
+		string $classname,
235
+		array $request_data = []
236
+	): JobHandlerInterface {
237
+		return $this->instantiateBatchJobHandlerFromJobParameters($this->_job_parameters);
238
+	}
239
+
240
+
241
+	/**
242
+	 * Creates a valid JobStepResponse object from an exception and method name.
243
+	 *
244
+	 * @param Exception $exception
245
+	 * @param string    $method_name
246
+	 * @return JobStepResponse
247
+	 */
248
+	protected function _get_error_response(Exception $exception, string $method_name): JobStepResponse
249
+	{
250
+		if (! $this->_job_parameters instanceof JobParameters) {
251
+			$this->_job_parameters = new JobParameters($this->_job_id, esc_html__('__Unknown__', 'event_espresso'), []);
252
+		}
253
+		$this->_job_parameters->set_status(JobParameters::status_error);
254
+
255
+		$error_message = sprintf(
256
+			esc_html__(
257
+				'%1$sWhile running %3$s the following %2$s occurred: %4$s %5$s',
258
+				'event_espresso'
259
+			),
260
+			'<h4>',
261
+			get_class($exception),
262
+			'<code>' . 'BatchRunner::' . $method_name . '()</code>',
263
+			'</h4><p>' . $exception->getMessage() . '</p>',
264
+			'<pre>' . $exception->getTraceAsString() . '</pre>'
265
+		);
266
+		return new JobStepResponse(
267
+			$this->_job_parameters,
268
+			"<div class='ee-batch-runner__error ee-status-outline ee-status-outline--error'>$error_message</div>"
269
+		);
270
+	}
271
+
272
+
273
+	/**
274
+	 * @param string $function
275
+	 * @param string $job_id
276
+	 * @param        $job_response
277
+	 * @throws BatchRequestException
278
+	 * @since   $VID:$
279
+	 */
280
+	private function validateResponse(string $function, string $job_id, $job_response)
281
+	{
282
+		if (! $job_response instanceof JobStepResponse) {
283
+			throw new BatchRequestException(
284
+				sprintf(
285
+					esc_html__(
286
+						'The class implementing JobHandlerInterface did not return a JobStepResponse when %1$s was called for job %2$s. It needs to return one or throw an Exception',
287
+						'event_espresso'
288
+					),
289
+					$function,
290
+					$job_id
291
+				)
292
+			);
293
+		}
294
+	}
295
+
296
+
297
+	/**
298
+	 * @param JobParameters $job_parameters
299
+	 * @throws BatchRequestException
300
+	 * @since   $VID:$
301
+	 */
302
+	private function verifyJobHandlerClassExists(JobParameters $job_parameters)
303
+	{
304
+		if (! class_exists($job_parameters->classname())) {
305
+			throw new BatchRequestException(
306
+				sprintf(
307
+					esc_html__(
308
+						'The class %1$s does not exist, and so could not be used for running a job. It should implement JobHandlerInterface.',
309
+						'event_espresso'
310
+					),
311
+					$job_parameters->classname()
312
+				)
313
+			);
314
+		}
315
+	}
316
+
317
+	/**
318
+	 * @param JobHandlerInterface|NULL $job_handler
319
+	 * @param JobParameters $job_parameters
320
+	 * @throws BatchRequestException
321
+	 * @since   $VID:$
322
+	 */
323
+	private function validateJobHandler(?JobHandlerInterface $job_handler, JobParameters $job_parameters)
324
+	{
325
+		if (! $job_handler instanceof JobHandlerInterface) {
326
+			throw new BatchRequestException(
327
+				sprintf(
328
+					esc_html__(
329
+						'The class %1$s does not implement JobHandlerInterface and so could not be used for running a job',
330
+						'event_espresso'
331
+					),
332
+					$job_parameters->classname()
333
+				)
334
+			);
335
+		}
336
+	}
337 337
 }
Please login to merge, or discard this patch.
core/db_classes/EE_Base_Class.class.php 1 patch
Indentation   +3358 added lines, -3358 removed lines patch added patch discarded remove patch
@@ -13,3374 +13,3374 @@
 block discarded – undo
13 13
  */
14 14
 abstract class EE_Base_Class
15 15
 {
16
-    /**
17
-     * This is an array of the original properties and values provided during construction
18
-     * of this model object. (keys are model field names, values are their values).
19
-     * This list is important to remember so that when we are merging data from the db, we know
20
-     * which values to override and which to not override.
21
-     *
22
-     * @var array
23
-     */
24
-    protected $_props_n_values_provided_in_constructor;
25
-
26
-    /**
27
-     * Timezone
28
-     * This gets set by the "set_timezone()" method so that we know what timezone incoming strings|timestamps are in.
29
-     * This can also be used before a get to set what timezone you want strings coming out of the object to be in.  NOT
30
-     * all EE_Base_Class child classes use this property but any that use a EE_Datetime_Field data type will have
31
-     * access to it.
32
-     *
33
-     * @var string
34
-     */
35
-    protected $_timezone;
36
-
37
-    /**
38
-     * date format
39
-     * pattern or format for displaying dates
40
-     *
41
-     * @var string $_dt_frmt
42
-     */
43
-    protected $_dt_frmt;
44
-
45
-    /**
46
-     * time format
47
-     * pattern or format for displaying time
48
-     *
49
-     * @var string $_tm_frmt
50
-     */
51
-    protected $_tm_frmt;
52
-
53
-    /**
54
-     * This property is for holding a cached array of object properties indexed by property name as the key.
55
-     * The purpose of this is for setting a cache on properties that may have calculated values after a
56
-     * prepare_for_get.  That way the cache can be checked first and the calculated property returned instead of having
57
-     * to recalculate. Used by _set_cached_property() and _get_cached_property() methods.
58
-     *
59
-     * @var array
60
-     */
61
-    protected $_cached_properties = array();
62
-
63
-    /**
64
-     * An array containing keys of the related model, and values are either an array of related mode objects or a
65
-     * single
66
-     * related model object. see the model's _model_relations. The keys should match those specified. And if the
67
-     * relation is of type EE_Belongs_To (or one of its children), then there should only be ONE related model object,
68
-     * all others have an array)
69
-     *
70
-     * @var array
71
-     */
72
-    protected $_model_relations = array();
73
-
74
-    /**
75
-     * Array where keys are field names (see the model's _fields property) and values are their values. To see what
76
-     * their types should be, look at what that field object returns on its prepare_for_get and prepare_for_set methods)
77
-     *
78
-     * @var array
79
-     */
80
-    protected $_fields = array();
81
-
82
-    /**
83
-     * @var boolean indicating whether or not this model object is intended to ever be saved
84
-     * For example, we might create model objects intended to only be used for the duration
85
-     * of this request and to be thrown away, and if they were accidentally saved
86
-     * it would be a bug.
87
-     */
88
-    protected $_allow_persist = true;
89
-
90
-    /**
91
-     * @var boolean indicating whether or not this model object's properties have changed since construction
92
-     */
93
-    protected $_has_changes = false;
94
-
95
-    /**
96
-     * @var EEM_Base
97
-     */
98
-    protected $_model;
99
-
100
-    /**
101
-     * This is a cache of results from custom selections done on a query that constructs this entity. The only purpose
102
-     * for these values is for retrieval of the results, they are not further queryable and they are not persisted to
103
-     * the db.  They also do not automatically update if there are any changes to the data that produced their results.
104
-     * The format is a simple array of field_alias => field_value.  So for instance if a custom select was something
105
-     * like,  "Select COUNT(Registration.REG_ID) as Registration_Count ...", then the resulting value will be in this
106
-     * array as:
107
-     * array(
108
-     *  'Registration_Count' => 24
109
-     * );
110
-     * Note: if the custom select configuration for the query included a data type, the value will be in the data type
111
-     * provided for the query (@see EventEspresso\core\domain\values\model\CustomSelects::__construct phpdocs for more
112
-     * info)
113
-     *
114
-     * @var array
115
-     */
116
-    protected $custom_selection_results = array();
117
-
118
-
119
-    /**
120
-     * basic constructor for Event Espresso classes, performs any necessary initialization, and verifies it's children
121
-     * play nice
122
-     *
123
-     * @param array   $fieldValues                             where each key is a field (ie, array key in the 2nd
124
-     *                                                         layer of the model's _fields array, (eg, EVT_ID,
125
-     *                                                         TXN_amount, QST_name, etc) and values are their values
126
-     * @param boolean $bydb                                    a flag for setting if the class is instantiated by the
127
-     *                                                         corresponding db model or not.
128
-     * @param string  $timezone                                indicate what timezone you want any datetime fields to
129
-     *                                                         be in when instantiating a EE_Base_Class object.
130
-     * @param array   $date_formats                            An array of date formats to set on construct where first
131
-     *                                                         value is the date_format and second value is the time
132
-     *                                                         format.
133
-     * @throws InvalidArgumentException
134
-     * @throws InvalidInterfaceException
135
-     * @throws InvalidDataTypeException
136
-     * @throws EE_Error
137
-     * @throws ReflectionException
138
-     */
139
-    protected function __construct($fieldValues = array(), $bydb = false, $timezone = '', $date_formats = array())
140
-    {
141
-        $className = get_class($this);
142
-        do_action("AHEE__{$className}__construct", $this, $fieldValues);
143
-        $model = $this->get_model();
144
-        $model_fields = $model->field_settings(false);
145
-        // ensure $fieldValues is an array
146
-        $fieldValues = is_array($fieldValues) ? $fieldValues : array($fieldValues);
147
-        // verify client code has not passed any invalid field names
148
-        foreach ($fieldValues as $field_name => $field_value) {
149
-            if (! isset($model_fields[ $field_name ])) {
150
-                throw new EE_Error(
151
-                    sprintf(
152
-                        esc_html__(
153
-                            'Invalid field (%s) passed to constructor of %s. Allowed fields are :%s',
154
-                            'event_espresso'
155
-                        ),
156
-                        $field_name,
157
-                        get_class($this),
158
-                        implode(', ', array_keys($model_fields))
159
-                    )
160
-                );
161
-            }
162
-        }
163
-        $this->_timezone = EEH_DTT_Helper::get_valid_timezone_string($timezone);
164
-        if (! empty($date_formats) && is_array($date_formats)) {
165
-            [$this->_dt_frmt, $this->_tm_frmt] = $date_formats;
166
-        } else {
167
-            // set default formats for date and time
168
-            $this->_dt_frmt = (string) get_option('date_format', 'Y-m-d');
169
-            $this->_tm_frmt = (string) get_option('time_format', 'g:i a');
170
-        }
171
-        // if db model is instantiating
172
-        if ($bydb) {
173
-            // client code has indicated these field values are from the database
174
-            foreach ($model_fields as $fieldName => $field) {
175
-                $this->set_from_db(
176
-                    $fieldName,
177
-                    isset($fieldValues[ $fieldName ]) ? $fieldValues[ $fieldName ] : null
178
-                );
179
-            }
180
-        } else {
181
-            // we're constructing a brand
182
-            // new instance of the model object. Generally, this means we'll need to do more field validation
183
-            foreach ($model_fields as $fieldName => $field) {
184
-                $this->set(
185
-                    $fieldName,
186
-                    isset($fieldValues[ $fieldName ]) ? $fieldValues[ $fieldName ] : null,
187
-                    true
188
-                );
189
-            }
190
-        }
191
-        // remember what values were passed to this constructor
192
-        $this->_props_n_values_provided_in_constructor = $fieldValues;
193
-        // remember in entity mapper
194
-        if (! $bydb && $model->has_primary_key_field() && $this->ID()) {
195
-            $model->add_to_entity_map($this);
196
-        }
197
-        // setup all the relations
198
-        foreach ($model->relation_settings() as $relation_name => $relation_obj) {
199
-            if ($relation_obj instanceof EE_Belongs_To_Relation) {
200
-                $this->_model_relations[ $relation_name ] = null;
201
-            } else {
202
-                $this->_model_relations[ $relation_name ] = array();
203
-            }
204
-        }
205
-        /**
206
-         * Action done at the end of each model object construction
207
-         *
208
-         * @param EE_Base_Class $this the model object just created
209
-         */
210
-        do_action('AHEE__EE_Base_Class__construct__finished', $this);
211
-    }
212
-
213
-
214
-    /**
215
-     * Gets whether or not this model object is allowed to persist/be saved to the database.
216
-     *
217
-     * @return boolean
218
-     */
219
-    public function allow_persist()
220
-    {
221
-        return $this->_allow_persist;
222
-    }
223
-
224
-
225
-    /**
226
-     * Sets whether or not this model object should be allowed to be saved to the DB.
227
-     * Normally once this is set to FALSE you wouldn't set it back to TRUE, unless
228
-     * you got new information that somehow made you change your mind.
229
-     *
230
-     * @param boolean $allow_persist
231
-     * @return boolean
232
-     */
233
-    public function set_allow_persist($allow_persist)
234
-    {
235
-        return $this->_allow_persist = $allow_persist;
236
-    }
237
-
238
-
239
-    /**
240
-     * Gets the field's original value when this object was constructed during this request.
241
-     * This can be helpful when determining if a model object has changed or not
242
-     *
243
-     * @param string $field_name
244
-     * @return mixed|null
245
-     * @throws ReflectionException
246
-     * @throws InvalidArgumentException
247
-     * @throws InvalidInterfaceException
248
-     * @throws InvalidDataTypeException
249
-     * @throws EE_Error
250
-     */
251
-    public function get_original($field_name)
252
-    {
253
-        if (
254
-            isset($this->_props_n_values_provided_in_constructor[ $field_name ])
255
-            && $field_settings = $this->get_model()->field_settings_for($field_name)
256
-        ) {
257
-            return $field_settings->prepare_for_get($this->_props_n_values_provided_in_constructor[ $field_name ]);
258
-        }
259
-        return null;
260
-    }
261
-
262
-
263
-    /**
264
-     * @param EE_Base_Class $obj
265
-     * @return string
266
-     */
267
-    public function get_class($obj)
268
-    {
269
-        return get_class($obj);
270
-    }
271
-
272
-
273
-    /**
274
-     * Overrides parent because parent expects old models.
275
-     * This also doesn't do any validation, and won't work for serialized arrays
276
-     *
277
-     * @param    string $field_name
278
-     * @param    mixed  $field_value
279
-     * @param bool      $use_default
280
-     * @throws InvalidArgumentException
281
-     * @throws InvalidInterfaceException
282
-     * @throws InvalidDataTypeException
283
-     * @throws EE_Error
284
-     * @throws ReflectionException
285
-     * @throws ReflectionException
286
-     * @throws ReflectionException
287
-     */
288
-    public function set($field_name, $field_value, $use_default = false)
289
-    {
290
-        // if not using default and nothing has changed, and object has already been setup (has ID),
291
-        // then don't do anything
292
-        if (
293
-            ! $use_default
294
-            && $this->_fields[ $field_name ] === $field_value
295
-            && $this->ID()
296
-        ) {
297
-            return;
298
-        }
299
-        $model = $this->get_model();
300
-        $this->_has_changes = true;
301
-        $field_obj = $model->field_settings_for($field_name);
302
-        if ($field_obj instanceof EE_Model_Field_Base) {
303
-            // if ( method_exists( $field_obj, 'set_timezone' )) {
304
-            if ($field_obj instanceof EE_Datetime_Field) {
305
-                $field_obj->set_timezone($this->_timezone);
306
-                $field_obj->set_date_format($this->_dt_frmt);
307
-                $field_obj->set_time_format($this->_tm_frmt);
308
-            }
309
-            $holder_of_value = $field_obj->prepare_for_set($field_value);
310
-            // should the value be null?
311
-            if (($field_value === null || $holder_of_value === null || $holder_of_value === '') && $use_default) {
312
-                $this->_fields[ $field_name ] = $field_obj->get_default_value();
313
-                /**
314
-                 * To save having to refactor all the models, if a default value is used for a
315
-                 * EE_Datetime_Field, and that value is not null nor is it a DateTime
316
-                 * object.  Then let's do a set again to ensure that it becomes a DateTime
317
-                 * object.
318
-                 *
319
-                 * @since 4.6.10+
320
-                 */
321
-                if (
322
-                    $field_obj instanceof EE_Datetime_Field
323
-                    && $this->_fields[ $field_name ] !== null
324
-                    && ! $this->_fields[ $field_name ] instanceof DateTime
325
-                ) {
326
-                    empty($this->_fields[ $field_name ])
327
-                        ? $this->set($field_name, time())
328
-                        : $this->set($field_name, $this->_fields[ $field_name ]);
329
-                }
330
-            } else {
331
-                $this->_fields[ $field_name ] = $holder_of_value;
332
-            }
333
-            // if we're not in the constructor...
334
-            // now check if what we set was a primary key
335
-            if (
16
+	/**
17
+	 * This is an array of the original properties and values provided during construction
18
+	 * of this model object. (keys are model field names, values are their values).
19
+	 * This list is important to remember so that when we are merging data from the db, we know
20
+	 * which values to override and which to not override.
21
+	 *
22
+	 * @var array
23
+	 */
24
+	protected $_props_n_values_provided_in_constructor;
25
+
26
+	/**
27
+	 * Timezone
28
+	 * This gets set by the "set_timezone()" method so that we know what timezone incoming strings|timestamps are in.
29
+	 * This can also be used before a get to set what timezone you want strings coming out of the object to be in.  NOT
30
+	 * all EE_Base_Class child classes use this property but any that use a EE_Datetime_Field data type will have
31
+	 * access to it.
32
+	 *
33
+	 * @var string
34
+	 */
35
+	protected $_timezone;
36
+
37
+	/**
38
+	 * date format
39
+	 * pattern or format for displaying dates
40
+	 *
41
+	 * @var string $_dt_frmt
42
+	 */
43
+	protected $_dt_frmt;
44
+
45
+	/**
46
+	 * time format
47
+	 * pattern or format for displaying time
48
+	 *
49
+	 * @var string $_tm_frmt
50
+	 */
51
+	protected $_tm_frmt;
52
+
53
+	/**
54
+	 * This property is for holding a cached array of object properties indexed by property name as the key.
55
+	 * The purpose of this is for setting a cache on properties that may have calculated values after a
56
+	 * prepare_for_get.  That way the cache can be checked first and the calculated property returned instead of having
57
+	 * to recalculate. Used by _set_cached_property() and _get_cached_property() methods.
58
+	 *
59
+	 * @var array
60
+	 */
61
+	protected $_cached_properties = array();
62
+
63
+	/**
64
+	 * An array containing keys of the related model, and values are either an array of related mode objects or a
65
+	 * single
66
+	 * related model object. see the model's _model_relations. The keys should match those specified. And if the
67
+	 * relation is of type EE_Belongs_To (or one of its children), then there should only be ONE related model object,
68
+	 * all others have an array)
69
+	 *
70
+	 * @var array
71
+	 */
72
+	protected $_model_relations = array();
73
+
74
+	/**
75
+	 * Array where keys are field names (see the model's _fields property) and values are their values. To see what
76
+	 * their types should be, look at what that field object returns on its prepare_for_get and prepare_for_set methods)
77
+	 *
78
+	 * @var array
79
+	 */
80
+	protected $_fields = array();
81
+
82
+	/**
83
+	 * @var boolean indicating whether or not this model object is intended to ever be saved
84
+	 * For example, we might create model objects intended to only be used for the duration
85
+	 * of this request and to be thrown away, and if they were accidentally saved
86
+	 * it would be a bug.
87
+	 */
88
+	protected $_allow_persist = true;
89
+
90
+	/**
91
+	 * @var boolean indicating whether or not this model object's properties have changed since construction
92
+	 */
93
+	protected $_has_changes = false;
94
+
95
+	/**
96
+	 * @var EEM_Base
97
+	 */
98
+	protected $_model;
99
+
100
+	/**
101
+	 * This is a cache of results from custom selections done on a query that constructs this entity. The only purpose
102
+	 * for these values is for retrieval of the results, they are not further queryable and they are not persisted to
103
+	 * the db.  They also do not automatically update if there are any changes to the data that produced their results.
104
+	 * The format is a simple array of field_alias => field_value.  So for instance if a custom select was something
105
+	 * like,  "Select COUNT(Registration.REG_ID) as Registration_Count ...", then the resulting value will be in this
106
+	 * array as:
107
+	 * array(
108
+	 *  'Registration_Count' => 24
109
+	 * );
110
+	 * Note: if the custom select configuration for the query included a data type, the value will be in the data type
111
+	 * provided for the query (@see EventEspresso\core\domain\values\model\CustomSelects::__construct phpdocs for more
112
+	 * info)
113
+	 *
114
+	 * @var array
115
+	 */
116
+	protected $custom_selection_results = array();
117
+
118
+
119
+	/**
120
+	 * basic constructor for Event Espresso classes, performs any necessary initialization, and verifies it's children
121
+	 * play nice
122
+	 *
123
+	 * @param array   $fieldValues                             where each key is a field (ie, array key in the 2nd
124
+	 *                                                         layer of the model's _fields array, (eg, EVT_ID,
125
+	 *                                                         TXN_amount, QST_name, etc) and values are their values
126
+	 * @param boolean $bydb                                    a flag for setting if the class is instantiated by the
127
+	 *                                                         corresponding db model or not.
128
+	 * @param string  $timezone                                indicate what timezone you want any datetime fields to
129
+	 *                                                         be in when instantiating a EE_Base_Class object.
130
+	 * @param array   $date_formats                            An array of date formats to set on construct where first
131
+	 *                                                         value is the date_format and second value is the time
132
+	 *                                                         format.
133
+	 * @throws InvalidArgumentException
134
+	 * @throws InvalidInterfaceException
135
+	 * @throws InvalidDataTypeException
136
+	 * @throws EE_Error
137
+	 * @throws ReflectionException
138
+	 */
139
+	protected function __construct($fieldValues = array(), $bydb = false, $timezone = '', $date_formats = array())
140
+	{
141
+		$className = get_class($this);
142
+		do_action("AHEE__{$className}__construct", $this, $fieldValues);
143
+		$model = $this->get_model();
144
+		$model_fields = $model->field_settings(false);
145
+		// ensure $fieldValues is an array
146
+		$fieldValues = is_array($fieldValues) ? $fieldValues : array($fieldValues);
147
+		// verify client code has not passed any invalid field names
148
+		foreach ($fieldValues as $field_name => $field_value) {
149
+			if (! isset($model_fields[ $field_name ])) {
150
+				throw new EE_Error(
151
+					sprintf(
152
+						esc_html__(
153
+							'Invalid field (%s) passed to constructor of %s. Allowed fields are :%s',
154
+							'event_espresso'
155
+						),
156
+						$field_name,
157
+						get_class($this),
158
+						implode(', ', array_keys($model_fields))
159
+					)
160
+				);
161
+			}
162
+		}
163
+		$this->_timezone = EEH_DTT_Helper::get_valid_timezone_string($timezone);
164
+		if (! empty($date_formats) && is_array($date_formats)) {
165
+			[$this->_dt_frmt, $this->_tm_frmt] = $date_formats;
166
+		} else {
167
+			// set default formats for date and time
168
+			$this->_dt_frmt = (string) get_option('date_format', 'Y-m-d');
169
+			$this->_tm_frmt = (string) get_option('time_format', 'g:i a');
170
+		}
171
+		// if db model is instantiating
172
+		if ($bydb) {
173
+			// client code has indicated these field values are from the database
174
+			foreach ($model_fields as $fieldName => $field) {
175
+				$this->set_from_db(
176
+					$fieldName,
177
+					isset($fieldValues[ $fieldName ]) ? $fieldValues[ $fieldName ] : null
178
+				);
179
+			}
180
+		} else {
181
+			// we're constructing a brand
182
+			// new instance of the model object. Generally, this means we'll need to do more field validation
183
+			foreach ($model_fields as $fieldName => $field) {
184
+				$this->set(
185
+					$fieldName,
186
+					isset($fieldValues[ $fieldName ]) ? $fieldValues[ $fieldName ] : null,
187
+					true
188
+				);
189
+			}
190
+		}
191
+		// remember what values were passed to this constructor
192
+		$this->_props_n_values_provided_in_constructor = $fieldValues;
193
+		// remember in entity mapper
194
+		if (! $bydb && $model->has_primary_key_field() && $this->ID()) {
195
+			$model->add_to_entity_map($this);
196
+		}
197
+		// setup all the relations
198
+		foreach ($model->relation_settings() as $relation_name => $relation_obj) {
199
+			if ($relation_obj instanceof EE_Belongs_To_Relation) {
200
+				$this->_model_relations[ $relation_name ] = null;
201
+			} else {
202
+				$this->_model_relations[ $relation_name ] = array();
203
+			}
204
+		}
205
+		/**
206
+		 * Action done at the end of each model object construction
207
+		 *
208
+		 * @param EE_Base_Class $this the model object just created
209
+		 */
210
+		do_action('AHEE__EE_Base_Class__construct__finished', $this);
211
+	}
212
+
213
+
214
+	/**
215
+	 * Gets whether or not this model object is allowed to persist/be saved to the database.
216
+	 *
217
+	 * @return boolean
218
+	 */
219
+	public function allow_persist()
220
+	{
221
+		return $this->_allow_persist;
222
+	}
223
+
224
+
225
+	/**
226
+	 * Sets whether or not this model object should be allowed to be saved to the DB.
227
+	 * Normally once this is set to FALSE you wouldn't set it back to TRUE, unless
228
+	 * you got new information that somehow made you change your mind.
229
+	 *
230
+	 * @param boolean $allow_persist
231
+	 * @return boolean
232
+	 */
233
+	public function set_allow_persist($allow_persist)
234
+	{
235
+		return $this->_allow_persist = $allow_persist;
236
+	}
237
+
238
+
239
+	/**
240
+	 * Gets the field's original value when this object was constructed during this request.
241
+	 * This can be helpful when determining if a model object has changed or not
242
+	 *
243
+	 * @param string $field_name
244
+	 * @return mixed|null
245
+	 * @throws ReflectionException
246
+	 * @throws InvalidArgumentException
247
+	 * @throws InvalidInterfaceException
248
+	 * @throws InvalidDataTypeException
249
+	 * @throws EE_Error
250
+	 */
251
+	public function get_original($field_name)
252
+	{
253
+		if (
254
+			isset($this->_props_n_values_provided_in_constructor[ $field_name ])
255
+			&& $field_settings = $this->get_model()->field_settings_for($field_name)
256
+		) {
257
+			return $field_settings->prepare_for_get($this->_props_n_values_provided_in_constructor[ $field_name ]);
258
+		}
259
+		return null;
260
+	}
261
+
262
+
263
+	/**
264
+	 * @param EE_Base_Class $obj
265
+	 * @return string
266
+	 */
267
+	public function get_class($obj)
268
+	{
269
+		return get_class($obj);
270
+	}
271
+
272
+
273
+	/**
274
+	 * Overrides parent because parent expects old models.
275
+	 * This also doesn't do any validation, and won't work for serialized arrays
276
+	 *
277
+	 * @param    string $field_name
278
+	 * @param    mixed  $field_value
279
+	 * @param bool      $use_default
280
+	 * @throws InvalidArgumentException
281
+	 * @throws InvalidInterfaceException
282
+	 * @throws InvalidDataTypeException
283
+	 * @throws EE_Error
284
+	 * @throws ReflectionException
285
+	 * @throws ReflectionException
286
+	 * @throws ReflectionException
287
+	 */
288
+	public function set($field_name, $field_value, $use_default = false)
289
+	{
290
+		// if not using default and nothing has changed, and object has already been setup (has ID),
291
+		// then don't do anything
292
+		if (
293
+			! $use_default
294
+			&& $this->_fields[ $field_name ] === $field_value
295
+			&& $this->ID()
296
+		) {
297
+			return;
298
+		}
299
+		$model = $this->get_model();
300
+		$this->_has_changes = true;
301
+		$field_obj = $model->field_settings_for($field_name);
302
+		if ($field_obj instanceof EE_Model_Field_Base) {
303
+			// if ( method_exists( $field_obj, 'set_timezone' )) {
304
+			if ($field_obj instanceof EE_Datetime_Field) {
305
+				$field_obj->set_timezone($this->_timezone);
306
+				$field_obj->set_date_format($this->_dt_frmt);
307
+				$field_obj->set_time_format($this->_tm_frmt);
308
+			}
309
+			$holder_of_value = $field_obj->prepare_for_set($field_value);
310
+			// should the value be null?
311
+			if (($field_value === null || $holder_of_value === null || $holder_of_value === '') && $use_default) {
312
+				$this->_fields[ $field_name ] = $field_obj->get_default_value();
313
+				/**
314
+				 * To save having to refactor all the models, if a default value is used for a
315
+				 * EE_Datetime_Field, and that value is not null nor is it a DateTime
316
+				 * object.  Then let's do a set again to ensure that it becomes a DateTime
317
+				 * object.
318
+				 *
319
+				 * @since 4.6.10+
320
+				 */
321
+				if (
322
+					$field_obj instanceof EE_Datetime_Field
323
+					&& $this->_fields[ $field_name ] !== null
324
+					&& ! $this->_fields[ $field_name ] instanceof DateTime
325
+				) {
326
+					empty($this->_fields[ $field_name ])
327
+						? $this->set($field_name, time())
328
+						: $this->set($field_name, $this->_fields[ $field_name ]);
329
+				}
330
+			} else {
331
+				$this->_fields[ $field_name ] = $holder_of_value;
332
+			}
333
+			// if we're not in the constructor...
334
+			// now check if what we set was a primary key
335
+			if (
336 336
 // note: props_n_values_provided_in_constructor is only set at the END of the constructor
337
-                $this->_props_n_values_provided_in_constructor
338
-                && $field_value
339
-                && $field_name === $model->primary_key_name()
340
-            ) {
341
-                // if so, we want all this object's fields to be filled either with
342
-                // what we've explicitly set on this model
343
-                // or what we have in the db
344
-                // echo "setting primary key!";
345
-                $fields_on_model = self::_get_model(get_class($this))->field_settings();
346
-                $obj_in_db = self::_get_model(get_class($this))->get_one_by_ID($field_value);
347
-                foreach ($fields_on_model as $field_obj) {
348
-                    if (
349
-                        ! array_key_exists($field_obj->get_name(), $this->_props_n_values_provided_in_constructor)
350
-                        && $field_obj->get_name() !== $field_name
351
-                    ) {
352
-                        $this->set($field_obj->get_name(), $obj_in_db->get($field_obj->get_name()));
353
-                    }
354
-                }
355
-                // oh this model object has an ID? well make sure its in the entity mapper
356
-                $model->add_to_entity_map($this);
357
-            }
358
-            // let's unset any cache for this field_name from the $_cached_properties property.
359
-            $this->_clear_cached_property($field_name);
360
-        } else {
361
-            throw new EE_Error(
362
-                sprintf(
363
-                    esc_html__(
364
-                        'A valid EE_Model_Field_Base could not be found for the given field name: %s',
365
-                        'event_espresso'
366
-                    ),
367
-                    $field_name
368
-                )
369
-            );
370
-        }
371
-    }
372
-
373
-
374
-    /**
375
-     * Set custom select values for model.
376
-     *
377
-     * @param array $custom_select_values
378
-     */
379
-    public function setCustomSelectsValues(array $custom_select_values)
380
-    {
381
-        $this->custom_selection_results = $custom_select_values;
382
-    }
383
-
384
-
385
-    /**
386
-     * Returns the custom select value for the provided alias if its set.
387
-     * If not set, returns null.
388
-     *
389
-     * @param string $alias
390
-     * @return string|int|float|null
391
-     */
392
-    public function getCustomSelect($alias)
393
-    {
394
-        return isset($this->custom_selection_results[ $alias ])
395
-            ? $this->custom_selection_results[ $alias ]
396
-            : null;
397
-    }
398
-
399
-
400
-    /**
401
-     * This sets the field value on the db column if it exists for the given $column_name or
402
-     * saves it to EE_Extra_Meta if the given $column_name does not match a db column.
403
-     *
404
-     * @see EE_message::get_column_value for related documentation on the necessity of this method.
405
-     * @param string $field_name  Must be the exact column name.
406
-     * @param mixed  $field_value The value to set.
407
-     * @return int|bool @see EE_Base_Class::update_extra_meta() for return docs.
408
-     * @throws InvalidArgumentException
409
-     * @throws InvalidInterfaceException
410
-     * @throws InvalidDataTypeException
411
-     * @throws EE_Error
412
-     * @throws ReflectionException
413
-     */
414
-    public function set_field_or_extra_meta($field_name, $field_value)
415
-    {
416
-        if ($this->get_model()->has_field($field_name)) {
417
-            $this->set($field_name, $field_value);
418
-            return true;
419
-        }
420
-        // ensure this object is saved first so that extra meta can be properly related.
421
-        $this->save();
422
-        return $this->update_extra_meta($field_name, $field_value);
423
-    }
424
-
425
-
426
-    /**
427
-     * This retrieves the value of the db column set on this class or if that's not present
428
-     * it will attempt to retrieve from extra_meta if found.
429
-     * Example Usage:
430
-     * Via EE_Message child class:
431
-     * Due to the dynamic nature of the EE_messages system, EE_messengers will always have a "to",
432
-     * "from", "subject", and "content" field (as represented in the EE_Message schema), however they may
433
-     * also have additional main fields specific to the messenger.  The system accommodates those extra
434
-     * fields through the EE_Extra_Meta table.  This method allows for EE_messengers to retrieve the
435
-     * value for those extra fields dynamically via the EE_message object.
436
-     *
437
-     * @param  string $field_name expecting the fully qualified field name.
438
-     * @return mixed|null  value for the field if found.  null if not found.
439
-     * @throws ReflectionException
440
-     * @throws InvalidArgumentException
441
-     * @throws InvalidInterfaceException
442
-     * @throws InvalidDataTypeException
443
-     * @throws EE_Error
444
-     */
445
-    public function get_field_or_extra_meta($field_name)
446
-    {
447
-        if ($this->get_model()->has_field($field_name)) {
448
-            $column_value = $this->get($field_name);
449
-        } else {
450
-            // This isn't a column in the main table, let's see if it is in the extra meta.
451
-            $column_value = $this->get_extra_meta($field_name, true, null);
452
-        }
453
-        return $column_value;
454
-    }
455
-
456
-
457
-    /**
458
-     * See $_timezone property for description of what the timezone property is for.  This SETS the timezone internally
459
-     * for being able to reference what timezone we are running conversions on when converting TO the internal timezone
460
-     * (UTC Unix Timestamp) for the object OR when converting FROM the internal timezone (UTC Unix Timestamp). This is
461
-     * available to all child classes that may be using the EE_Datetime_Field for a field data type.
462
-     *
463
-     * @access public
464
-     * @param string $timezone A valid timezone string as described by @link http://www.php.net/manual/en/timezones.php
465
-     * @return void
466
-     * @throws InvalidArgumentException
467
-     * @throws InvalidInterfaceException
468
-     * @throws InvalidDataTypeException
469
-     * @throws EE_Error
470
-     * @throws ReflectionException
471
-     */
472
-    public function set_timezone($timezone = '')
473
-    {
474
-        $this->_timezone = EEH_DTT_Helper::get_valid_timezone_string($timezone);
475
-        // make sure we clear all cached properties because they won't be relevant now
476
-        $this->_clear_cached_properties();
477
-        // make sure we update field settings and the date for all EE_Datetime_Fields
478
-        $model_fields = $this->get_model()->field_settings(false);
479
-        foreach ($model_fields as $field_name => $field_obj) {
480
-            if ($field_obj instanceof EE_Datetime_Field) {
481
-                $field_obj->set_timezone($this->_timezone);
482
-                if (isset($this->_fields[ $field_name ]) && $this->_fields[ $field_name ] instanceof DateTime) {
483
-                    EEH_DTT_Helper::setTimezone($this->_fields[ $field_name ], new DateTimeZone($this->_timezone));
484
-                }
485
-            }
486
-        }
487
-    }
488
-
489
-
490
-    /**
491
-     * This just returns whatever is set for the current timezone.
492
-     *
493
-     * @access public
494
-     * @return string timezone string
495
-     */
496
-    public function get_timezone()
497
-    {
498
-        return $this->_timezone;
499
-    }
500
-
501
-
502
-    /**
503
-     * This sets the internal date format to what is sent in to be used as the new default for the class
504
-     * internally instead of wp set date format options
505
-     *
506
-     * @since 4.6
507
-     * @param string $format should be a format recognizable by PHP date() functions.
508
-     */
509
-    public function set_date_format($format)
510
-    {
511
-        $this->_dt_frmt = $format;
512
-        // clear cached_properties because they won't be relevant now.
513
-        $this->_clear_cached_properties();
514
-    }
515
-
516
-
517
-    /**
518
-     * This sets the internal time format string to what is sent in to be used as the new default for the
519
-     * class internally instead of wp set time format options.
520
-     *
521
-     * @since 4.6
522
-     * @param string $format should be a format recognizable by PHP date() functions.
523
-     */
524
-    public function set_time_format($format)
525
-    {
526
-        $this->_tm_frmt = $format;
527
-        // clear cached_properties because they won't be relevant now.
528
-        $this->_clear_cached_properties();
529
-    }
530
-
531
-
532
-    /**
533
-     * This returns the current internal set format for the date and time formats.
534
-     *
535
-     * @param bool $full           if true (default), then return the full format.  Otherwise will return an array
536
-     *                             where the first value is the date format and the second value is the time format.
537
-     * @return mixed string|array
538
-     */
539
-    public function get_format($full = true)
540
-    {
541
-        return $full ? $this->_dt_frmt . ' ' . $this->_tm_frmt : array($this->_dt_frmt, $this->_tm_frmt);
542
-    }
543
-
544
-
545
-    /**
546
-     * cache
547
-     * stores the passed model object on the current model object.
548
-     * In certain circumstances, we can use this cached model object instead of querying for another one entirely.
549
-     *
550
-     * @param string        $relationName    one of the keys in the _model_relations array on the model. Eg
551
-     *                                       'Registration' associated with this model object
552
-     * @param EE_Base_Class $object_to_cache that has a relation to this model object. (Eg, if this is a Transaction,
553
-     *                                       that could be a payment or a registration)
554
-     * @param null          $cache_id        a string or number that will be used as the key for any Belongs_To_Many
555
-     *                                       items which will be stored in an array on this object
556
-     * @throws ReflectionException
557
-     * @throws InvalidArgumentException
558
-     * @throws InvalidInterfaceException
559
-     * @throws InvalidDataTypeException
560
-     * @throws EE_Error
561
-     * @return mixed    index into cache, or just TRUE if the relation is of type Belongs_To (because there's only one
562
-     *                                       related thing, no array)
563
-     */
564
-    public function cache($relationName = '', $object_to_cache = null, $cache_id = null)
565
-    {
566
-        // its entirely possible that there IS no related object yet in which case there is nothing to cache.
567
-        if (! $object_to_cache instanceof EE_Base_Class) {
568
-            return false;
569
-        }
570
-        // also get "how" the object is related, or throw an error
571
-        if (! $relationship_to_model = $this->get_model()->related_settings_for($relationName)) {
572
-            throw new EE_Error(
573
-                sprintf(
574
-                    esc_html__('There is no relationship to %s on a %s. Cannot cache it', 'event_espresso'),
575
-                    $relationName,
576
-                    get_class($this)
577
-                )
578
-            );
579
-        }
580
-        // how many things are related ?
581
-        if ($relationship_to_model instanceof EE_Belongs_To_Relation) {
582
-            // if it's a "belongs to" relationship, then there's only one related model object
583
-            // eg, if this is a registration, there's only 1 attendee for it
584
-            // so for these model objects just set it to be cached
585
-            $this->_model_relations[ $relationName ] = $object_to_cache;
586
-            $return = true;
587
-        } else {
588
-            // otherwise, this is the "many" side of a one to many relationship,
589
-            // so we'll add the object to the array of related objects for that type.
590
-            // eg: if this is an event, there are many registrations for that event,
591
-            // so we cache the registrations in an array
592
-            if (! is_array($this->_model_relations[ $relationName ])) {
593
-                // if for some reason, the cached item is a model object,
594
-                // then stick that in the array, otherwise start with an empty array
595
-                $this->_model_relations[ $relationName ] = $this->_model_relations[ $relationName ]
596
-                                                           instanceof
597
-                                                           EE_Base_Class
598
-                    ? array($this->_model_relations[ $relationName ]) : array();
599
-            }
600
-            // first check for a cache_id which is normally empty
601
-            if (! empty($cache_id)) {
602
-                // if the cache_id exists, then it means we are purposely trying to cache this
603
-                // with a known key that can then be used to retrieve the object later on
604
-                $this->_model_relations[ $relationName ][ $cache_id ] = $object_to_cache;
605
-                $return = $cache_id;
606
-            } elseif ($object_to_cache->ID()) {
607
-                // OR the cached object originally came from the db, so let's just use it's PK for an ID
608
-                $this->_model_relations[ $relationName ][ $object_to_cache->ID() ] = $object_to_cache;
609
-                $return = $object_to_cache->ID();
610
-            } else {
611
-                // OR it's a new object with no ID, so just throw it in the array with an auto-incremented ID
612
-                $this->_model_relations[ $relationName ][] = $object_to_cache;
613
-                // move the internal pointer to the end of the array
614
-                end($this->_model_relations[ $relationName ]);
615
-                // and grab the key so that we can return it
616
-                $return = key($this->_model_relations[ $relationName ]);
617
-            }
618
-        }
619
-        return $return;
620
-    }
621
-
622
-
623
-    /**
624
-     * For adding an item to the cached_properties property.
625
-     *
626
-     * @access protected
627
-     * @param string      $fieldname the property item the corresponding value is for.
628
-     * @param mixed       $value     The value we are caching.
629
-     * @param string|null $cache_type
630
-     * @return void
631
-     * @throws ReflectionException
632
-     * @throws InvalidArgumentException
633
-     * @throws InvalidInterfaceException
634
-     * @throws InvalidDataTypeException
635
-     * @throws EE_Error
636
-     */
637
-    protected function _set_cached_property($fieldname, $value, $cache_type = null)
638
-    {
639
-        // first make sure this property exists
640
-        $this->get_model()->field_settings_for($fieldname);
641
-        $cache_type = empty($cache_type) ? 'standard' : $cache_type;
642
-        $this->_cached_properties[ $fieldname ][ $cache_type ] = $value;
643
-    }
644
-
645
-
646
-    /**
647
-     * This returns the value cached property if it exists OR the actual property value if the cache doesn't exist.
648
-     * This also SETS the cache if we return the actual property!
649
-     *
650
-     * @param string $fieldname        the name of the property we're trying to retrieve
651
-     * @param bool   $pretty
652
-     * @param string $extra_cache_ref  This allows the user to specify an extra cache ref for the given property
653
-     *                                 (in cases where the same property may be used for different outputs
654
-     *                                 - i.e. datetime, money etc.)
655
-     *                                 It can also accept certain pre-defined "schema" strings
656
-     *                                 to define how to output the property.
657
-     *                                 see the field's prepare_for_pretty_echoing for what strings can be used
658
-     * @return mixed                   whatever the value for the property is we're retrieving
659
-     * @throws ReflectionException
660
-     * @throws InvalidArgumentException
661
-     * @throws InvalidInterfaceException
662
-     * @throws InvalidDataTypeException
663
-     * @throws EE_Error
664
-     */
665
-    protected function _get_cached_property($fieldname, $pretty = false, $extra_cache_ref = null)
666
-    {
667
-        // verify the field exists
668
-        $model = $this->get_model();
669
-        $model->field_settings_for($fieldname);
670
-        $cache_type = $pretty ? 'pretty' : 'standard';
671
-        $cache_type .= ! empty($extra_cache_ref) ? '_' . $extra_cache_ref : '';
672
-        if (isset($this->_cached_properties[ $fieldname ][ $cache_type ])) {
673
-            return $this->_cached_properties[ $fieldname ][ $cache_type ];
674
-        }
675
-        $value = $this->_get_fresh_property($fieldname, $pretty, $extra_cache_ref);
676
-        $this->_set_cached_property($fieldname, $value, $cache_type);
677
-        return $value;
678
-    }
679
-
680
-
681
-    /**
682
-     * If the cache didn't fetch the needed item, this fetches it.
683
-     *
684
-     * @param string $fieldname
685
-     * @param bool   $pretty
686
-     * @param string $extra_cache_ref
687
-     * @return mixed
688
-     * @throws InvalidArgumentException
689
-     * @throws InvalidInterfaceException
690
-     * @throws InvalidDataTypeException
691
-     * @throws EE_Error
692
-     * @throws ReflectionException
693
-     */
694
-    protected function _get_fresh_property($fieldname, $pretty = false, $extra_cache_ref = null)
695
-    {
696
-        $field_obj = $this->get_model()->field_settings_for($fieldname);
697
-        // If this is an EE_Datetime_Field we need to make sure timezone, formats, and output are correct
698
-        if ($field_obj instanceof EE_Datetime_Field) {
699
-            $this->_prepare_datetime_field($field_obj, $pretty, $extra_cache_ref);
700
-        }
701
-        if (! isset($this->_fields[ $fieldname ])) {
702
-            $this->_fields[ $fieldname ] = null;
703
-        }
704
-        return $pretty
705
-            ? $field_obj->prepare_for_pretty_echoing($this->_fields[ $fieldname ], $extra_cache_ref)
706
-            : $field_obj->prepare_for_get($this->_fields[ $fieldname ]);
707
-    }
708
-
709
-
710
-    /**
711
-     * set timezone, formats, and output for EE_Datetime_Field objects
712
-     *
713
-     * @param EE_Datetime_Field $datetime_field
714
-     * @param bool              $pretty
715
-     * @param null              $date_or_time
716
-     * @return void
717
-     * @throws InvalidArgumentException
718
-     * @throws InvalidInterfaceException
719
-     * @throws InvalidDataTypeException
720
-     */
721
-    protected function _prepare_datetime_field(
722
-        EE_Datetime_Field $datetime_field,
723
-        $pretty = false,
724
-        $date_or_time = null
725
-    ) {
726
-        $datetime_field->set_timezone($this->_timezone);
727
-        $datetime_field->set_date_format($this->_dt_frmt, $pretty);
728
-        $datetime_field->set_time_format($this->_tm_frmt, $pretty);
729
-        // set the output returned
730
-        switch ($date_or_time) {
731
-            case 'D':
732
-                $datetime_field->set_date_time_output('date');
733
-                break;
734
-            case 'T':
735
-                $datetime_field->set_date_time_output('time');
736
-                break;
737
-            default:
738
-                $datetime_field->set_date_time_output();
739
-        }
740
-    }
741
-
742
-
743
-    /**
744
-     * This just takes care of clearing out the cached_properties
745
-     *
746
-     * @return void
747
-     */
748
-    protected function _clear_cached_properties()
749
-    {
750
-        $this->_cached_properties = array();
751
-    }
752
-
753
-
754
-    /**
755
-     * This just clears out ONE property if it exists in the cache
756
-     *
757
-     * @param  string $property_name the property to remove if it exists (from the _cached_properties array)
758
-     * @return void
759
-     */
760
-    protected function _clear_cached_property($property_name)
761
-    {
762
-        if (isset($this->_cached_properties[ $property_name ])) {
763
-            unset($this->_cached_properties[ $property_name ]);
764
-        }
765
-    }
766
-
767
-
768
-    /**
769
-     * Ensures that this related thing is a model object.
770
-     *
771
-     * @param mixed  $object_or_id EE_base_Class/int/string either a related model object, or its ID
772
-     * @param string $model_name   name of the related thing, eg 'Attendee',
773
-     * @return EE_Base_Class
774
-     * @throws ReflectionException
775
-     * @throws InvalidArgumentException
776
-     * @throws InvalidInterfaceException
777
-     * @throws InvalidDataTypeException
778
-     * @throws EE_Error
779
-     */
780
-    protected function ensure_related_thing_is_model_obj($object_or_id, $model_name)
781
-    {
782
-        $other_model_instance = self::_get_model_instance_with_name(
783
-            self::_get_model_classname($model_name),
784
-            $this->_timezone
785
-        );
786
-        return $other_model_instance->ensure_is_obj($object_or_id);
787
-    }
788
-
789
-
790
-    /**
791
-     * Forgets the cached model of the given relation Name. So the next time we request it,
792
-     * we will fetch it again from the database. (Handy if you know it's changed somehow).
793
-     * If a specific object is supplied, and the relationship to it is either a HasMany or HABTM,
794
-     * then only remove that one object from our cached array. Otherwise, clear the entire list
795
-     *
796
-     * @param string $relationName                         one of the keys in the _model_relations array on the model.
797
-     *                                                     Eg 'Registration'
798
-     * @param mixed  $object_to_remove_or_index_into_array or an index into the array of cached things, or NULL
799
-     *                                                     if you intend to use $clear_all = TRUE, or the relation only
800
-     *                                                     has 1 object anyways (ie, it's a BelongsToRelation)
801
-     * @param bool   $clear_all                            This flags clearing the entire cache relation property if
802
-     *                                                     this is HasMany or HABTM.
803
-     * @throws ReflectionException
804
-     * @throws InvalidArgumentException
805
-     * @throws InvalidInterfaceException
806
-     * @throws InvalidDataTypeException
807
-     * @throws EE_Error
808
-     * @return EE_Base_Class | boolean from which was cleared from the cache, or true if we requested to remove a
809
-     *                                                     relation from all
810
-     */
811
-    public function clear_cache($relationName, $object_to_remove_or_index_into_array = null, $clear_all = false)
812
-    {
813
-        $relationship_to_model = $this->get_model()->related_settings_for($relationName);
814
-        $index_in_cache = '';
815
-        if (! $relationship_to_model) {
816
-            throw new EE_Error(
817
-                sprintf(
818
-                    esc_html__('There is no relationship to %s on a %s. Cannot clear that cache', 'event_espresso'),
819
-                    $relationName,
820
-                    get_class($this)
821
-                )
822
-            );
823
-        }
824
-        if ($clear_all) {
825
-            $obj_removed = true;
826
-            $this->_model_relations[ $relationName ] = null;
827
-        } elseif ($relationship_to_model instanceof EE_Belongs_To_Relation) {
828
-            $obj_removed = $this->_model_relations[ $relationName ];
829
-            $this->_model_relations[ $relationName ] = null;
830
-        } else {
831
-            if (
832
-                $object_to_remove_or_index_into_array instanceof EE_Base_Class
833
-                && $object_to_remove_or_index_into_array->ID()
834
-            ) {
835
-                $index_in_cache = $object_to_remove_or_index_into_array->ID();
836
-                if (
837
-                    is_array($this->_model_relations[ $relationName ])
838
-                    && ! isset($this->_model_relations[ $relationName ][ $index_in_cache ])
839
-                ) {
840
-                    $index_found_at = null;
841
-                    // find this object in the array even though it has a different key
842
-                    foreach ($this->_model_relations[ $relationName ] as $index => $obj) {
843
-                        /** @noinspection TypeUnsafeComparisonInspection */
844
-                        if (
845
-                            $obj instanceof EE_Base_Class
846
-                            && (
847
-                                $obj == $object_to_remove_or_index_into_array
848
-                                || $obj->ID() === $object_to_remove_or_index_into_array->ID()
849
-                            )
850
-                        ) {
851
-                            $index_found_at = $index;
852
-                            break;
853
-                        }
854
-                    }
855
-                    if ($index_found_at) {
856
-                        $index_in_cache = $index_found_at;
857
-                    } else {
858
-                        // it wasn't found. huh. well obviously it doesn't need to be removed from teh cache
859
-                        // if it wasn't in it to begin with. So we're done
860
-                        return $object_to_remove_or_index_into_array;
861
-                    }
862
-                }
863
-            } elseif ($object_to_remove_or_index_into_array instanceof EE_Base_Class) {
864
-                // so they provided a model object, but it's not yet saved to the DB... so let's go hunting for it!
865
-                foreach ($this->get_all_from_cache($relationName) as $index => $potentially_obj_we_want) {
866
-                    /** @noinspection TypeUnsafeComparisonInspection */
867
-                    if ($potentially_obj_we_want == $object_to_remove_or_index_into_array) {
868
-                        $index_in_cache = $index;
869
-                    }
870
-                }
871
-            } else {
872
-                $index_in_cache = $object_to_remove_or_index_into_array;
873
-            }
874
-            // supposedly we've found it. But it could just be that the client code
875
-            // provided a bad index/object
876
-            if (isset($this->_model_relations[ $relationName ][ $index_in_cache ])) {
877
-                $obj_removed = $this->_model_relations[ $relationName ][ $index_in_cache ];
878
-                unset($this->_model_relations[ $relationName ][ $index_in_cache ]);
879
-            } else {
880
-                // that thing was never cached anyways.
881
-                $obj_removed = null;
882
-            }
883
-        }
884
-        return $obj_removed;
885
-    }
886
-
887
-
888
-    /**
889
-     * update_cache_after_object_save
890
-     * Allows a cached item to have it's cache ID (within the array of cached items) reset using the new ID it has
891
-     * obtained after being saved to the db
892
-     *
893
-     * @param string        $relationName       - the type of object that is cached
894
-     * @param EE_Base_Class $newly_saved_object - the newly saved object to be re-cached
895
-     * @param string        $current_cache_id   - the ID that was used when originally caching the object
896
-     * @return boolean TRUE on success, FALSE on fail
897
-     * @throws ReflectionException
898
-     * @throws InvalidArgumentException
899
-     * @throws InvalidInterfaceException
900
-     * @throws InvalidDataTypeException
901
-     * @throws EE_Error
902
-     */
903
-    public function update_cache_after_object_save(
904
-        $relationName,
905
-        EE_Base_Class $newly_saved_object,
906
-        $current_cache_id = ''
907
-    ) {
908
-        // verify that incoming object is of the correct type
909
-        $obj_class = 'EE_' . $relationName;
910
-        if ($newly_saved_object instanceof $obj_class) {
911
-            /* @type EE_Base_Class $newly_saved_object */
912
-            // now get the type of relation
913
-            $relationship_to_model = $this->get_model()->related_settings_for($relationName);
914
-            // if this is a 1:1 relationship
915
-            if ($relationship_to_model instanceof EE_Belongs_To_Relation) {
916
-                // then just replace the cached object with the newly saved object
917
-                $this->_model_relations[ $relationName ] = $newly_saved_object;
918
-                return true;
919
-                // or if it's some kind of sordid feral polyamorous relationship...
920
-            }
921
-            if (
922
-                is_array($this->_model_relations[ $relationName ])
923
-                && isset($this->_model_relations[ $relationName ][ $current_cache_id ])
924
-            ) {
925
-                // then remove the current cached item
926
-                unset($this->_model_relations[ $relationName ][ $current_cache_id ]);
927
-                // and cache the newly saved object using it's new ID
928
-                $this->_model_relations[ $relationName ][ $newly_saved_object->ID() ] = $newly_saved_object;
929
-                return true;
930
-            }
931
-        }
932
-        return false;
933
-    }
934
-
935
-
936
-    /**
937
-     * Fetches a single EE_Base_Class on that relation. (If the relation is of type
938
-     * BelongsTo, it will only ever have 1 object. However, other relations could have an array of objects)
939
-     *
940
-     * @param string $relationName
941
-     * @return EE_Base_Class
942
-     */
943
-    public function get_one_from_cache($relationName)
944
-    {
945
-        $cached_array_or_object = isset($this->_model_relations[ $relationName ])
946
-            ? $this->_model_relations[ $relationName ]
947
-            : null;
948
-        if (is_array($cached_array_or_object)) {
949
-            return array_shift($cached_array_or_object);
950
-        }
951
-        return $cached_array_or_object;
952
-    }
953
-
954
-
955
-    /**
956
-     * Fetches a single EE_Base_Class on that relation. (If the relation is of type
957
-     * BelongsTo, it will only ever have 1 object. However, other relations could have an array of objects)
958
-     *
959
-     * @param string $relationName
960
-     * @throws ReflectionException
961
-     * @throws InvalidArgumentException
962
-     * @throws InvalidInterfaceException
963
-     * @throws InvalidDataTypeException
964
-     * @throws EE_Error
965
-     * @return EE_Base_Class[] NOT necessarily indexed by primary keys
966
-     */
967
-    public function get_all_from_cache($relationName)
968
-    {
969
-        $objects = isset($this->_model_relations[ $relationName ]) ? $this->_model_relations[ $relationName ] : array();
970
-        // if the result is not an array, but exists, make it an array
971
-        $objects = is_array($objects) ? $objects : array($objects);
972
-        // bugfix for https://events.codebasehq.com/projects/event-espresso/tickets/7143
973
-        // basically, if this model object was stored in the session, and these cached model objects
974
-        // already have IDs, let's make sure they're in their model's entity mapper
975
-        // otherwise we will have duplicates next time we call
976
-        // EE_Registry::instance()->load_model( $relationName )->get_one_by_ID( $result->ID() );
977
-        $model = EE_Registry::instance()->load_model($relationName);
978
-        foreach ($objects as $model_object) {
979
-            if ($model instanceof EEM_Base && $model_object instanceof EE_Base_Class) {
980
-                // ensure its in the map if it has an ID; otherwise it will be added to the map when its saved
981
-                if ($model_object->ID()) {
982
-                    $model->add_to_entity_map($model_object);
983
-                }
984
-            } else {
985
-                throw new EE_Error(
986
-                    sprintf(
987
-                        esc_html__(
988
-                            'Error retrieving related model objects. Either $1%s is not a model or $2%s is not a model object',
989
-                            'event_espresso'
990
-                        ),
991
-                        $relationName,
992
-                        gettype($model_object)
993
-                    )
994
-                );
995
-            }
996
-        }
997
-        return $objects;
998
-    }
999
-
1000
-
1001
-    /**
1002
-     * Returns the next x number of EE_Base_Class objects in sequence from this object as found in the database
1003
-     * matching the given query conditions.
1004
-     *
1005
-     * @param null  $field_to_order_by  What field is being used as the reference point.
1006
-     * @param int   $limit              How many objects to return.
1007
-     * @param array $query_params       Any additional conditions on the query.
1008
-     * @param null  $columns_to_select  If left null, then an array of EE_Base_Class objects is returned, otherwise
1009
-     *                                  you can indicate just the columns you want returned
1010
-     * @return array|EE_Base_Class[]
1011
-     * @throws ReflectionException
1012
-     * @throws InvalidArgumentException
1013
-     * @throws InvalidInterfaceException
1014
-     * @throws InvalidDataTypeException
1015
-     * @throws EE_Error
1016
-     */
1017
-    public function next_x($field_to_order_by = null, $limit = 1, $query_params = array(), $columns_to_select = null)
1018
-    {
1019
-        $model = $this->get_model();
1020
-        $field = empty($field_to_order_by) && $model->has_primary_key_field()
1021
-            ? $model->get_primary_key_field()->get_name()
1022
-            : $field_to_order_by;
1023
-        $current_value = ! empty($field) ? $this->get($field) : null;
1024
-        if (empty($field) || empty($current_value)) {
1025
-            return array();
1026
-        }
1027
-        return $model->next_x($current_value, $field, $limit, $query_params, $columns_to_select);
1028
-    }
1029
-
1030
-
1031
-    /**
1032
-     * Returns the previous x number of EE_Base_Class objects in sequence from this object as found in the database
1033
-     * matching the given query conditions.
1034
-     *
1035
-     * @param null  $field_to_order_by  What field is being used as the reference point.
1036
-     * @param int   $limit              How many objects to return.
1037
-     * @param array $query_params       Any additional conditions on the query.
1038
-     * @param null  $columns_to_select  If left null, then an array of EE_Base_Class objects is returned, otherwise
1039
-     *                                  you can indicate just the columns you want returned
1040
-     * @return array|EE_Base_Class[]
1041
-     * @throws ReflectionException
1042
-     * @throws InvalidArgumentException
1043
-     * @throws InvalidInterfaceException
1044
-     * @throws InvalidDataTypeException
1045
-     * @throws EE_Error
1046
-     */
1047
-    public function previous_x(
1048
-        $field_to_order_by = null,
1049
-        $limit = 1,
1050
-        $query_params = array(),
1051
-        $columns_to_select = null
1052
-    ) {
1053
-        $model = $this->get_model();
1054
-        $field = empty($field_to_order_by) && $model->has_primary_key_field()
1055
-            ? $model->get_primary_key_field()->get_name()
1056
-            : $field_to_order_by;
1057
-        $current_value = ! empty($field) ? $this->get($field) : null;
1058
-        if (empty($field) || empty($current_value)) {
1059
-            return array();
1060
-        }
1061
-        return $model->previous_x($current_value, $field, $limit, $query_params, $columns_to_select);
1062
-    }
1063
-
1064
-
1065
-    /**
1066
-     * Returns the next EE_Base_Class object in sequence from this object as found in the database
1067
-     * matching the given query conditions.
1068
-     *
1069
-     * @param null  $field_to_order_by  What field is being used as the reference point.
1070
-     * @param array $query_params       Any additional conditions on the query.
1071
-     * @param null  $columns_to_select  If left null, then an array of EE_Base_Class objects is returned, otherwise
1072
-     *                                  you can indicate just the columns you want returned
1073
-     * @return array|EE_Base_Class
1074
-     * @throws ReflectionException
1075
-     * @throws InvalidArgumentException
1076
-     * @throws InvalidInterfaceException
1077
-     * @throws InvalidDataTypeException
1078
-     * @throws EE_Error
1079
-     */
1080
-    public function next($field_to_order_by = null, $query_params = array(), $columns_to_select = null)
1081
-    {
1082
-        $model = $this->get_model();
1083
-        $field = empty($field_to_order_by) && $model->has_primary_key_field()
1084
-            ? $model->get_primary_key_field()->get_name()
1085
-            : $field_to_order_by;
1086
-        $current_value = ! empty($field) ? $this->get($field) : null;
1087
-        if (empty($field) || empty($current_value)) {
1088
-            return array();
1089
-        }
1090
-        return $model->next($current_value, $field, $query_params, $columns_to_select);
1091
-    }
1092
-
1093
-
1094
-    /**
1095
-     * Returns the previous EE_Base_Class object in sequence from this object as found in the database
1096
-     * matching the given query conditions.
1097
-     *
1098
-     * @param null  $field_to_order_by  What field is being used as the reference point.
1099
-     * @param array $query_params       Any additional conditions on the query.
1100
-     * @param null  $columns_to_select  If left null, then an EE_Base_Class object is returned, otherwise
1101
-     *                                  you can indicate just the column you want returned
1102
-     * @return array|EE_Base_Class
1103
-     * @throws ReflectionException
1104
-     * @throws InvalidArgumentException
1105
-     * @throws InvalidInterfaceException
1106
-     * @throws InvalidDataTypeException
1107
-     * @throws EE_Error
1108
-     */
1109
-    public function previous($field_to_order_by = null, $query_params = array(), $columns_to_select = null)
1110
-    {
1111
-        $model = $this->get_model();
1112
-        $field = empty($field_to_order_by) && $model->has_primary_key_field()
1113
-            ? $model->get_primary_key_field()->get_name()
1114
-            : $field_to_order_by;
1115
-        $current_value = ! empty($field) ? $this->get($field) : null;
1116
-        if (empty($field) || empty($current_value)) {
1117
-            return array();
1118
-        }
1119
-        return $model->previous($current_value, $field, $query_params, $columns_to_select);
1120
-    }
1121
-
1122
-
1123
-    /**
1124
-     * Overrides parent because parent expects old models.
1125
-     * This also doesn't do any validation, and won't work for serialized arrays
1126
-     *
1127
-     * @param string $field_name
1128
-     * @param mixed  $field_value_from_db
1129
-     * @throws ReflectionException
1130
-     * @throws InvalidArgumentException
1131
-     * @throws InvalidInterfaceException
1132
-     * @throws InvalidDataTypeException
1133
-     * @throws EE_Error
1134
-     */
1135
-    public function set_from_db($field_name, $field_value_from_db)
1136
-    {
1137
-        $field_obj = $this->get_model()->field_settings_for($field_name);
1138
-        if ($field_obj instanceof EE_Model_Field_Base) {
1139
-            // you would think the DB has no NULLs for non-null label fields right? wrong!
1140
-            // eg, a CPT model object could have an entry in the posts table, but no
1141
-            // entry in the meta table. Meaning that all its columns in the meta table
1142
-            // are null! yikes! so when we find one like that, use defaults for its meta columns
1143
-            if ($field_value_from_db === null) {
1144
-                if ($field_obj->is_nullable()) {
1145
-                    // if the field allows nulls, then let it be null
1146
-                    $field_value = null;
1147
-                } else {
1148
-                    $field_value = $field_obj->get_default_value();
1149
-                }
1150
-            } else {
1151
-                $field_value = $field_obj->prepare_for_set_from_db($field_value_from_db);
1152
-            }
1153
-            $this->_fields[ $field_name ] = $field_value;
1154
-            $this->_clear_cached_property($field_name);
1155
-        }
1156
-    }
1157
-
1158
-
1159
-    /**
1160
-     * verifies that the specified field is of the correct type
1161
-     *
1162
-     * @param string $field_name
1163
-     * @param string $extra_cache_ref This allows the user to specify an extra cache ref for the given property
1164
-     *                                (in cases where the same property may be used for different outputs
1165
-     *                                - i.e. datetime, money etc.)
1166
-     * @return mixed
1167
-     * @throws ReflectionException
1168
-     * @throws InvalidArgumentException
1169
-     * @throws InvalidInterfaceException
1170
-     * @throws InvalidDataTypeException
1171
-     * @throws EE_Error
1172
-     */
1173
-    public function get($field_name, $extra_cache_ref = null)
1174
-    {
1175
-        return $this->_get_cached_property($field_name, false, $extra_cache_ref);
1176
-    }
1177
-
1178
-
1179
-    /**
1180
-     * This method simply returns the RAW unprocessed value for the given property in this class
1181
-     *
1182
-     * @param  string $field_name A valid fieldname
1183
-     * @return mixed              Whatever the raw value stored on the property is.
1184
-     * @throws ReflectionException
1185
-     * @throws InvalidArgumentException
1186
-     * @throws InvalidInterfaceException
1187
-     * @throws InvalidDataTypeException
1188
-     * @throws EE_Error if fieldSettings is misconfigured or the field doesn't exist.
1189
-     */
1190
-    public function get_raw($field_name)
1191
-    {
1192
-        $field_settings = $this->get_model()->field_settings_for($field_name);
1193
-        return $field_settings instanceof EE_Datetime_Field && $this->_fields[ $field_name ] instanceof DateTime
1194
-            ? $this->_fields[ $field_name ]->format('U')
1195
-            : $this->_fields[ $field_name ];
1196
-    }
1197
-
1198
-
1199
-    /**
1200
-     * This is used to return the internal DateTime object used for a field that is a
1201
-     * EE_Datetime_Field.
1202
-     *
1203
-     * @param string $field_name               The field name retrieving the DateTime object.
1204
-     * @return mixed null | false | DateTime  If the requested field is NOT a EE_Datetime_Field then
1205
-     * @throws EE_Error an error is set and false returned.  If the field IS an
1206
-     *                                         EE_Datetime_Field and but the field value is null, then
1207
-     *                                         just null is returned (because that indicates that likely
1208
-     *                                         this field is nullable).
1209
-     * @throws InvalidArgumentException
1210
-     * @throws InvalidDataTypeException
1211
-     * @throws InvalidInterfaceException
1212
-     * @throws ReflectionException
1213
-     */
1214
-    public function get_DateTime_object($field_name)
1215
-    {
1216
-        $field_settings = $this->get_model()->field_settings_for($field_name);
1217
-        if (! $field_settings instanceof EE_Datetime_Field) {
1218
-            EE_Error::add_error(
1219
-                sprintf(
1220
-                    esc_html__(
1221
-                        'The field %s is not an EE_Datetime_Field field.  There is no DateTime object stored on this field type.',
1222
-                        'event_espresso'
1223
-                    ),
1224
-                    $field_name
1225
-                ),
1226
-                __FILE__,
1227
-                __FUNCTION__,
1228
-                __LINE__
1229
-            );
1230
-            return false;
1231
-        }
1232
-        return isset($this->_fields[ $field_name ]) && $this->_fields[ $field_name ] instanceof DateTime
1233
-            ? clone $this->_fields[ $field_name ]
1234
-            : null;
1235
-    }
1236
-
1237
-
1238
-    /**
1239
-     * To be used in template to immediately echo out the value, and format it for output.
1240
-     * Eg, should call stripslashes and whatnot before echoing
1241
-     *
1242
-     * @param string $field_name      the name of the field as it appears in the DB
1243
-     * @param string $extra_cache_ref This allows the user to specify an extra cache ref for the given property
1244
-     *                                (in cases where the same property may be used for different outputs
1245
-     *                                - i.e. datetime, money etc.)
1246
-     * @return void
1247
-     * @throws ReflectionException
1248
-     * @throws InvalidArgumentException
1249
-     * @throws InvalidInterfaceException
1250
-     * @throws InvalidDataTypeException
1251
-     * @throws EE_Error
1252
-     */
1253
-    public function e($field_name, $extra_cache_ref = null)
1254
-    {
1255
-        echo wp_kses($this->get_pretty($field_name, $extra_cache_ref), AllowedTags::getWithFormTags());
1256
-    }
1257
-
1258
-
1259
-    /**
1260
-     * Exactly like e(), echoes out the field, but sets its schema to 'form_input', so that it
1261
-     * can be easily used as the value of form input.
1262
-     *
1263
-     * @param string $field_name
1264
-     * @return void
1265
-     * @throws ReflectionException
1266
-     * @throws InvalidArgumentException
1267
-     * @throws InvalidInterfaceException
1268
-     * @throws InvalidDataTypeException
1269
-     * @throws EE_Error
1270
-     */
1271
-    public function f($field_name)
1272
-    {
1273
-        $this->e($field_name, 'form_input');
1274
-    }
1275
-
1276
-
1277
-    /**
1278
-     * Same as `f()` but just returns the value instead of echoing it
1279
-     *
1280
-     * @param string $field_name
1281
-     * @return string
1282
-     * @throws ReflectionException
1283
-     * @throws InvalidArgumentException
1284
-     * @throws InvalidInterfaceException
1285
-     * @throws InvalidDataTypeException
1286
-     * @throws EE_Error
1287
-     */
1288
-    public function get_f($field_name)
1289
-    {
1290
-        return (string) $this->get_pretty($field_name, 'form_input');
1291
-    }
1292
-
1293
-
1294
-    /**
1295
-     * Gets a pretty view of the field's value. $extra_cache_ref can specify different formats for this.
1296
-     * The $extra_cache_ref will be passed to the model field's prepare_for_pretty_echoing, so consult the field's class
1297
-     * to see what options are available.
1298
-     *
1299
-     * @param string $field_name
1300
-     * @param string $extra_cache_ref This allows the user to specify an extra cache ref for the given property
1301
-     *                                (in cases where the same property may be used for different outputs
1302
-     *                                - i.e. datetime, money etc.)
1303
-     * @return mixed
1304
-     * @throws ReflectionException
1305
-     * @throws InvalidArgumentException
1306
-     * @throws InvalidInterfaceException
1307
-     * @throws InvalidDataTypeException
1308
-     * @throws EE_Error
1309
-     */
1310
-    public function get_pretty($field_name, $extra_cache_ref = null)
1311
-    {
1312
-        return $this->_get_cached_property($field_name, true, $extra_cache_ref);
1313
-    }
1314
-
1315
-
1316
-    /**
1317
-     * This simply returns the datetime for the given field name
1318
-     * Note: this protected function is called by the wrapper get_date or get_time or get_datetime functions
1319
-     * (and the equivalent e_date, e_time, e_datetime).
1320
-     *
1321
-     * @access   protected
1322
-     * @param string      $field_name   Field on the instantiated EE_Base_Class child object
1323
-     * @param string|null $date_format  valid datetime format used for date
1324
-     *                                  (if '' then we just use the default on the field,
1325
-     *                                  if NULL we use the last-used format)
1326
-     * @param string|null $time_format  Same as above except this is for time format
1327
-     * @param string|null $date_or_time if NULL then both are returned, otherwise "D" = only date and "T" = only time.
1328
-     * @param bool|null   $echo         Whether the datetime is pretty echoing or just returned using vanilla get
1329
-     * @return string|bool|EE_Error string on success, FALSE on fail, or EE_Error Exception is thrown
1330
-     *                                  if field is not a valid dtt field, or void if echoing
1331
-     * @throws EE_Error
1332
-     * @throws ReflectionException
1333
-     */
1334
-    protected function _get_datetime(
1335
-        string $field_name,
1336
-        ?string $date_format = '',
1337
-        ?string $time_format = '',
1338
-        ?string $date_or_time = '',
1339
-        ?bool $echo = false
1340
-    ) {
1341
-        // clear cached property
1342
-        $this->_clear_cached_property($field_name);
1343
-        // reset format properties because they are used in get()
1344
-        $this->_dt_frmt = $date_format !== '' ? $date_format : $this->_dt_frmt;
1345
-        $this->_tm_frmt = $time_format !== '' ? $time_format : $this->_tm_frmt;
1346
-        if ($echo) {
1347
-            $this->e($field_name, $date_or_time);
1348
-            return '';
1349
-        }
1350
-        return $this->get($field_name, $date_or_time);
1351
-    }
1352
-
1353
-
1354
-    /**
1355
-     * below are wrapper functions for the various datetime outputs that can be obtained for JUST returning the date
1356
-     * portion of a datetime value. (note the only difference between get_ and e_ is one returns the value and the
1357
-     * other echoes the pretty value for dtt)
1358
-     *
1359
-     * @param  string $field_name name of model object datetime field holding the value
1360
-     * @param  string $format     format for the date returned (if NULL we use default in dt_frmt property)
1361
-     * @return string            datetime value formatted
1362
-     * @throws ReflectionException
1363
-     * @throws InvalidArgumentException
1364
-     * @throws InvalidInterfaceException
1365
-     * @throws InvalidDataTypeException
1366
-     * @throws EE_Error
1367
-     */
1368
-    public function get_date($field_name, $format = '')
1369
-    {
1370
-        return $this->_get_datetime($field_name, $format, null, 'D');
1371
-    }
1372
-
1373
-
1374
-    /**
1375
-     * @param        $field_name
1376
-     * @param string $format
1377
-     * @throws ReflectionException
1378
-     * @throws InvalidArgumentException
1379
-     * @throws InvalidInterfaceException
1380
-     * @throws InvalidDataTypeException
1381
-     * @throws EE_Error
1382
-     */
1383
-    public function e_date($field_name, $format = '')
1384
-    {
1385
-        $this->_get_datetime($field_name, $format, null, 'D', true);
1386
-    }
1387
-
1388
-
1389
-    /**
1390
-     * below are wrapper functions for the various datetime outputs that can be obtained for JUST returning the time
1391
-     * portion of a datetime value. (note the only difference between get_ and e_ is one returns the value and the
1392
-     * other echoes the pretty value for dtt)
1393
-     *
1394
-     * @param  string $field_name name of model object datetime field holding the value
1395
-     * @param  string $format     format for the time returned ( if NULL we use default in tm_frmt property)
1396
-     * @return string             datetime value formatted
1397
-     * @throws ReflectionException
1398
-     * @throws InvalidArgumentException
1399
-     * @throws InvalidInterfaceException
1400
-     * @throws InvalidDataTypeException
1401
-     * @throws EE_Error
1402
-     */
1403
-    public function get_time($field_name, $format = '')
1404
-    {
1405
-        return $this->_get_datetime($field_name, null, $format, 'T');
1406
-    }
1407
-
1408
-
1409
-    /**
1410
-     * @param        $field_name
1411
-     * @param string $format
1412
-     * @throws ReflectionException
1413
-     * @throws InvalidArgumentException
1414
-     * @throws InvalidInterfaceException
1415
-     * @throws InvalidDataTypeException
1416
-     * @throws EE_Error
1417
-     */
1418
-    public function e_time($field_name, $format = '')
1419
-    {
1420
-        $this->_get_datetime($field_name, null, $format, 'T', true);
1421
-    }
1422
-
1423
-
1424
-    /**
1425
-     * below are wrapper functions for the various datetime outputs that can be obtained for returning the date AND
1426
-     * time portion of a datetime value. (note the only difference between get_ and e_ is one returns the value and the
1427
-     * other echoes the pretty value for dtt)
1428
-     *
1429
-     * @param  string $field_name name of model object datetime field holding the value
1430
-     * @param  string $dt_frmt    format for the date returned (if NULL we use default in dt_frmt property)
1431
-     * @param  string $tm_frmt    format for the time returned (if NULL we use default in tm_frmt property)
1432
-     * @return string             datetime value formatted
1433
-     * @throws ReflectionException
1434
-     * @throws InvalidArgumentException
1435
-     * @throws InvalidInterfaceException
1436
-     * @throws InvalidDataTypeException
1437
-     * @throws EE_Error
1438
-     */
1439
-    public function get_datetime($field_name, $dt_frmt = '', $tm_frmt = '')
1440
-    {
1441
-        return $this->_get_datetime($field_name, $dt_frmt, $tm_frmt);
1442
-    }
1443
-
1444
-
1445
-    /**
1446
-     * @param string $field_name
1447
-     * @param string $dt_frmt
1448
-     * @param string $tm_frmt
1449
-     * @throws ReflectionException
1450
-     * @throws InvalidArgumentException
1451
-     * @throws InvalidInterfaceException
1452
-     * @throws InvalidDataTypeException
1453
-     * @throws EE_Error
1454
-     */
1455
-    public function e_datetime($field_name, $dt_frmt = '', $tm_frmt = '')
1456
-    {
1457
-        $this->_get_datetime($field_name, $dt_frmt, $tm_frmt, null, true);
1458
-    }
1459
-
1460
-
1461
-    /**
1462
-     * Get the i8ln value for a date using the WordPress @see date_i18n function.
1463
-     *
1464
-     * @param string $field_name The EE_Datetime_Field reference for the date being retrieved.
1465
-     * @param string $format     PHP valid date/time string format.  If none is provided then the internal set format
1466
-     *                           on the object will be used.
1467
-     * @return string Date and time string in set locale or false if no field exists for the given
1468
-     * @throws ReflectionException
1469
-     * @throws InvalidArgumentException
1470
-     * @throws InvalidInterfaceException
1471
-     * @throws InvalidDataTypeException
1472
-     * @throws EE_Error
1473
-     *                           field name.
1474
-     */
1475
-    public function get_i18n_datetime($field_name, $format = '')
1476
-    {
1477
-        $format = empty($format) ? $this->_dt_frmt . ' ' . $this->_tm_frmt : $format;
1478
-        return date_i18n(
1479
-            $format,
1480
-            EEH_DTT_Helper::get_timestamp_with_offset(
1481
-                $this->get_raw($field_name),
1482
-                $this->_timezone
1483
-            )
1484
-        );
1485
-    }
1486
-
1487
-
1488
-    /**
1489
-     * This method validates whether the given field name is a valid field on the model object as well as it is of a
1490
-     * type EE_Datetime_Field.  On success there will be returned the field settings.  On fail an EE_Error exception is
1491
-     * thrown.
1492
-     *
1493
-     * @param  string $field_name The field name being checked
1494
-     * @throws ReflectionException
1495
-     * @throws InvalidArgumentException
1496
-     * @throws InvalidInterfaceException
1497
-     * @throws InvalidDataTypeException
1498
-     * @throws EE_Error
1499
-     * @return EE_Datetime_Field
1500
-     */
1501
-    protected function _get_dtt_field_settings($field_name)
1502
-    {
1503
-        $field = $this->get_model()->field_settings_for($field_name);
1504
-        // check if field is dtt
1505
-        if ($field instanceof EE_Datetime_Field) {
1506
-            return $field;
1507
-        }
1508
-        throw new EE_Error(
1509
-            sprintf(
1510
-                esc_html__(
1511
-                    'The field name "%s" has been requested for the EE_Base_Class datetime functions and it is not a valid EE_Datetime_Field.  Please check the spelling of the field and make sure it has been setup as a EE_Datetime_Field in the %s model constructor',
1512
-                    'event_espresso'
1513
-                ),
1514
-                $field_name,
1515
-                self::_get_model_classname(get_class($this))
1516
-            )
1517
-        );
1518
-    }
1519
-
1520
-
1521
-
1522
-
1523
-    /**
1524
-     * NOTE ABOUT BELOW:
1525
-     * These convenience date and time setters are for setting date and time independently.  In other words you might
1526
-     * want to change the time on a datetime_field but leave the date the same (or vice versa). IF on the other hand
1527
-     * you want to set both date and time at the same time, you can just use the models default set($fieldname,$value)
1528
-     * method and make sure you send the entire datetime value for setting.
1529
-     */
1530
-    /**
1531
-     * sets the time on a datetime property
1532
-     *
1533
-     * @access protected
1534
-     * @param string|Datetime $time      a valid time string for php datetime functions (or DateTime object)
1535
-     * @param string          $fieldname the name of the field the time is being set on (must match a EE_Datetime_Field)
1536
-     * @throws ReflectionException
1537
-     * @throws InvalidArgumentException
1538
-     * @throws InvalidInterfaceException
1539
-     * @throws InvalidDataTypeException
1540
-     * @throws EE_Error
1541
-     */
1542
-    protected function _set_time_for($time, $fieldname)
1543
-    {
1544
-        $this->_set_date_time('T', $time, $fieldname);
1545
-    }
1546
-
1547
-
1548
-    /**
1549
-     * sets the date on a datetime property
1550
-     *
1551
-     * @access protected
1552
-     * @param string|DateTime $date      a valid date string for php datetime functions ( or DateTime object)
1553
-     * @param string          $fieldname the name of the field the date is being set on (must match a EE_Datetime_Field)
1554
-     * @throws ReflectionException
1555
-     * @throws InvalidArgumentException
1556
-     * @throws InvalidInterfaceException
1557
-     * @throws InvalidDataTypeException
1558
-     * @throws EE_Error
1559
-     */
1560
-    protected function _set_date_for($date, $fieldname)
1561
-    {
1562
-        $this->_set_date_time('D', $date, $fieldname);
1563
-    }
1564
-
1565
-
1566
-    /**
1567
-     * This takes care of setting a date or time independently on a given model object property. This method also
1568
-     * verifies that the given field_name matches a model object property and is for a EE_Datetime_Field field
1569
-     *
1570
-     * @access protected
1571
-     * @param string          $what           "T" for time, 'B' for both, 'D' for Date.
1572
-     * @param string|DateTime $datetime_value A valid Date or Time string (or DateTime object)
1573
-     * @param string          $field_name     the name of the field the date OR time is being set on (must match a
1574
-     *                                        EE_Datetime_Field property)
1575
-     * @throws ReflectionException
1576
-     * @throws InvalidArgumentException
1577
-     * @throws InvalidInterfaceException
1578
-     * @throws InvalidDataTypeException
1579
-     * @throws EE_Error
1580
-     */
1581
-    protected function _set_date_time(string $what, $datetime_value, string $field_name)
1582
-    {
1583
-        $field = $this->_get_dtt_field_settings($field_name);
1584
-        $field->set_timezone($this->_timezone);
1585
-        $field->set_date_format($this->_dt_frmt);
1586
-        $field->set_time_format($this->_tm_frmt);
1587
-        switch ($what) {
1588
-            case 'T':
1589
-                $this->_fields[ $field_name ] = $field->prepare_for_set_with_new_time(
1590
-                    $datetime_value,
1591
-                    $this->_fields[ $field_name ]
1592
-                );
1593
-                $this->_has_changes = true;
1594
-                break;
1595
-            case 'D':
1596
-                $this->_fields[ $field_name ] = $field->prepare_for_set_with_new_date(
1597
-                    $datetime_value,
1598
-                    $this->_fields[ $field_name ]
1599
-                );
1600
-                $this->_has_changes = true;
1601
-                break;
1602
-            case 'B':
1603
-                $this->_fields[ $field_name ] = $field->prepare_for_set($datetime_value);
1604
-                $this->_has_changes = true;
1605
-                break;
1606
-        }
1607
-        $this->_clear_cached_property($field_name);
1608
-    }
1609
-
1610
-
1611
-    /**
1612
-     * This will return a timestamp for the website timezone but ONLY when the current website timezone is different
1613
-     * than the timezone set for the website. NOTE, this currently only works well with methods that return values.  If
1614
-     * you use it with methods that echo values the $_timestamp property may not get reset to its original value and
1615
-     * that could lead to some unexpected results!
1616
-     *
1617
-     * @access public
1618
-     * @param string $field_name               This is the name of the field on the object that contains the date/time
1619
-     *                                         value being returned.
1620
-     * @param string $callback                 must match a valid method in this class (defaults to get_datetime)
1621
-     * @param mixed (array|string) $args       This is the arguments that will be passed to the callback.
1622
-     * @param string $prepend                  You can include something to prepend on the timestamp
1623
-     * @param string $append                   You can include something to append on the timestamp
1624
-     * @throws ReflectionException
1625
-     * @throws InvalidArgumentException
1626
-     * @throws InvalidInterfaceException
1627
-     * @throws InvalidDataTypeException
1628
-     * @throws EE_Error
1629
-     * @return string timestamp
1630
-     */
1631
-    public function display_in_my_timezone(
1632
-        $field_name,
1633
-        $callback = 'get_datetime',
1634
-        $args = null,
1635
-        $prepend = '',
1636
-        $append = ''
1637
-    ) {
1638
-        $timezone = EEH_DTT_Helper::get_timezone();
1639
-        if ($timezone === $this->_timezone) {
1640
-            return '';
1641
-        }
1642
-        $original_timezone = $this->_timezone;
1643
-        $this->set_timezone($timezone);
1644
-        $fn = (array) $field_name;
1645
-        $args = array_merge($fn, (array) $args);
1646
-        if (! method_exists($this, $callback)) {
1647
-            throw new EE_Error(
1648
-                sprintf(
1649
-                    esc_html__(
1650
-                        'The method named "%s" given as the callback param in "display_in_my_timezone" does not exist.  Please check your spelling',
1651
-                        'event_espresso'
1652
-                    ),
1653
-                    $callback
1654
-                )
1655
-            );
1656
-        }
1657
-        $args = (array) $args;
1658
-        $return = $prepend . call_user_func_array(array($this, $callback), $args) . $append;
1659
-        $this->set_timezone($original_timezone);
1660
-        return $return;
1661
-    }
1662
-
1663
-
1664
-    /**
1665
-     * Deletes this model object.
1666
-     * This calls the `EE_Base_Class::_delete` method.  Child classes wishing to change default behaviour should
1667
-     * override
1668
-     * `EE_Base_Class::_delete` NOT this class.
1669
-     *
1670
-     * @return boolean | int
1671
-     * @throws ReflectionException
1672
-     * @throws InvalidArgumentException
1673
-     * @throws InvalidInterfaceException
1674
-     * @throws InvalidDataTypeException
1675
-     * @throws EE_Error
1676
-     */
1677
-    public function delete()
1678
-    {
1679
-        /**
1680
-         * Called just before the `EE_Base_Class::_delete` method call.
1681
-         * Note:
1682
-         * `EE_Base_Class::_delete` might be overridden by child classes so any client code hooking into these actions
1683
-         * should be aware that `_delete` may not always result in a permanent delete.
1684
-         * For example, `EE_Soft_Delete_Base_Class::_delete`
1685
-         * soft deletes (trash) the object and does not permanently delete it.
1686
-         *
1687
-         * @param EE_Base_Class $model_object about to be 'deleted'
1688
-         */
1689
-        do_action('AHEE__EE_Base_Class__delete__before', $this);
1690
-        $result = $this->_delete();
1691
-        /**
1692
-         * Called just after the `EE_Base_Class::_delete` method call.
1693
-         * Note:
1694
-         * `EE_Base_Class::_delete` might be overridden by child classes so any client code hooking into these actions
1695
-         * should be aware that `_delete` may not always result in a permanent delete.
1696
-         * For example `EE_Soft_Base_Class::_delete`
1697
-         * soft deletes (trash) the object and does not permanently delete it.
1698
-         *
1699
-         * @param EE_Base_Class $model_object that was just 'deleted'
1700
-         * @param boolean       $result
1701
-         */
1702
-        do_action('AHEE__EE_Base_Class__delete__end', $this, $result);
1703
-        return $result;
1704
-    }
1705
-
1706
-
1707
-    /**
1708
-     * Calls the specific delete method for the instantiated class.
1709
-     * This method is called by the public `EE_Base_Class::delete` method.  Any child classes desiring to override
1710
-     * default functionality for "delete" (which is to call `permanently_delete`) should override this method NOT
1711
-     * `EE_Base_Class::delete`
1712
-     *
1713
-     * @return bool|int
1714
-     * @throws ReflectionException
1715
-     * @throws InvalidArgumentException
1716
-     * @throws InvalidInterfaceException
1717
-     * @throws InvalidDataTypeException
1718
-     * @throws EE_Error
1719
-     */
1720
-    protected function _delete()
1721
-    {
1722
-        return $this->delete_permanently();
1723
-    }
1724
-
1725
-
1726
-    /**
1727
-     * Deletes this model object permanently from db
1728
-     * (but keep in mind related models may block the delete and return an error)
1729
-     *
1730
-     * @return bool | int
1731
-     * @throws ReflectionException
1732
-     * @throws InvalidArgumentException
1733
-     * @throws InvalidInterfaceException
1734
-     * @throws InvalidDataTypeException
1735
-     * @throws EE_Error
1736
-     */
1737
-    public function delete_permanently()
1738
-    {
1739
-        /**
1740
-         * Called just before HARD deleting a model object
1741
-         *
1742
-         * @param EE_Base_Class $model_object about to be 'deleted'
1743
-         */
1744
-        do_action('AHEE__EE_Base_Class__delete_permanently__before', $this);
1745
-        $model = $this->get_model();
1746
-        $result = $model->delete_permanently_by_ID($this->ID());
1747
-        $this->refresh_cache_of_related_objects();
1748
-        /**
1749
-         * Called just after HARD deleting a model object
1750
-         *
1751
-         * @param EE_Base_Class $model_object that was just 'deleted'
1752
-         * @param boolean       $result
1753
-         */
1754
-        do_action('AHEE__EE_Base_Class__delete_permanently__end', $this, $result);
1755
-        return $result;
1756
-    }
1757
-
1758
-
1759
-    /**
1760
-     * When this model object is deleted, it may still be cached on related model objects. This clears the cache of
1761
-     * related model objects
1762
-     *
1763
-     * @throws ReflectionException
1764
-     * @throws InvalidArgumentException
1765
-     * @throws InvalidInterfaceException
1766
-     * @throws InvalidDataTypeException
1767
-     * @throws EE_Error
1768
-     */
1769
-    public function refresh_cache_of_related_objects()
1770
-    {
1771
-        $model = $this->get_model();
1772
-        foreach ($model->relation_settings() as $relation_name => $relation_obj) {
1773
-            if (! empty($this->_model_relations[ $relation_name ])) {
1774
-                $related_objects = $this->_model_relations[ $relation_name ];
1775
-                if ($relation_obj instanceof EE_Belongs_To_Relation) {
1776
-                    // this relation only stores a single model object, not an array
1777
-                    // but let's make it consistent
1778
-                    $related_objects = array($related_objects);
1779
-                }
1780
-                foreach ($related_objects as $related_object) {
1781
-                    // only refresh their cache if they're in memory
1782
-                    if ($related_object instanceof EE_Base_Class) {
1783
-                        $related_object->clear_cache(
1784
-                            $model->get_this_model_name(),
1785
-                            $this
1786
-                        );
1787
-                    }
1788
-                }
1789
-            }
1790
-        }
1791
-    }
1792
-
1793
-
1794
-    /**
1795
-     *        Saves this object to the database. An array may be supplied to set some values on this
1796
-     * object just before saving.
1797
-     *
1798
-     * @access public
1799
-     * @param array $set_cols_n_values keys are field names, values are their new values,
1800
-     *                                 if provided during the save() method (often client code will change the fields'
1801
-     *                                 values before calling save)
1802
-     * @return bool|int|string         1 on a successful update
1803
-     *                                 the ID of the new entry on insert
1804
-     *                                 0 on failure or if the model object isn't allowed to persist
1805
-     *                                 (as determined by EE_Base_Class::allow_persist())
1806
-     * @throws InvalidInterfaceException
1807
-     * @throws InvalidDataTypeException
1808
-     * @throws EE_Error
1809
-     * @throws InvalidArgumentException
1810
-     * @throws ReflectionException
1811
-     * @throws ReflectionException
1812
-     * @throws ReflectionException
1813
-     */
1814
-    public function save($set_cols_n_values = array())
1815
-    {
1816
-        $model = $this->get_model();
1817
-        /**
1818
-         * Filters the fields we're about to save on the model object
1819
-         *
1820
-         * @param array         $set_cols_n_values
1821
-         * @param EE_Base_Class $model_object
1822
-         */
1823
-        $set_cols_n_values = (array) apply_filters(
1824
-            'FHEE__EE_Base_Class__save__set_cols_n_values',
1825
-            $set_cols_n_values,
1826
-            $this
1827
-        );
1828
-        // set attributes as provided in $set_cols_n_values
1829
-        foreach ($set_cols_n_values as $column => $value) {
1830
-            $this->set($column, $value);
1831
-        }
1832
-        // no changes ? then don't do anything
1833
-        if (! $this->_has_changes && $this->ID() && $model->get_primary_key_field()->is_auto_increment()) {
1834
-            return 0;
1835
-        }
1836
-        /**
1837
-         * Saving a model object.
1838
-         * Before we perform a save, this action is fired.
1839
-         *
1840
-         * @param EE_Base_Class $model_object the model object about to be saved.
1841
-         */
1842
-        do_action('AHEE__EE_Base_Class__save__begin', $this);
1843
-        if (! $this->allow_persist()) {
1844
-            return 0;
1845
-        }
1846
-        // now get current attribute values
1847
-        $save_cols_n_values = $this->_fields;
1848
-        // if the object already has an ID, update it. Otherwise, insert it
1849
-        // also: change the assumption about values passed to the model NOT being prepare dby the model object.
1850
-        // They have been
1851
-        $old_assumption_concerning_value_preparation = $model
1852
-            ->get_assumption_concerning_values_already_prepared_by_model_object();
1853
-        $model->assume_values_already_prepared_by_model_object(true);
1854
-        // does this model have an autoincrement PK?
1855
-        if ($model->has_primary_key_field()) {
1856
-            if ($model->get_primary_key_field()->is_auto_increment()) {
1857
-                // ok check if it's set, if so: update; if not, insert
1858
-                if (! empty($save_cols_n_values[ $model->primary_key_name() ])) {
1859
-                    $results = $model->update_by_ID($save_cols_n_values, $this->ID());
1860
-                } else {
1861
-                    unset($save_cols_n_values[ $model->primary_key_name() ]);
1862
-                    $results = $model->insert($save_cols_n_values);
1863
-                    if ($results) {
1864
-                        // if successful, set the primary key
1865
-                        // but don't use the normal SET method, because it will check if
1866
-                        // an item with the same ID exists in the mapper & db, then
1867
-                        // will find it in the db (because we just added it) and THAT object
1868
-                        // will get added to the mapper before we can add this one!
1869
-                        // but if we just avoid using the SET method, all that headache can be avoided
1870
-                        $pk_field_name = $model->primary_key_name();
1871
-                        $this->_fields[ $pk_field_name ] = $results;
1872
-                        $this->_clear_cached_property($pk_field_name);
1873
-                        $model->add_to_entity_map($this);
1874
-                        $this->_update_cached_related_model_objs_fks();
1875
-                    }
1876
-                }
1877
-            } else {// PK is NOT auto-increment
1878
-                // so check if one like it already exists in the db
1879
-                if ($model->exists_by_ID($this->ID())) {
1880
-                    if (WP_DEBUG && ! $this->in_entity_map()) {
1881
-                        throw new EE_Error(
1882
-                            sprintf(
1883
-                                esc_html__(
1884
-                                    'Using a model object %1$s that is NOT in the entity map, can lead to unexpected errors. You should either: %4$s 1. Put it in the entity mapper by calling %2$s %4$s 2. Discard this model object and use what is in the entity mapper %4$s 3. Fetch from the database using %3$s',
1885
-                                    'event_espresso'
1886
-                                ),
1887
-                                get_class($this),
1888
-                                get_class($model) . '::instance()->add_to_entity_map()',
1889
-                                get_class($model) . '::instance()->get_one_by_ID()',
1890
-                                '<br />'
1891
-                            )
1892
-                        );
1893
-                    }
1894
-                    $results = $model->update_by_ID($save_cols_n_values, $this->ID());
1895
-                } else {
1896
-                    $results = $model->insert($save_cols_n_values);
1897
-                    $this->_update_cached_related_model_objs_fks();
1898
-                }
1899
-            }
1900
-        } else {// there is NO primary key
1901
-            $already_in_db = false;
1902
-            foreach ($model->unique_indexes() as $index) {
1903
-                $uniqueness_where_params = array_intersect_key($save_cols_n_values, $index->fields());
1904
-                if ($model->exists(array($uniqueness_where_params))) {
1905
-                    $already_in_db = true;
1906
-                }
1907
-            }
1908
-            if ($already_in_db) {
1909
-                $combined_pk_fields_n_values = array_intersect_key(
1910
-                    $save_cols_n_values,
1911
-                    $model->get_combined_primary_key_fields()
1912
-                );
1913
-                $results = $model->update(
1914
-                    $save_cols_n_values,
1915
-                    $combined_pk_fields_n_values
1916
-                );
1917
-            } else {
1918
-                $results = $model->insert($save_cols_n_values);
1919
-            }
1920
-        }
1921
-        // restore the old assumption about values being prepared by the model object
1922
-        $model->assume_values_already_prepared_by_model_object(
1923
-            $old_assumption_concerning_value_preparation
1924
-        );
1925
-        /**
1926
-         * After saving the model object this action is called
1927
-         *
1928
-         * @param EE_Base_Class $model_object which was just saved
1929
-         * @param boolean|int   $results      if it were updated, TRUE or FALSE; if it were newly inserted
1930
-         *                                    the new ID (or 0 if an error occurred and it wasn't updated)
1931
-         */
1932
-        do_action('AHEE__EE_Base_Class__save__end', $this, $results);
1933
-        $this->_has_changes = false;
1934
-        return $results;
1935
-    }
1936
-
1937
-
1938
-    /**
1939
-     * Updates the foreign key on related models objects pointing to this to have this model object's ID
1940
-     * as their foreign key.  If the cached related model objects already exist in the db, saves them (so that the DB
1941
-     * is consistent) Especially useful in case we JUST added this model object ot the database and we want to let its
1942
-     * cached relations with foreign keys to it know about that change. Eg: we've created a transaction but haven't
1943
-     * saved it to the db. We also create a registration and don't save it to the DB, but we DO cache it on the
1944
-     * transaction. Now, when we save the transaction, the registration's TXN_ID will be automatically updated, whether
1945
-     * or not they exist in the DB (if they do, their DB records will be automatically updated)
1946
-     *
1947
-     * @return void
1948
-     * @throws ReflectionException
1949
-     * @throws InvalidArgumentException
1950
-     * @throws InvalidInterfaceException
1951
-     * @throws InvalidDataTypeException
1952
-     * @throws EE_Error
1953
-     */
1954
-    protected function _update_cached_related_model_objs_fks()
1955
-    {
1956
-        $model = $this->get_model();
1957
-        foreach ($model->relation_settings() as $relation_name => $relation_obj) {
1958
-            if ($relation_obj instanceof EE_Has_Many_Relation) {
1959
-                foreach ($this->get_all_from_cache($relation_name) as $related_model_obj_in_cache) {
1960
-                    $fk_to_this = $related_model_obj_in_cache->get_model()->get_foreign_key_to(
1961
-                        $model->get_this_model_name()
1962
-                    );
1963
-                    $related_model_obj_in_cache->set($fk_to_this->get_name(), $this->ID());
1964
-                    if ($related_model_obj_in_cache->ID()) {
1965
-                        $related_model_obj_in_cache->save();
1966
-                    }
1967
-                }
1968
-            }
1969
-        }
1970
-    }
1971
-
1972
-
1973
-    /**
1974
-     * Saves this model object and its NEW cached relations to the database.
1975
-     * (Meaning, for now, IT DOES NOT WORK if the cached items already exist in the DB.
1976
-     * In order for that to work, we would need to mark model objects as dirty/clean...
1977
-     * because otherwise, there's a potential for infinite looping of saving
1978
-     * Saves the cached related model objects, and ensures the relation between them
1979
-     * and this object and properly setup
1980
-     *
1981
-     * @return int ID of new model object on save; 0 on failure+
1982
-     * @throws ReflectionException
1983
-     * @throws InvalidArgumentException
1984
-     * @throws InvalidInterfaceException
1985
-     * @throws InvalidDataTypeException
1986
-     * @throws EE_Error
1987
-     */
1988
-    public function save_new_cached_related_model_objs()
1989
-    {
1990
-        // make sure this has been saved
1991
-        if (! $this->ID()) {
1992
-            $id = $this->save();
1993
-        } else {
1994
-            $id = $this->ID();
1995
-        }
1996
-        // now save all the NEW cached model objects  (ie they don't exist in the DB)
1997
-        foreach ($this->get_model()->relation_settings() as $relationName => $relationObj) {
1998
-            if ($this->_model_relations[ $relationName ]) {
1999
-                // is this a relation where we should expect just ONE related object (ie, EE_Belongs_To_relation)
2000
-                // or MANY related objects (ie, EE_HABTM_Relation or EE_Has_Many_Relation)?
2001
-                /* @var $related_model_obj EE_Base_Class */
2002
-                if ($relationObj instanceof EE_Belongs_To_Relation) {
2003
-                    // add a relation to that relation type (which saves the appropriate thing in the process)
2004
-                    // but ONLY if it DOES NOT exist in the DB
2005
-                    $related_model_obj = $this->_model_relations[ $relationName ];
2006
-                    // if( ! $related_model_obj->ID()){
2007
-                    $this->_add_relation_to($related_model_obj, $relationName);
2008
-                    $related_model_obj->save_new_cached_related_model_objs();
2009
-                    // }
2010
-                } else {
2011
-                    foreach ($this->_model_relations[ $relationName ] as $related_model_obj) {
2012
-                        // add a relation to that relation type (which saves the appropriate thing in the process)
2013
-                        // but ONLY if it DOES NOT exist in the DB
2014
-                        // if( ! $related_model_obj->ID()){
2015
-                        $this->_add_relation_to($related_model_obj, $relationName);
2016
-                        $related_model_obj->save_new_cached_related_model_objs();
2017
-                        // }
2018
-                    }
2019
-                }
2020
-            }
2021
-        }
2022
-        return $id;
2023
-    }
2024
-
2025
-
2026
-    /**
2027
-     * for getting a model while instantiated.
2028
-     *
2029
-     * @return EEM_Base | EEM_CPT_Base
2030
-     * @throws ReflectionException
2031
-     * @throws InvalidArgumentException
2032
-     * @throws InvalidInterfaceException
2033
-     * @throws InvalidDataTypeException
2034
-     * @throws EE_Error
2035
-     */
2036
-    public function get_model()
2037
-    {
2038
-        if (! $this->_model) {
2039
-            $modelName = self::_get_model_classname(get_class($this));
2040
-            $this->_model = self::_get_model_instance_with_name($modelName, $this->_timezone);
2041
-        } else {
2042
-            $this->_model->set_timezone($this->_timezone);
2043
-        }
2044
-        return $this->_model;
2045
-    }
2046
-
2047
-
2048
-    /**
2049
-     * @param $props_n_values
2050
-     * @param $classname
2051
-     * @return mixed bool|EE_Base_Class|EEM_CPT_Base
2052
-     * @throws ReflectionException
2053
-     * @throws InvalidArgumentException
2054
-     * @throws InvalidInterfaceException
2055
-     * @throws InvalidDataTypeException
2056
-     * @throws EE_Error
2057
-     */
2058
-    protected static function _get_object_from_entity_mapper($props_n_values, $classname)
2059
-    {
2060
-        // TODO: will not work for Term_Relationships because they have no PK!
2061
-        $primary_id_ref = self::_get_primary_key_name($classname);
2062
-        if (
2063
-            array_key_exists($primary_id_ref, $props_n_values)
2064
-            && ! empty($props_n_values[ $primary_id_ref ])
2065
-        ) {
2066
-            $id = $props_n_values[ $primary_id_ref ];
2067
-            return self::_get_model($classname)->get_from_entity_map($id);
2068
-        }
2069
-        return false;
2070
-    }
2071
-
2072
-
2073
-    /**
2074
-     * This is called by child static "new_instance" method and we'll check to see if there is an existing db entry for
2075
-     * the primary key (if present in incoming values). If there is a key in the incoming array that matches the
2076
-     * primary key for the model AND it is not null, then we check the db. If there's a an object we return it.  If not
2077
-     * we return false.
2078
-     *
2079
-     * @param  array  $props_n_values   incoming array of properties and their values
2080
-     * @param  string $classname        the classname of the child class
2081
-     * @param null    $timezone
2082
-     * @param array   $date_formats     incoming date_formats in an array where the first value is the
2083
-     *                                  date_format and the second value is the time format
2084
-     * @return mixed (EE_Base_Class|bool)
2085
-     * @throws InvalidArgumentException
2086
-     * @throws InvalidInterfaceException
2087
-     * @throws InvalidDataTypeException
2088
-     * @throws EE_Error
2089
-     * @throws ReflectionException
2090
-     * @throws ReflectionException
2091
-     * @throws ReflectionException
2092
-     */
2093
-    protected static function _check_for_object($props_n_values, $classname, $timezone = null, $date_formats = array())
2094
-    {
2095
-        $existing = null;
2096
-        $model = self::_get_model($classname, $timezone);
2097
-        if ($model->has_primary_key_field()) {
2098
-            $primary_id_ref = self::_get_primary_key_name($classname);
2099
-            if (
2100
-                array_key_exists($primary_id_ref, $props_n_values)
2101
-                && ! empty($props_n_values[ $primary_id_ref ])
2102
-            ) {
2103
-                $existing = $model->get_one_by_ID(
2104
-                    $props_n_values[ $primary_id_ref ]
2105
-                );
2106
-            }
2107
-        } elseif ($model->has_all_combined_primary_key_fields($props_n_values)) {
2108
-            // no primary key on this model, but there's still a matching item in the DB
2109
-            $existing = self::_get_model($classname, $timezone)->get_one_by_ID(
2110
-                self::_get_model($classname, $timezone)
2111
-                    ->get_index_primary_key_string($props_n_values)
2112
-            );
2113
-        }
2114
-        if ($existing) {
2115
-            // set date formats if present before setting values
2116
-            if (! empty($date_formats) && is_array($date_formats)) {
2117
-                $existing->set_date_format($date_formats[0]);
2118
-                $existing->set_time_format($date_formats[1]);
2119
-            } else {
2120
-                // set default formats for date and time
2121
-                $existing->set_date_format(get_option('date_format'));
2122
-                $existing->set_time_format(get_option('time_format'));
2123
-            }
2124
-            foreach ($props_n_values as $property => $field_value) {
2125
-                $existing->set($property, $field_value);
2126
-            }
2127
-            return $existing;
2128
-        }
2129
-        return false;
2130
-    }
2131
-
2132
-
2133
-    /**
2134
-     * Gets the EEM_*_Model for this class
2135
-     *
2136
-     * @access public now, as this is more convenient
2137
-     * @param      $classname
2138
-     * @param null $timezone
2139
-     * @throws ReflectionException
2140
-     * @throws InvalidArgumentException
2141
-     * @throws InvalidInterfaceException
2142
-     * @throws InvalidDataTypeException
2143
-     * @throws EE_Error
2144
-     * @return EEM_Base
2145
-     */
2146
-    protected static function _get_model($classname, $timezone = null)
2147
-    {
2148
-        // find model for this class
2149
-        if (! $classname) {
2150
-            throw new EE_Error(
2151
-                sprintf(
2152
-                    esc_html__(
2153
-                        'What were you thinking calling _get_model(%s)?? You need to specify the class name',
2154
-                        'event_espresso'
2155
-                    ),
2156
-                    $classname
2157
-                )
2158
-            );
2159
-        }
2160
-        $modelName = self::_get_model_classname($classname);
2161
-        return self::_get_model_instance_with_name($modelName, $timezone);
2162
-    }
2163
-
2164
-
2165
-    /**
2166
-     * Gets the model instance (eg instance of EEM_Attendee) given its classname (eg EE_Attendee)
2167
-     *
2168
-     * @param string $model_classname
2169
-     * @param null   $timezone
2170
-     * @return EEM_Base
2171
-     * @throws ReflectionException
2172
-     * @throws InvalidArgumentException
2173
-     * @throws InvalidInterfaceException
2174
-     * @throws InvalidDataTypeException
2175
-     * @throws EE_Error
2176
-     */
2177
-    protected static function _get_model_instance_with_name($model_classname, $timezone = null)
2178
-    {
2179
-        $model_classname = str_replace('EEM_', '', $model_classname);
2180
-        $model = EE_Registry::instance()->load_model($model_classname);
2181
-        $model->set_timezone($timezone);
2182
-        return $model;
2183
-    }
2184
-
2185
-
2186
-    /**
2187
-     * If a model name is provided (eg Registration), gets the model classname for that model.
2188
-     * Also works if a model class's classname is provided (eg EE_Registration).
2189
-     *
2190
-     * @param string|null $model_name
2191
-     * @return string like EEM_Attendee
2192
-     */
2193
-    private static function _get_model_classname($model_name = '')
2194
-    {
2195
-        return strpos((string) $model_name, 'EE_') === 0
2196
-            ? str_replace('EE_', 'EEM_', $model_name)
2197
-            : 'EEM_' . $model_name;
2198
-    }
2199
-
2200
-
2201
-    /**
2202
-     * returns the name of the primary key attribute
2203
-     *
2204
-     * @param null $classname
2205
-     * @throws ReflectionException
2206
-     * @throws InvalidArgumentException
2207
-     * @throws InvalidInterfaceException
2208
-     * @throws InvalidDataTypeException
2209
-     * @throws EE_Error
2210
-     * @return string
2211
-     */
2212
-    protected static function _get_primary_key_name($classname = null)
2213
-    {
2214
-        if (! $classname) {
2215
-            throw new EE_Error(
2216
-                sprintf(
2217
-                    esc_html__('What were you thinking calling _get_primary_key_name(%s)', 'event_espresso'),
2218
-                    $classname
2219
-                )
2220
-            );
2221
-        }
2222
-        return self::_get_model($classname)->get_primary_key_field()->get_name();
2223
-    }
2224
-
2225
-
2226
-    /**
2227
-     * Gets the value of the primary key.
2228
-     * If the object hasn't yet been saved, it should be whatever the model field's default was
2229
-     * (eg, if this were the EE_Event class, look at the primary key field on EEM_Event and see what its default value
2230
-     * is. Usually defaults for integer primary keys are 0; string primary keys are usually NULL).
2231
-     *
2232
-     * @return mixed, if the primary key is of type INT it'll be an int. Otherwise it could be a string
2233
-     * @throws ReflectionException
2234
-     * @throws InvalidArgumentException
2235
-     * @throws InvalidInterfaceException
2236
-     * @throws InvalidDataTypeException
2237
-     * @throws EE_Error
2238
-     */
2239
-    public function ID()
2240
-    {
2241
-        $model = $this->get_model();
2242
-        // now that we know the name of the variable, use a variable variable to get its value and return its
2243
-        if ($model->has_primary_key_field()) {
2244
-            return $this->_fields[ $model->primary_key_name() ];
2245
-        }
2246
-        return $model->get_index_primary_key_string($this->_fields);
2247
-    }
2248
-
2249
-
2250
-    /**
2251
-     * @param EE_Base_Class|int|string $otherModelObjectOrID
2252
-     * @param string                   $relationName
2253
-     * @return bool
2254
-     * @throws EE_Error
2255
-     * @throws ReflectionException
2256
-     * @since   $VID:$
2257
-     */
2258
-    public function hasRelation($otherModelObjectOrID, string $relationName): bool
2259
-    {
2260
-        $other_model = self::_get_model_instance_with_name(
2261
-            self::_get_model_classname($relationName),
2262
-            $this->_timezone
2263
-        );
2264
-        $primary_key = $other_model->primary_key_name();
2265
-        /** @var EE_Base_Class $otherModelObject */
2266
-        $otherModelObject = $other_model->ensure_is_obj($otherModelObjectOrID, $relationName);
2267
-        return $this->count_related($relationName, [[$primary_key => $otherModelObject->ID()]]) > 0;
2268
-    }
2269
-
2270
-
2271
-    /**
2272
-     * Adds a relationship to the specified EE_Base_Class object, given the relationship's name. Eg, if the current
2273
-     * model is related to a group of events, the $relationName should be 'Event', and should be a key in the EE
2274
-     * Model's $_model_relations array. If this model object doesn't exist in the DB, just caches the related thing
2275
-     *
2276
-     * @param mixed  $otherObjectModelObjectOrID       EE_Base_Class or the ID of the other object
2277
-     * @param string $relationName                     eg 'Events','Question',etc.
2278
-     *                                                 an attendee to a group, you also want to specify which role they
2279
-     *                                                 will have in that group. So you would use this parameter to
2280
-     *                                                 specify array('role-column-name'=>'role-id')
2281
-     * @param array  $extra_join_model_fields_n_values You can optionally include an array of key=>value pairs that
2282
-     *                                                 allow you to further constrict the relation to being added.
2283
-     *                                                 However, keep in mind that the columns (keys) given must match a
2284
-     *                                                 column on the JOIN table and currently only the HABTM models
2285
-     *                                                 accept these additional conditions.  Also remember that if an
2286
-     *                                                 exact match isn't found for these extra cols/val pairs, then a
2287
-     *                                                 NEW row is created in the join table.
2288
-     * @param null   $cache_id
2289
-     * @throws ReflectionException
2290
-     * @throws InvalidArgumentException
2291
-     * @throws InvalidInterfaceException
2292
-     * @throws InvalidDataTypeException
2293
-     * @throws EE_Error
2294
-     * @return EE_Base_Class the object the relation was added to
2295
-     */
2296
-    public function _add_relation_to(
2297
-        $otherObjectModelObjectOrID,
2298
-        $relationName,
2299
-        $extra_join_model_fields_n_values = array(),
2300
-        $cache_id = null
2301
-    ) {
2302
-        $model = $this->get_model();
2303
-        // if this thing exists in the DB, save the relation to the DB
2304
-        if ($this->ID()) {
2305
-            $otherObject = $model->add_relationship_to(
2306
-                $this,
2307
-                $otherObjectModelObjectOrID,
2308
-                $relationName,
2309
-                $extra_join_model_fields_n_values
2310
-            );
2311
-            // clear cache so future get_many_related and get_first_related() return new results.
2312
-            $this->clear_cache($relationName, $otherObject, true);
2313
-            if ($otherObject instanceof EE_Base_Class) {
2314
-                $otherObject->clear_cache($model->get_this_model_name(), $this);
2315
-            }
2316
-        } else {
2317
-            // this thing doesn't exist in the DB,  so just cache it
2318
-            if (! $otherObjectModelObjectOrID instanceof EE_Base_Class) {
2319
-                throw new EE_Error(
2320
-                    sprintf(
2321
-                        esc_html__(
2322
-                            'Before a model object is saved to the database, calls to _add_relation_to must be passed an actual object, not just an ID. You provided %s as the model object to a %s',
2323
-                            'event_espresso'
2324
-                        ),
2325
-                        $otherObjectModelObjectOrID,
2326
-                        get_class($this)
2327
-                    )
2328
-                );
2329
-            }
2330
-            $otherObject = $otherObjectModelObjectOrID;
2331
-            $this->cache($relationName, $otherObjectModelObjectOrID, $cache_id);
2332
-        }
2333
-        if ($otherObject instanceof EE_Base_Class) {
2334
-            // fix the reciprocal relation too
2335
-            if ($otherObject->ID()) {
2336
-                // its saved so assumed relations exist in the DB, so we can just
2337
-                // clear the cache so future queries use the updated info in the DB
2338
-                $otherObject->clear_cache(
2339
-                    $model->get_this_model_name(),
2340
-                    null,
2341
-                    true
2342
-                );
2343
-            } else {
2344
-                // it's not saved, so it caches relations like this
2345
-                $otherObject->cache($model->get_this_model_name(), $this);
2346
-            }
2347
-        }
2348
-        return $otherObject;
2349
-    }
2350
-
2351
-
2352
-    /**
2353
-     * Removes a relationship to the specified EE_Base_Class object, given the relationships' name. Eg, if the current
2354
-     * model is related to a group of events, the $relationName should be 'Events', and should be a key in the EE
2355
-     * Model's $_model_relations array. If this model object doesn't exist in the DB, just removes the related thing
2356
-     * from the cache
2357
-     *
2358
-     * @param mixed  $otherObjectModelObjectOrID
2359
-     *                EE_Base_Class or the ID of the other object, OR an array key into the cache if this isn't saved
2360
-     *                to the DB yet
2361
-     * @param string $relationName
2362
-     * @param array  $where_query
2363
-     *                You can optionally include an array of key=>value pairs that allow you to further constrict the
2364
-     *                relation to being added. However, keep in mind that the columns (keys) given must match a column
2365
-     *                on the JOIN table and currently only the HABTM models accept these additional conditions. Also
2366
-     *                remember that if an exact match isn't found for these extra cols/val pairs, then no row is
2367
-     *                deleted.
2368
-     * @return EE_Base_Class the relation was removed from
2369
-     * @throws ReflectionException
2370
-     * @throws InvalidArgumentException
2371
-     * @throws InvalidInterfaceException
2372
-     * @throws InvalidDataTypeException
2373
-     * @throws EE_Error
2374
-     */
2375
-    public function _remove_relation_to($otherObjectModelObjectOrID, $relationName, $where_query = array())
2376
-    {
2377
-        if ($this->ID()) {
2378
-            // if this exists in the DB, save the relation change to the DB too
2379
-            $otherObject = $this->get_model()->remove_relationship_to(
2380
-                $this,
2381
-                $otherObjectModelObjectOrID,
2382
-                $relationName,
2383
-                $where_query
2384
-            );
2385
-            $this->clear_cache(
2386
-                $relationName,
2387
-                $otherObject
2388
-            );
2389
-        } else {
2390
-            // this doesn't exist in the DB, just remove it from the cache
2391
-            $otherObject = $this->clear_cache(
2392
-                $relationName,
2393
-                $otherObjectModelObjectOrID
2394
-            );
2395
-        }
2396
-        if ($otherObject instanceof EE_Base_Class) {
2397
-            $otherObject->clear_cache(
2398
-                $this->get_model()->get_this_model_name(),
2399
-                $this
2400
-            );
2401
-        }
2402
-        return $otherObject;
2403
-    }
2404
-
2405
-
2406
-    /**
2407
-     * Removes ALL the related things for the $relationName.
2408
-     *
2409
-     * @param string $relationName
2410
-     * @param array  $where_query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
2411
-     * @return EE_Base_Class
2412
-     * @throws ReflectionException
2413
-     * @throws InvalidArgumentException
2414
-     * @throws InvalidInterfaceException
2415
-     * @throws InvalidDataTypeException
2416
-     * @throws EE_Error
2417
-     */
2418
-    public function _remove_relations($relationName, $where_query_params = array())
2419
-    {
2420
-        if ($this->ID()) {
2421
-            // if this exists in the DB, save the relation change to the DB too
2422
-            $otherObjects = $this->get_model()->remove_relations(
2423
-                $this,
2424
-                $relationName,
2425
-                $where_query_params
2426
-            );
2427
-            $this->clear_cache(
2428
-                $relationName,
2429
-                null,
2430
-                true
2431
-            );
2432
-        } else {
2433
-            // this doesn't exist in the DB, just remove it from the cache
2434
-            $otherObjects = $this->clear_cache(
2435
-                $relationName,
2436
-                null,
2437
-                true
2438
-            );
2439
-        }
2440
-        if (is_array($otherObjects)) {
2441
-            foreach ($otherObjects as $otherObject) {
2442
-                $otherObject->clear_cache(
2443
-                    $this->get_model()->get_this_model_name(),
2444
-                    $this
2445
-                );
2446
-            }
2447
-        }
2448
-        return $otherObjects;
2449
-    }
2450
-
2451
-
2452
-    /**
2453
-     * Gets all the related model objects of the specified type. Eg, if the current class if
2454
-     * EE_Event, you could call $this->get_many_related('Registration') to get an array of all the
2455
-     * EE_Registration objects which related to this event. Note: by default, we remove the "default query params"
2456
-     * because we want to get even deleted items etc.
2457
-     *
2458
-     * @param string $relationName key in the model's _model_relations array
2459
-     * @param array  $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
2460
-     * @return EE_Base_Class[]     Results not necessarily indexed by IDs, because some results might not have primary
2461
-     *                             keys or might not be saved yet. Consider using EEM_Base::get_IDs() on these
2462
-     *                             results if you want IDs
2463
-     * @throws ReflectionException
2464
-     * @throws InvalidArgumentException
2465
-     * @throws InvalidInterfaceException
2466
-     * @throws InvalidDataTypeException
2467
-     * @throws EE_Error
2468
-     */
2469
-    public function get_many_related($relationName, $query_params = array())
2470
-    {
2471
-        if ($this->ID()) {
2472
-            // this exists in the DB, so get the related things from either the cache or the DB
2473
-            // if there are query parameters, forget about caching the related model objects.
2474
-            if ($query_params) {
2475
-                $related_model_objects = $this->get_model()->get_all_related(
2476
-                    $this,
2477
-                    $relationName,
2478
-                    $query_params
2479
-                );
2480
-            } else {
2481
-                // did we already cache the result of this query?
2482
-                $cached_results = $this->get_all_from_cache($relationName);
2483
-                if (! $cached_results) {
2484
-                    $related_model_objects = $this->get_model()->get_all_related(
2485
-                        $this,
2486
-                        $relationName,
2487
-                        $query_params
2488
-                    );
2489
-                    // if no query parameters were passed, then we got all the related model objects
2490
-                    // for that relation. We can cache them then.
2491
-                    foreach ($related_model_objects as $related_model_object) {
2492
-                        $this->cache($relationName, $related_model_object);
2493
-                    }
2494
-                } else {
2495
-                    $related_model_objects = $cached_results;
2496
-                }
2497
-            }
2498
-        } else {
2499
-            // this doesn't exist in the DB, so just get the related things from the cache
2500
-            $related_model_objects = $this->get_all_from_cache($relationName);
2501
-        }
2502
-        return $related_model_objects;
2503
-    }
2504
-
2505
-
2506
-    /**
2507
-     * Instead of getting the related model objects, simply counts them. Ignores default_where_conditions by default,
2508
-     * unless otherwise specified in the $query_params
2509
-     *
2510
-     * @param string $relation_name  model_name like 'Event', or 'Registration'
2511
-     * @param array  $query_params   @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2512
-     * @param string $field_to_count name of field to count by. By default, uses primary key
2513
-     * @param bool   $distinct       if we want to only count the distinct values for the column then you can trigger
2514
-     *                               that by the setting $distinct to TRUE;
2515
-     * @return int
2516
-     * @throws ReflectionException
2517
-     * @throws InvalidArgumentException
2518
-     * @throws InvalidInterfaceException
2519
-     * @throws InvalidDataTypeException
2520
-     * @throws EE_Error
2521
-     */
2522
-    public function count_related($relation_name, $query_params = array(), $field_to_count = null, $distinct = false)
2523
-    {
2524
-        return $this->get_model()->count_related(
2525
-            $this,
2526
-            $relation_name,
2527
-            $query_params,
2528
-            $field_to_count,
2529
-            $distinct
2530
-        );
2531
-    }
2532
-
2533
-
2534
-    /**
2535
-     * Instead of getting the related model objects, simply sums up the values of the specified field.
2536
-     * Note: ignores default_where_conditions by default, unless otherwise specified in the $query_params
2537
-     *
2538
-     * @param string $relation_name model_name like 'Event', or 'Registration'
2539
-     * @param array  $query_params  @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2540
-     * @param string $field_to_sum  name of field to count by.
2541
-     *                              By default, uses primary key
2542
-     *                              (which doesn't make much sense, so you should probably change it)
2543
-     * @return int
2544
-     * @throws ReflectionException
2545
-     * @throws InvalidArgumentException
2546
-     * @throws InvalidInterfaceException
2547
-     * @throws InvalidDataTypeException
2548
-     * @throws EE_Error
2549
-     */
2550
-    public function sum_related($relation_name, $query_params = array(), $field_to_sum = null)
2551
-    {
2552
-        return $this->get_model()->sum_related(
2553
-            $this,
2554
-            $relation_name,
2555
-            $query_params,
2556
-            $field_to_sum
2557
-        );
2558
-    }
2559
-
2560
-
2561
-    /**
2562
-     * Gets the first (ie, one) related model object of the specified type.
2563
-     *
2564
-     * @param string $relationName key in the model's _model_relations array
2565
-     * @param array  $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2566
-     * @return EE_Base_Class (not an array, a single object)
2567
-     * @throws ReflectionException
2568
-     * @throws InvalidArgumentException
2569
-     * @throws InvalidInterfaceException
2570
-     * @throws InvalidDataTypeException
2571
-     * @throws EE_Error
2572
-     */
2573
-    public function get_first_related($relationName, $query_params = array())
2574
-    {
2575
-        $model = $this->get_model();
2576
-        if ($this->ID()) {// this exists in the DB, get from the cache OR the DB
2577
-            // if they've provided some query parameters, don't bother trying to cache the result
2578
-            // also make sure we're not caching the result of get_first_related
2579
-            // on a relation which should have an array of objects (because the cache might have an array of objects)
2580
-            if (
2581
-                $query_params
2582
-                || ! $model->related_settings_for($relationName)
2583
-                     instanceof
2584
-                     EE_Belongs_To_Relation
2585
-            ) {
2586
-                $related_model_object = $model->get_first_related(
2587
-                    $this,
2588
-                    $relationName,
2589
-                    $query_params
2590
-                );
2591
-            } else {
2592
-                // first, check if we've already cached the result of this query
2593
-                $cached_result = $this->get_one_from_cache($relationName);
2594
-                if (! $cached_result) {
2595
-                    $related_model_object = $model->get_first_related(
2596
-                        $this,
2597
-                        $relationName,
2598
-                        $query_params
2599
-                    );
2600
-                    $this->cache($relationName, $related_model_object);
2601
-                } else {
2602
-                    $related_model_object = $cached_result;
2603
-                }
2604
-            }
2605
-        } else {
2606
-            $related_model_object = null;
2607
-            // this doesn't exist in the Db,
2608
-            // but maybe the relation is of type belongs to, and so the related thing might
2609
-            if ($model->related_settings_for($relationName) instanceof EE_Belongs_To_Relation) {
2610
-                $related_model_object = $model->get_first_related(
2611
-                    $this,
2612
-                    $relationName,
2613
-                    $query_params
2614
-                );
2615
-            }
2616
-            // this doesn't exist in the DB and apparently the thing it belongs to doesn't either,
2617
-            // just get what's cached on this object
2618
-            if (! $related_model_object) {
2619
-                $related_model_object = $this->get_one_from_cache($relationName);
2620
-            }
2621
-        }
2622
-        return $related_model_object;
2623
-    }
2624
-
2625
-
2626
-    /**
2627
-     * Does a delete on all related objects of type $relationName and removes
2628
-     * the current model object's relation to them. If they can't be deleted (because
2629
-     * of blocking related model objects) does nothing. If the related model objects are
2630
-     * soft-deletable, they will be soft-deleted regardless of related blocking model objects.
2631
-     * If this model object doesn't exist yet in the DB, just removes its related things
2632
-     *
2633
-     * @param string $relationName
2634
-     * @param array  $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2635
-     * @return int how many deleted
2636
-     * @throws ReflectionException
2637
-     * @throws InvalidArgumentException
2638
-     * @throws InvalidInterfaceException
2639
-     * @throws InvalidDataTypeException
2640
-     * @throws EE_Error
2641
-     */
2642
-    public function delete_related($relationName, $query_params = array())
2643
-    {
2644
-        if ($this->ID()) {
2645
-            $count = $this->get_model()->delete_related(
2646
-                $this,
2647
-                $relationName,
2648
-                $query_params
2649
-            );
2650
-        } else {
2651
-            $count = count($this->get_all_from_cache($relationName));
2652
-            $this->clear_cache($relationName, null, true);
2653
-        }
2654
-        return $count;
2655
-    }
2656
-
2657
-
2658
-    /**
2659
-     * Does a hard delete (ie, removes the DB row) on all related objects of type $relationName and removes
2660
-     * the current model object's relation to them. If they can't be deleted (because
2661
-     * of blocking related model objects) just does a soft delete on it instead, if possible.
2662
-     * If the related thing isn't a soft-deletable model object, this function is identical
2663
-     * to delete_related(). If this model object doesn't exist in the DB, just remove its related things
2664
-     *
2665
-     * @param string $relationName
2666
-     * @param array  $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2667
-     * @return int how many deleted (including those soft deleted)
2668
-     * @throws ReflectionException
2669
-     * @throws InvalidArgumentException
2670
-     * @throws InvalidInterfaceException
2671
-     * @throws InvalidDataTypeException
2672
-     * @throws EE_Error
2673
-     */
2674
-    public function delete_related_permanently($relationName, $query_params = array())
2675
-    {
2676
-        if ($this->ID()) {
2677
-            $count = $this->get_model()->delete_related_permanently(
2678
-                $this,
2679
-                $relationName,
2680
-                $query_params
2681
-            );
2682
-        } else {
2683
-            $count = count($this->get_all_from_cache($relationName));
2684
-        }
2685
-        $this->clear_cache($relationName, null, true);
2686
-        return $count;
2687
-    }
2688
-
2689
-
2690
-    /**
2691
-     * is_set
2692
-     * Just a simple utility function children can use for checking if property exists
2693
-     *
2694
-     * @access  public
2695
-     * @param  string $field_name property to check
2696
-     * @return bool                              TRUE if existing,FALSE if not.
2697
-     */
2698
-    public function is_set($field_name)
2699
-    {
2700
-        return isset($this->_fields[ $field_name ]);
2701
-    }
2702
-
2703
-
2704
-    /**
2705
-     * Just a simple utility function children can use for checking if property (or properties) exists and throwing an
2706
-     * EE_Error exception if they don't
2707
-     *
2708
-     * @param  mixed (string|array) $properties properties to check
2709
-     * @throws EE_Error
2710
-     * @return bool                              TRUE if existing, throw EE_Error if not.
2711
-     */
2712
-    protected function _property_exists($properties)
2713
-    {
2714
-        foreach ((array) $properties as $property_name) {
2715
-            // first make sure this property exists
2716
-            if (! $this->_fields[ $property_name ]) {
2717
-                throw new EE_Error(
2718
-                    sprintf(
2719
-                        esc_html__(
2720
-                            'Trying to retrieve a non-existent property (%s).  Double check the spelling please',
2721
-                            'event_espresso'
2722
-                        ),
2723
-                        $property_name
2724
-                    )
2725
-                );
2726
-            }
2727
-        }
2728
-        return true;
2729
-    }
2730
-
2731
-
2732
-    /**
2733
-     * This simply returns an array of model fields for this object
2734
-     *
2735
-     * @return array
2736
-     * @throws ReflectionException
2737
-     * @throws InvalidArgumentException
2738
-     * @throws InvalidInterfaceException
2739
-     * @throws InvalidDataTypeException
2740
-     * @throws EE_Error
2741
-     */
2742
-    public function model_field_array()
2743
-    {
2744
-        $fields = $this->get_model()->field_settings(false);
2745
-        $properties = array();
2746
-        // remove prepended underscore
2747
-        foreach ($fields as $field_name => $settings) {
2748
-            $properties[ $field_name ] = $this->get($field_name);
2749
-        }
2750
-        return $properties;
2751
-    }
2752
-
2753
-
2754
-    /**
2755
-     * Very handy general function to allow for plugins to extend any child of EE_Base_Class.
2756
-     * If a method is called on a child of EE_Base_Class that doesn't exist, this function is called
2757
-     * (http://www.garfieldtech.com/blog/php-magic-call) and passed the method's name and arguments.
2758
-     * Instead of requiring a plugin to extend the EE_Base_Class
2759
-     * (which works fine is there's only 1 plugin, but when will that happen?)
2760
-     * they can add a hook onto 'filters_hook_espresso__{className}__{methodName}'
2761
-     * (eg, filters_hook_espresso__EE_Answer__my_great_function)
2762
-     * and accepts 2 arguments: the object on which the function was called,
2763
-     * and an array of the original arguments passed to the function.
2764
-     * Whatever their callback function returns will be returned by this function.
2765
-     * Example: in functions.php (or in a plugin):
2766
-     *      add_filter('FHEE__EE_Answer__my_callback','my_callback',10,3);
2767
-     *      function my_callback($previousReturnValue,EE_Base_Class $object,$argsArray){
2768
-     *          $returnString= "you called my_callback! and passed args:".implode(",",$argsArray);
2769
-     *          return $previousReturnValue.$returnString;
2770
-     *      }
2771
-     * require('EE_Answer.class.php');
2772
-     * echo EE_Answer::new_instance(['REG_ID' => 2,'QST_ID' => 3,'ANS_value' => The answer is 42'])
2773
-     *      ->my_callback('monkeys',100);
2774
-     * // will output "you called my_callback! and passed args:monkeys,100"
2775
-     *
2776
-     * @param string $methodName name of method which was called on a child of EE_Base_Class, but which
2777
-     * @param array  $args       array of original arguments passed to the function
2778
-     * @throws EE_Error
2779
-     * @return mixed whatever the plugin which calls add_filter decides
2780
-     */
2781
-    public function __call($methodName, $args)
2782
-    {
2783
-        $className = get_class($this);
2784
-        $tagName = "FHEE__{$className}__{$methodName}";
2785
-        if (! has_filter($tagName)) {
2786
-            throw new EE_Error(
2787
-                sprintf(
2788
-                    esc_html__(
2789
-                        "Method %s on class %s does not exist! You can create one with the following code in functions.php or in a plugin: add_filter('%s','my_callback',10,3);function my_callback(\$previousReturnValue,EE_Base_Class \$object, \$argsArray){/*function body*/return \$whatever;}",
2790
-                        'event_espresso'
2791
-                    ),
2792
-                    $methodName,
2793
-                    $className,
2794
-                    $tagName
2795
-                )
2796
-            );
2797
-        }
2798
-        return apply_filters($tagName, null, $this, $args);
2799
-    }
2800
-
2801
-
2802
-    /**
2803
-     * Similar to insert_post_meta, adds a record in the Extra_Meta model's table with the given key and value.
2804
-     * A $previous_value can be specified in case there are many meta rows with the same key
2805
-     *
2806
-     * @param string $meta_key
2807
-     * @param mixed  $meta_value
2808
-     * @param mixed  $previous_value
2809
-     * @return bool|int # of records updated (or BOOLEAN if we actually ended up inserting the extra meta row)
2810
-     *                  NOTE: if the values haven't changed, returns 0
2811
-     * @throws InvalidArgumentException
2812
-     * @throws InvalidInterfaceException
2813
-     * @throws InvalidDataTypeException
2814
-     * @throws EE_Error
2815
-     * @throws ReflectionException
2816
-     */
2817
-    public function update_extra_meta(string $meta_key, $meta_value, $previous_value = null)
2818
-    {
2819
-        $query_params = [
2820
-            [
2821
-                'EXM_key'  => $meta_key,
2822
-                'OBJ_ID'   => $this->ID(),
2823
-                'EXM_type' => $this->get_model()->get_this_model_name(),
2824
-            ],
2825
-        ];
2826
-        if ($previous_value !== null) {
2827
-            $query_params[0]['EXM_value'] = $meta_value;
2828
-        }
2829
-        $existing_rows_like_that = EEM_Extra_Meta::instance()->get_all($query_params);
2830
-        if (! $existing_rows_like_that) {
2831
-            return $this->add_extra_meta($meta_key, $meta_value);
2832
-        }
2833
-        foreach ($existing_rows_like_that as $existing_row) {
2834
-            $existing_row->save(['EXM_value' => $meta_value]);
2835
-        }
2836
-        return count($existing_rows_like_that);
2837
-    }
2838
-
2839
-
2840
-    /**
2841
-     * Adds a new extra meta record. If $unique is set to TRUE, we'll first double-check
2842
-     * no other extra meta for this model object have the same key. Returns TRUE if the
2843
-     * extra meta row was entered, false if not
2844
-     *
2845
-     * @param string $meta_key
2846
-     * @param mixed  $meta_value
2847
-     * @param bool   $unique
2848
-     * @return bool
2849
-     * @throws InvalidArgumentException
2850
-     * @throws InvalidInterfaceException
2851
-     * @throws InvalidDataTypeException
2852
-     * @throws EE_Error
2853
-     * @throws ReflectionException
2854
-     * @throws ReflectionException
2855
-     */
2856
-    public function add_extra_meta(string $meta_key, $meta_value, bool $unique = false): bool
2857
-    {
2858
-        if ($unique) {
2859
-            $existing_extra_meta = EEM_Extra_Meta::instance()->get_one(
2860
-                [
2861
-                    [
2862
-                        'EXM_key'  => $meta_key,
2863
-                        'OBJ_ID'   => $this->ID(),
2864
-                        'EXM_type' => $this->get_model()->get_this_model_name(),
2865
-                    ],
2866
-                ]
2867
-            );
2868
-            if ($existing_extra_meta) {
2869
-                return false;
2870
-            }
2871
-        }
2872
-        $new_extra_meta = EE_Extra_Meta::new_instance(
2873
-            [
2874
-                'EXM_key'   => $meta_key,
2875
-                'EXM_value' => $meta_value,
2876
-                'OBJ_ID'    => $this->ID(),
2877
-                'EXM_type'  => $this->get_model()->get_this_model_name(),
2878
-            ]
2879
-        );
2880
-        $new_extra_meta->save();
2881
-        return true;
2882
-    }
2883
-
2884
-
2885
-    /**
2886
-     * Deletes all the extra meta rows for this record as specified by key. If $meta_value
2887
-     * is specified, only deletes extra meta records with that value.
2888
-     *
2889
-     * @param string $meta_key
2890
-     * @param mixed  $meta_value
2891
-     * @return int|bool number of extra meta rows deleted
2892
-     * @throws InvalidArgumentException
2893
-     * @throws InvalidInterfaceException
2894
-     * @throws InvalidDataTypeException
2895
-     * @throws EE_Error
2896
-     * @throws ReflectionException
2897
-     */
2898
-    public function delete_extra_meta(string $meta_key, $meta_value = null)
2899
-    {
2900
-        $query_params = [
2901
-            [
2902
-                'EXM_key'  => $meta_key,
2903
-                'OBJ_ID'   => $this->ID(),
2904
-                'EXM_type' => $this->get_model()->get_this_model_name(),
2905
-            ],
2906
-        ];
2907
-        if ($meta_value !== null) {
2908
-            $query_params[0]['EXM_value'] = $meta_value;
2909
-        }
2910
-        return EEM_Extra_Meta::instance()->delete($query_params);
2911
-    }
2912
-
2913
-
2914
-    /**
2915
-     * Gets the extra meta with the given meta key. If you specify "single" we just return 1, otherwise
2916
-     * an array of everything found. Requires that this model actually have a relation of type EE_Has_Many_Any_Relation.
2917
-     * You can specify $default is case you haven't found the extra meta
2918
-     *
2919
-     * @param string     $meta_key
2920
-     * @param bool       $single
2921
-     * @param mixed      $default if we don't find anything, what should we return?
2922
-     * @param array|null $extra_where
2923
-     * @return mixed single value if $single; array if ! $single
2924
-     * @throws ReflectionException
2925
-     * @throws EE_Error
2926
-     */
2927
-    public function get_extra_meta(string $meta_key, bool $single = false, $default = null, ?array $extra_where = [])
2928
-    {
2929
-        $query_params = [ $extra_where + ['EXM_key' => $meta_key] ];
2930
-        if ($single) {
2931
-            $result = $this->get_first_related('Extra_Meta', $query_params);
2932
-            if ($result instanceof EE_Extra_Meta) {
2933
-                return $result->value();
2934
-            }
2935
-        } else {
2936
-            $results = $this->get_many_related('Extra_Meta', $query_params);
2937
-            if ($results) {
2938
-                $values = [];
2939
-                foreach ($results as $result) {
2940
-                    if ($result instanceof EE_Extra_Meta) {
2941
-                        $values[ $result->ID() ] = $result->value();
2942
-                    }
2943
-                }
2944
-                return $values;
2945
-            }
2946
-        }
2947
-        // if nothing discovered yet return default.
2948
-        return apply_filters(
2949
-            'FHEE__EE_Base_Class__get_extra_meta__default_value',
2950
-            $default,
2951
-            $meta_key,
2952
-            $single,
2953
-            $this
2954
-        );
2955
-    }
2956
-
2957
-
2958
-    /**
2959
-     * Returns a simple array of all the extra meta associated with this model object.
2960
-     * If $one_of_each_key is true (Default), it will be an array of simple key-value pairs, keys being the
2961
-     * extra meta's key, and teh value being its value. However, if there are duplicate extra meta rows with
2962
-     * the same key, only one will be used. (eg array('foo'=>'bar','monkey'=>123))
2963
-     * If $one_of_each_key is false, it will return an array with the top-level keys being
2964
-     * the extra meta keys, but their values are also arrays, which have the extra-meta's ID as their sub-key, and
2965
-     * finally the extra meta's value as each sub-value. (eg
2966
-     * array('foo'=>array(1=>'bar',2=>'bill'),'monkey'=>array(3=>123)))
2967
-     *
2968
-     * @param bool $one_of_each_key
2969
-     * @return array
2970
-     * @throws ReflectionException
2971
-     * @throws InvalidArgumentException
2972
-     * @throws InvalidInterfaceException
2973
-     * @throws InvalidDataTypeException
2974
-     * @throws EE_Error
2975
-     */
2976
-    public function all_extra_meta_array(bool $one_of_each_key = true): array
2977
-    {
2978
-        $return_array = [];
2979
-        if ($one_of_each_key) {
2980
-            $extra_meta_objs = $this->get_many_related(
2981
-                'Extra_Meta',
2982
-                ['group_by' => 'EXM_key']
2983
-            );
2984
-            foreach ($extra_meta_objs as $extra_meta_obj) {
2985
-                if ($extra_meta_obj instanceof EE_Extra_Meta) {
2986
-                    $return_array[ $extra_meta_obj->key() ] = $extra_meta_obj->value();
2987
-                }
2988
-            }
2989
-        } else {
2990
-            $extra_meta_objs = $this->get_many_related('Extra_Meta');
2991
-            foreach ($extra_meta_objs as $extra_meta_obj) {
2992
-                if ($extra_meta_obj instanceof EE_Extra_Meta) {
2993
-                    if (! isset($return_array[ $extra_meta_obj->key() ])) {
2994
-                        $return_array[ $extra_meta_obj->key() ] = [];
2995
-                    }
2996
-                    $return_array[ $extra_meta_obj->key() ][ $extra_meta_obj->ID() ] = $extra_meta_obj->value();
2997
-                }
2998
-            }
2999
-        }
3000
-        return $return_array;
3001
-    }
3002
-
3003
-
3004
-    /**
3005
-     * Gets a pretty nice displayable nice for this model object. Often overridden
3006
-     *
3007
-     * @return string
3008
-     * @throws ReflectionException
3009
-     * @throws InvalidArgumentException
3010
-     * @throws InvalidInterfaceException
3011
-     * @throws InvalidDataTypeException
3012
-     * @throws EE_Error
3013
-     */
3014
-    public function name()
3015
-    {
3016
-        // find a field that's not a text field
3017
-        $field_we_can_use = $this->get_model()->get_a_field_of_type('EE_Text_Field_Base');
3018
-        if ($field_we_can_use) {
3019
-            return $this->get($field_we_can_use->get_name());
3020
-        }
3021
-        $first_few_properties = $this->model_field_array();
3022
-        $first_few_properties = array_slice($first_few_properties, 0, 3);
3023
-        $name_parts = array();
3024
-        foreach ($first_few_properties as $name => $value) {
3025
-            $name_parts[] = "$name:$value";
3026
-        }
3027
-        return implode(',', $name_parts);
3028
-    }
3029
-
3030
-
3031
-    /**
3032
-     * in_entity_map
3033
-     * Checks if this model object has been proven to already be in the entity map
3034
-     *
3035
-     * @return boolean
3036
-     * @throws ReflectionException
3037
-     * @throws InvalidArgumentException
3038
-     * @throws InvalidInterfaceException
3039
-     * @throws InvalidDataTypeException
3040
-     * @throws EE_Error
3041
-     */
3042
-    public function in_entity_map()
3043
-    {
3044
-        // well, if we looked, did we find it in the entity map?
3045
-        return $this->ID() && $this->get_model()->get_from_entity_map($this->ID()) === $this;
3046
-    }
3047
-
3048
-
3049
-    /**
3050
-     * refresh_from_db
3051
-     * Makes sure the fields and values on this model object are in-sync with what's in the database.
3052
-     *
3053
-     * @throws ReflectionException
3054
-     * @throws InvalidArgumentException
3055
-     * @throws InvalidInterfaceException
3056
-     * @throws InvalidDataTypeException
3057
-     * @throws EE_Error if this model object isn't in the entity mapper (because then you should
3058
-     * just use what's in the entity mapper and refresh it) and WP_DEBUG is TRUE
3059
-     */
3060
-    public function refresh_from_db()
3061
-    {
3062
-        if ($this->ID() && $this->in_entity_map()) {
3063
-            $this->get_model()->refresh_entity_map_from_db($this->ID());
3064
-        } else {
3065
-            // if it doesn't have ID, you shouldn't be asking to refresh it from teh database (because its not in the database)
3066
-            // if it has an ID but it's not in the map, and you're asking me to refresh it
3067
-            // that's kinda dangerous. You should just use what's in the entity map, or add this to the entity map if there's
3068
-            // absolutely nothing in it for this ID
3069
-            if (WP_DEBUG) {
3070
-                throw new EE_Error(
3071
-                    sprintf(
3072
-                        esc_html__(
3073
-                            'Trying to refresh a model object with ID "%1$s" that\'s not in the entity map? First off: you should put it in the entity map by calling %2$s. Second off, if you want what\'s in the database right now, you should just call %3$s yourself and discard this model object.',
3074
-                            'event_espresso'
3075
-                        ),
3076
-                        $this->ID(),
3077
-                        get_class($this->get_model()) . '::instance()->add_to_entity_map()',
3078
-                        get_class($this->get_model()) . '::instance()->refresh_entity_map()'
3079
-                    )
3080
-                );
3081
-            }
3082
-        }
3083
-    }
3084
-
3085
-
3086
-    /**
3087
-     * Change $fields' values to $new_value_sql (which is a string of raw SQL)
3088
-     *
3089
-     * @since 4.9.80.p
3090
-     * @param EE_Model_Field_Base[] $fields
3091
-     * @param string $new_value_sql
3092
-     *      example: 'column_name=123',
3093
-     *      or 'column_name=column_name+1',
3094
-     *      or 'column_name= CASE
3095
-     *          WHEN (`column_name` + `other_column` + 5) <= `yet_another_column`
3096
-     *          THEN `column_name` + 5
3097
-     *          ELSE `column_name`
3098
-     *      END'
3099
-     *      Also updates $field on this model object with the latest value from the database.
3100
-     * @return bool
3101
-     * @throws EE_Error
3102
-     * @throws InvalidArgumentException
3103
-     * @throws InvalidDataTypeException
3104
-     * @throws InvalidInterfaceException
3105
-     * @throws ReflectionException
3106
-     */
3107
-    protected function updateFieldsInDB($fields, $new_value_sql)
3108
-    {
3109
-        // First make sure this model object actually exists in the DB. It would be silly to try to update it in the DB
3110
-        // if it wasn't even there to start off.
3111
-        if (! $this->ID()) {
3112
-            $this->save();
3113
-        }
3114
-        global $wpdb;
3115
-        if (empty($fields)) {
3116
-            throw new InvalidArgumentException(
3117
-                esc_html__(
3118
-                    'EE_Base_Class::updateFieldsInDB was passed an empty array of fields.',
3119
-                    'event_espresso'
3120
-                )
3121
-            );
3122
-        }
3123
-        $first_field = reset($fields);
3124
-        $table_alias = $first_field->get_table_alias();
3125
-        foreach ($fields as $field) {
3126
-            if ($table_alias !== $field->get_table_alias()) {
3127
-                throw new InvalidArgumentException(
3128
-                    sprintf(
3129
-                        esc_html__(
3130
-                            // @codingStandardsIgnoreStart
3131
-                            'EE_Base_Class::updateFieldsInDB was passed fields for different tables ("%1$s" and "%2$s"), which is not supported. Instead, please call the method multiple times.',
3132
-                            // @codingStandardsIgnoreEnd
3133
-                            'event_espresso'
3134
-                        ),
3135
-                        $table_alias,
3136
-                        $field->get_table_alias()
3137
-                    )
3138
-                );
3139
-            }
3140
-        }
3141
-        // Ok the fields are now known to all be for the same table. Proceed with creating the SQL to update it.
3142
-        $table_obj = $this->get_model()->get_table_obj_by_alias($table_alias);
3143
-        $table_pk_value = $this->ID();
3144
-        $table_name = $table_obj->get_table_name();
3145
-        if ($table_obj instanceof EE_Secondary_Table) {
3146
-            $table_pk_field_name = $table_obj->get_fk_on_table();
3147
-        } else {
3148
-            $table_pk_field_name = $table_obj->get_pk_column();
3149
-        }
3150
-
3151
-        $query =
3152
-            "UPDATE `{$table_name}`
337
+				$this->_props_n_values_provided_in_constructor
338
+				&& $field_value
339
+				&& $field_name === $model->primary_key_name()
340
+			) {
341
+				// if so, we want all this object's fields to be filled either with
342
+				// what we've explicitly set on this model
343
+				// or what we have in the db
344
+				// echo "setting primary key!";
345
+				$fields_on_model = self::_get_model(get_class($this))->field_settings();
346
+				$obj_in_db = self::_get_model(get_class($this))->get_one_by_ID($field_value);
347
+				foreach ($fields_on_model as $field_obj) {
348
+					if (
349
+						! array_key_exists($field_obj->get_name(), $this->_props_n_values_provided_in_constructor)
350
+						&& $field_obj->get_name() !== $field_name
351
+					) {
352
+						$this->set($field_obj->get_name(), $obj_in_db->get($field_obj->get_name()));
353
+					}
354
+				}
355
+				// oh this model object has an ID? well make sure its in the entity mapper
356
+				$model->add_to_entity_map($this);
357
+			}
358
+			// let's unset any cache for this field_name from the $_cached_properties property.
359
+			$this->_clear_cached_property($field_name);
360
+		} else {
361
+			throw new EE_Error(
362
+				sprintf(
363
+					esc_html__(
364
+						'A valid EE_Model_Field_Base could not be found for the given field name: %s',
365
+						'event_espresso'
366
+					),
367
+					$field_name
368
+				)
369
+			);
370
+		}
371
+	}
372
+
373
+
374
+	/**
375
+	 * Set custom select values for model.
376
+	 *
377
+	 * @param array $custom_select_values
378
+	 */
379
+	public function setCustomSelectsValues(array $custom_select_values)
380
+	{
381
+		$this->custom_selection_results = $custom_select_values;
382
+	}
383
+
384
+
385
+	/**
386
+	 * Returns the custom select value for the provided alias if its set.
387
+	 * If not set, returns null.
388
+	 *
389
+	 * @param string $alias
390
+	 * @return string|int|float|null
391
+	 */
392
+	public function getCustomSelect($alias)
393
+	{
394
+		return isset($this->custom_selection_results[ $alias ])
395
+			? $this->custom_selection_results[ $alias ]
396
+			: null;
397
+	}
398
+
399
+
400
+	/**
401
+	 * This sets the field value on the db column if it exists for the given $column_name or
402
+	 * saves it to EE_Extra_Meta if the given $column_name does not match a db column.
403
+	 *
404
+	 * @see EE_message::get_column_value for related documentation on the necessity of this method.
405
+	 * @param string $field_name  Must be the exact column name.
406
+	 * @param mixed  $field_value The value to set.
407
+	 * @return int|bool @see EE_Base_Class::update_extra_meta() for return docs.
408
+	 * @throws InvalidArgumentException
409
+	 * @throws InvalidInterfaceException
410
+	 * @throws InvalidDataTypeException
411
+	 * @throws EE_Error
412
+	 * @throws ReflectionException
413
+	 */
414
+	public function set_field_or_extra_meta($field_name, $field_value)
415
+	{
416
+		if ($this->get_model()->has_field($field_name)) {
417
+			$this->set($field_name, $field_value);
418
+			return true;
419
+		}
420
+		// ensure this object is saved first so that extra meta can be properly related.
421
+		$this->save();
422
+		return $this->update_extra_meta($field_name, $field_value);
423
+	}
424
+
425
+
426
+	/**
427
+	 * This retrieves the value of the db column set on this class or if that's not present
428
+	 * it will attempt to retrieve from extra_meta if found.
429
+	 * Example Usage:
430
+	 * Via EE_Message child class:
431
+	 * Due to the dynamic nature of the EE_messages system, EE_messengers will always have a "to",
432
+	 * "from", "subject", and "content" field (as represented in the EE_Message schema), however they may
433
+	 * also have additional main fields specific to the messenger.  The system accommodates those extra
434
+	 * fields through the EE_Extra_Meta table.  This method allows for EE_messengers to retrieve the
435
+	 * value for those extra fields dynamically via the EE_message object.
436
+	 *
437
+	 * @param  string $field_name expecting the fully qualified field name.
438
+	 * @return mixed|null  value for the field if found.  null if not found.
439
+	 * @throws ReflectionException
440
+	 * @throws InvalidArgumentException
441
+	 * @throws InvalidInterfaceException
442
+	 * @throws InvalidDataTypeException
443
+	 * @throws EE_Error
444
+	 */
445
+	public function get_field_or_extra_meta($field_name)
446
+	{
447
+		if ($this->get_model()->has_field($field_name)) {
448
+			$column_value = $this->get($field_name);
449
+		} else {
450
+			// This isn't a column in the main table, let's see if it is in the extra meta.
451
+			$column_value = $this->get_extra_meta($field_name, true, null);
452
+		}
453
+		return $column_value;
454
+	}
455
+
456
+
457
+	/**
458
+	 * See $_timezone property for description of what the timezone property is for.  This SETS the timezone internally
459
+	 * for being able to reference what timezone we are running conversions on when converting TO the internal timezone
460
+	 * (UTC Unix Timestamp) for the object OR when converting FROM the internal timezone (UTC Unix Timestamp). This is
461
+	 * available to all child classes that may be using the EE_Datetime_Field for a field data type.
462
+	 *
463
+	 * @access public
464
+	 * @param string $timezone A valid timezone string as described by @link http://www.php.net/manual/en/timezones.php
465
+	 * @return void
466
+	 * @throws InvalidArgumentException
467
+	 * @throws InvalidInterfaceException
468
+	 * @throws InvalidDataTypeException
469
+	 * @throws EE_Error
470
+	 * @throws ReflectionException
471
+	 */
472
+	public function set_timezone($timezone = '')
473
+	{
474
+		$this->_timezone = EEH_DTT_Helper::get_valid_timezone_string($timezone);
475
+		// make sure we clear all cached properties because they won't be relevant now
476
+		$this->_clear_cached_properties();
477
+		// make sure we update field settings and the date for all EE_Datetime_Fields
478
+		$model_fields = $this->get_model()->field_settings(false);
479
+		foreach ($model_fields as $field_name => $field_obj) {
480
+			if ($field_obj instanceof EE_Datetime_Field) {
481
+				$field_obj->set_timezone($this->_timezone);
482
+				if (isset($this->_fields[ $field_name ]) && $this->_fields[ $field_name ] instanceof DateTime) {
483
+					EEH_DTT_Helper::setTimezone($this->_fields[ $field_name ], new DateTimeZone($this->_timezone));
484
+				}
485
+			}
486
+		}
487
+	}
488
+
489
+
490
+	/**
491
+	 * This just returns whatever is set for the current timezone.
492
+	 *
493
+	 * @access public
494
+	 * @return string timezone string
495
+	 */
496
+	public function get_timezone()
497
+	{
498
+		return $this->_timezone;
499
+	}
500
+
501
+
502
+	/**
503
+	 * This sets the internal date format to what is sent in to be used as the new default for the class
504
+	 * internally instead of wp set date format options
505
+	 *
506
+	 * @since 4.6
507
+	 * @param string $format should be a format recognizable by PHP date() functions.
508
+	 */
509
+	public function set_date_format($format)
510
+	{
511
+		$this->_dt_frmt = $format;
512
+		// clear cached_properties because they won't be relevant now.
513
+		$this->_clear_cached_properties();
514
+	}
515
+
516
+
517
+	/**
518
+	 * This sets the internal time format string to what is sent in to be used as the new default for the
519
+	 * class internally instead of wp set time format options.
520
+	 *
521
+	 * @since 4.6
522
+	 * @param string $format should be a format recognizable by PHP date() functions.
523
+	 */
524
+	public function set_time_format($format)
525
+	{
526
+		$this->_tm_frmt = $format;
527
+		// clear cached_properties because they won't be relevant now.
528
+		$this->_clear_cached_properties();
529
+	}
530
+
531
+
532
+	/**
533
+	 * This returns the current internal set format for the date and time formats.
534
+	 *
535
+	 * @param bool $full           if true (default), then return the full format.  Otherwise will return an array
536
+	 *                             where the first value is the date format and the second value is the time format.
537
+	 * @return mixed string|array
538
+	 */
539
+	public function get_format($full = true)
540
+	{
541
+		return $full ? $this->_dt_frmt . ' ' . $this->_tm_frmt : array($this->_dt_frmt, $this->_tm_frmt);
542
+	}
543
+
544
+
545
+	/**
546
+	 * cache
547
+	 * stores the passed model object on the current model object.
548
+	 * In certain circumstances, we can use this cached model object instead of querying for another one entirely.
549
+	 *
550
+	 * @param string        $relationName    one of the keys in the _model_relations array on the model. Eg
551
+	 *                                       'Registration' associated with this model object
552
+	 * @param EE_Base_Class $object_to_cache that has a relation to this model object. (Eg, if this is a Transaction,
553
+	 *                                       that could be a payment or a registration)
554
+	 * @param null          $cache_id        a string or number that will be used as the key for any Belongs_To_Many
555
+	 *                                       items which will be stored in an array on this object
556
+	 * @throws ReflectionException
557
+	 * @throws InvalidArgumentException
558
+	 * @throws InvalidInterfaceException
559
+	 * @throws InvalidDataTypeException
560
+	 * @throws EE_Error
561
+	 * @return mixed    index into cache, or just TRUE if the relation is of type Belongs_To (because there's only one
562
+	 *                                       related thing, no array)
563
+	 */
564
+	public function cache($relationName = '', $object_to_cache = null, $cache_id = null)
565
+	{
566
+		// its entirely possible that there IS no related object yet in which case there is nothing to cache.
567
+		if (! $object_to_cache instanceof EE_Base_Class) {
568
+			return false;
569
+		}
570
+		// also get "how" the object is related, or throw an error
571
+		if (! $relationship_to_model = $this->get_model()->related_settings_for($relationName)) {
572
+			throw new EE_Error(
573
+				sprintf(
574
+					esc_html__('There is no relationship to %s on a %s. Cannot cache it', 'event_espresso'),
575
+					$relationName,
576
+					get_class($this)
577
+				)
578
+			);
579
+		}
580
+		// how many things are related ?
581
+		if ($relationship_to_model instanceof EE_Belongs_To_Relation) {
582
+			// if it's a "belongs to" relationship, then there's only one related model object
583
+			// eg, if this is a registration, there's only 1 attendee for it
584
+			// so for these model objects just set it to be cached
585
+			$this->_model_relations[ $relationName ] = $object_to_cache;
586
+			$return = true;
587
+		} else {
588
+			// otherwise, this is the "many" side of a one to many relationship,
589
+			// so we'll add the object to the array of related objects for that type.
590
+			// eg: if this is an event, there are many registrations for that event,
591
+			// so we cache the registrations in an array
592
+			if (! is_array($this->_model_relations[ $relationName ])) {
593
+				// if for some reason, the cached item is a model object,
594
+				// then stick that in the array, otherwise start with an empty array
595
+				$this->_model_relations[ $relationName ] = $this->_model_relations[ $relationName ]
596
+														   instanceof
597
+														   EE_Base_Class
598
+					? array($this->_model_relations[ $relationName ]) : array();
599
+			}
600
+			// first check for a cache_id which is normally empty
601
+			if (! empty($cache_id)) {
602
+				// if the cache_id exists, then it means we are purposely trying to cache this
603
+				// with a known key that can then be used to retrieve the object later on
604
+				$this->_model_relations[ $relationName ][ $cache_id ] = $object_to_cache;
605
+				$return = $cache_id;
606
+			} elseif ($object_to_cache->ID()) {
607
+				// OR the cached object originally came from the db, so let's just use it's PK for an ID
608
+				$this->_model_relations[ $relationName ][ $object_to_cache->ID() ] = $object_to_cache;
609
+				$return = $object_to_cache->ID();
610
+			} else {
611
+				// OR it's a new object with no ID, so just throw it in the array with an auto-incremented ID
612
+				$this->_model_relations[ $relationName ][] = $object_to_cache;
613
+				// move the internal pointer to the end of the array
614
+				end($this->_model_relations[ $relationName ]);
615
+				// and grab the key so that we can return it
616
+				$return = key($this->_model_relations[ $relationName ]);
617
+			}
618
+		}
619
+		return $return;
620
+	}
621
+
622
+
623
+	/**
624
+	 * For adding an item to the cached_properties property.
625
+	 *
626
+	 * @access protected
627
+	 * @param string      $fieldname the property item the corresponding value is for.
628
+	 * @param mixed       $value     The value we are caching.
629
+	 * @param string|null $cache_type
630
+	 * @return void
631
+	 * @throws ReflectionException
632
+	 * @throws InvalidArgumentException
633
+	 * @throws InvalidInterfaceException
634
+	 * @throws InvalidDataTypeException
635
+	 * @throws EE_Error
636
+	 */
637
+	protected function _set_cached_property($fieldname, $value, $cache_type = null)
638
+	{
639
+		// first make sure this property exists
640
+		$this->get_model()->field_settings_for($fieldname);
641
+		$cache_type = empty($cache_type) ? 'standard' : $cache_type;
642
+		$this->_cached_properties[ $fieldname ][ $cache_type ] = $value;
643
+	}
644
+
645
+
646
+	/**
647
+	 * This returns the value cached property if it exists OR the actual property value if the cache doesn't exist.
648
+	 * This also SETS the cache if we return the actual property!
649
+	 *
650
+	 * @param string $fieldname        the name of the property we're trying to retrieve
651
+	 * @param bool   $pretty
652
+	 * @param string $extra_cache_ref  This allows the user to specify an extra cache ref for the given property
653
+	 *                                 (in cases where the same property may be used for different outputs
654
+	 *                                 - i.e. datetime, money etc.)
655
+	 *                                 It can also accept certain pre-defined "schema" strings
656
+	 *                                 to define how to output the property.
657
+	 *                                 see the field's prepare_for_pretty_echoing for what strings can be used
658
+	 * @return mixed                   whatever the value for the property is we're retrieving
659
+	 * @throws ReflectionException
660
+	 * @throws InvalidArgumentException
661
+	 * @throws InvalidInterfaceException
662
+	 * @throws InvalidDataTypeException
663
+	 * @throws EE_Error
664
+	 */
665
+	protected function _get_cached_property($fieldname, $pretty = false, $extra_cache_ref = null)
666
+	{
667
+		// verify the field exists
668
+		$model = $this->get_model();
669
+		$model->field_settings_for($fieldname);
670
+		$cache_type = $pretty ? 'pretty' : 'standard';
671
+		$cache_type .= ! empty($extra_cache_ref) ? '_' . $extra_cache_ref : '';
672
+		if (isset($this->_cached_properties[ $fieldname ][ $cache_type ])) {
673
+			return $this->_cached_properties[ $fieldname ][ $cache_type ];
674
+		}
675
+		$value = $this->_get_fresh_property($fieldname, $pretty, $extra_cache_ref);
676
+		$this->_set_cached_property($fieldname, $value, $cache_type);
677
+		return $value;
678
+	}
679
+
680
+
681
+	/**
682
+	 * If the cache didn't fetch the needed item, this fetches it.
683
+	 *
684
+	 * @param string $fieldname
685
+	 * @param bool   $pretty
686
+	 * @param string $extra_cache_ref
687
+	 * @return mixed
688
+	 * @throws InvalidArgumentException
689
+	 * @throws InvalidInterfaceException
690
+	 * @throws InvalidDataTypeException
691
+	 * @throws EE_Error
692
+	 * @throws ReflectionException
693
+	 */
694
+	protected function _get_fresh_property($fieldname, $pretty = false, $extra_cache_ref = null)
695
+	{
696
+		$field_obj = $this->get_model()->field_settings_for($fieldname);
697
+		// If this is an EE_Datetime_Field we need to make sure timezone, formats, and output are correct
698
+		if ($field_obj instanceof EE_Datetime_Field) {
699
+			$this->_prepare_datetime_field($field_obj, $pretty, $extra_cache_ref);
700
+		}
701
+		if (! isset($this->_fields[ $fieldname ])) {
702
+			$this->_fields[ $fieldname ] = null;
703
+		}
704
+		return $pretty
705
+			? $field_obj->prepare_for_pretty_echoing($this->_fields[ $fieldname ], $extra_cache_ref)
706
+			: $field_obj->prepare_for_get($this->_fields[ $fieldname ]);
707
+	}
708
+
709
+
710
+	/**
711
+	 * set timezone, formats, and output for EE_Datetime_Field objects
712
+	 *
713
+	 * @param EE_Datetime_Field $datetime_field
714
+	 * @param bool              $pretty
715
+	 * @param null              $date_or_time
716
+	 * @return void
717
+	 * @throws InvalidArgumentException
718
+	 * @throws InvalidInterfaceException
719
+	 * @throws InvalidDataTypeException
720
+	 */
721
+	protected function _prepare_datetime_field(
722
+		EE_Datetime_Field $datetime_field,
723
+		$pretty = false,
724
+		$date_or_time = null
725
+	) {
726
+		$datetime_field->set_timezone($this->_timezone);
727
+		$datetime_field->set_date_format($this->_dt_frmt, $pretty);
728
+		$datetime_field->set_time_format($this->_tm_frmt, $pretty);
729
+		// set the output returned
730
+		switch ($date_or_time) {
731
+			case 'D':
732
+				$datetime_field->set_date_time_output('date');
733
+				break;
734
+			case 'T':
735
+				$datetime_field->set_date_time_output('time');
736
+				break;
737
+			default:
738
+				$datetime_field->set_date_time_output();
739
+		}
740
+	}
741
+
742
+
743
+	/**
744
+	 * This just takes care of clearing out the cached_properties
745
+	 *
746
+	 * @return void
747
+	 */
748
+	protected function _clear_cached_properties()
749
+	{
750
+		$this->_cached_properties = array();
751
+	}
752
+
753
+
754
+	/**
755
+	 * This just clears out ONE property if it exists in the cache
756
+	 *
757
+	 * @param  string $property_name the property to remove if it exists (from the _cached_properties array)
758
+	 * @return void
759
+	 */
760
+	protected function _clear_cached_property($property_name)
761
+	{
762
+		if (isset($this->_cached_properties[ $property_name ])) {
763
+			unset($this->_cached_properties[ $property_name ]);
764
+		}
765
+	}
766
+
767
+
768
+	/**
769
+	 * Ensures that this related thing is a model object.
770
+	 *
771
+	 * @param mixed  $object_or_id EE_base_Class/int/string either a related model object, or its ID
772
+	 * @param string $model_name   name of the related thing, eg 'Attendee',
773
+	 * @return EE_Base_Class
774
+	 * @throws ReflectionException
775
+	 * @throws InvalidArgumentException
776
+	 * @throws InvalidInterfaceException
777
+	 * @throws InvalidDataTypeException
778
+	 * @throws EE_Error
779
+	 */
780
+	protected function ensure_related_thing_is_model_obj($object_or_id, $model_name)
781
+	{
782
+		$other_model_instance = self::_get_model_instance_with_name(
783
+			self::_get_model_classname($model_name),
784
+			$this->_timezone
785
+		);
786
+		return $other_model_instance->ensure_is_obj($object_or_id);
787
+	}
788
+
789
+
790
+	/**
791
+	 * Forgets the cached model of the given relation Name. So the next time we request it,
792
+	 * we will fetch it again from the database. (Handy if you know it's changed somehow).
793
+	 * If a specific object is supplied, and the relationship to it is either a HasMany or HABTM,
794
+	 * then only remove that one object from our cached array. Otherwise, clear the entire list
795
+	 *
796
+	 * @param string $relationName                         one of the keys in the _model_relations array on the model.
797
+	 *                                                     Eg 'Registration'
798
+	 * @param mixed  $object_to_remove_or_index_into_array or an index into the array of cached things, or NULL
799
+	 *                                                     if you intend to use $clear_all = TRUE, or the relation only
800
+	 *                                                     has 1 object anyways (ie, it's a BelongsToRelation)
801
+	 * @param bool   $clear_all                            This flags clearing the entire cache relation property if
802
+	 *                                                     this is HasMany or HABTM.
803
+	 * @throws ReflectionException
804
+	 * @throws InvalidArgumentException
805
+	 * @throws InvalidInterfaceException
806
+	 * @throws InvalidDataTypeException
807
+	 * @throws EE_Error
808
+	 * @return EE_Base_Class | boolean from which was cleared from the cache, or true if we requested to remove a
809
+	 *                                                     relation from all
810
+	 */
811
+	public function clear_cache($relationName, $object_to_remove_or_index_into_array = null, $clear_all = false)
812
+	{
813
+		$relationship_to_model = $this->get_model()->related_settings_for($relationName);
814
+		$index_in_cache = '';
815
+		if (! $relationship_to_model) {
816
+			throw new EE_Error(
817
+				sprintf(
818
+					esc_html__('There is no relationship to %s on a %s. Cannot clear that cache', 'event_espresso'),
819
+					$relationName,
820
+					get_class($this)
821
+				)
822
+			);
823
+		}
824
+		if ($clear_all) {
825
+			$obj_removed = true;
826
+			$this->_model_relations[ $relationName ] = null;
827
+		} elseif ($relationship_to_model instanceof EE_Belongs_To_Relation) {
828
+			$obj_removed = $this->_model_relations[ $relationName ];
829
+			$this->_model_relations[ $relationName ] = null;
830
+		} else {
831
+			if (
832
+				$object_to_remove_or_index_into_array instanceof EE_Base_Class
833
+				&& $object_to_remove_or_index_into_array->ID()
834
+			) {
835
+				$index_in_cache = $object_to_remove_or_index_into_array->ID();
836
+				if (
837
+					is_array($this->_model_relations[ $relationName ])
838
+					&& ! isset($this->_model_relations[ $relationName ][ $index_in_cache ])
839
+				) {
840
+					$index_found_at = null;
841
+					// find this object in the array even though it has a different key
842
+					foreach ($this->_model_relations[ $relationName ] as $index => $obj) {
843
+						/** @noinspection TypeUnsafeComparisonInspection */
844
+						if (
845
+							$obj instanceof EE_Base_Class
846
+							&& (
847
+								$obj == $object_to_remove_or_index_into_array
848
+								|| $obj->ID() === $object_to_remove_or_index_into_array->ID()
849
+							)
850
+						) {
851
+							$index_found_at = $index;
852
+							break;
853
+						}
854
+					}
855
+					if ($index_found_at) {
856
+						$index_in_cache = $index_found_at;
857
+					} else {
858
+						// it wasn't found. huh. well obviously it doesn't need to be removed from teh cache
859
+						// if it wasn't in it to begin with. So we're done
860
+						return $object_to_remove_or_index_into_array;
861
+					}
862
+				}
863
+			} elseif ($object_to_remove_or_index_into_array instanceof EE_Base_Class) {
864
+				// so they provided a model object, but it's not yet saved to the DB... so let's go hunting for it!
865
+				foreach ($this->get_all_from_cache($relationName) as $index => $potentially_obj_we_want) {
866
+					/** @noinspection TypeUnsafeComparisonInspection */
867
+					if ($potentially_obj_we_want == $object_to_remove_or_index_into_array) {
868
+						$index_in_cache = $index;
869
+					}
870
+				}
871
+			} else {
872
+				$index_in_cache = $object_to_remove_or_index_into_array;
873
+			}
874
+			// supposedly we've found it. But it could just be that the client code
875
+			// provided a bad index/object
876
+			if (isset($this->_model_relations[ $relationName ][ $index_in_cache ])) {
877
+				$obj_removed = $this->_model_relations[ $relationName ][ $index_in_cache ];
878
+				unset($this->_model_relations[ $relationName ][ $index_in_cache ]);
879
+			} else {
880
+				// that thing was never cached anyways.
881
+				$obj_removed = null;
882
+			}
883
+		}
884
+		return $obj_removed;
885
+	}
886
+
887
+
888
+	/**
889
+	 * update_cache_after_object_save
890
+	 * Allows a cached item to have it's cache ID (within the array of cached items) reset using the new ID it has
891
+	 * obtained after being saved to the db
892
+	 *
893
+	 * @param string        $relationName       - the type of object that is cached
894
+	 * @param EE_Base_Class $newly_saved_object - the newly saved object to be re-cached
895
+	 * @param string        $current_cache_id   - the ID that was used when originally caching the object
896
+	 * @return boolean TRUE on success, FALSE on fail
897
+	 * @throws ReflectionException
898
+	 * @throws InvalidArgumentException
899
+	 * @throws InvalidInterfaceException
900
+	 * @throws InvalidDataTypeException
901
+	 * @throws EE_Error
902
+	 */
903
+	public function update_cache_after_object_save(
904
+		$relationName,
905
+		EE_Base_Class $newly_saved_object,
906
+		$current_cache_id = ''
907
+	) {
908
+		// verify that incoming object is of the correct type
909
+		$obj_class = 'EE_' . $relationName;
910
+		if ($newly_saved_object instanceof $obj_class) {
911
+			/* @type EE_Base_Class $newly_saved_object */
912
+			// now get the type of relation
913
+			$relationship_to_model = $this->get_model()->related_settings_for($relationName);
914
+			// if this is a 1:1 relationship
915
+			if ($relationship_to_model instanceof EE_Belongs_To_Relation) {
916
+				// then just replace the cached object with the newly saved object
917
+				$this->_model_relations[ $relationName ] = $newly_saved_object;
918
+				return true;
919
+				// or if it's some kind of sordid feral polyamorous relationship...
920
+			}
921
+			if (
922
+				is_array($this->_model_relations[ $relationName ])
923
+				&& isset($this->_model_relations[ $relationName ][ $current_cache_id ])
924
+			) {
925
+				// then remove the current cached item
926
+				unset($this->_model_relations[ $relationName ][ $current_cache_id ]);
927
+				// and cache the newly saved object using it's new ID
928
+				$this->_model_relations[ $relationName ][ $newly_saved_object->ID() ] = $newly_saved_object;
929
+				return true;
930
+			}
931
+		}
932
+		return false;
933
+	}
934
+
935
+
936
+	/**
937
+	 * Fetches a single EE_Base_Class on that relation. (If the relation is of type
938
+	 * BelongsTo, it will only ever have 1 object. However, other relations could have an array of objects)
939
+	 *
940
+	 * @param string $relationName
941
+	 * @return EE_Base_Class
942
+	 */
943
+	public function get_one_from_cache($relationName)
944
+	{
945
+		$cached_array_or_object = isset($this->_model_relations[ $relationName ])
946
+			? $this->_model_relations[ $relationName ]
947
+			: null;
948
+		if (is_array($cached_array_or_object)) {
949
+			return array_shift($cached_array_or_object);
950
+		}
951
+		return $cached_array_or_object;
952
+	}
953
+
954
+
955
+	/**
956
+	 * Fetches a single EE_Base_Class on that relation. (If the relation is of type
957
+	 * BelongsTo, it will only ever have 1 object. However, other relations could have an array of objects)
958
+	 *
959
+	 * @param string $relationName
960
+	 * @throws ReflectionException
961
+	 * @throws InvalidArgumentException
962
+	 * @throws InvalidInterfaceException
963
+	 * @throws InvalidDataTypeException
964
+	 * @throws EE_Error
965
+	 * @return EE_Base_Class[] NOT necessarily indexed by primary keys
966
+	 */
967
+	public function get_all_from_cache($relationName)
968
+	{
969
+		$objects = isset($this->_model_relations[ $relationName ]) ? $this->_model_relations[ $relationName ] : array();
970
+		// if the result is not an array, but exists, make it an array
971
+		$objects = is_array($objects) ? $objects : array($objects);
972
+		// bugfix for https://events.codebasehq.com/projects/event-espresso/tickets/7143
973
+		// basically, if this model object was stored in the session, and these cached model objects
974
+		// already have IDs, let's make sure they're in their model's entity mapper
975
+		// otherwise we will have duplicates next time we call
976
+		// EE_Registry::instance()->load_model( $relationName )->get_one_by_ID( $result->ID() );
977
+		$model = EE_Registry::instance()->load_model($relationName);
978
+		foreach ($objects as $model_object) {
979
+			if ($model instanceof EEM_Base && $model_object instanceof EE_Base_Class) {
980
+				// ensure its in the map if it has an ID; otherwise it will be added to the map when its saved
981
+				if ($model_object->ID()) {
982
+					$model->add_to_entity_map($model_object);
983
+				}
984
+			} else {
985
+				throw new EE_Error(
986
+					sprintf(
987
+						esc_html__(
988
+							'Error retrieving related model objects. Either $1%s is not a model or $2%s is not a model object',
989
+							'event_espresso'
990
+						),
991
+						$relationName,
992
+						gettype($model_object)
993
+					)
994
+				);
995
+			}
996
+		}
997
+		return $objects;
998
+	}
999
+
1000
+
1001
+	/**
1002
+	 * Returns the next x number of EE_Base_Class objects in sequence from this object as found in the database
1003
+	 * matching the given query conditions.
1004
+	 *
1005
+	 * @param null  $field_to_order_by  What field is being used as the reference point.
1006
+	 * @param int   $limit              How many objects to return.
1007
+	 * @param array $query_params       Any additional conditions on the query.
1008
+	 * @param null  $columns_to_select  If left null, then an array of EE_Base_Class objects is returned, otherwise
1009
+	 *                                  you can indicate just the columns you want returned
1010
+	 * @return array|EE_Base_Class[]
1011
+	 * @throws ReflectionException
1012
+	 * @throws InvalidArgumentException
1013
+	 * @throws InvalidInterfaceException
1014
+	 * @throws InvalidDataTypeException
1015
+	 * @throws EE_Error
1016
+	 */
1017
+	public function next_x($field_to_order_by = null, $limit = 1, $query_params = array(), $columns_to_select = null)
1018
+	{
1019
+		$model = $this->get_model();
1020
+		$field = empty($field_to_order_by) && $model->has_primary_key_field()
1021
+			? $model->get_primary_key_field()->get_name()
1022
+			: $field_to_order_by;
1023
+		$current_value = ! empty($field) ? $this->get($field) : null;
1024
+		if (empty($field) || empty($current_value)) {
1025
+			return array();
1026
+		}
1027
+		return $model->next_x($current_value, $field, $limit, $query_params, $columns_to_select);
1028
+	}
1029
+
1030
+
1031
+	/**
1032
+	 * Returns the previous x number of EE_Base_Class objects in sequence from this object as found in the database
1033
+	 * matching the given query conditions.
1034
+	 *
1035
+	 * @param null  $field_to_order_by  What field is being used as the reference point.
1036
+	 * @param int   $limit              How many objects to return.
1037
+	 * @param array $query_params       Any additional conditions on the query.
1038
+	 * @param null  $columns_to_select  If left null, then an array of EE_Base_Class objects is returned, otherwise
1039
+	 *                                  you can indicate just the columns you want returned
1040
+	 * @return array|EE_Base_Class[]
1041
+	 * @throws ReflectionException
1042
+	 * @throws InvalidArgumentException
1043
+	 * @throws InvalidInterfaceException
1044
+	 * @throws InvalidDataTypeException
1045
+	 * @throws EE_Error
1046
+	 */
1047
+	public function previous_x(
1048
+		$field_to_order_by = null,
1049
+		$limit = 1,
1050
+		$query_params = array(),
1051
+		$columns_to_select = null
1052
+	) {
1053
+		$model = $this->get_model();
1054
+		$field = empty($field_to_order_by) && $model->has_primary_key_field()
1055
+			? $model->get_primary_key_field()->get_name()
1056
+			: $field_to_order_by;
1057
+		$current_value = ! empty($field) ? $this->get($field) : null;
1058
+		if (empty($field) || empty($current_value)) {
1059
+			return array();
1060
+		}
1061
+		return $model->previous_x($current_value, $field, $limit, $query_params, $columns_to_select);
1062
+	}
1063
+
1064
+
1065
+	/**
1066
+	 * Returns the next EE_Base_Class object in sequence from this object as found in the database
1067
+	 * matching the given query conditions.
1068
+	 *
1069
+	 * @param null  $field_to_order_by  What field is being used as the reference point.
1070
+	 * @param array $query_params       Any additional conditions on the query.
1071
+	 * @param null  $columns_to_select  If left null, then an array of EE_Base_Class objects is returned, otherwise
1072
+	 *                                  you can indicate just the columns you want returned
1073
+	 * @return array|EE_Base_Class
1074
+	 * @throws ReflectionException
1075
+	 * @throws InvalidArgumentException
1076
+	 * @throws InvalidInterfaceException
1077
+	 * @throws InvalidDataTypeException
1078
+	 * @throws EE_Error
1079
+	 */
1080
+	public function next($field_to_order_by = null, $query_params = array(), $columns_to_select = null)
1081
+	{
1082
+		$model = $this->get_model();
1083
+		$field = empty($field_to_order_by) && $model->has_primary_key_field()
1084
+			? $model->get_primary_key_field()->get_name()
1085
+			: $field_to_order_by;
1086
+		$current_value = ! empty($field) ? $this->get($field) : null;
1087
+		if (empty($field) || empty($current_value)) {
1088
+			return array();
1089
+		}
1090
+		return $model->next($current_value, $field, $query_params, $columns_to_select);
1091
+	}
1092
+
1093
+
1094
+	/**
1095
+	 * Returns the previous EE_Base_Class object in sequence from this object as found in the database
1096
+	 * matching the given query conditions.
1097
+	 *
1098
+	 * @param null  $field_to_order_by  What field is being used as the reference point.
1099
+	 * @param array $query_params       Any additional conditions on the query.
1100
+	 * @param null  $columns_to_select  If left null, then an EE_Base_Class object is returned, otherwise
1101
+	 *                                  you can indicate just the column you want returned
1102
+	 * @return array|EE_Base_Class
1103
+	 * @throws ReflectionException
1104
+	 * @throws InvalidArgumentException
1105
+	 * @throws InvalidInterfaceException
1106
+	 * @throws InvalidDataTypeException
1107
+	 * @throws EE_Error
1108
+	 */
1109
+	public function previous($field_to_order_by = null, $query_params = array(), $columns_to_select = null)
1110
+	{
1111
+		$model = $this->get_model();
1112
+		$field = empty($field_to_order_by) && $model->has_primary_key_field()
1113
+			? $model->get_primary_key_field()->get_name()
1114
+			: $field_to_order_by;
1115
+		$current_value = ! empty($field) ? $this->get($field) : null;
1116
+		if (empty($field) || empty($current_value)) {
1117
+			return array();
1118
+		}
1119
+		return $model->previous($current_value, $field, $query_params, $columns_to_select);
1120
+	}
1121
+
1122
+
1123
+	/**
1124
+	 * Overrides parent because parent expects old models.
1125
+	 * This also doesn't do any validation, and won't work for serialized arrays
1126
+	 *
1127
+	 * @param string $field_name
1128
+	 * @param mixed  $field_value_from_db
1129
+	 * @throws ReflectionException
1130
+	 * @throws InvalidArgumentException
1131
+	 * @throws InvalidInterfaceException
1132
+	 * @throws InvalidDataTypeException
1133
+	 * @throws EE_Error
1134
+	 */
1135
+	public function set_from_db($field_name, $field_value_from_db)
1136
+	{
1137
+		$field_obj = $this->get_model()->field_settings_for($field_name);
1138
+		if ($field_obj instanceof EE_Model_Field_Base) {
1139
+			// you would think the DB has no NULLs for non-null label fields right? wrong!
1140
+			// eg, a CPT model object could have an entry in the posts table, but no
1141
+			// entry in the meta table. Meaning that all its columns in the meta table
1142
+			// are null! yikes! so when we find one like that, use defaults for its meta columns
1143
+			if ($field_value_from_db === null) {
1144
+				if ($field_obj->is_nullable()) {
1145
+					// if the field allows nulls, then let it be null
1146
+					$field_value = null;
1147
+				} else {
1148
+					$field_value = $field_obj->get_default_value();
1149
+				}
1150
+			} else {
1151
+				$field_value = $field_obj->prepare_for_set_from_db($field_value_from_db);
1152
+			}
1153
+			$this->_fields[ $field_name ] = $field_value;
1154
+			$this->_clear_cached_property($field_name);
1155
+		}
1156
+	}
1157
+
1158
+
1159
+	/**
1160
+	 * verifies that the specified field is of the correct type
1161
+	 *
1162
+	 * @param string $field_name
1163
+	 * @param string $extra_cache_ref This allows the user to specify an extra cache ref for the given property
1164
+	 *                                (in cases where the same property may be used for different outputs
1165
+	 *                                - i.e. datetime, money etc.)
1166
+	 * @return mixed
1167
+	 * @throws ReflectionException
1168
+	 * @throws InvalidArgumentException
1169
+	 * @throws InvalidInterfaceException
1170
+	 * @throws InvalidDataTypeException
1171
+	 * @throws EE_Error
1172
+	 */
1173
+	public function get($field_name, $extra_cache_ref = null)
1174
+	{
1175
+		return $this->_get_cached_property($field_name, false, $extra_cache_ref);
1176
+	}
1177
+
1178
+
1179
+	/**
1180
+	 * This method simply returns the RAW unprocessed value for the given property in this class
1181
+	 *
1182
+	 * @param  string $field_name A valid fieldname
1183
+	 * @return mixed              Whatever the raw value stored on the property is.
1184
+	 * @throws ReflectionException
1185
+	 * @throws InvalidArgumentException
1186
+	 * @throws InvalidInterfaceException
1187
+	 * @throws InvalidDataTypeException
1188
+	 * @throws EE_Error if fieldSettings is misconfigured or the field doesn't exist.
1189
+	 */
1190
+	public function get_raw($field_name)
1191
+	{
1192
+		$field_settings = $this->get_model()->field_settings_for($field_name);
1193
+		return $field_settings instanceof EE_Datetime_Field && $this->_fields[ $field_name ] instanceof DateTime
1194
+			? $this->_fields[ $field_name ]->format('U')
1195
+			: $this->_fields[ $field_name ];
1196
+	}
1197
+
1198
+
1199
+	/**
1200
+	 * This is used to return the internal DateTime object used for a field that is a
1201
+	 * EE_Datetime_Field.
1202
+	 *
1203
+	 * @param string $field_name               The field name retrieving the DateTime object.
1204
+	 * @return mixed null | false | DateTime  If the requested field is NOT a EE_Datetime_Field then
1205
+	 * @throws EE_Error an error is set and false returned.  If the field IS an
1206
+	 *                                         EE_Datetime_Field and but the field value is null, then
1207
+	 *                                         just null is returned (because that indicates that likely
1208
+	 *                                         this field is nullable).
1209
+	 * @throws InvalidArgumentException
1210
+	 * @throws InvalidDataTypeException
1211
+	 * @throws InvalidInterfaceException
1212
+	 * @throws ReflectionException
1213
+	 */
1214
+	public function get_DateTime_object($field_name)
1215
+	{
1216
+		$field_settings = $this->get_model()->field_settings_for($field_name);
1217
+		if (! $field_settings instanceof EE_Datetime_Field) {
1218
+			EE_Error::add_error(
1219
+				sprintf(
1220
+					esc_html__(
1221
+						'The field %s is not an EE_Datetime_Field field.  There is no DateTime object stored on this field type.',
1222
+						'event_espresso'
1223
+					),
1224
+					$field_name
1225
+				),
1226
+				__FILE__,
1227
+				__FUNCTION__,
1228
+				__LINE__
1229
+			);
1230
+			return false;
1231
+		}
1232
+		return isset($this->_fields[ $field_name ]) && $this->_fields[ $field_name ] instanceof DateTime
1233
+			? clone $this->_fields[ $field_name ]
1234
+			: null;
1235
+	}
1236
+
1237
+
1238
+	/**
1239
+	 * To be used in template to immediately echo out the value, and format it for output.
1240
+	 * Eg, should call stripslashes and whatnot before echoing
1241
+	 *
1242
+	 * @param string $field_name      the name of the field as it appears in the DB
1243
+	 * @param string $extra_cache_ref This allows the user to specify an extra cache ref for the given property
1244
+	 *                                (in cases where the same property may be used for different outputs
1245
+	 *                                - i.e. datetime, money etc.)
1246
+	 * @return void
1247
+	 * @throws ReflectionException
1248
+	 * @throws InvalidArgumentException
1249
+	 * @throws InvalidInterfaceException
1250
+	 * @throws InvalidDataTypeException
1251
+	 * @throws EE_Error
1252
+	 */
1253
+	public function e($field_name, $extra_cache_ref = null)
1254
+	{
1255
+		echo wp_kses($this->get_pretty($field_name, $extra_cache_ref), AllowedTags::getWithFormTags());
1256
+	}
1257
+
1258
+
1259
+	/**
1260
+	 * Exactly like e(), echoes out the field, but sets its schema to 'form_input', so that it
1261
+	 * can be easily used as the value of form input.
1262
+	 *
1263
+	 * @param string $field_name
1264
+	 * @return void
1265
+	 * @throws ReflectionException
1266
+	 * @throws InvalidArgumentException
1267
+	 * @throws InvalidInterfaceException
1268
+	 * @throws InvalidDataTypeException
1269
+	 * @throws EE_Error
1270
+	 */
1271
+	public function f($field_name)
1272
+	{
1273
+		$this->e($field_name, 'form_input');
1274
+	}
1275
+
1276
+
1277
+	/**
1278
+	 * Same as `f()` but just returns the value instead of echoing it
1279
+	 *
1280
+	 * @param string $field_name
1281
+	 * @return string
1282
+	 * @throws ReflectionException
1283
+	 * @throws InvalidArgumentException
1284
+	 * @throws InvalidInterfaceException
1285
+	 * @throws InvalidDataTypeException
1286
+	 * @throws EE_Error
1287
+	 */
1288
+	public function get_f($field_name)
1289
+	{
1290
+		return (string) $this->get_pretty($field_name, 'form_input');
1291
+	}
1292
+
1293
+
1294
+	/**
1295
+	 * Gets a pretty view of the field's value. $extra_cache_ref can specify different formats for this.
1296
+	 * The $extra_cache_ref will be passed to the model field's prepare_for_pretty_echoing, so consult the field's class
1297
+	 * to see what options are available.
1298
+	 *
1299
+	 * @param string $field_name
1300
+	 * @param string $extra_cache_ref This allows the user to specify an extra cache ref for the given property
1301
+	 *                                (in cases where the same property may be used for different outputs
1302
+	 *                                - i.e. datetime, money etc.)
1303
+	 * @return mixed
1304
+	 * @throws ReflectionException
1305
+	 * @throws InvalidArgumentException
1306
+	 * @throws InvalidInterfaceException
1307
+	 * @throws InvalidDataTypeException
1308
+	 * @throws EE_Error
1309
+	 */
1310
+	public function get_pretty($field_name, $extra_cache_ref = null)
1311
+	{
1312
+		return $this->_get_cached_property($field_name, true, $extra_cache_ref);
1313
+	}
1314
+
1315
+
1316
+	/**
1317
+	 * This simply returns the datetime for the given field name
1318
+	 * Note: this protected function is called by the wrapper get_date or get_time or get_datetime functions
1319
+	 * (and the equivalent e_date, e_time, e_datetime).
1320
+	 *
1321
+	 * @access   protected
1322
+	 * @param string      $field_name   Field on the instantiated EE_Base_Class child object
1323
+	 * @param string|null $date_format  valid datetime format used for date
1324
+	 *                                  (if '' then we just use the default on the field,
1325
+	 *                                  if NULL we use the last-used format)
1326
+	 * @param string|null $time_format  Same as above except this is for time format
1327
+	 * @param string|null $date_or_time if NULL then both are returned, otherwise "D" = only date and "T" = only time.
1328
+	 * @param bool|null   $echo         Whether the datetime is pretty echoing or just returned using vanilla get
1329
+	 * @return string|bool|EE_Error string on success, FALSE on fail, or EE_Error Exception is thrown
1330
+	 *                                  if field is not a valid dtt field, or void if echoing
1331
+	 * @throws EE_Error
1332
+	 * @throws ReflectionException
1333
+	 */
1334
+	protected function _get_datetime(
1335
+		string $field_name,
1336
+		?string $date_format = '',
1337
+		?string $time_format = '',
1338
+		?string $date_or_time = '',
1339
+		?bool $echo = false
1340
+	) {
1341
+		// clear cached property
1342
+		$this->_clear_cached_property($field_name);
1343
+		// reset format properties because they are used in get()
1344
+		$this->_dt_frmt = $date_format !== '' ? $date_format : $this->_dt_frmt;
1345
+		$this->_tm_frmt = $time_format !== '' ? $time_format : $this->_tm_frmt;
1346
+		if ($echo) {
1347
+			$this->e($field_name, $date_or_time);
1348
+			return '';
1349
+		}
1350
+		return $this->get($field_name, $date_or_time);
1351
+	}
1352
+
1353
+
1354
+	/**
1355
+	 * below are wrapper functions for the various datetime outputs that can be obtained for JUST returning the date
1356
+	 * portion of a datetime value. (note the only difference between get_ and e_ is one returns the value and the
1357
+	 * other echoes the pretty value for dtt)
1358
+	 *
1359
+	 * @param  string $field_name name of model object datetime field holding the value
1360
+	 * @param  string $format     format for the date returned (if NULL we use default in dt_frmt property)
1361
+	 * @return string            datetime value formatted
1362
+	 * @throws ReflectionException
1363
+	 * @throws InvalidArgumentException
1364
+	 * @throws InvalidInterfaceException
1365
+	 * @throws InvalidDataTypeException
1366
+	 * @throws EE_Error
1367
+	 */
1368
+	public function get_date($field_name, $format = '')
1369
+	{
1370
+		return $this->_get_datetime($field_name, $format, null, 'D');
1371
+	}
1372
+
1373
+
1374
+	/**
1375
+	 * @param        $field_name
1376
+	 * @param string $format
1377
+	 * @throws ReflectionException
1378
+	 * @throws InvalidArgumentException
1379
+	 * @throws InvalidInterfaceException
1380
+	 * @throws InvalidDataTypeException
1381
+	 * @throws EE_Error
1382
+	 */
1383
+	public function e_date($field_name, $format = '')
1384
+	{
1385
+		$this->_get_datetime($field_name, $format, null, 'D', true);
1386
+	}
1387
+
1388
+
1389
+	/**
1390
+	 * below are wrapper functions for the various datetime outputs that can be obtained for JUST returning the time
1391
+	 * portion of a datetime value. (note the only difference between get_ and e_ is one returns the value and the
1392
+	 * other echoes the pretty value for dtt)
1393
+	 *
1394
+	 * @param  string $field_name name of model object datetime field holding the value
1395
+	 * @param  string $format     format for the time returned ( if NULL we use default in tm_frmt property)
1396
+	 * @return string             datetime value formatted
1397
+	 * @throws ReflectionException
1398
+	 * @throws InvalidArgumentException
1399
+	 * @throws InvalidInterfaceException
1400
+	 * @throws InvalidDataTypeException
1401
+	 * @throws EE_Error
1402
+	 */
1403
+	public function get_time($field_name, $format = '')
1404
+	{
1405
+		return $this->_get_datetime($field_name, null, $format, 'T');
1406
+	}
1407
+
1408
+
1409
+	/**
1410
+	 * @param        $field_name
1411
+	 * @param string $format
1412
+	 * @throws ReflectionException
1413
+	 * @throws InvalidArgumentException
1414
+	 * @throws InvalidInterfaceException
1415
+	 * @throws InvalidDataTypeException
1416
+	 * @throws EE_Error
1417
+	 */
1418
+	public function e_time($field_name, $format = '')
1419
+	{
1420
+		$this->_get_datetime($field_name, null, $format, 'T', true);
1421
+	}
1422
+
1423
+
1424
+	/**
1425
+	 * below are wrapper functions for the various datetime outputs that can be obtained for returning the date AND
1426
+	 * time portion of a datetime value. (note the only difference between get_ and e_ is one returns the value and the
1427
+	 * other echoes the pretty value for dtt)
1428
+	 *
1429
+	 * @param  string $field_name name of model object datetime field holding the value
1430
+	 * @param  string $dt_frmt    format for the date returned (if NULL we use default in dt_frmt property)
1431
+	 * @param  string $tm_frmt    format for the time returned (if NULL we use default in tm_frmt property)
1432
+	 * @return string             datetime value formatted
1433
+	 * @throws ReflectionException
1434
+	 * @throws InvalidArgumentException
1435
+	 * @throws InvalidInterfaceException
1436
+	 * @throws InvalidDataTypeException
1437
+	 * @throws EE_Error
1438
+	 */
1439
+	public function get_datetime($field_name, $dt_frmt = '', $tm_frmt = '')
1440
+	{
1441
+		return $this->_get_datetime($field_name, $dt_frmt, $tm_frmt);
1442
+	}
1443
+
1444
+
1445
+	/**
1446
+	 * @param string $field_name
1447
+	 * @param string $dt_frmt
1448
+	 * @param string $tm_frmt
1449
+	 * @throws ReflectionException
1450
+	 * @throws InvalidArgumentException
1451
+	 * @throws InvalidInterfaceException
1452
+	 * @throws InvalidDataTypeException
1453
+	 * @throws EE_Error
1454
+	 */
1455
+	public function e_datetime($field_name, $dt_frmt = '', $tm_frmt = '')
1456
+	{
1457
+		$this->_get_datetime($field_name, $dt_frmt, $tm_frmt, null, true);
1458
+	}
1459
+
1460
+
1461
+	/**
1462
+	 * Get the i8ln value for a date using the WordPress @see date_i18n function.
1463
+	 *
1464
+	 * @param string $field_name The EE_Datetime_Field reference for the date being retrieved.
1465
+	 * @param string $format     PHP valid date/time string format.  If none is provided then the internal set format
1466
+	 *                           on the object will be used.
1467
+	 * @return string Date and time string in set locale or false if no field exists for the given
1468
+	 * @throws ReflectionException
1469
+	 * @throws InvalidArgumentException
1470
+	 * @throws InvalidInterfaceException
1471
+	 * @throws InvalidDataTypeException
1472
+	 * @throws EE_Error
1473
+	 *                           field name.
1474
+	 */
1475
+	public function get_i18n_datetime($field_name, $format = '')
1476
+	{
1477
+		$format = empty($format) ? $this->_dt_frmt . ' ' . $this->_tm_frmt : $format;
1478
+		return date_i18n(
1479
+			$format,
1480
+			EEH_DTT_Helper::get_timestamp_with_offset(
1481
+				$this->get_raw($field_name),
1482
+				$this->_timezone
1483
+			)
1484
+		);
1485
+	}
1486
+
1487
+
1488
+	/**
1489
+	 * This method validates whether the given field name is a valid field on the model object as well as it is of a
1490
+	 * type EE_Datetime_Field.  On success there will be returned the field settings.  On fail an EE_Error exception is
1491
+	 * thrown.
1492
+	 *
1493
+	 * @param  string $field_name The field name being checked
1494
+	 * @throws ReflectionException
1495
+	 * @throws InvalidArgumentException
1496
+	 * @throws InvalidInterfaceException
1497
+	 * @throws InvalidDataTypeException
1498
+	 * @throws EE_Error
1499
+	 * @return EE_Datetime_Field
1500
+	 */
1501
+	protected function _get_dtt_field_settings($field_name)
1502
+	{
1503
+		$field = $this->get_model()->field_settings_for($field_name);
1504
+		// check if field is dtt
1505
+		if ($field instanceof EE_Datetime_Field) {
1506
+			return $field;
1507
+		}
1508
+		throw new EE_Error(
1509
+			sprintf(
1510
+				esc_html__(
1511
+					'The field name "%s" has been requested for the EE_Base_Class datetime functions and it is not a valid EE_Datetime_Field.  Please check the spelling of the field and make sure it has been setup as a EE_Datetime_Field in the %s model constructor',
1512
+					'event_espresso'
1513
+				),
1514
+				$field_name,
1515
+				self::_get_model_classname(get_class($this))
1516
+			)
1517
+		);
1518
+	}
1519
+
1520
+
1521
+
1522
+
1523
+	/**
1524
+	 * NOTE ABOUT BELOW:
1525
+	 * These convenience date and time setters are for setting date and time independently.  In other words you might
1526
+	 * want to change the time on a datetime_field but leave the date the same (or vice versa). IF on the other hand
1527
+	 * you want to set both date and time at the same time, you can just use the models default set($fieldname,$value)
1528
+	 * method and make sure you send the entire datetime value for setting.
1529
+	 */
1530
+	/**
1531
+	 * sets the time on a datetime property
1532
+	 *
1533
+	 * @access protected
1534
+	 * @param string|Datetime $time      a valid time string for php datetime functions (or DateTime object)
1535
+	 * @param string          $fieldname the name of the field the time is being set on (must match a EE_Datetime_Field)
1536
+	 * @throws ReflectionException
1537
+	 * @throws InvalidArgumentException
1538
+	 * @throws InvalidInterfaceException
1539
+	 * @throws InvalidDataTypeException
1540
+	 * @throws EE_Error
1541
+	 */
1542
+	protected function _set_time_for($time, $fieldname)
1543
+	{
1544
+		$this->_set_date_time('T', $time, $fieldname);
1545
+	}
1546
+
1547
+
1548
+	/**
1549
+	 * sets the date on a datetime property
1550
+	 *
1551
+	 * @access protected
1552
+	 * @param string|DateTime $date      a valid date string for php datetime functions ( or DateTime object)
1553
+	 * @param string          $fieldname the name of the field the date is being set on (must match a EE_Datetime_Field)
1554
+	 * @throws ReflectionException
1555
+	 * @throws InvalidArgumentException
1556
+	 * @throws InvalidInterfaceException
1557
+	 * @throws InvalidDataTypeException
1558
+	 * @throws EE_Error
1559
+	 */
1560
+	protected function _set_date_for($date, $fieldname)
1561
+	{
1562
+		$this->_set_date_time('D', $date, $fieldname);
1563
+	}
1564
+
1565
+
1566
+	/**
1567
+	 * This takes care of setting a date or time independently on a given model object property. This method also
1568
+	 * verifies that the given field_name matches a model object property and is for a EE_Datetime_Field field
1569
+	 *
1570
+	 * @access protected
1571
+	 * @param string          $what           "T" for time, 'B' for both, 'D' for Date.
1572
+	 * @param string|DateTime $datetime_value A valid Date or Time string (or DateTime object)
1573
+	 * @param string          $field_name     the name of the field the date OR time is being set on (must match a
1574
+	 *                                        EE_Datetime_Field property)
1575
+	 * @throws ReflectionException
1576
+	 * @throws InvalidArgumentException
1577
+	 * @throws InvalidInterfaceException
1578
+	 * @throws InvalidDataTypeException
1579
+	 * @throws EE_Error
1580
+	 */
1581
+	protected function _set_date_time(string $what, $datetime_value, string $field_name)
1582
+	{
1583
+		$field = $this->_get_dtt_field_settings($field_name);
1584
+		$field->set_timezone($this->_timezone);
1585
+		$field->set_date_format($this->_dt_frmt);
1586
+		$field->set_time_format($this->_tm_frmt);
1587
+		switch ($what) {
1588
+			case 'T':
1589
+				$this->_fields[ $field_name ] = $field->prepare_for_set_with_new_time(
1590
+					$datetime_value,
1591
+					$this->_fields[ $field_name ]
1592
+				);
1593
+				$this->_has_changes = true;
1594
+				break;
1595
+			case 'D':
1596
+				$this->_fields[ $field_name ] = $field->prepare_for_set_with_new_date(
1597
+					$datetime_value,
1598
+					$this->_fields[ $field_name ]
1599
+				);
1600
+				$this->_has_changes = true;
1601
+				break;
1602
+			case 'B':
1603
+				$this->_fields[ $field_name ] = $field->prepare_for_set($datetime_value);
1604
+				$this->_has_changes = true;
1605
+				break;
1606
+		}
1607
+		$this->_clear_cached_property($field_name);
1608
+	}
1609
+
1610
+
1611
+	/**
1612
+	 * This will return a timestamp for the website timezone but ONLY when the current website timezone is different
1613
+	 * than the timezone set for the website. NOTE, this currently only works well with methods that return values.  If
1614
+	 * you use it with methods that echo values the $_timestamp property may not get reset to its original value and
1615
+	 * that could lead to some unexpected results!
1616
+	 *
1617
+	 * @access public
1618
+	 * @param string $field_name               This is the name of the field on the object that contains the date/time
1619
+	 *                                         value being returned.
1620
+	 * @param string $callback                 must match a valid method in this class (defaults to get_datetime)
1621
+	 * @param mixed (array|string) $args       This is the arguments that will be passed to the callback.
1622
+	 * @param string $prepend                  You can include something to prepend on the timestamp
1623
+	 * @param string $append                   You can include something to append on the timestamp
1624
+	 * @throws ReflectionException
1625
+	 * @throws InvalidArgumentException
1626
+	 * @throws InvalidInterfaceException
1627
+	 * @throws InvalidDataTypeException
1628
+	 * @throws EE_Error
1629
+	 * @return string timestamp
1630
+	 */
1631
+	public function display_in_my_timezone(
1632
+		$field_name,
1633
+		$callback = 'get_datetime',
1634
+		$args = null,
1635
+		$prepend = '',
1636
+		$append = ''
1637
+	) {
1638
+		$timezone = EEH_DTT_Helper::get_timezone();
1639
+		if ($timezone === $this->_timezone) {
1640
+			return '';
1641
+		}
1642
+		$original_timezone = $this->_timezone;
1643
+		$this->set_timezone($timezone);
1644
+		$fn = (array) $field_name;
1645
+		$args = array_merge($fn, (array) $args);
1646
+		if (! method_exists($this, $callback)) {
1647
+			throw new EE_Error(
1648
+				sprintf(
1649
+					esc_html__(
1650
+						'The method named "%s" given as the callback param in "display_in_my_timezone" does not exist.  Please check your spelling',
1651
+						'event_espresso'
1652
+					),
1653
+					$callback
1654
+				)
1655
+			);
1656
+		}
1657
+		$args = (array) $args;
1658
+		$return = $prepend . call_user_func_array(array($this, $callback), $args) . $append;
1659
+		$this->set_timezone($original_timezone);
1660
+		return $return;
1661
+	}
1662
+
1663
+
1664
+	/**
1665
+	 * Deletes this model object.
1666
+	 * This calls the `EE_Base_Class::_delete` method.  Child classes wishing to change default behaviour should
1667
+	 * override
1668
+	 * `EE_Base_Class::_delete` NOT this class.
1669
+	 *
1670
+	 * @return boolean | int
1671
+	 * @throws ReflectionException
1672
+	 * @throws InvalidArgumentException
1673
+	 * @throws InvalidInterfaceException
1674
+	 * @throws InvalidDataTypeException
1675
+	 * @throws EE_Error
1676
+	 */
1677
+	public function delete()
1678
+	{
1679
+		/**
1680
+		 * Called just before the `EE_Base_Class::_delete` method call.
1681
+		 * Note:
1682
+		 * `EE_Base_Class::_delete` might be overridden by child classes so any client code hooking into these actions
1683
+		 * should be aware that `_delete` may not always result in a permanent delete.
1684
+		 * For example, `EE_Soft_Delete_Base_Class::_delete`
1685
+		 * soft deletes (trash) the object and does not permanently delete it.
1686
+		 *
1687
+		 * @param EE_Base_Class $model_object about to be 'deleted'
1688
+		 */
1689
+		do_action('AHEE__EE_Base_Class__delete__before', $this);
1690
+		$result = $this->_delete();
1691
+		/**
1692
+		 * Called just after the `EE_Base_Class::_delete` method call.
1693
+		 * Note:
1694
+		 * `EE_Base_Class::_delete` might be overridden by child classes so any client code hooking into these actions
1695
+		 * should be aware that `_delete` may not always result in a permanent delete.
1696
+		 * For example `EE_Soft_Base_Class::_delete`
1697
+		 * soft deletes (trash) the object and does not permanently delete it.
1698
+		 *
1699
+		 * @param EE_Base_Class $model_object that was just 'deleted'
1700
+		 * @param boolean       $result
1701
+		 */
1702
+		do_action('AHEE__EE_Base_Class__delete__end', $this, $result);
1703
+		return $result;
1704
+	}
1705
+
1706
+
1707
+	/**
1708
+	 * Calls the specific delete method for the instantiated class.
1709
+	 * This method is called by the public `EE_Base_Class::delete` method.  Any child classes desiring to override
1710
+	 * default functionality for "delete" (which is to call `permanently_delete`) should override this method NOT
1711
+	 * `EE_Base_Class::delete`
1712
+	 *
1713
+	 * @return bool|int
1714
+	 * @throws ReflectionException
1715
+	 * @throws InvalidArgumentException
1716
+	 * @throws InvalidInterfaceException
1717
+	 * @throws InvalidDataTypeException
1718
+	 * @throws EE_Error
1719
+	 */
1720
+	protected function _delete()
1721
+	{
1722
+		return $this->delete_permanently();
1723
+	}
1724
+
1725
+
1726
+	/**
1727
+	 * Deletes this model object permanently from db
1728
+	 * (but keep in mind related models may block the delete and return an error)
1729
+	 *
1730
+	 * @return bool | int
1731
+	 * @throws ReflectionException
1732
+	 * @throws InvalidArgumentException
1733
+	 * @throws InvalidInterfaceException
1734
+	 * @throws InvalidDataTypeException
1735
+	 * @throws EE_Error
1736
+	 */
1737
+	public function delete_permanently()
1738
+	{
1739
+		/**
1740
+		 * Called just before HARD deleting a model object
1741
+		 *
1742
+		 * @param EE_Base_Class $model_object about to be 'deleted'
1743
+		 */
1744
+		do_action('AHEE__EE_Base_Class__delete_permanently__before', $this);
1745
+		$model = $this->get_model();
1746
+		$result = $model->delete_permanently_by_ID($this->ID());
1747
+		$this->refresh_cache_of_related_objects();
1748
+		/**
1749
+		 * Called just after HARD deleting a model object
1750
+		 *
1751
+		 * @param EE_Base_Class $model_object that was just 'deleted'
1752
+		 * @param boolean       $result
1753
+		 */
1754
+		do_action('AHEE__EE_Base_Class__delete_permanently__end', $this, $result);
1755
+		return $result;
1756
+	}
1757
+
1758
+
1759
+	/**
1760
+	 * When this model object is deleted, it may still be cached on related model objects. This clears the cache of
1761
+	 * related model objects
1762
+	 *
1763
+	 * @throws ReflectionException
1764
+	 * @throws InvalidArgumentException
1765
+	 * @throws InvalidInterfaceException
1766
+	 * @throws InvalidDataTypeException
1767
+	 * @throws EE_Error
1768
+	 */
1769
+	public function refresh_cache_of_related_objects()
1770
+	{
1771
+		$model = $this->get_model();
1772
+		foreach ($model->relation_settings() as $relation_name => $relation_obj) {
1773
+			if (! empty($this->_model_relations[ $relation_name ])) {
1774
+				$related_objects = $this->_model_relations[ $relation_name ];
1775
+				if ($relation_obj instanceof EE_Belongs_To_Relation) {
1776
+					// this relation only stores a single model object, not an array
1777
+					// but let's make it consistent
1778
+					$related_objects = array($related_objects);
1779
+				}
1780
+				foreach ($related_objects as $related_object) {
1781
+					// only refresh their cache if they're in memory
1782
+					if ($related_object instanceof EE_Base_Class) {
1783
+						$related_object->clear_cache(
1784
+							$model->get_this_model_name(),
1785
+							$this
1786
+						);
1787
+					}
1788
+				}
1789
+			}
1790
+		}
1791
+	}
1792
+
1793
+
1794
+	/**
1795
+	 *        Saves this object to the database. An array may be supplied to set some values on this
1796
+	 * object just before saving.
1797
+	 *
1798
+	 * @access public
1799
+	 * @param array $set_cols_n_values keys are field names, values are their new values,
1800
+	 *                                 if provided during the save() method (often client code will change the fields'
1801
+	 *                                 values before calling save)
1802
+	 * @return bool|int|string         1 on a successful update
1803
+	 *                                 the ID of the new entry on insert
1804
+	 *                                 0 on failure or if the model object isn't allowed to persist
1805
+	 *                                 (as determined by EE_Base_Class::allow_persist())
1806
+	 * @throws InvalidInterfaceException
1807
+	 * @throws InvalidDataTypeException
1808
+	 * @throws EE_Error
1809
+	 * @throws InvalidArgumentException
1810
+	 * @throws ReflectionException
1811
+	 * @throws ReflectionException
1812
+	 * @throws ReflectionException
1813
+	 */
1814
+	public function save($set_cols_n_values = array())
1815
+	{
1816
+		$model = $this->get_model();
1817
+		/**
1818
+		 * Filters the fields we're about to save on the model object
1819
+		 *
1820
+		 * @param array         $set_cols_n_values
1821
+		 * @param EE_Base_Class $model_object
1822
+		 */
1823
+		$set_cols_n_values = (array) apply_filters(
1824
+			'FHEE__EE_Base_Class__save__set_cols_n_values',
1825
+			$set_cols_n_values,
1826
+			$this
1827
+		);
1828
+		// set attributes as provided in $set_cols_n_values
1829
+		foreach ($set_cols_n_values as $column => $value) {
1830
+			$this->set($column, $value);
1831
+		}
1832
+		// no changes ? then don't do anything
1833
+		if (! $this->_has_changes && $this->ID() && $model->get_primary_key_field()->is_auto_increment()) {
1834
+			return 0;
1835
+		}
1836
+		/**
1837
+		 * Saving a model object.
1838
+		 * Before we perform a save, this action is fired.
1839
+		 *
1840
+		 * @param EE_Base_Class $model_object the model object about to be saved.
1841
+		 */
1842
+		do_action('AHEE__EE_Base_Class__save__begin', $this);
1843
+		if (! $this->allow_persist()) {
1844
+			return 0;
1845
+		}
1846
+		// now get current attribute values
1847
+		$save_cols_n_values = $this->_fields;
1848
+		// if the object already has an ID, update it. Otherwise, insert it
1849
+		// also: change the assumption about values passed to the model NOT being prepare dby the model object.
1850
+		// They have been
1851
+		$old_assumption_concerning_value_preparation = $model
1852
+			->get_assumption_concerning_values_already_prepared_by_model_object();
1853
+		$model->assume_values_already_prepared_by_model_object(true);
1854
+		// does this model have an autoincrement PK?
1855
+		if ($model->has_primary_key_field()) {
1856
+			if ($model->get_primary_key_field()->is_auto_increment()) {
1857
+				// ok check if it's set, if so: update; if not, insert
1858
+				if (! empty($save_cols_n_values[ $model->primary_key_name() ])) {
1859
+					$results = $model->update_by_ID($save_cols_n_values, $this->ID());
1860
+				} else {
1861
+					unset($save_cols_n_values[ $model->primary_key_name() ]);
1862
+					$results = $model->insert($save_cols_n_values);
1863
+					if ($results) {
1864
+						// if successful, set the primary key
1865
+						// but don't use the normal SET method, because it will check if
1866
+						// an item with the same ID exists in the mapper & db, then
1867
+						// will find it in the db (because we just added it) and THAT object
1868
+						// will get added to the mapper before we can add this one!
1869
+						// but if we just avoid using the SET method, all that headache can be avoided
1870
+						$pk_field_name = $model->primary_key_name();
1871
+						$this->_fields[ $pk_field_name ] = $results;
1872
+						$this->_clear_cached_property($pk_field_name);
1873
+						$model->add_to_entity_map($this);
1874
+						$this->_update_cached_related_model_objs_fks();
1875
+					}
1876
+				}
1877
+			} else {// PK is NOT auto-increment
1878
+				// so check if one like it already exists in the db
1879
+				if ($model->exists_by_ID($this->ID())) {
1880
+					if (WP_DEBUG && ! $this->in_entity_map()) {
1881
+						throw new EE_Error(
1882
+							sprintf(
1883
+								esc_html__(
1884
+									'Using a model object %1$s that is NOT in the entity map, can lead to unexpected errors. You should either: %4$s 1. Put it in the entity mapper by calling %2$s %4$s 2. Discard this model object and use what is in the entity mapper %4$s 3. Fetch from the database using %3$s',
1885
+									'event_espresso'
1886
+								),
1887
+								get_class($this),
1888
+								get_class($model) . '::instance()->add_to_entity_map()',
1889
+								get_class($model) . '::instance()->get_one_by_ID()',
1890
+								'<br />'
1891
+							)
1892
+						);
1893
+					}
1894
+					$results = $model->update_by_ID($save_cols_n_values, $this->ID());
1895
+				} else {
1896
+					$results = $model->insert($save_cols_n_values);
1897
+					$this->_update_cached_related_model_objs_fks();
1898
+				}
1899
+			}
1900
+		} else {// there is NO primary key
1901
+			$already_in_db = false;
1902
+			foreach ($model->unique_indexes() as $index) {
1903
+				$uniqueness_where_params = array_intersect_key($save_cols_n_values, $index->fields());
1904
+				if ($model->exists(array($uniqueness_where_params))) {
1905
+					$already_in_db = true;
1906
+				}
1907
+			}
1908
+			if ($already_in_db) {
1909
+				$combined_pk_fields_n_values = array_intersect_key(
1910
+					$save_cols_n_values,
1911
+					$model->get_combined_primary_key_fields()
1912
+				);
1913
+				$results = $model->update(
1914
+					$save_cols_n_values,
1915
+					$combined_pk_fields_n_values
1916
+				);
1917
+			} else {
1918
+				$results = $model->insert($save_cols_n_values);
1919
+			}
1920
+		}
1921
+		// restore the old assumption about values being prepared by the model object
1922
+		$model->assume_values_already_prepared_by_model_object(
1923
+			$old_assumption_concerning_value_preparation
1924
+		);
1925
+		/**
1926
+		 * After saving the model object this action is called
1927
+		 *
1928
+		 * @param EE_Base_Class $model_object which was just saved
1929
+		 * @param boolean|int   $results      if it were updated, TRUE or FALSE; if it were newly inserted
1930
+		 *                                    the new ID (or 0 if an error occurred and it wasn't updated)
1931
+		 */
1932
+		do_action('AHEE__EE_Base_Class__save__end', $this, $results);
1933
+		$this->_has_changes = false;
1934
+		return $results;
1935
+	}
1936
+
1937
+
1938
+	/**
1939
+	 * Updates the foreign key on related models objects pointing to this to have this model object's ID
1940
+	 * as their foreign key.  If the cached related model objects already exist in the db, saves them (so that the DB
1941
+	 * is consistent) Especially useful in case we JUST added this model object ot the database and we want to let its
1942
+	 * cached relations with foreign keys to it know about that change. Eg: we've created a transaction but haven't
1943
+	 * saved it to the db. We also create a registration and don't save it to the DB, but we DO cache it on the
1944
+	 * transaction. Now, when we save the transaction, the registration's TXN_ID will be automatically updated, whether
1945
+	 * or not they exist in the DB (if they do, their DB records will be automatically updated)
1946
+	 *
1947
+	 * @return void
1948
+	 * @throws ReflectionException
1949
+	 * @throws InvalidArgumentException
1950
+	 * @throws InvalidInterfaceException
1951
+	 * @throws InvalidDataTypeException
1952
+	 * @throws EE_Error
1953
+	 */
1954
+	protected function _update_cached_related_model_objs_fks()
1955
+	{
1956
+		$model = $this->get_model();
1957
+		foreach ($model->relation_settings() as $relation_name => $relation_obj) {
1958
+			if ($relation_obj instanceof EE_Has_Many_Relation) {
1959
+				foreach ($this->get_all_from_cache($relation_name) as $related_model_obj_in_cache) {
1960
+					$fk_to_this = $related_model_obj_in_cache->get_model()->get_foreign_key_to(
1961
+						$model->get_this_model_name()
1962
+					);
1963
+					$related_model_obj_in_cache->set($fk_to_this->get_name(), $this->ID());
1964
+					if ($related_model_obj_in_cache->ID()) {
1965
+						$related_model_obj_in_cache->save();
1966
+					}
1967
+				}
1968
+			}
1969
+		}
1970
+	}
1971
+
1972
+
1973
+	/**
1974
+	 * Saves this model object and its NEW cached relations to the database.
1975
+	 * (Meaning, for now, IT DOES NOT WORK if the cached items already exist in the DB.
1976
+	 * In order for that to work, we would need to mark model objects as dirty/clean...
1977
+	 * because otherwise, there's a potential for infinite looping of saving
1978
+	 * Saves the cached related model objects, and ensures the relation between them
1979
+	 * and this object and properly setup
1980
+	 *
1981
+	 * @return int ID of new model object on save; 0 on failure+
1982
+	 * @throws ReflectionException
1983
+	 * @throws InvalidArgumentException
1984
+	 * @throws InvalidInterfaceException
1985
+	 * @throws InvalidDataTypeException
1986
+	 * @throws EE_Error
1987
+	 */
1988
+	public function save_new_cached_related_model_objs()
1989
+	{
1990
+		// make sure this has been saved
1991
+		if (! $this->ID()) {
1992
+			$id = $this->save();
1993
+		} else {
1994
+			$id = $this->ID();
1995
+		}
1996
+		// now save all the NEW cached model objects  (ie they don't exist in the DB)
1997
+		foreach ($this->get_model()->relation_settings() as $relationName => $relationObj) {
1998
+			if ($this->_model_relations[ $relationName ]) {
1999
+				// is this a relation where we should expect just ONE related object (ie, EE_Belongs_To_relation)
2000
+				// or MANY related objects (ie, EE_HABTM_Relation or EE_Has_Many_Relation)?
2001
+				/* @var $related_model_obj EE_Base_Class */
2002
+				if ($relationObj instanceof EE_Belongs_To_Relation) {
2003
+					// add a relation to that relation type (which saves the appropriate thing in the process)
2004
+					// but ONLY if it DOES NOT exist in the DB
2005
+					$related_model_obj = $this->_model_relations[ $relationName ];
2006
+					// if( ! $related_model_obj->ID()){
2007
+					$this->_add_relation_to($related_model_obj, $relationName);
2008
+					$related_model_obj->save_new_cached_related_model_objs();
2009
+					// }
2010
+				} else {
2011
+					foreach ($this->_model_relations[ $relationName ] as $related_model_obj) {
2012
+						// add a relation to that relation type (which saves the appropriate thing in the process)
2013
+						// but ONLY if it DOES NOT exist in the DB
2014
+						// if( ! $related_model_obj->ID()){
2015
+						$this->_add_relation_to($related_model_obj, $relationName);
2016
+						$related_model_obj->save_new_cached_related_model_objs();
2017
+						// }
2018
+					}
2019
+				}
2020
+			}
2021
+		}
2022
+		return $id;
2023
+	}
2024
+
2025
+
2026
+	/**
2027
+	 * for getting a model while instantiated.
2028
+	 *
2029
+	 * @return EEM_Base | EEM_CPT_Base
2030
+	 * @throws ReflectionException
2031
+	 * @throws InvalidArgumentException
2032
+	 * @throws InvalidInterfaceException
2033
+	 * @throws InvalidDataTypeException
2034
+	 * @throws EE_Error
2035
+	 */
2036
+	public function get_model()
2037
+	{
2038
+		if (! $this->_model) {
2039
+			$modelName = self::_get_model_classname(get_class($this));
2040
+			$this->_model = self::_get_model_instance_with_name($modelName, $this->_timezone);
2041
+		} else {
2042
+			$this->_model->set_timezone($this->_timezone);
2043
+		}
2044
+		return $this->_model;
2045
+	}
2046
+
2047
+
2048
+	/**
2049
+	 * @param $props_n_values
2050
+	 * @param $classname
2051
+	 * @return mixed bool|EE_Base_Class|EEM_CPT_Base
2052
+	 * @throws ReflectionException
2053
+	 * @throws InvalidArgumentException
2054
+	 * @throws InvalidInterfaceException
2055
+	 * @throws InvalidDataTypeException
2056
+	 * @throws EE_Error
2057
+	 */
2058
+	protected static function _get_object_from_entity_mapper($props_n_values, $classname)
2059
+	{
2060
+		// TODO: will not work for Term_Relationships because they have no PK!
2061
+		$primary_id_ref = self::_get_primary_key_name($classname);
2062
+		if (
2063
+			array_key_exists($primary_id_ref, $props_n_values)
2064
+			&& ! empty($props_n_values[ $primary_id_ref ])
2065
+		) {
2066
+			$id = $props_n_values[ $primary_id_ref ];
2067
+			return self::_get_model($classname)->get_from_entity_map($id);
2068
+		}
2069
+		return false;
2070
+	}
2071
+
2072
+
2073
+	/**
2074
+	 * This is called by child static "new_instance" method and we'll check to see if there is an existing db entry for
2075
+	 * the primary key (if present in incoming values). If there is a key in the incoming array that matches the
2076
+	 * primary key for the model AND it is not null, then we check the db. If there's a an object we return it.  If not
2077
+	 * we return false.
2078
+	 *
2079
+	 * @param  array  $props_n_values   incoming array of properties and their values
2080
+	 * @param  string $classname        the classname of the child class
2081
+	 * @param null    $timezone
2082
+	 * @param array   $date_formats     incoming date_formats in an array where the first value is the
2083
+	 *                                  date_format and the second value is the time format
2084
+	 * @return mixed (EE_Base_Class|bool)
2085
+	 * @throws InvalidArgumentException
2086
+	 * @throws InvalidInterfaceException
2087
+	 * @throws InvalidDataTypeException
2088
+	 * @throws EE_Error
2089
+	 * @throws ReflectionException
2090
+	 * @throws ReflectionException
2091
+	 * @throws ReflectionException
2092
+	 */
2093
+	protected static function _check_for_object($props_n_values, $classname, $timezone = null, $date_formats = array())
2094
+	{
2095
+		$existing = null;
2096
+		$model = self::_get_model($classname, $timezone);
2097
+		if ($model->has_primary_key_field()) {
2098
+			$primary_id_ref = self::_get_primary_key_name($classname);
2099
+			if (
2100
+				array_key_exists($primary_id_ref, $props_n_values)
2101
+				&& ! empty($props_n_values[ $primary_id_ref ])
2102
+			) {
2103
+				$existing = $model->get_one_by_ID(
2104
+					$props_n_values[ $primary_id_ref ]
2105
+				);
2106
+			}
2107
+		} elseif ($model->has_all_combined_primary_key_fields($props_n_values)) {
2108
+			// no primary key on this model, but there's still a matching item in the DB
2109
+			$existing = self::_get_model($classname, $timezone)->get_one_by_ID(
2110
+				self::_get_model($classname, $timezone)
2111
+					->get_index_primary_key_string($props_n_values)
2112
+			);
2113
+		}
2114
+		if ($existing) {
2115
+			// set date formats if present before setting values
2116
+			if (! empty($date_formats) && is_array($date_formats)) {
2117
+				$existing->set_date_format($date_formats[0]);
2118
+				$existing->set_time_format($date_formats[1]);
2119
+			} else {
2120
+				// set default formats for date and time
2121
+				$existing->set_date_format(get_option('date_format'));
2122
+				$existing->set_time_format(get_option('time_format'));
2123
+			}
2124
+			foreach ($props_n_values as $property => $field_value) {
2125
+				$existing->set($property, $field_value);
2126
+			}
2127
+			return $existing;
2128
+		}
2129
+		return false;
2130
+	}
2131
+
2132
+
2133
+	/**
2134
+	 * Gets the EEM_*_Model for this class
2135
+	 *
2136
+	 * @access public now, as this is more convenient
2137
+	 * @param      $classname
2138
+	 * @param null $timezone
2139
+	 * @throws ReflectionException
2140
+	 * @throws InvalidArgumentException
2141
+	 * @throws InvalidInterfaceException
2142
+	 * @throws InvalidDataTypeException
2143
+	 * @throws EE_Error
2144
+	 * @return EEM_Base
2145
+	 */
2146
+	protected static function _get_model($classname, $timezone = null)
2147
+	{
2148
+		// find model for this class
2149
+		if (! $classname) {
2150
+			throw new EE_Error(
2151
+				sprintf(
2152
+					esc_html__(
2153
+						'What were you thinking calling _get_model(%s)?? You need to specify the class name',
2154
+						'event_espresso'
2155
+					),
2156
+					$classname
2157
+				)
2158
+			);
2159
+		}
2160
+		$modelName = self::_get_model_classname($classname);
2161
+		return self::_get_model_instance_with_name($modelName, $timezone);
2162
+	}
2163
+
2164
+
2165
+	/**
2166
+	 * Gets the model instance (eg instance of EEM_Attendee) given its classname (eg EE_Attendee)
2167
+	 *
2168
+	 * @param string $model_classname
2169
+	 * @param null   $timezone
2170
+	 * @return EEM_Base
2171
+	 * @throws ReflectionException
2172
+	 * @throws InvalidArgumentException
2173
+	 * @throws InvalidInterfaceException
2174
+	 * @throws InvalidDataTypeException
2175
+	 * @throws EE_Error
2176
+	 */
2177
+	protected static function _get_model_instance_with_name($model_classname, $timezone = null)
2178
+	{
2179
+		$model_classname = str_replace('EEM_', '', $model_classname);
2180
+		$model = EE_Registry::instance()->load_model($model_classname);
2181
+		$model->set_timezone($timezone);
2182
+		return $model;
2183
+	}
2184
+
2185
+
2186
+	/**
2187
+	 * If a model name is provided (eg Registration), gets the model classname for that model.
2188
+	 * Also works if a model class's classname is provided (eg EE_Registration).
2189
+	 *
2190
+	 * @param string|null $model_name
2191
+	 * @return string like EEM_Attendee
2192
+	 */
2193
+	private static function _get_model_classname($model_name = '')
2194
+	{
2195
+		return strpos((string) $model_name, 'EE_') === 0
2196
+			? str_replace('EE_', 'EEM_', $model_name)
2197
+			: 'EEM_' . $model_name;
2198
+	}
2199
+
2200
+
2201
+	/**
2202
+	 * returns the name of the primary key attribute
2203
+	 *
2204
+	 * @param null $classname
2205
+	 * @throws ReflectionException
2206
+	 * @throws InvalidArgumentException
2207
+	 * @throws InvalidInterfaceException
2208
+	 * @throws InvalidDataTypeException
2209
+	 * @throws EE_Error
2210
+	 * @return string
2211
+	 */
2212
+	protected static function _get_primary_key_name($classname = null)
2213
+	{
2214
+		if (! $classname) {
2215
+			throw new EE_Error(
2216
+				sprintf(
2217
+					esc_html__('What were you thinking calling _get_primary_key_name(%s)', 'event_espresso'),
2218
+					$classname
2219
+				)
2220
+			);
2221
+		}
2222
+		return self::_get_model($classname)->get_primary_key_field()->get_name();
2223
+	}
2224
+
2225
+
2226
+	/**
2227
+	 * Gets the value of the primary key.
2228
+	 * If the object hasn't yet been saved, it should be whatever the model field's default was
2229
+	 * (eg, if this were the EE_Event class, look at the primary key field on EEM_Event and see what its default value
2230
+	 * is. Usually defaults for integer primary keys are 0; string primary keys are usually NULL).
2231
+	 *
2232
+	 * @return mixed, if the primary key is of type INT it'll be an int. Otherwise it could be a string
2233
+	 * @throws ReflectionException
2234
+	 * @throws InvalidArgumentException
2235
+	 * @throws InvalidInterfaceException
2236
+	 * @throws InvalidDataTypeException
2237
+	 * @throws EE_Error
2238
+	 */
2239
+	public function ID()
2240
+	{
2241
+		$model = $this->get_model();
2242
+		// now that we know the name of the variable, use a variable variable to get its value and return its
2243
+		if ($model->has_primary_key_field()) {
2244
+			return $this->_fields[ $model->primary_key_name() ];
2245
+		}
2246
+		return $model->get_index_primary_key_string($this->_fields);
2247
+	}
2248
+
2249
+
2250
+	/**
2251
+	 * @param EE_Base_Class|int|string $otherModelObjectOrID
2252
+	 * @param string                   $relationName
2253
+	 * @return bool
2254
+	 * @throws EE_Error
2255
+	 * @throws ReflectionException
2256
+	 * @since   $VID:$
2257
+	 */
2258
+	public function hasRelation($otherModelObjectOrID, string $relationName): bool
2259
+	{
2260
+		$other_model = self::_get_model_instance_with_name(
2261
+			self::_get_model_classname($relationName),
2262
+			$this->_timezone
2263
+		);
2264
+		$primary_key = $other_model->primary_key_name();
2265
+		/** @var EE_Base_Class $otherModelObject */
2266
+		$otherModelObject = $other_model->ensure_is_obj($otherModelObjectOrID, $relationName);
2267
+		return $this->count_related($relationName, [[$primary_key => $otherModelObject->ID()]]) > 0;
2268
+	}
2269
+
2270
+
2271
+	/**
2272
+	 * Adds a relationship to the specified EE_Base_Class object, given the relationship's name. Eg, if the current
2273
+	 * model is related to a group of events, the $relationName should be 'Event', and should be a key in the EE
2274
+	 * Model's $_model_relations array. If this model object doesn't exist in the DB, just caches the related thing
2275
+	 *
2276
+	 * @param mixed  $otherObjectModelObjectOrID       EE_Base_Class or the ID of the other object
2277
+	 * @param string $relationName                     eg 'Events','Question',etc.
2278
+	 *                                                 an attendee to a group, you also want to specify which role they
2279
+	 *                                                 will have in that group. So you would use this parameter to
2280
+	 *                                                 specify array('role-column-name'=>'role-id')
2281
+	 * @param array  $extra_join_model_fields_n_values You can optionally include an array of key=>value pairs that
2282
+	 *                                                 allow you to further constrict the relation to being added.
2283
+	 *                                                 However, keep in mind that the columns (keys) given must match a
2284
+	 *                                                 column on the JOIN table and currently only the HABTM models
2285
+	 *                                                 accept these additional conditions.  Also remember that if an
2286
+	 *                                                 exact match isn't found for these extra cols/val pairs, then a
2287
+	 *                                                 NEW row is created in the join table.
2288
+	 * @param null   $cache_id
2289
+	 * @throws ReflectionException
2290
+	 * @throws InvalidArgumentException
2291
+	 * @throws InvalidInterfaceException
2292
+	 * @throws InvalidDataTypeException
2293
+	 * @throws EE_Error
2294
+	 * @return EE_Base_Class the object the relation was added to
2295
+	 */
2296
+	public function _add_relation_to(
2297
+		$otherObjectModelObjectOrID,
2298
+		$relationName,
2299
+		$extra_join_model_fields_n_values = array(),
2300
+		$cache_id = null
2301
+	) {
2302
+		$model = $this->get_model();
2303
+		// if this thing exists in the DB, save the relation to the DB
2304
+		if ($this->ID()) {
2305
+			$otherObject = $model->add_relationship_to(
2306
+				$this,
2307
+				$otherObjectModelObjectOrID,
2308
+				$relationName,
2309
+				$extra_join_model_fields_n_values
2310
+			);
2311
+			// clear cache so future get_many_related and get_first_related() return new results.
2312
+			$this->clear_cache($relationName, $otherObject, true);
2313
+			if ($otherObject instanceof EE_Base_Class) {
2314
+				$otherObject->clear_cache($model->get_this_model_name(), $this);
2315
+			}
2316
+		} else {
2317
+			// this thing doesn't exist in the DB,  so just cache it
2318
+			if (! $otherObjectModelObjectOrID instanceof EE_Base_Class) {
2319
+				throw new EE_Error(
2320
+					sprintf(
2321
+						esc_html__(
2322
+							'Before a model object is saved to the database, calls to _add_relation_to must be passed an actual object, not just an ID. You provided %s as the model object to a %s',
2323
+							'event_espresso'
2324
+						),
2325
+						$otherObjectModelObjectOrID,
2326
+						get_class($this)
2327
+					)
2328
+				);
2329
+			}
2330
+			$otherObject = $otherObjectModelObjectOrID;
2331
+			$this->cache($relationName, $otherObjectModelObjectOrID, $cache_id);
2332
+		}
2333
+		if ($otherObject instanceof EE_Base_Class) {
2334
+			// fix the reciprocal relation too
2335
+			if ($otherObject->ID()) {
2336
+				// its saved so assumed relations exist in the DB, so we can just
2337
+				// clear the cache so future queries use the updated info in the DB
2338
+				$otherObject->clear_cache(
2339
+					$model->get_this_model_name(),
2340
+					null,
2341
+					true
2342
+				);
2343
+			} else {
2344
+				// it's not saved, so it caches relations like this
2345
+				$otherObject->cache($model->get_this_model_name(), $this);
2346
+			}
2347
+		}
2348
+		return $otherObject;
2349
+	}
2350
+
2351
+
2352
+	/**
2353
+	 * Removes a relationship to the specified EE_Base_Class object, given the relationships' name. Eg, if the current
2354
+	 * model is related to a group of events, the $relationName should be 'Events', and should be a key in the EE
2355
+	 * Model's $_model_relations array. If this model object doesn't exist in the DB, just removes the related thing
2356
+	 * from the cache
2357
+	 *
2358
+	 * @param mixed  $otherObjectModelObjectOrID
2359
+	 *                EE_Base_Class or the ID of the other object, OR an array key into the cache if this isn't saved
2360
+	 *                to the DB yet
2361
+	 * @param string $relationName
2362
+	 * @param array  $where_query
2363
+	 *                You can optionally include an array of key=>value pairs that allow you to further constrict the
2364
+	 *                relation to being added. However, keep in mind that the columns (keys) given must match a column
2365
+	 *                on the JOIN table and currently only the HABTM models accept these additional conditions. Also
2366
+	 *                remember that if an exact match isn't found for these extra cols/val pairs, then no row is
2367
+	 *                deleted.
2368
+	 * @return EE_Base_Class the relation was removed from
2369
+	 * @throws ReflectionException
2370
+	 * @throws InvalidArgumentException
2371
+	 * @throws InvalidInterfaceException
2372
+	 * @throws InvalidDataTypeException
2373
+	 * @throws EE_Error
2374
+	 */
2375
+	public function _remove_relation_to($otherObjectModelObjectOrID, $relationName, $where_query = array())
2376
+	{
2377
+		if ($this->ID()) {
2378
+			// if this exists in the DB, save the relation change to the DB too
2379
+			$otherObject = $this->get_model()->remove_relationship_to(
2380
+				$this,
2381
+				$otherObjectModelObjectOrID,
2382
+				$relationName,
2383
+				$where_query
2384
+			);
2385
+			$this->clear_cache(
2386
+				$relationName,
2387
+				$otherObject
2388
+			);
2389
+		} else {
2390
+			// this doesn't exist in the DB, just remove it from the cache
2391
+			$otherObject = $this->clear_cache(
2392
+				$relationName,
2393
+				$otherObjectModelObjectOrID
2394
+			);
2395
+		}
2396
+		if ($otherObject instanceof EE_Base_Class) {
2397
+			$otherObject->clear_cache(
2398
+				$this->get_model()->get_this_model_name(),
2399
+				$this
2400
+			);
2401
+		}
2402
+		return $otherObject;
2403
+	}
2404
+
2405
+
2406
+	/**
2407
+	 * Removes ALL the related things for the $relationName.
2408
+	 *
2409
+	 * @param string $relationName
2410
+	 * @param array  $where_query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
2411
+	 * @return EE_Base_Class
2412
+	 * @throws ReflectionException
2413
+	 * @throws InvalidArgumentException
2414
+	 * @throws InvalidInterfaceException
2415
+	 * @throws InvalidDataTypeException
2416
+	 * @throws EE_Error
2417
+	 */
2418
+	public function _remove_relations($relationName, $where_query_params = array())
2419
+	{
2420
+		if ($this->ID()) {
2421
+			// if this exists in the DB, save the relation change to the DB too
2422
+			$otherObjects = $this->get_model()->remove_relations(
2423
+				$this,
2424
+				$relationName,
2425
+				$where_query_params
2426
+			);
2427
+			$this->clear_cache(
2428
+				$relationName,
2429
+				null,
2430
+				true
2431
+			);
2432
+		} else {
2433
+			// this doesn't exist in the DB, just remove it from the cache
2434
+			$otherObjects = $this->clear_cache(
2435
+				$relationName,
2436
+				null,
2437
+				true
2438
+			);
2439
+		}
2440
+		if (is_array($otherObjects)) {
2441
+			foreach ($otherObjects as $otherObject) {
2442
+				$otherObject->clear_cache(
2443
+					$this->get_model()->get_this_model_name(),
2444
+					$this
2445
+				);
2446
+			}
2447
+		}
2448
+		return $otherObjects;
2449
+	}
2450
+
2451
+
2452
+	/**
2453
+	 * Gets all the related model objects of the specified type. Eg, if the current class if
2454
+	 * EE_Event, you could call $this->get_many_related('Registration') to get an array of all the
2455
+	 * EE_Registration objects which related to this event. Note: by default, we remove the "default query params"
2456
+	 * because we want to get even deleted items etc.
2457
+	 *
2458
+	 * @param string $relationName key in the model's _model_relations array
2459
+	 * @param array  $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
2460
+	 * @return EE_Base_Class[]     Results not necessarily indexed by IDs, because some results might not have primary
2461
+	 *                             keys or might not be saved yet. Consider using EEM_Base::get_IDs() on these
2462
+	 *                             results if you want IDs
2463
+	 * @throws ReflectionException
2464
+	 * @throws InvalidArgumentException
2465
+	 * @throws InvalidInterfaceException
2466
+	 * @throws InvalidDataTypeException
2467
+	 * @throws EE_Error
2468
+	 */
2469
+	public function get_many_related($relationName, $query_params = array())
2470
+	{
2471
+		if ($this->ID()) {
2472
+			// this exists in the DB, so get the related things from either the cache or the DB
2473
+			// if there are query parameters, forget about caching the related model objects.
2474
+			if ($query_params) {
2475
+				$related_model_objects = $this->get_model()->get_all_related(
2476
+					$this,
2477
+					$relationName,
2478
+					$query_params
2479
+				);
2480
+			} else {
2481
+				// did we already cache the result of this query?
2482
+				$cached_results = $this->get_all_from_cache($relationName);
2483
+				if (! $cached_results) {
2484
+					$related_model_objects = $this->get_model()->get_all_related(
2485
+						$this,
2486
+						$relationName,
2487
+						$query_params
2488
+					);
2489
+					// if no query parameters were passed, then we got all the related model objects
2490
+					// for that relation. We can cache them then.
2491
+					foreach ($related_model_objects as $related_model_object) {
2492
+						$this->cache($relationName, $related_model_object);
2493
+					}
2494
+				} else {
2495
+					$related_model_objects = $cached_results;
2496
+				}
2497
+			}
2498
+		} else {
2499
+			// this doesn't exist in the DB, so just get the related things from the cache
2500
+			$related_model_objects = $this->get_all_from_cache($relationName);
2501
+		}
2502
+		return $related_model_objects;
2503
+	}
2504
+
2505
+
2506
+	/**
2507
+	 * Instead of getting the related model objects, simply counts them. Ignores default_where_conditions by default,
2508
+	 * unless otherwise specified in the $query_params
2509
+	 *
2510
+	 * @param string $relation_name  model_name like 'Event', or 'Registration'
2511
+	 * @param array  $query_params   @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2512
+	 * @param string $field_to_count name of field to count by. By default, uses primary key
2513
+	 * @param bool   $distinct       if we want to only count the distinct values for the column then you can trigger
2514
+	 *                               that by the setting $distinct to TRUE;
2515
+	 * @return int
2516
+	 * @throws ReflectionException
2517
+	 * @throws InvalidArgumentException
2518
+	 * @throws InvalidInterfaceException
2519
+	 * @throws InvalidDataTypeException
2520
+	 * @throws EE_Error
2521
+	 */
2522
+	public function count_related($relation_name, $query_params = array(), $field_to_count = null, $distinct = false)
2523
+	{
2524
+		return $this->get_model()->count_related(
2525
+			$this,
2526
+			$relation_name,
2527
+			$query_params,
2528
+			$field_to_count,
2529
+			$distinct
2530
+		);
2531
+	}
2532
+
2533
+
2534
+	/**
2535
+	 * Instead of getting the related model objects, simply sums up the values of the specified field.
2536
+	 * Note: ignores default_where_conditions by default, unless otherwise specified in the $query_params
2537
+	 *
2538
+	 * @param string $relation_name model_name like 'Event', or 'Registration'
2539
+	 * @param array  $query_params  @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2540
+	 * @param string $field_to_sum  name of field to count by.
2541
+	 *                              By default, uses primary key
2542
+	 *                              (which doesn't make much sense, so you should probably change it)
2543
+	 * @return int
2544
+	 * @throws ReflectionException
2545
+	 * @throws InvalidArgumentException
2546
+	 * @throws InvalidInterfaceException
2547
+	 * @throws InvalidDataTypeException
2548
+	 * @throws EE_Error
2549
+	 */
2550
+	public function sum_related($relation_name, $query_params = array(), $field_to_sum = null)
2551
+	{
2552
+		return $this->get_model()->sum_related(
2553
+			$this,
2554
+			$relation_name,
2555
+			$query_params,
2556
+			$field_to_sum
2557
+		);
2558
+	}
2559
+
2560
+
2561
+	/**
2562
+	 * Gets the first (ie, one) related model object of the specified type.
2563
+	 *
2564
+	 * @param string $relationName key in the model's _model_relations array
2565
+	 * @param array  $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2566
+	 * @return EE_Base_Class (not an array, a single object)
2567
+	 * @throws ReflectionException
2568
+	 * @throws InvalidArgumentException
2569
+	 * @throws InvalidInterfaceException
2570
+	 * @throws InvalidDataTypeException
2571
+	 * @throws EE_Error
2572
+	 */
2573
+	public function get_first_related($relationName, $query_params = array())
2574
+	{
2575
+		$model = $this->get_model();
2576
+		if ($this->ID()) {// this exists in the DB, get from the cache OR the DB
2577
+			// if they've provided some query parameters, don't bother trying to cache the result
2578
+			// also make sure we're not caching the result of get_first_related
2579
+			// on a relation which should have an array of objects (because the cache might have an array of objects)
2580
+			if (
2581
+				$query_params
2582
+				|| ! $model->related_settings_for($relationName)
2583
+					 instanceof
2584
+					 EE_Belongs_To_Relation
2585
+			) {
2586
+				$related_model_object = $model->get_first_related(
2587
+					$this,
2588
+					$relationName,
2589
+					$query_params
2590
+				);
2591
+			} else {
2592
+				// first, check if we've already cached the result of this query
2593
+				$cached_result = $this->get_one_from_cache($relationName);
2594
+				if (! $cached_result) {
2595
+					$related_model_object = $model->get_first_related(
2596
+						$this,
2597
+						$relationName,
2598
+						$query_params
2599
+					);
2600
+					$this->cache($relationName, $related_model_object);
2601
+				} else {
2602
+					$related_model_object = $cached_result;
2603
+				}
2604
+			}
2605
+		} else {
2606
+			$related_model_object = null;
2607
+			// this doesn't exist in the Db,
2608
+			// but maybe the relation is of type belongs to, and so the related thing might
2609
+			if ($model->related_settings_for($relationName) instanceof EE_Belongs_To_Relation) {
2610
+				$related_model_object = $model->get_first_related(
2611
+					$this,
2612
+					$relationName,
2613
+					$query_params
2614
+				);
2615
+			}
2616
+			// this doesn't exist in the DB and apparently the thing it belongs to doesn't either,
2617
+			// just get what's cached on this object
2618
+			if (! $related_model_object) {
2619
+				$related_model_object = $this->get_one_from_cache($relationName);
2620
+			}
2621
+		}
2622
+		return $related_model_object;
2623
+	}
2624
+
2625
+
2626
+	/**
2627
+	 * Does a delete on all related objects of type $relationName and removes
2628
+	 * the current model object's relation to them. If they can't be deleted (because
2629
+	 * of blocking related model objects) does nothing. If the related model objects are
2630
+	 * soft-deletable, they will be soft-deleted regardless of related blocking model objects.
2631
+	 * If this model object doesn't exist yet in the DB, just removes its related things
2632
+	 *
2633
+	 * @param string $relationName
2634
+	 * @param array  $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2635
+	 * @return int how many deleted
2636
+	 * @throws ReflectionException
2637
+	 * @throws InvalidArgumentException
2638
+	 * @throws InvalidInterfaceException
2639
+	 * @throws InvalidDataTypeException
2640
+	 * @throws EE_Error
2641
+	 */
2642
+	public function delete_related($relationName, $query_params = array())
2643
+	{
2644
+		if ($this->ID()) {
2645
+			$count = $this->get_model()->delete_related(
2646
+				$this,
2647
+				$relationName,
2648
+				$query_params
2649
+			);
2650
+		} else {
2651
+			$count = count($this->get_all_from_cache($relationName));
2652
+			$this->clear_cache($relationName, null, true);
2653
+		}
2654
+		return $count;
2655
+	}
2656
+
2657
+
2658
+	/**
2659
+	 * Does a hard delete (ie, removes the DB row) on all related objects of type $relationName and removes
2660
+	 * the current model object's relation to them. If they can't be deleted (because
2661
+	 * of blocking related model objects) just does a soft delete on it instead, if possible.
2662
+	 * If the related thing isn't a soft-deletable model object, this function is identical
2663
+	 * to delete_related(). If this model object doesn't exist in the DB, just remove its related things
2664
+	 *
2665
+	 * @param string $relationName
2666
+	 * @param array  $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2667
+	 * @return int how many deleted (including those soft deleted)
2668
+	 * @throws ReflectionException
2669
+	 * @throws InvalidArgumentException
2670
+	 * @throws InvalidInterfaceException
2671
+	 * @throws InvalidDataTypeException
2672
+	 * @throws EE_Error
2673
+	 */
2674
+	public function delete_related_permanently($relationName, $query_params = array())
2675
+	{
2676
+		if ($this->ID()) {
2677
+			$count = $this->get_model()->delete_related_permanently(
2678
+				$this,
2679
+				$relationName,
2680
+				$query_params
2681
+			);
2682
+		} else {
2683
+			$count = count($this->get_all_from_cache($relationName));
2684
+		}
2685
+		$this->clear_cache($relationName, null, true);
2686
+		return $count;
2687
+	}
2688
+
2689
+
2690
+	/**
2691
+	 * is_set
2692
+	 * Just a simple utility function children can use for checking if property exists
2693
+	 *
2694
+	 * @access  public
2695
+	 * @param  string $field_name property to check
2696
+	 * @return bool                              TRUE if existing,FALSE if not.
2697
+	 */
2698
+	public function is_set($field_name)
2699
+	{
2700
+		return isset($this->_fields[ $field_name ]);
2701
+	}
2702
+
2703
+
2704
+	/**
2705
+	 * Just a simple utility function children can use for checking if property (or properties) exists and throwing an
2706
+	 * EE_Error exception if they don't
2707
+	 *
2708
+	 * @param  mixed (string|array) $properties properties to check
2709
+	 * @throws EE_Error
2710
+	 * @return bool                              TRUE if existing, throw EE_Error if not.
2711
+	 */
2712
+	protected function _property_exists($properties)
2713
+	{
2714
+		foreach ((array) $properties as $property_name) {
2715
+			// first make sure this property exists
2716
+			if (! $this->_fields[ $property_name ]) {
2717
+				throw new EE_Error(
2718
+					sprintf(
2719
+						esc_html__(
2720
+							'Trying to retrieve a non-existent property (%s).  Double check the spelling please',
2721
+							'event_espresso'
2722
+						),
2723
+						$property_name
2724
+					)
2725
+				);
2726
+			}
2727
+		}
2728
+		return true;
2729
+	}
2730
+
2731
+
2732
+	/**
2733
+	 * This simply returns an array of model fields for this object
2734
+	 *
2735
+	 * @return array
2736
+	 * @throws ReflectionException
2737
+	 * @throws InvalidArgumentException
2738
+	 * @throws InvalidInterfaceException
2739
+	 * @throws InvalidDataTypeException
2740
+	 * @throws EE_Error
2741
+	 */
2742
+	public function model_field_array()
2743
+	{
2744
+		$fields = $this->get_model()->field_settings(false);
2745
+		$properties = array();
2746
+		// remove prepended underscore
2747
+		foreach ($fields as $field_name => $settings) {
2748
+			$properties[ $field_name ] = $this->get($field_name);
2749
+		}
2750
+		return $properties;
2751
+	}
2752
+
2753
+
2754
+	/**
2755
+	 * Very handy general function to allow for plugins to extend any child of EE_Base_Class.
2756
+	 * If a method is called on a child of EE_Base_Class that doesn't exist, this function is called
2757
+	 * (http://www.garfieldtech.com/blog/php-magic-call) and passed the method's name and arguments.
2758
+	 * Instead of requiring a plugin to extend the EE_Base_Class
2759
+	 * (which works fine is there's only 1 plugin, but when will that happen?)
2760
+	 * they can add a hook onto 'filters_hook_espresso__{className}__{methodName}'
2761
+	 * (eg, filters_hook_espresso__EE_Answer__my_great_function)
2762
+	 * and accepts 2 arguments: the object on which the function was called,
2763
+	 * and an array of the original arguments passed to the function.
2764
+	 * Whatever their callback function returns will be returned by this function.
2765
+	 * Example: in functions.php (or in a plugin):
2766
+	 *      add_filter('FHEE__EE_Answer__my_callback','my_callback',10,3);
2767
+	 *      function my_callback($previousReturnValue,EE_Base_Class $object,$argsArray){
2768
+	 *          $returnString= "you called my_callback! and passed args:".implode(",",$argsArray);
2769
+	 *          return $previousReturnValue.$returnString;
2770
+	 *      }
2771
+	 * require('EE_Answer.class.php');
2772
+	 * echo EE_Answer::new_instance(['REG_ID' => 2,'QST_ID' => 3,'ANS_value' => The answer is 42'])
2773
+	 *      ->my_callback('monkeys',100);
2774
+	 * // will output "you called my_callback! and passed args:monkeys,100"
2775
+	 *
2776
+	 * @param string $methodName name of method which was called on a child of EE_Base_Class, but which
2777
+	 * @param array  $args       array of original arguments passed to the function
2778
+	 * @throws EE_Error
2779
+	 * @return mixed whatever the plugin which calls add_filter decides
2780
+	 */
2781
+	public function __call($methodName, $args)
2782
+	{
2783
+		$className = get_class($this);
2784
+		$tagName = "FHEE__{$className}__{$methodName}";
2785
+		if (! has_filter($tagName)) {
2786
+			throw new EE_Error(
2787
+				sprintf(
2788
+					esc_html__(
2789
+						"Method %s on class %s does not exist! You can create one with the following code in functions.php or in a plugin: add_filter('%s','my_callback',10,3);function my_callback(\$previousReturnValue,EE_Base_Class \$object, \$argsArray){/*function body*/return \$whatever;}",
2790
+						'event_espresso'
2791
+					),
2792
+					$methodName,
2793
+					$className,
2794
+					$tagName
2795
+				)
2796
+			);
2797
+		}
2798
+		return apply_filters($tagName, null, $this, $args);
2799
+	}
2800
+
2801
+
2802
+	/**
2803
+	 * Similar to insert_post_meta, adds a record in the Extra_Meta model's table with the given key and value.
2804
+	 * A $previous_value can be specified in case there are many meta rows with the same key
2805
+	 *
2806
+	 * @param string $meta_key
2807
+	 * @param mixed  $meta_value
2808
+	 * @param mixed  $previous_value
2809
+	 * @return bool|int # of records updated (or BOOLEAN if we actually ended up inserting the extra meta row)
2810
+	 *                  NOTE: if the values haven't changed, returns 0
2811
+	 * @throws InvalidArgumentException
2812
+	 * @throws InvalidInterfaceException
2813
+	 * @throws InvalidDataTypeException
2814
+	 * @throws EE_Error
2815
+	 * @throws ReflectionException
2816
+	 */
2817
+	public function update_extra_meta(string $meta_key, $meta_value, $previous_value = null)
2818
+	{
2819
+		$query_params = [
2820
+			[
2821
+				'EXM_key'  => $meta_key,
2822
+				'OBJ_ID'   => $this->ID(),
2823
+				'EXM_type' => $this->get_model()->get_this_model_name(),
2824
+			],
2825
+		];
2826
+		if ($previous_value !== null) {
2827
+			$query_params[0]['EXM_value'] = $meta_value;
2828
+		}
2829
+		$existing_rows_like_that = EEM_Extra_Meta::instance()->get_all($query_params);
2830
+		if (! $existing_rows_like_that) {
2831
+			return $this->add_extra_meta($meta_key, $meta_value);
2832
+		}
2833
+		foreach ($existing_rows_like_that as $existing_row) {
2834
+			$existing_row->save(['EXM_value' => $meta_value]);
2835
+		}
2836
+		return count($existing_rows_like_that);
2837
+	}
2838
+
2839
+
2840
+	/**
2841
+	 * Adds a new extra meta record. If $unique is set to TRUE, we'll first double-check
2842
+	 * no other extra meta for this model object have the same key. Returns TRUE if the
2843
+	 * extra meta row was entered, false if not
2844
+	 *
2845
+	 * @param string $meta_key
2846
+	 * @param mixed  $meta_value
2847
+	 * @param bool   $unique
2848
+	 * @return bool
2849
+	 * @throws InvalidArgumentException
2850
+	 * @throws InvalidInterfaceException
2851
+	 * @throws InvalidDataTypeException
2852
+	 * @throws EE_Error
2853
+	 * @throws ReflectionException
2854
+	 * @throws ReflectionException
2855
+	 */
2856
+	public function add_extra_meta(string $meta_key, $meta_value, bool $unique = false): bool
2857
+	{
2858
+		if ($unique) {
2859
+			$existing_extra_meta = EEM_Extra_Meta::instance()->get_one(
2860
+				[
2861
+					[
2862
+						'EXM_key'  => $meta_key,
2863
+						'OBJ_ID'   => $this->ID(),
2864
+						'EXM_type' => $this->get_model()->get_this_model_name(),
2865
+					],
2866
+				]
2867
+			);
2868
+			if ($existing_extra_meta) {
2869
+				return false;
2870
+			}
2871
+		}
2872
+		$new_extra_meta = EE_Extra_Meta::new_instance(
2873
+			[
2874
+				'EXM_key'   => $meta_key,
2875
+				'EXM_value' => $meta_value,
2876
+				'OBJ_ID'    => $this->ID(),
2877
+				'EXM_type'  => $this->get_model()->get_this_model_name(),
2878
+			]
2879
+		);
2880
+		$new_extra_meta->save();
2881
+		return true;
2882
+	}
2883
+
2884
+
2885
+	/**
2886
+	 * Deletes all the extra meta rows for this record as specified by key. If $meta_value
2887
+	 * is specified, only deletes extra meta records with that value.
2888
+	 *
2889
+	 * @param string $meta_key
2890
+	 * @param mixed  $meta_value
2891
+	 * @return int|bool number of extra meta rows deleted
2892
+	 * @throws InvalidArgumentException
2893
+	 * @throws InvalidInterfaceException
2894
+	 * @throws InvalidDataTypeException
2895
+	 * @throws EE_Error
2896
+	 * @throws ReflectionException
2897
+	 */
2898
+	public function delete_extra_meta(string $meta_key, $meta_value = null)
2899
+	{
2900
+		$query_params = [
2901
+			[
2902
+				'EXM_key'  => $meta_key,
2903
+				'OBJ_ID'   => $this->ID(),
2904
+				'EXM_type' => $this->get_model()->get_this_model_name(),
2905
+			],
2906
+		];
2907
+		if ($meta_value !== null) {
2908
+			$query_params[0]['EXM_value'] = $meta_value;
2909
+		}
2910
+		return EEM_Extra_Meta::instance()->delete($query_params);
2911
+	}
2912
+
2913
+
2914
+	/**
2915
+	 * Gets the extra meta with the given meta key. If you specify "single" we just return 1, otherwise
2916
+	 * an array of everything found. Requires that this model actually have a relation of type EE_Has_Many_Any_Relation.
2917
+	 * You can specify $default is case you haven't found the extra meta
2918
+	 *
2919
+	 * @param string     $meta_key
2920
+	 * @param bool       $single
2921
+	 * @param mixed      $default if we don't find anything, what should we return?
2922
+	 * @param array|null $extra_where
2923
+	 * @return mixed single value if $single; array if ! $single
2924
+	 * @throws ReflectionException
2925
+	 * @throws EE_Error
2926
+	 */
2927
+	public function get_extra_meta(string $meta_key, bool $single = false, $default = null, ?array $extra_where = [])
2928
+	{
2929
+		$query_params = [ $extra_where + ['EXM_key' => $meta_key] ];
2930
+		if ($single) {
2931
+			$result = $this->get_first_related('Extra_Meta', $query_params);
2932
+			if ($result instanceof EE_Extra_Meta) {
2933
+				return $result->value();
2934
+			}
2935
+		} else {
2936
+			$results = $this->get_many_related('Extra_Meta', $query_params);
2937
+			if ($results) {
2938
+				$values = [];
2939
+				foreach ($results as $result) {
2940
+					if ($result instanceof EE_Extra_Meta) {
2941
+						$values[ $result->ID() ] = $result->value();
2942
+					}
2943
+				}
2944
+				return $values;
2945
+			}
2946
+		}
2947
+		// if nothing discovered yet return default.
2948
+		return apply_filters(
2949
+			'FHEE__EE_Base_Class__get_extra_meta__default_value',
2950
+			$default,
2951
+			$meta_key,
2952
+			$single,
2953
+			$this
2954
+		);
2955
+	}
2956
+
2957
+
2958
+	/**
2959
+	 * Returns a simple array of all the extra meta associated with this model object.
2960
+	 * If $one_of_each_key is true (Default), it will be an array of simple key-value pairs, keys being the
2961
+	 * extra meta's key, and teh value being its value. However, if there are duplicate extra meta rows with
2962
+	 * the same key, only one will be used. (eg array('foo'=>'bar','monkey'=>123))
2963
+	 * If $one_of_each_key is false, it will return an array with the top-level keys being
2964
+	 * the extra meta keys, but their values are also arrays, which have the extra-meta's ID as their sub-key, and
2965
+	 * finally the extra meta's value as each sub-value. (eg
2966
+	 * array('foo'=>array(1=>'bar',2=>'bill'),'monkey'=>array(3=>123)))
2967
+	 *
2968
+	 * @param bool $one_of_each_key
2969
+	 * @return array
2970
+	 * @throws ReflectionException
2971
+	 * @throws InvalidArgumentException
2972
+	 * @throws InvalidInterfaceException
2973
+	 * @throws InvalidDataTypeException
2974
+	 * @throws EE_Error
2975
+	 */
2976
+	public function all_extra_meta_array(bool $one_of_each_key = true): array
2977
+	{
2978
+		$return_array = [];
2979
+		if ($one_of_each_key) {
2980
+			$extra_meta_objs = $this->get_many_related(
2981
+				'Extra_Meta',
2982
+				['group_by' => 'EXM_key']
2983
+			);
2984
+			foreach ($extra_meta_objs as $extra_meta_obj) {
2985
+				if ($extra_meta_obj instanceof EE_Extra_Meta) {
2986
+					$return_array[ $extra_meta_obj->key() ] = $extra_meta_obj->value();
2987
+				}
2988
+			}
2989
+		} else {
2990
+			$extra_meta_objs = $this->get_many_related('Extra_Meta');
2991
+			foreach ($extra_meta_objs as $extra_meta_obj) {
2992
+				if ($extra_meta_obj instanceof EE_Extra_Meta) {
2993
+					if (! isset($return_array[ $extra_meta_obj->key() ])) {
2994
+						$return_array[ $extra_meta_obj->key() ] = [];
2995
+					}
2996
+					$return_array[ $extra_meta_obj->key() ][ $extra_meta_obj->ID() ] = $extra_meta_obj->value();
2997
+				}
2998
+			}
2999
+		}
3000
+		return $return_array;
3001
+	}
3002
+
3003
+
3004
+	/**
3005
+	 * Gets a pretty nice displayable nice for this model object. Often overridden
3006
+	 *
3007
+	 * @return string
3008
+	 * @throws ReflectionException
3009
+	 * @throws InvalidArgumentException
3010
+	 * @throws InvalidInterfaceException
3011
+	 * @throws InvalidDataTypeException
3012
+	 * @throws EE_Error
3013
+	 */
3014
+	public function name()
3015
+	{
3016
+		// find a field that's not a text field
3017
+		$field_we_can_use = $this->get_model()->get_a_field_of_type('EE_Text_Field_Base');
3018
+		if ($field_we_can_use) {
3019
+			return $this->get($field_we_can_use->get_name());
3020
+		}
3021
+		$first_few_properties = $this->model_field_array();
3022
+		$first_few_properties = array_slice($first_few_properties, 0, 3);
3023
+		$name_parts = array();
3024
+		foreach ($first_few_properties as $name => $value) {
3025
+			$name_parts[] = "$name:$value";
3026
+		}
3027
+		return implode(',', $name_parts);
3028
+	}
3029
+
3030
+
3031
+	/**
3032
+	 * in_entity_map
3033
+	 * Checks if this model object has been proven to already be in the entity map
3034
+	 *
3035
+	 * @return boolean
3036
+	 * @throws ReflectionException
3037
+	 * @throws InvalidArgumentException
3038
+	 * @throws InvalidInterfaceException
3039
+	 * @throws InvalidDataTypeException
3040
+	 * @throws EE_Error
3041
+	 */
3042
+	public function in_entity_map()
3043
+	{
3044
+		// well, if we looked, did we find it in the entity map?
3045
+		return $this->ID() && $this->get_model()->get_from_entity_map($this->ID()) === $this;
3046
+	}
3047
+
3048
+
3049
+	/**
3050
+	 * refresh_from_db
3051
+	 * Makes sure the fields and values on this model object are in-sync with what's in the database.
3052
+	 *
3053
+	 * @throws ReflectionException
3054
+	 * @throws InvalidArgumentException
3055
+	 * @throws InvalidInterfaceException
3056
+	 * @throws InvalidDataTypeException
3057
+	 * @throws EE_Error if this model object isn't in the entity mapper (because then you should
3058
+	 * just use what's in the entity mapper and refresh it) and WP_DEBUG is TRUE
3059
+	 */
3060
+	public function refresh_from_db()
3061
+	{
3062
+		if ($this->ID() && $this->in_entity_map()) {
3063
+			$this->get_model()->refresh_entity_map_from_db($this->ID());
3064
+		} else {
3065
+			// if it doesn't have ID, you shouldn't be asking to refresh it from teh database (because its not in the database)
3066
+			// if it has an ID but it's not in the map, and you're asking me to refresh it
3067
+			// that's kinda dangerous. You should just use what's in the entity map, or add this to the entity map if there's
3068
+			// absolutely nothing in it for this ID
3069
+			if (WP_DEBUG) {
3070
+				throw new EE_Error(
3071
+					sprintf(
3072
+						esc_html__(
3073
+							'Trying to refresh a model object with ID "%1$s" that\'s not in the entity map? First off: you should put it in the entity map by calling %2$s. Second off, if you want what\'s in the database right now, you should just call %3$s yourself and discard this model object.',
3074
+							'event_espresso'
3075
+						),
3076
+						$this->ID(),
3077
+						get_class($this->get_model()) . '::instance()->add_to_entity_map()',
3078
+						get_class($this->get_model()) . '::instance()->refresh_entity_map()'
3079
+					)
3080
+				);
3081
+			}
3082
+		}
3083
+	}
3084
+
3085
+
3086
+	/**
3087
+	 * Change $fields' values to $new_value_sql (which is a string of raw SQL)
3088
+	 *
3089
+	 * @since 4.9.80.p
3090
+	 * @param EE_Model_Field_Base[] $fields
3091
+	 * @param string $new_value_sql
3092
+	 *      example: 'column_name=123',
3093
+	 *      or 'column_name=column_name+1',
3094
+	 *      or 'column_name= CASE
3095
+	 *          WHEN (`column_name` + `other_column` + 5) <= `yet_another_column`
3096
+	 *          THEN `column_name` + 5
3097
+	 *          ELSE `column_name`
3098
+	 *      END'
3099
+	 *      Also updates $field on this model object with the latest value from the database.
3100
+	 * @return bool
3101
+	 * @throws EE_Error
3102
+	 * @throws InvalidArgumentException
3103
+	 * @throws InvalidDataTypeException
3104
+	 * @throws InvalidInterfaceException
3105
+	 * @throws ReflectionException
3106
+	 */
3107
+	protected function updateFieldsInDB($fields, $new_value_sql)
3108
+	{
3109
+		// First make sure this model object actually exists in the DB. It would be silly to try to update it in the DB
3110
+		// if it wasn't even there to start off.
3111
+		if (! $this->ID()) {
3112
+			$this->save();
3113
+		}
3114
+		global $wpdb;
3115
+		if (empty($fields)) {
3116
+			throw new InvalidArgumentException(
3117
+				esc_html__(
3118
+					'EE_Base_Class::updateFieldsInDB was passed an empty array of fields.',
3119
+					'event_espresso'
3120
+				)
3121
+			);
3122
+		}
3123
+		$first_field = reset($fields);
3124
+		$table_alias = $first_field->get_table_alias();
3125
+		foreach ($fields as $field) {
3126
+			if ($table_alias !== $field->get_table_alias()) {
3127
+				throw new InvalidArgumentException(
3128
+					sprintf(
3129
+						esc_html__(
3130
+							// @codingStandardsIgnoreStart
3131
+							'EE_Base_Class::updateFieldsInDB was passed fields for different tables ("%1$s" and "%2$s"), which is not supported. Instead, please call the method multiple times.',
3132
+							// @codingStandardsIgnoreEnd
3133
+							'event_espresso'
3134
+						),
3135
+						$table_alias,
3136
+						$field->get_table_alias()
3137
+					)
3138
+				);
3139
+			}
3140
+		}
3141
+		// Ok the fields are now known to all be for the same table. Proceed with creating the SQL to update it.
3142
+		$table_obj = $this->get_model()->get_table_obj_by_alias($table_alias);
3143
+		$table_pk_value = $this->ID();
3144
+		$table_name = $table_obj->get_table_name();
3145
+		if ($table_obj instanceof EE_Secondary_Table) {
3146
+			$table_pk_field_name = $table_obj->get_fk_on_table();
3147
+		} else {
3148
+			$table_pk_field_name = $table_obj->get_pk_column();
3149
+		}
3150
+
3151
+		$query =
3152
+			"UPDATE `{$table_name}`
3153 3153
             SET "
3154
-            . $new_value_sql
3155
-            . $wpdb->prepare(
3156
-                "
3154
+			. $new_value_sql
3155
+			. $wpdb->prepare(
3156
+				"
3157 3157
             WHERE `{$table_pk_field_name}` = %d;",
3158
-                $table_pk_value
3159
-            );
3160
-        $result = $wpdb->query($query);
3161
-        foreach ($fields as $field) {
3162
-            // If it was successful, we'd like to know the new value.
3163
-            // If it failed, we'd also like to know the new value.
3164
-            $new_value = $this->get_model()->get_var(
3165
-                $this->get_model()->alter_query_params_to_restrict_by_ID(
3166
-                    $this->get_model()->get_index_primary_key_string(
3167
-                        $this->model_field_array()
3168
-                    ),
3169
-                    array(
3170
-                        'default_where_conditions' => 'minimum',
3171
-                    )
3172
-                ),
3173
-                $field->get_name()
3174
-            );
3175
-            $this->set_from_db(
3176
-                $field->get_name(),
3177
-                $new_value
3178
-            );
3179
-        }
3180
-        return (bool) $result;
3181
-    }
3182
-
3183
-
3184
-    /**
3185
-     * Nudges $field_name's value by $quantity, without any conditionals (in comparison to bumpConditionally()).
3186
-     * Does not allow negative values, however.
3187
-     *
3188
-     * @since 4.9.80.p
3189
-     * @param array $fields_n_quantities keys are the field names, and values are the amount by which to bump them
3190
-     *                                   (positive or negative). One important gotcha: all these values must be
3191
-     *                                   on the same table (eg don't pass in one field for the posts table and
3192
-     *                                   another for the event meta table.)
3193
-     * @return bool
3194
-     * @throws EE_Error
3195
-     * @throws InvalidArgumentException
3196
-     * @throws InvalidDataTypeException
3197
-     * @throws InvalidInterfaceException
3198
-     * @throws ReflectionException
3199
-     */
3200
-    public function adjustNumericFieldsInDb(array $fields_n_quantities)
3201
-    {
3202
-        global $wpdb;
3203
-        if (empty($fields_n_quantities)) {
3204
-            // No fields to update? Well sure, we updated them to that value just fine.
3205
-            return true;
3206
-        }
3207
-        $fields = [];
3208
-        $set_sql_statements = [];
3209
-        foreach ($fields_n_quantities as $field_name => $quantity) {
3210
-            $field = $this->get_model()->field_settings_for($field_name, true);
3211
-            $fields[] = $field;
3212
-            $column_name = $field->get_table_column();
3213
-
3214
-            $abs_qty = absint($quantity);
3215
-            if ($quantity > 0) {
3216
-                // don't let the value be negative as often these fields are unsigned
3217
-                $set_sql_statements[] = $wpdb->prepare(
3218
-                    "`{$column_name}` = `{$column_name}` + %d",
3219
-                    $abs_qty
3220
-                );
3221
-            } else {
3222
-                $set_sql_statements[] = $wpdb->prepare(
3223
-                    "`{$column_name}` = CASE
3158
+				$table_pk_value
3159
+			);
3160
+		$result = $wpdb->query($query);
3161
+		foreach ($fields as $field) {
3162
+			// If it was successful, we'd like to know the new value.
3163
+			// If it failed, we'd also like to know the new value.
3164
+			$new_value = $this->get_model()->get_var(
3165
+				$this->get_model()->alter_query_params_to_restrict_by_ID(
3166
+					$this->get_model()->get_index_primary_key_string(
3167
+						$this->model_field_array()
3168
+					),
3169
+					array(
3170
+						'default_where_conditions' => 'minimum',
3171
+					)
3172
+				),
3173
+				$field->get_name()
3174
+			);
3175
+			$this->set_from_db(
3176
+				$field->get_name(),
3177
+				$new_value
3178
+			);
3179
+		}
3180
+		return (bool) $result;
3181
+	}
3182
+
3183
+
3184
+	/**
3185
+	 * Nudges $field_name's value by $quantity, without any conditionals (in comparison to bumpConditionally()).
3186
+	 * Does not allow negative values, however.
3187
+	 *
3188
+	 * @since 4.9.80.p
3189
+	 * @param array $fields_n_quantities keys are the field names, and values are the amount by which to bump them
3190
+	 *                                   (positive or negative). One important gotcha: all these values must be
3191
+	 *                                   on the same table (eg don't pass in one field for the posts table and
3192
+	 *                                   another for the event meta table.)
3193
+	 * @return bool
3194
+	 * @throws EE_Error
3195
+	 * @throws InvalidArgumentException
3196
+	 * @throws InvalidDataTypeException
3197
+	 * @throws InvalidInterfaceException
3198
+	 * @throws ReflectionException
3199
+	 */
3200
+	public function adjustNumericFieldsInDb(array $fields_n_quantities)
3201
+	{
3202
+		global $wpdb;
3203
+		if (empty($fields_n_quantities)) {
3204
+			// No fields to update? Well sure, we updated them to that value just fine.
3205
+			return true;
3206
+		}
3207
+		$fields = [];
3208
+		$set_sql_statements = [];
3209
+		foreach ($fields_n_quantities as $field_name => $quantity) {
3210
+			$field = $this->get_model()->field_settings_for($field_name, true);
3211
+			$fields[] = $field;
3212
+			$column_name = $field->get_table_column();
3213
+
3214
+			$abs_qty = absint($quantity);
3215
+			if ($quantity > 0) {
3216
+				// don't let the value be negative as often these fields are unsigned
3217
+				$set_sql_statements[] = $wpdb->prepare(
3218
+					"`{$column_name}` = `{$column_name}` + %d",
3219
+					$abs_qty
3220
+				);
3221
+			} else {
3222
+				$set_sql_statements[] = $wpdb->prepare(
3223
+					"`{$column_name}` = CASE
3224 3224
                        WHEN (`{$column_name}` >= %d)
3225 3225
                        THEN `{$column_name}` - %d
3226 3226
                        ELSE 0
3227 3227
                     END",
3228
-                    $abs_qty,
3229
-                    $abs_qty
3230
-                );
3231
-            }
3232
-        }
3233
-        return $this->updateFieldsInDB(
3234
-            $fields,
3235
-            implode(', ', $set_sql_statements)
3236
-        );
3237
-    }
3238
-
3239
-
3240
-    /**
3241
-     * Increases the value of the field $field_name_to_bump by $quantity, but only if the values of
3242
-     * $field_name_to_bump plus $field_name_affecting_total and $quantity won't exceed $limit_field_name's value.
3243
-     * For example, this is useful when bumping the value of TKT_reserved, TKT_sold, DTT_reserved or DTT_sold.
3244
-     * Returns true if the value was successfully bumped, and updates the value on this model object.
3245
-     * Otherwise returns false.
3246
-     *
3247
-     * @since 4.9.80.p
3248
-     * @param string $field_name_to_bump
3249
-     * @param string $field_name_affecting_total
3250
-     * @param string $limit_field_name
3251
-     * @param int    $quantity
3252
-     * @return bool
3253
-     * @throws EE_Error
3254
-     * @throws InvalidArgumentException
3255
-     * @throws InvalidDataTypeException
3256
-     * @throws InvalidInterfaceException
3257
-     * @throws ReflectionException
3258
-     */
3259
-    public function incrementFieldConditionallyInDb($field_name_to_bump, $field_name_affecting_total, $limit_field_name, $quantity)
3260
-    {
3261
-        global $wpdb;
3262
-        $field = $this->get_model()->field_settings_for($field_name_to_bump, true);
3263
-        $column_name = $field->get_table_column();
3264
-
3265
-        $field_affecting_total = $this->get_model()->field_settings_for($field_name_affecting_total, true);
3266
-        $column_affecting_total = $field_affecting_total->get_table_column();
3267
-
3268
-        $limiting_field = $this->get_model()->field_settings_for($limit_field_name, true);
3269
-        $limiting_column = $limiting_field->get_table_column();
3270
-        return $this->updateFieldsInDB(
3271
-            [$field],
3272
-            $wpdb->prepare(
3273
-                "`{$column_name}` =
3228
+					$abs_qty,
3229
+					$abs_qty
3230
+				);
3231
+			}
3232
+		}
3233
+		return $this->updateFieldsInDB(
3234
+			$fields,
3235
+			implode(', ', $set_sql_statements)
3236
+		);
3237
+	}
3238
+
3239
+
3240
+	/**
3241
+	 * Increases the value of the field $field_name_to_bump by $quantity, but only if the values of
3242
+	 * $field_name_to_bump plus $field_name_affecting_total and $quantity won't exceed $limit_field_name's value.
3243
+	 * For example, this is useful when bumping the value of TKT_reserved, TKT_sold, DTT_reserved or DTT_sold.
3244
+	 * Returns true if the value was successfully bumped, and updates the value on this model object.
3245
+	 * Otherwise returns false.
3246
+	 *
3247
+	 * @since 4.9.80.p
3248
+	 * @param string $field_name_to_bump
3249
+	 * @param string $field_name_affecting_total
3250
+	 * @param string $limit_field_name
3251
+	 * @param int    $quantity
3252
+	 * @return bool
3253
+	 * @throws EE_Error
3254
+	 * @throws InvalidArgumentException
3255
+	 * @throws InvalidDataTypeException
3256
+	 * @throws InvalidInterfaceException
3257
+	 * @throws ReflectionException
3258
+	 */
3259
+	public function incrementFieldConditionallyInDb($field_name_to_bump, $field_name_affecting_total, $limit_field_name, $quantity)
3260
+	{
3261
+		global $wpdb;
3262
+		$field = $this->get_model()->field_settings_for($field_name_to_bump, true);
3263
+		$column_name = $field->get_table_column();
3264
+
3265
+		$field_affecting_total = $this->get_model()->field_settings_for($field_name_affecting_total, true);
3266
+		$column_affecting_total = $field_affecting_total->get_table_column();
3267
+
3268
+		$limiting_field = $this->get_model()->field_settings_for($limit_field_name, true);
3269
+		$limiting_column = $limiting_field->get_table_column();
3270
+		return $this->updateFieldsInDB(
3271
+			[$field],
3272
+			$wpdb->prepare(
3273
+				"`{$column_name}` =
3274 3274
             CASE
3275 3275
                WHEN ((`{$column_name}` + `{$column_affecting_total}` + %d) <= `{$limiting_column}`) OR `{$limiting_column}` = %d
3276 3276
                THEN `{$column_name}` + %d
3277 3277
                ELSE `{$column_name}`
3278 3278
             END",
3279
-                $quantity,
3280
-                EE_INF_IN_DB,
3281
-                $quantity
3282
-            )
3283
-        );
3284
-    }
3285
-
3286
-
3287
-    /**
3288
-     * Because some other plugins, like Advanced Cron Manager, expect all objects to have this method
3289
-     * (probably a bad assumption they have made, oh well)
3290
-     *
3291
-     * @return string
3292
-     */
3293
-    public function __toString()
3294
-    {
3295
-        try {
3296
-            return sprintf('%s (%s)', $this->name(), $this->ID());
3297
-        } catch (Exception $e) {
3298
-            EE_Error::add_error($e->getMessage(), __FILE__, __FUNCTION__, __LINE__);
3299
-            return '';
3300
-        }
3301
-    }
3302
-
3303
-
3304
-    /**
3305
-     * Clear related model objects if they're already in the DB, because otherwise when we
3306
-     * UN-serialize this model object we'll need to be careful to add them to the entity map.
3307
-     * This means if we have made changes to those related model objects, and want to unserialize
3308
-     * the this model object on a subsequent request, changes to those related model objects will be lost.
3309
-     * Instead, those related model objects should be directly serialized and stored.
3310
-     * Eg, the following won't work:
3311
-     * $reg = EEM_Registration::instance()->get_one_by_ID( 123 );
3312
-     * $att = $reg->attendee();
3313
-     * $att->set( 'ATT_fname', 'Dirk' );
3314
-     * update_option( 'my_option', serialize( $reg ) );
3315
-     * //END REQUEST
3316
-     * //START NEXT REQUEST
3317
-     * $reg = get_option( 'my_option' );
3318
-     * $reg->attendee()->save();
3319
-     * And would need to be replace with:
3320
-     * $reg = EEM_Registration::instance()->get_one_by_ID( 123 );
3321
-     * $att = $reg->attendee();
3322
-     * $att->set( 'ATT_fname', 'Dirk' );
3323
-     * update_option( 'my_option', serialize( $reg ) );
3324
-     * //END REQUEST
3325
-     * //START NEXT REQUEST
3326
-     * $att = get_option( 'my_option' );
3327
-     * $att->save();
3328
-     *
3329
-     * @return array
3330
-     * @throws ReflectionException
3331
-     * @throws InvalidArgumentException
3332
-     * @throws InvalidInterfaceException
3333
-     * @throws InvalidDataTypeException
3334
-     * @throws EE_Error
3335
-     */
3336
-    public function __sleep()
3337
-    {
3338
-        $model = $this->get_model();
3339
-        foreach ($model->relation_settings() as $relation_name => $relation_obj) {
3340
-            if ($relation_obj instanceof EE_Belongs_To_Relation) {
3341
-                $classname = 'EE_' . $model->get_this_model_name();
3342
-                if (
3343
-                    $this->get_one_from_cache($relation_name) instanceof $classname
3344
-                    && $this->get_one_from_cache($relation_name)->ID()
3345
-                ) {
3346
-                    $this->clear_cache(
3347
-                        $relation_name,
3348
-                        $this->get_one_from_cache($relation_name)->ID()
3349
-                    );
3350
-                }
3351
-            }
3352
-        }
3353
-        $this->_props_n_values_provided_in_constructor = array();
3354
-        $properties_to_serialize = get_object_vars($this);
3355
-        // don't serialize the model. It's big and that risks recursion
3356
-        unset($properties_to_serialize['_model']);
3357
-        return array_keys($properties_to_serialize);
3358
-    }
3359
-
3360
-
3361
-    /**
3362
-     * restore _props_n_values_provided_in_constructor
3363
-     * PLZ NOTE: this will reset the array to whatever fields values were present prior to serialization,
3364
-     * and therefore should NOT be used to determine if state change has occurred since initial construction.
3365
-     * At best, you would only be able to detect if state change has occurred during THIS request.
3366
-     */
3367
-    public function __wakeup()
3368
-    {
3369
-        $this->_props_n_values_provided_in_constructor = $this->_fields;
3370
-    }
3371
-
3372
-
3373
-    /**
3374
-     * Usage of this magic method is to ensure any internally cached references to object instances that must remain
3375
-     * distinct with the clone host instance are also cloned.
3376
-     */
3377
-    public function __clone()
3378
-    {
3379
-        // handle DateTimes (this is handled in here because there's no one specific child class that uses datetimes).
3380
-        foreach ($this->_fields as $field => $value) {
3381
-            if ($value instanceof DateTime) {
3382
-                $this->_fields[ $field ] = clone $value;
3383
-            }
3384
-        }
3385
-    }
3279
+				$quantity,
3280
+				EE_INF_IN_DB,
3281
+				$quantity
3282
+			)
3283
+		);
3284
+	}
3285
+
3286
+
3287
+	/**
3288
+	 * Because some other plugins, like Advanced Cron Manager, expect all objects to have this method
3289
+	 * (probably a bad assumption they have made, oh well)
3290
+	 *
3291
+	 * @return string
3292
+	 */
3293
+	public function __toString()
3294
+	{
3295
+		try {
3296
+			return sprintf('%s (%s)', $this->name(), $this->ID());
3297
+		} catch (Exception $e) {
3298
+			EE_Error::add_error($e->getMessage(), __FILE__, __FUNCTION__, __LINE__);
3299
+			return '';
3300
+		}
3301
+	}
3302
+
3303
+
3304
+	/**
3305
+	 * Clear related model objects if they're already in the DB, because otherwise when we
3306
+	 * UN-serialize this model object we'll need to be careful to add them to the entity map.
3307
+	 * This means if we have made changes to those related model objects, and want to unserialize
3308
+	 * the this model object on a subsequent request, changes to those related model objects will be lost.
3309
+	 * Instead, those related model objects should be directly serialized and stored.
3310
+	 * Eg, the following won't work:
3311
+	 * $reg = EEM_Registration::instance()->get_one_by_ID( 123 );
3312
+	 * $att = $reg->attendee();
3313
+	 * $att->set( 'ATT_fname', 'Dirk' );
3314
+	 * update_option( 'my_option', serialize( $reg ) );
3315
+	 * //END REQUEST
3316
+	 * //START NEXT REQUEST
3317
+	 * $reg = get_option( 'my_option' );
3318
+	 * $reg->attendee()->save();
3319
+	 * And would need to be replace with:
3320
+	 * $reg = EEM_Registration::instance()->get_one_by_ID( 123 );
3321
+	 * $att = $reg->attendee();
3322
+	 * $att->set( 'ATT_fname', 'Dirk' );
3323
+	 * update_option( 'my_option', serialize( $reg ) );
3324
+	 * //END REQUEST
3325
+	 * //START NEXT REQUEST
3326
+	 * $att = get_option( 'my_option' );
3327
+	 * $att->save();
3328
+	 *
3329
+	 * @return array
3330
+	 * @throws ReflectionException
3331
+	 * @throws InvalidArgumentException
3332
+	 * @throws InvalidInterfaceException
3333
+	 * @throws InvalidDataTypeException
3334
+	 * @throws EE_Error
3335
+	 */
3336
+	public function __sleep()
3337
+	{
3338
+		$model = $this->get_model();
3339
+		foreach ($model->relation_settings() as $relation_name => $relation_obj) {
3340
+			if ($relation_obj instanceof EE_Belongs_To_Relation) {
3341
+				$classname = 'EE_' . $model->get_this_model_name();
3342
+				if (
3343
+					$this->get_one_from_cache($relation_name) instanceof $classname
3344
+					&& $this->get_one_from_cache($relation_name)->ID()
3345
+				) {
3346
+					$this->clear_cache(
3347
+						$relation_name,
3348
+						$this->get_one_from_cache($relation_name)->ID()
3349
+					);
3350
+				}
3351
+			}
3352
+		}
3353
+		$this->_props_n_values_provided_in_constructor = array();
3354
+		$properties_to_serialize = get_object_vars($this);
3355
+		// don't serialize the model. It's big and that risks recursion
3356
+		unset($properties_to_serialize['_model']);
3357
+		return array_keys($properties_to_serialize);
3358
+	}
3359
+
3360
+
3361
+	/**
3362
+	 * restore _props_n_values_provided_in_constructor
3363
+	 * PLZ NOTE: this will reset the array to whatever fields values were present prior to serialization,
3364
+	 * and therefore should NOT be used to determine if state change has occurred since initial construction.
3365
+	 * At best, you would only be able to detect if state change has occurred during THIS request.
3366
+	 */
3367
+	public function __wakeup()
3368
+	{
3369
+		$this->_props_n_values_provided_in_constructor = $this->_fields;
3370
+	}
3371
+
3372
+
3373
+	/**
3374
+	 * Usage of this magic method is to ensure any internally cached references to object instances that must remain
3375
+	 * distinct with the clone host instance are also cloned.
3376
+	 */
3377
+	public function __clone()
3378
+	{
3379
+		// handle DateTimes (this is handled in here because there's no one specific child class that uses datetimes).
3380
+		foreach ($this->_fields as $field => $value) {
3381
+			if ($value instanceof DateTime) {
3382
+				$this->_fields[ $field ] = clone $value;
3383
+			}
3384
+		}
3385
+	}
3386 3386
 }
Please login to merge, or discard this patch.