Completed
Branch dependabot/npm_and_yarn/wordpr... (e552b3)
by
unknown
84:27 queued 76:28
created
core/domain/values/assets/ManifestFile.php 1 patch
Indentation   +22 added lines, -22 removed lines patch added patch discarded remove patch
@@ -16,26 +16,26 @@
 block discarded – undo
16 16
 class ManifestFile extends Asset
17 17
 {
18 18
 
19
-    /**
20
-     * Asset constructor.
21
-     *
22
-     * @param DomainInterface $domain
23
-     * @throws InvalidDataTypeException
24
-     */
25
-    public function __construct(DomainInterface $domain)
26
-    {
27
-        parent::__construct(Asset::TYPE_MANIFEST, $domain->assetNamespace(), $domain);
28
-    }
29
-
30
-
31
-    public function urlBase()
32
-    {
33
-        return $this->domain->distributionAssetsUrl();
34
-    }
35
-
36
-
37
-    public function filepath()
38
-    {
39
-        return $this->domain->distributionAssetsPath();
40
-    }
19
+	/**
20
+	 * Asset constructor.
21
+	 *
22
+	 * @param DomainInterface $domain
23
+	 * @throws InvalidDataTypeException
24
+	 */
25
+	public function __construct(DomainInterface $domain)
26
+	{
27
+		parent::__construct(Asset::TYPE_MANIFEST, $domain->assetNamespace(), $domain);
28
+	}
29
+
30
+
31
+	public function urlBase()
32
+	{
33
+		return $this->domain->distributionAssetsUrl();
34
+	}
35
+
36
+
37
+	public function filepath()
38
+	{
39
+		return $this->domain->distributionAssetsPath();
40
+	}
41 41
 }
Please login to merge, or discard this patch.
core/domain/values/assets/Asset.php 2 patches
Spacing   +2 added lines, -2 removed lines patch added patch discarded remove patch
@@ -82,7 +82,7 @@  discard block
 block discarded – undo
82 82
      */
83 83
     private function setType($type)
84 84
     {
85
-        if (! in_array($type, $this->validAssetTypes(), true)) {
85
+        if ( ! in_array($type, $this->validAssetTypes(), true)) {
86 86
             throw new InvalidDataTypeException(
87 87
                 'Asset::$type',
88 88
                 $type,
@@ -99,7 +99,7 @@  discard block
 block discarded – undo
99 99
      */
100 100
     private function setHandle($handle)
101 101
     {
102
-        if (! is_string($handle)) {
102
+        if ( ! is_string($handle)) {
103 103
             throw new InvalidDataTypeException(
104 104
                 '$handle',
105 105
                 $handle,
Please login to merge, or discard this patch.
Indentation   +160 added lines, -160 removed lines patch added patch discarded remove patch
@@ -16,164 +16,164 @@
 block discarded – undo
16 16
 abstract class Asset
17 17
 {
18 18
 
19
-    /**
20
-     * indicates the file extension for a build distribution CSS file
21
-     */
22
-    const FILE_EXTENSION_DISTRIBUTION_CSS = '.dist.css';
23
-
24
-    /**
25
-     * indicates the file extension for a build distribution JS file
26
-     */
27
-    const FILE_EXTENSION_DISTRIBUTION_JS = '.dist.js';
28
-
29
-    /**
30
-     * Indicates the file extension for a build distribution dependencies json file.
31
-     */
32
-    const FILE_EXTENSION_DISTRIBUTION_DEPS = '.dist.deps.json';
33
-
34
-    /**
35
-     * indicates a Cascading Style Sheet asset
36
-     */
37
-    const TYPE_CSS = 'css';
38
-
39
-    /**
40
-     * indicates a Javascript asset
41
-     */
42
-    const TYPE_JS = 'js';
43
-
44
-    /**
45
-     * indicates a JSON asset
46
-     */
47
-    CONST TYPE_JSON = 'json';
48
-
49
-    /**
50
-     * indicates a Javascript manifest file
51
-     */
52
-    const TYPE_MANIFEST = 'manifest';
53
-
54
-    /**
55
-     * @var DomainInterface $domain
56
-     */
57
-    protected $domain;
58
-
59
-    /**
60
-     * @var string $type
61
-     */
62
-    private $type;
63
-
64
-    /**
65
-     * @var string $handle
66
-     */
67
-    private $handle;
68
-
69
-    /**
70
-     * @var bool $registered
71
-     */
72
-    private $registered = false;
73
-
74
-
75
-    /**
76
-     * Asset constructor.
77
-     *
78
-     * @param                 $type
79
-     * @param string          $handle
80
-     * @param DomainInterface $domain
81
-     * @throws InvalidDataTypeException
82
-     */
83
-    public function __construct($type, $handle, DomainInterface $domain)
84
-    {
85
-        $this->domain = $domain;
86
-        $this->setType($type);
87
-        $this->setHandle($handle);
88
-    }
89
-
90
-
91
-    /**
92
-     * @return array
93
-     */
94
-    public function validAssetTypes()
95
-    {
96
-        return array(
97
-            Asset::TYPE_CSS,
98
-            Asset::TYPE_JS,
99
-            Asset::TYPE_MANIFEST,
100
-        );
101
-    }
102
-
103
-
104
-    /**
105
-     * @param string $type
106
-     * @throws InvalidDataTypeException
107
-     */
108
-    private function setType($type)
109
-    {
110
-        if (! in_array($type, $this->validAssetTypes(), true)) {
111
-            throw new InvalidDataTypeException(
112
-                'Asset::$type',
113
-                $type,
114
-                'one of the TYPE_* class constants on \EventEspresso\core\domain\values\Asset is required'
115
-            );
116
-        }
117
-        $this->type = $type;
118
-    }
119
-
120
-
121
-    /**
122
-     * @param string $handle
123
-     * @throws InvalidDataTypeException
124
-     */
125
-    private function setHandle($handle)
126
-    {
127
-        if (! is_string($handle)) {
128
-            throw new InvalidDataTypeException(
129
-                '$handle',
130
-                $handle,
131
-                'string'
132
-            );
133
-        }
134
-        $this->handle = $handle;
135
-    }
136
-
137
-
138
-    /**
139
-     * @return string
140
-     */
141
-    public function assetNamespace()
142
-    {
143
-        return $this->domain->assetNamespace();
144
-    }
145
-
146
-
147
-    /**
148
-     * @return string
149
-     */
150
-    public function type()
151
-    {
152
-        return $this->type;
153
-    }
154
-
155
-
156
-    /**
157
-     * @return string
158
-     */
159
-    public function handle()
160
-    {
161
-        return $this->handle;
162
-    }
163
-
164
-    /**
165
-     * @return bool
166
-     */
167
-    public function isRegistered()
168
-    {
169
-        return $this->registered;
170
-    }
171
-
172
-    /**
173
-     * @param bool $registered
174
-     */
175
-    public function setRegistered($registered = true)
176
-    {
177
-        $this->registered = filter_var($registered, FILTER_VALIDATE_BOOLEAN);
178
-    }
19
+	/**
20
+	 * indicates the file extension for a build distribution CSS file
21
+	 */
22
+	const FILE_EXTENSION_DISTRIBUTION_CSS = '.dist.css';
23
+
24
+	/**
25
+	 * indicates the file extension for a build distribution JS file
26
+	 */
27
+	const FILE_EXTENSION_DISTRIBUTION_JS = '.dist.js';
28
+
29
+	/**
30
+	 * Indicates the file extension for a build distribution dependencies json file.
31
+	 */
32
+	const FILE_EXTENSION_DISTRIBUTION_DEPS = '.dist.deps.json';
33
+
34
+	/**
35
+	 * indicates a Cascading Style Sheet asset
36
+	 */
37
+	const TYPE_CSS = 'css';
38
+
39
+	/**
40
+	 * indicates a Javascript asset
41
+	 */
42
+	const TYPE_JS = 'js';
43
+
44
+	/**
45
+	 * indicates a JSON asset
46
+	 */
47
+	CONST TYPE_JSON = 'json';
48
+
49
+	/**
50
+	 * indicates a Javascript manifest file
51
+	 */
52
+	const TYPE_MANIFEST = 'manifest';
53
+
54
+	/**
55
+	 * @var DomainInterface $domain
56
+	 */
57
+	protected $domain;
58
+
59
+	/**
60
+	 * @var string $type
61
+	 */
62
+	private $type;
63
+
64
+	/**
65
+	 * @var string $handle
66
+	 */
67
+	private $handle;
68
+
69
+	/**
70
+	 * @var bool $registered
71
+	 */
72
+	private $registered = false;
73
+
74
+
75
+	/**
76
+	 * Asset constructor.
77
+	 *
78
+	 * @param                 $type
79
+	 * @param string          $handle
80
+	 * @param DomainInterface $domain
81
+	 * @throws InvalidDataTypeException
82
+	 */
83
+	public function __construct($type, $handle, DomainInterface $domain)
84
+	{
85
+		$this->domain = $domain;
86
+		$this->setType($type);
87
+		$this->setHandle($handle);
88
+	}
89
+
90
+
91
+	/**
92
+	 * @return array
93
+	 */
94
+	public function validAssetTypes()
95
+	{
96
+		return array(
97
+			Asset::TYPE_CSS,
98
+			Asset::TYPE_JS,
99
+			Asset::TYPE_MANIFEST,
100
+		);
101
+	}
102
+
103
+
104
+	/**
105
+	 * @param string $type
106
+	 * @throws InvalidDataTypeException
107
+	 */
108
+	private function setType($type)
109
+	{
110
+		if (! in_array($type, $this->validAssetTypes(), true)) {
111
+			throw new InvalidDataTypeException(
112
+				'Asset::$type',
113
+				$type,
114
+				'one of the TYPE_* class constants on \EventEspresso\core\domain\values\Asset is required'
115
+			);
116
+		}
117
+		$this->type = $type;
118
+	}
119
+
120
+
121
+	/**
122
+	 * @param string $handle
123
+	 * @throws InvalidDataTypeException
124
+	 */
125
+	private function setHandle($handle)
126
+	{
127
+		if (! is_string($handle)) {
128
+			throw new InvalidDataTypeException(
129
+				'$handle',
130
+				$handle,
131
+				'string'
132
+			);
133
+		}
134
+		$this->handle = $handle;
135
+	}
136
+
137
+
138
+	/**
139
+	 * @return string
140
+	 */
141
+	public function assetNamespace()
142
+	{
143
+		return $this->domain->assetNamespace();
144
+	}
145
+
146
+
147
+	/**
148
+	 * @return string
149
+	 */
150
+	public function type()
151
+	{
152
+		return $this->type;
153
+	}
154
+
155
+
156
+	/**
157
+	 * @return string
158
+	 */
159
+	public function handle()
160
+	{
161
+		return $this->handle;
162
+	}
163
+
164
+	/**
165
+	 * @return bool
166
+	 */
167
+	public function isRegistered()
168
+	{
169
+		return $this->registered;
170
+	}
171
+
172
+	/**
173
+	 * @param bool $registered
174
+	 */
175
+	public function setRegistered($registered = true)
176
+	{
177
+		$this->registered = filter_var($registered, FILTER_VALIDATE_BOOLEAN);
178
+	}
179 179
 }
Please login to merge, or discard this patch.
core/domain/values/assets/StylesheetAsset.php 2 patches
Spacing   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -54,7 +54,7 @@
 block discarded – undo
54 54
      */
55 55
     private function setMedia($media)
56 56
     {
57
-        if (! is_string($media)) {
57
+        if ( ! is_string($media)) {
58 58
             throw new InvalidDataTypeException(
59 59
                 '$media',
60 60
                 $media,
Please login to merge, or discard this patch.
Indentation   +48 added lines, -48 removed lines patch added patch discarded remove patch
@@ -16,60 +16,60 @@
 block discarded – undo
16 16
 class StylesheetAsset extends BrowserAsset
17 17
 {
18 18
 
19
-    /**
20
-     * @var string $media
21
-     */
22
-    private $media;
19
+	/**
20
+	 * @var string $media
21
+	 */
22
+	private $media;
23 23
 
24 24
 
25
-    /**
26
-     * CssFile constructor.
27
-     *
28
-     * @param                 $handle
29
-     * @param string          $source
30
-     * @param array           $dependencies
31
-     * @param DomainInterface $domain
32
-     * @param                 $media
33
-     * @throws InvalidDataTypeException
34
-     */
35
-    public function __construct($handle, $source, array $dependencies, DomainInterface $domain, $media = 'all')
36
-    {
37
-        parent::__construct(Asset::TYPE_CSS, $handle, $source, $dependencies, $domain);
38
-        $this->setMedia($media);
39
-    }
25
+	/**
26
+	 * CssFile constructor.
27
+	 *
28
+	 * @param                 $handle
29
+	 * @param string          $source
30
+	 * @param array           $dependencies
31
+	 * @param DomainInterface $domain
32
+	 * @param                 $media
33
+	 * @throws InvalidDataTypeException
34
+	 */
35
+	public function __construct($handle, $source, array $dependencies, DomainInterface $domain, $media = 'all')
36
+	{
37
+		parent::__construct(Asset::TYPE_CSS, $handle, $source, $dependencies, $domain);
38
+		$this->setMedia($media);
39
+	}
40 40
 
41 41
 
42
-    /**
43
-     * @return string
44
-     */
45
-    public function media()
46
-    {
47
-        return $this->media;
48
-    }
42
+	/**
43
+	 * @return string
44
+	 */
45
+	public function media()
46
+	{
47
+		return $this->media;
48
+	}
49 49
 
50 50
 
51
-    /**
52
-     * @param string $media
53
-     * @throws InvalidDataTypeException
54
-     */
55
-    private function setMedia($media)
56
-    {
57
-        if (! is_string($media)) {
58
-            throw new InvalidDataTypeException(
59
-                '$media',
60
-                $media,
61
-                'string'
62
-            );
63
-        }
64
-        $this->media = $media;
65
-    }
51
+	/**
52
+	 * @param string $media
53
+	 * @throws InvalidDataTypeException
54
+	 */
55
+	private function setMedia($media)
56
+	{
57
+		if (! is_string($media)) {
58
+			throw new InvalidDataTypeException(
59
+				'$media',
60
+				$media,
61
+				'string'
62
+			);
63
+		}
64
+		$this->media = $media;
65
+	}
66 66
 
67 67
 
68
-    /**
69
-     * @since 4.9.62.p
70
-     */
71
-    public function enqueueAsset()
72
-    {
73
-        wp_enqueue_style($this->handle());
74
-    }
68
+	/**
69
+	 * @since 4.9.62.p
70
+	 */
71
+	public function enqueueAsset()
72
+	{
73
+		wp_enqueue_style($this->handle());
74
+	}
75 75
 }
Please login to merge, or discard this patch.
core/db_classes/EE_Base_Class.class.php 3 patches
Doc Comments   +7 added lines, -7 removed lines patch added patch discarded remove patch
@@ -712,7 +712,7 @@  discard block
 block discarded – undo
712 712
      *
713 713
      * @param \EE_Datetime_Field $datetime_field
714 714
      * @param bool               $pretty
715
-     * @param null               $date_or_time
715
+     * @param string|null               $date_or_time
716 716
      * @return void
717 717
      * @throws InvalidArgumentException
718 718
      * @throws InvalidInterfaceException
@@ -1066,7 +1066,7 @@  discard block
 block discarded – undo
1066 1066
      *
1067 1067
      * @param null  $field_to_order_by  What field is being used as the reference point.
1068 1068
      * @param array $query_params       Any additional conditions on the query.
1069
-     * @param null  $columns_to_select  If left null, then an array of EE_Base_Class objects is returned, otherwise
1069
+     * @param string  $columns_to_select  If left null, then an array of EE_Base_Class objects is returned, otherwise
1070 1070
      *                                  you can indicate just the columns you want returned
1071 1071
      * @return array|EE_Base_Class
1072 1072
      * @throws ReflectionException
@@ -1095,7 +1095,7 @@  discard block
 block discarded – undo
1095 1095
      *
1096 1096
      * @param null  $field_to_order_by  What field is being used as the reference point.
1097 1097
      * @param array $query_params       Any additional conditions on the query.
1098
-     * @param null  $columns_to_select  If left null, then an EE_Base_Class object is returned, otherwise
1098
+     * @param string  $columns_to_select  If left null, then an EE_Base_Class object is returned, otherwise
1099 1099
      *                                  you can indicate just the column you want returned
1100 1100
      * @return array|EE_Base_Class
1101 1101
      * @throws ReflectionException
@@ -1527,7 +1527,7 @@  discard block
 block discarded – undo
1527 1527
      * sets the time on a datetime property
1528 1528
      *
1529 1529
      * @access protected
1530
-     * @param string|Datetime $time      a valid time string for php datetime functions (or DateTime object)
1530
+     * @param string $time      a valid time string for php datetime functions (or DateTime object)
1531 1531
      * @param string          $fieldname the name of the field the time is being set on (must match a EE_Datetime_Field)
1532 1532
      * @throws ReflectionException
1533 1533
      * @throws InvalidArgumentException
@@ -1545,7 +1545,7 @@  discard block
 block discarded – undo
1545 1545
      * sets the date on a datetime property
1546 1546
      *
1547 1547
      * @access protected
1548
-     * @param string|DateTime $date      a valid date string for php datetime functions ( or DateTime object)
1548
+     * @param string $date      a valid date string for php datetime functions ( or DateTime object)
1549 1549
      * @param string          $fieldname the name of the field the date is being set on (must match a EE_Datetime_Field)
1550 1550
      * @throws ReflectionException
1551 1551
      * @throws InvalidArgumentException
@@ -2067,7 +2067,7 @@  discard block
 block discarded – undo
2067 2067
      *
2068 2068
      * @param  array  $props_n_values   incoming array of properties and their values
2069 2069
      * @param  string $classname        the classname of the child class
2070
-     * @param null    $timezone
2070
+     * @param string|null    $timezone
2071 2071
      * @param array   $date_formats     incoming date_formats in an array where the first value is the
2072 2072
      *                                  date_format and the second value is the time format
2073 2073
      * @return mixed (EE_Base_Class|bool)
@@ -2154,7 +2154,7 @@  discard block
 block discarded – undo
2154 2154
      * Gets the model instance (eg instance of EEM_Attendee) given its classname (eg EE_Attendee)
2155 2155
      *
2156 2156
      * @param string $model_classname
2157
-     * @param null   $timezone
2157
+     * @param string|null   $timezone
2158 2158
      * @return EEM_Base
2159 2159
      * @throws ReflectionException
2160 2160
      * @throws InvalidArgumentException
Please login to merge, or discard this patch.
Indentation   +3333 added lines, -3333 removed lines patch added patch discarded remove patch
@@ -13,3348 +13,3348 @@
 block discarded – undo
13 13
 abstract class EE_Base_Class
14 14
 {
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
-            list($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 (isset($this->_props_n_values_provided_in_constructor[ $field_name ])
254
-            && $field_settings = $this->get_model()->field_settings_for($field_name)
255
-        ) {
256
-            return $field_settings->prepare_for_get($this->_props_n_values_provided_in_constructor[ $field_name ]);
257
-        }
258
-        return null;
259
-    }
260
-
261
-
262
-    /**
263
-     * @param EE_Base_Class $obj
264
-     * @return string
265
-     */
266
-    public function get_class($obj)
267
-    {
268
-        return get_class($obj);
269
-    }
270
-
271
-
272
-    /**
273
-     * Overrides parent because parent expects old models.
274
-     * This also doesn't do any validation, and won't work for serialized arrays
275
-     *
276
-     * @param    string $field_name
277
-     * @param    mixed  $field_value
278
-     * @param bool      $use_default
279
-     * @throws InvalidArgumentException
280
-     * @throws InvalidInterfaceException
281
-     * @throws InvalidDataTypeException
282
-     * @throws EE_Error
283
-     * @throws ReflectionException
284
-     * @throws ReflectionException
285
-     * @throws ReflectionException
286
-     */
287
-    public function set($field_name, $field_value, $use_default = false)
288
-    {
289
-        // if not using default and nothing has changed, and object has already been setup (has ID),
290
-        // then don't do anything
291
-        if (! $use_default
292
-            && $this->_fields[ $field_name ] === $field_value
293
-            && $this->ID()
294
-        ) {
295
-            return;
296
-        }
297
-        $model = $this->get_model();
298
-        $this->_has_changes = true;
299
-        $field_obj = $model->field_settings_for($field_name);
300
-        if ($field_obj instanceof EE_Model_Field_Base) {
301
-            // if ( method_exists( $field_obj, 'set_timezone' )) {
302
-            if ($field_obj instanceof EE_Datetime_Field) {
303
-                $field_obj->set_timezone($this->_timezone);
304
-                $field_obj->set_date_format($this->_dt_frmt);
305
-                $field_obj->set_time_format($this->_tm_frmt);
306
-            }
307
-            $holder_of_value = $field_obj->prepare_for_set($field_value);
308
-            // should the value be null?
309
-            if (($field_value === null || $holder_of_value === null || $holder_of_value === '') && $use_default) {
310
-                $this->_fields[ $field_name ] = $field_obj->get_default_value();
311
-                /**
312
-                 * To save having to refactor all the models, if a default value is used for a
313
-                 * EE_Datetime_Field, and that value is not null nor is it a DateTime
314
-                 * object.  Then let's do a set again to ensure that it becomes a DateTime
315
-                 * object.
316
-                 *
317
-                 * @since 4.6.10+
318
-                 */
319
-                if ($field_obj instanceof EE_Datetime_Field
320
-                    && $this->_fields[ $field_name ] !== null
321
-                    && ! $this->_fields[ $field_name ] instanceof DateTime
322
-                ) {
323
-                    empty($this->_fields[ $field_name ])
324
-                        ? $this->set($field_name, time())
325
-                        : $this->set($field_name, $this->_fields[ $field_name ]);
326
-                }
327
-            } else {
328
-                $this->_fields[ $field_name ] = $holder_of_value;
329
-            }
330
-            // if we're not in the constructor...
331
-            // now check if what we set was a primary key
332
-            if (// note: props_n_values_provided_in_constructor is only set at the END of the constructor
333
-                $this->_props_n_values_provided_in_constructor
334
-                && $field_value
335
-                && $field_name === $model->primary_key_name()
336
-            ) {
337
-                // if so, we want all this object's fields to be filled either with
338
-                // what we've explicitly set on this model
339
-                // or what we have in the db
340
-                // echo "setting primary key!";
341
-                $fields_on_model = self::_get_model(get_class($this))->field_settings();
342
-                $obj_in_db = self::_get_model(get_class($this))->get_one_by_ID($field_value);
343
-                foreach ($fields_on_model as $field_obj) {
344
-                    if (! array_key_exists($field_obj->get_name(), $this->_props_n_values_provided_in_constructor)
345
-                        && $field_obj->get_name() !== $field_name
346
-                    ) {
347
-                        $this->set($field_obj->get_name(), $obj_in_db->get($field_obj->get_name()));
348
-                    }
349
-                }
350
-                // oh this model object has an ID? well make sure its in the entity mapper
351
-                $model->add_to_entity_map($this);
352
-            }
353
-            // let's unset any cache for this field_name from the $_cached_properties property.
354
-            $this->_clear_cached_property($field_name);
355
-        } else {
356
-            throw new EE_Error(
357
-                sprintf(
358
-                    esc_html__(
359
-                        'A valid EE_Model_Field_Base could not be found for the given field name: %s',
360
-                        'event_espresso'
361
-                    ),
362
-                    $field_name
363
-                )
364
-            );
365
-        }
366
-    }
367
-
368
-
369
-    /**
370
-     * Set custom select values for model.
371
-     *
372
-     * @param array $custom_select_values
373
-     */
374
-    public function setCustomSelectsValues(array $custom_select_values)
375
-    {
376
-        $this->custom_selection_results = $custom_select_values;
377
-    }
378
-
379
-
380
-    /**
381
-     * Returns the custom select value for the provided alias if its set.
382
-     * If not set, returns null.
383
-     *
384
-     * @param string $alias
385
-     * @return string|int|float|null
386
-     */
387
-    public function getCustomSelect($alias)
388
-    {
389
-        return isset($this->custom_selection_results[ $alias ])
390
-            ? $this->custom_selection_results[ $alias ]
391
-            : null;
392
-    }
393
-
394
-
395
-    /**
396
-     * This sets the field value on the db column if it exists for the given $column_name or
397
-     * saves it to EE_Extra_Meta if the given $column_name does not match a db column.
398
-     *
399
-     * @see EE_message::get_column_value for related documentation on the necessity of this method.
400
-     * @param string $field_name  Must be the exact column name.
401
-     * @param mixed  $field_value The value to set.
402
-     * @return int|bool @see EE_Base_Class::update_extra_meta() for return docs.
403
-     * @throws InvalidArgumentException
404
-     * @throws InvalidInterfaceException
405
-     * @throws InvalidDataTypeException
406
-     * @throws EE_Error
407
-     * @throws ReflectionException
408
-     */
409
-    public function set_field_or_extra_meta($field_name, $field_value)
410
-    {
411
-        if ($this->get_model()->has_field($field_name)) {
412
-            $this->set($field_name, $field_value);
413
-            return true;
414
-        }
415
-        // ensure this object is saved first so that extra meta can be properly related.
416
-        $this->save();
417
-        return $this->update_extra_meta($field_name, $field_value);
418
-    }
419
-
420
-
421
-    /**
422
-     * This retrieves the value of the db column set on this class or if that's not present
423
-     * it will attempt to retrieve from extra_meta if found.
424
-     * Example Usage:
425
-     * Via EE_Message child class:
426
-     * Due to the dynamic nature of the EE_messages system, EE_messengers will always have a "to",
427
-     * "from", "subject", and "content" field (as represented in the EE_Message schema), however they may
428
-     * also have additional main fields specific to the messenger.  The system accommodates those extra
429
-     * fields through the EE_Extra_Meta table.  This method allows for EE_messengers to retrieve the
430
-     * value for those extra fields dynamically via the EE_message object.
431
-     *
432
-     * @param  string $field_name expecting the fully qualified field name.
433
-     * @return mixed|null  value for the field if found.  null if not found.
434
-     * @throws ReflectionException
435
-     * @throws InvalidArgumentException
436
-     * @throws InvalidInterfaceException
437
-     * @throws InvalidDataTypeException
438
-     * @throws EE_Error
439
-     */
440
-    public function get_field_or_extra_meta($field_name)
441
-    {
442
-        if ($this->get_model()->has_field($field_name)) {
443
-            $column_value = $this->get($field_name);
444
-        } else {
445
-            // This isn't a column in the main table, let's see if it is in the extra meta.
446
-            $column_value = $this->get_extra_meta($field_name, true, null);
447
-        }
448
-        return $column_value;
449
-    }
450
-
451
-
452
-    /**
453
-     * See $_timezone property for description of what the timezone property is for.  This SETS the timezone internally
454
-     * for being able to reference what timezone we are running conversions on when converting TO the internal timezone
455
-     * (UTC Unix Timestamp) for the object OR when converting FROM the internal timezone (UTC Unix Timestamp). This is
456
-     * available to all child classes that may be using the EE_Datetime_Field for a field data type.
457
-     *
458
-     * @access public
459
-     * @param string $timezone A valid timezone string as described by @link http://www.php.net/manual/en/timezones.php
460
-     * @return void
461
-     * @throws InvalidArgumentException
462
-     * @throws InvalidInterfaceException
463
-     * @throws InvalidDataTypeException
464
-     * @throws EE_Error
465
-     * @throws ReflectionException
466
-     */
467
-    public function set_timezone($timezone = '')
468
-    {
469
-        $this->_timezone = EEH_DTT_Helper::get_valid_timezone_string($timezone);
470
-        // make sure we clear all cached properties because they won't be relevant now
471
-        $this->_clear_cached_properties();
472
-        // make sure we update field settings and the date for all EE_Datetime_Fields
473
-        $model_fields = $this->get_model()->field_settings(false);
474
-        foreach ($model_fields as $field_name => $field_obj) {
475
-            if ($field_obj instanceof EE_Datetime_Field) {
476
-                $field_obj->set_timezone($this->_timezone);
477
-                if (isset($this->_fields[ $field_name ]) && $this->_fields[ $field_name ] instanceof DateTime) {
478
-                    EEH_DTT_Helper::setTimezone($this->_fields[ $field_name ], new DateTimeZone($this->_timezone));
479
-                }
480
-            }
481
-        }
482
-    }
483
-
484
-
485
-    /**
486
-     * This just returns whatever is set for the current timezone.
487
-     *
488
-     * @access public
489
-     * @return string timezone string
490
-     */
491
-    public function get_timezone()
492
-    {
493
-        return $this->_timezone;
494
-    }
495
-
496
-
497
-    /**
498
-     * This sets the internal date format to what is sent in to be used as the new default for the class
499
-     * internally instead of wp set date format options
500
-     *
501
-     * @since 4.6
502
-     * @param string $format should be a format recognizable by PHP date() functions.
503
-     */
504
-    public function set_date_format($format)
505
-    {
506
-        $this->_dt_frmt = $format;
507
-        // clear cached_properties because they won't be relevant now.
508
-        $this->_clear_cached_properties();
509
-    }
510
-
511
-
512
-    /**
513
-     * This sets the internal time format string to what is sent in to be used as the new default for the
514
-     * class internally instead of wp set time format options.
515
-     *
516
-     * @since 4.6
517
-     * @param string $format should be a format recognizable by PHP date() functions.
518
-     */
519
-    public function set_time_format($format)
520
-    {
521
-        $this->_tm_frmt = $format;
522
-        // clear cached_properties because they won't be relevant now.
523
-        $this->_clear_cached_properties();
524
-    }
525
-
526
-
527
-    /**
528
-     * This returns the current internal set format for the date and time formats.
529
-     *
530
-     * @param bool $full           if true (default), then return the full format.  Otherwise will return an array
531
-     *                             where the first value is the date format and the second value is the time format.
532
-     * @return mixed string|array
533
-     */
534
-    public function get_format($full = true)
535
-    {
536
-        return $full ? $this->_dt_frmt . ' ' . $this->_tm_frmt : array($this->_dt_frmt, $this->_tm_frmt);
537
-    }
538
-
539
-
540
-    /**
541
-     * cache
542
-     * stores the passed model object on the current model object.
543
-     * In certain circumstances, we can use this cached model object instead of querying for another one entirely.
544
-     *
545
-     * @param string        $relationName    one of the keys in the _model_relations array on the model. Eg
546
-     *                                       'Registration' associated with this model object
547
-     * @param EE_Base_Class $object_to_cache that has a relation to this model object. (Eg, if this is a Transaction,
548
-     *                                       that could be a payment or a registration)
549
-     * @param null          $cache_id        a string or number that will be used as the key for any Belongs_To_Many
550
-     *                                       items which will be stored in an array on this object
551
-     * @throws ReflectionException
552
-     * @throws InvalidArgumentException
553
-     * @throws InvalidInterfaceException
554
-     * @throws InvalidDataTypeException
555
-     * @throws EE_Error
556
-     * @return mixed    index into cache, or just TRUE if the relation is of type Belongs_To (because there's only one
557
-     *                                       related thing, no array)
558
-     */
559
-    public function cache($relationName = '', $object_to_cache = null, $cache_id = null)
560
-    {
561
-        // its entirely possible that there IS no related object yet in which case there is nothing to cache.
562
-        if (! $object_to_cache instanceof EE_Base_Class) {
563
-            return false;
564
-        }
565
-        // also get "how" the object is related, or throw an error
566
-        if (! $relationship_to_model = $this->get_model()->related_settings_for($relationName)) {
567
-            throw new EE_Error(
568
-                sprintf(
569
-                    esc_html__('There is no relationship to %s on a %s. Cannot cache it', 'event_espresso'),
570
-                    $relationName,
571
-                    get_class($this)
572
-                )
573
-            );
574
-        }
575
-        // how many things are related ?
576
-        if ($relationship_to_model instanceof EE_Belongs_To_Relation) {
577
-            // if it's a "belongs to" relationship, then there's only one related model object
578
-            // eg, if this is a registration, there's only 1 attendee for it
579
-            // so for these model objects just set it to be cached
580
-            $this->_model_relations[ $relationName ] = $object_to_cache;
581
-            $return = true;
582
-        } else {
583
-            // otherwise, this is the "many" side of a one to many relationship,
584
-            // so we'll add the object to the array of related objects for that type.
585
-            // eg: if this is an event, there are many registrations for that event,
586
-            // so we cache the registrations in an array
587
-            if (! is_array($this->_model_relations[ $relationName ])) {
588
-                // if for some reason, the cached item is a model object,
589
-                // then stick that in the array, otherwise start with an empty array
590
-                $this->_model_relations[ $relationName ] = $this->_model_relations[ $relationName ]
591
-                                                           instanceof
592
-                                                           EE_Base_Class
593
-                    ? array($this->_model_relations[ $relationName ]) : array();
594
-            }
595
-            // first check for a cache_id which is normally empty
596
-            if (! empty($cache_id)) {
597
-                // if the cache_id exists, then it means we are purposely trying to cache this
598
-                // with a known key that can then be used to retrieve the object later on
599
-                $this->_model_relations[ $relationName ][ $cache_id ] = $object_to_cache;
600
-                $return = $cache_id;
601
-            } elseif ($object_to_cache->ID()) {
602
-                // OR the cached object originally came from the db, so let's just use it's PK for an ID
603
-                $this->_model_relations[ $relationName ][ $object_to_cache->ID() ] = $object_to_cache;
604
-                $return = $object_to_cache->ID();
605
-            } else {
606
-                // OR it's a new object with no ID, so just throw it in the array with an auto-incremented ID
607
-                $this->_model_relations[ $relationName ][] = $object_to_cache;
608
-                // move the internal pointer to the end of the array
609
-                end($this->_model_relations[ $relationName ]);
610
-                // and grab the key so that we can return it
611
-                $return = key($this->_model_relations[ $relationName ]);
612
-            }
613
-        }
614
-        return $return;
615
-    }
616
-
617
-
618
-    /**
619
-     * For adding an item to the cached_properties property.
620
-     *
621
-     * @access protected
622
-     * @param string      $fieldname the property item the corresponding value is for.
623
-     * @param mixed       $value     The value we are caching.
624
-     * @param string|null $cache_type
625
-     * @return void
626
-     * @throws ReflectionException
627
-     * @throws InvalidArgumentException
628
-     * @throws InvalidInterfaceException
629
-     * @throws InvalidDataTypeException
630
-     * @throws EE_Error
631
-     */
632
-    protected function _set_cached_property($fieldname, $value, $cache_type = null)
633
-    {
634
-        // first make sure this property exists
635
-        $this->get_model()->field_settings_for($fieldname);
636
-        $cache_type = empty($cache_type) ? 'standard' : $cache_type;
637
-        $this->_cached_properties[ $fieldname ][ $cache_type ] = $value;
638
-    }
639
-
640
-
641
-    /**
642
-     * This returns the value cached property if it exists OR the actual property value if the cache doesn't exist.
643
-     * This also SETS the cache if we return the actual property!
644
-     *
645
-     * @param string $fieldname        the name of the property we're trying to retrieve
646
-     * @param bool   $pretty
647
-     * @param string $extra_cache_ref  This allows the user to specify an extra cache ref for the given property
648
-     *                                 (in cases where the same property may be used for different outputs
649
-     *                                 - i.e. datetime, money etc.)
650
-     *                                 It can also accept certain pre-defined "schema" strings
651
-     *                                 to define how to output the property.
652
-     *                                 see the field's prepare_for_pretty_echoing for what strings can be used
653
-     * @return mixed                   whatever the value for the property is we're retrieving
654
-     * @throws ReflectionException
655
-     * @throws InvalidArgumentException
656
-     * @throws InvalidInterfaceException
657
-     * @throws InvalidDataTypeException
658
-     * @throws EE_Error
659
-     */
660
-    protected function _get_cached_property($fieldname, $pretty = false, $extra_cache_ref = null)
661
-    {
662
-        // verify the field exists
663
-        $model = $this->get_model();
664
-        $model->field_settings_for($fieldname);
665
-        $cache_type = $pretty ? 'pretty' : 'standard';
666
-        $cache_type .= ! empty($extra_cache_ref) ? '_' . $extra_cache_ref : '';
667
-        if (isset($this->_cached_properties[ $fieldname ][ $cache_type ])) {
668
-            return $this->_cached_properties[ $fieldname ][ $cache_type ];
669
-        }
670
-        $value = $this->_get_fresh_property($fieldname, $pretty, $extra_cache_ref);
671
-        $this->_set_cached_property($fieldname, $value, $cache_type);
672
-        return $value;
673
-    }
674
-
675
-
676
-    /**
677
-     * If the cache didn't fetch the needed item, this fetches it.
678
-     *
679
-     * @param string $fieldname
680
-     * @param bool   $pretty
681
-     * @param string $extra_cache_ref
682
-     * @return mixed
683
-     * @throws InvalidArgumentException
684
-     * @throws InvalidInterfaceException
685
-     * @throws InvalidDataTypeException
686
-     * @throws EE_Error
687
-     * @throws ReflectionException
688
-     */
689
-    protected function _get_fresh_property($fieldname, $pretty = false, $extra_cache_ref = null)
690
-    {
691
-        $field_obj = $this->get_model()->field_settings_for($fieldname);
692
-        // If this is an EE_Datetime_Field we need to make sure timezone, formats, and output are correct
693
-        if ($field_obj instanceof EE_Datetime_Field) {
694
-            $this->_prepare_datetime_field($field_obj, $pretty, $extra_cache_ref);
695
-        }
696
-        if (! isset($this->_fields[ $fieldname ])) {
697
-            $this->_fields[ $fieldname ] = null;
698
-        }
699
-        $value = $pretty
700
-            ? $field_obj->prepare_for_pretty_echoing($this->_fields[ $fieldname ], $extra_cache_ref)
701
-            : $field_obj->prepare_for_get($this->_fields[ $fieldname ]);
702
-        return $value;
703
-    }
704
-
705
-
706
-    /**
707
-     * set timezone, formats, and output for EE_Datetime_Field objects
708
-     *
709
-     * @param \EE_Datetime_Field $datetime_field
710
-     * @param bool               $pretty
711
-     * @param null               $date_or_time
712
-     * @return void
713
-     * @throws InvalidArgumentException
714
-     * @throws InvalidInterfaceException
715
-     * @throws InvalidDataTypeException
716
-     * @throws EE_Error
717
-     */
718
-    protected function _prepare_datetime_field(
719
-        EE_Datetime_Field $datetime_field,
720
-        $pretty = false,
721
-        $date_or_time = null
722
-    ) {
723
-        $datetime_field->set_timezone($this->_timezone);
724
-        $datetime_field->set_date_format($this->_dt_frmt, $pretty);
725
-        $datetime_field->set_time_format($this->_tm_frmt, $pretty);
726
-        // set the output returned
727
-        switch ($date_or_time) {
728
-            case 'D':
729
-                $datetime_field->set_date_time_output('date');
730
-                break;
731
-            case 'T':
732
-                $datetime_field->set_date_time_output('time');
733
-                break;
734
-            default:
735
-                $datetime_field->set_date_time_output();
736
-        }
737
-    }
738
-
739
-
740
-    /**
741
-     * This just takes care of clearing out the cached_properties
742
-     *
743
-     * @return void
744
-     */
745
-    protected function _clear_cached_properties()
746
-    {
747
-        $this->_cached_properties = array();
748
-    }
749
-
750
-
751
-    /**
752
-     * This just clears out ONE property if it exists in the cache
753
-     *
754
-     * @param  string $property_name the property to remove if it exists (from the _cached_properties array)
755
-     * @return void
756
-     */
757
-    protected function _clear_cached_property($property_name)
758
-    {
759
-        if (isset($this->_cached_properties[ $property_name ])) {
760
-            unset($this->_cached_properties[ $property_name ]);
761
-        }
762
-    }
763
-
764
-
765
-    /**
766
-     * Ensures that this related thing is a model object.
767
-     *
768
-     * @param mixed  $object_or_id EE_base_Class/int/string either a related model object, or its ID
769
-     * @param string $model_name   name of the related thing, eg 'Attendee',
770
-     * @return EE_Base_Class
771
-     * @throws ReflectionException
772
-     * @throws InvalidArgumentException
773
-     * @throws InvalidInterfaceException
774
-     * @throws InvalidDataTypeException
775
-     * @throws EE_Error
776
-     */
777
-    protected function ensure_related_thing_is_model_obj($object_or_id, $model_name)
778
-    {
779
-        $other_model_instance = self::_get_model_instance_with_name(
780
-            self::_get_model_classname($model_name),
781
-            $this->_timezone
782
-        );
783
-        return $other_model_instance->ensure_is_obj($object_or_id);
784
-    }
785
-
786
-
787
-    /**
788
-     * Forgets the cached model of the given relation Name. So the next time we request it,
789
-     * we will fetch it again from the database. (Handy if you know it's changed somehow).
790
-     * If a specific object is supplied, and the relationship to it is either a HasMany or HABTM,
791
-     * then only remove that one object from our cached array. Otherwise, clear the entire list
792
-     *
793
-     * @param string $relationName                         one of the keys in the _model_relations array on the model.
794
-     *                                                     Eg 'Registration'
795
-     * @param mixed  $object_to_remove_or_index_into_array or an index into the array of cached things, or NULL
796
-     *                                                     if you intend to use $clear_all = TRUE, or the relation only
797
-     *                                                     has 1 object anyways (ie, it's a BelongsToRelation)
798
-     * @param bool   $clear_all                            This flags clearing the entire cache relation property if
799
-     *                                                     this is HasMany or HABTM.
800
-     * @throws ReflectionException
801
-     * @throws InvalidArgumentException
802
-     * @throws InvalidInterfaceException
803
-     * @throws InvalidDataTypeException
804
-     * @throws EE_Error
805
-     * @return EE_Base_Class | boolean from which was cleared from the cache, or true if we requested to remove a
806
-     *                                                     relation from all
807
-     */
808
-    public function clear_cache($relationName, $object_to_remove_or_index_into_array = null, $clear_all = false)
809
-    {
810
-        $relationship_to_model = $this->get_model()->related_settings_for($relationName);
811
-        $index_in_cache = '';
812
-        if (! $relationship_to_model) {
813
-            throw new EE_Error(
814
-                sprintf(
815
-                    esc_html__('There is no relationship to %s on a %s. Cannot clear that cache', 'event_espresso'),
816
-                    $relationName,
817
-                    get_class($this)
818
-                )
819
-            );
820
-        }
821
-        if ($clear_all) {
822
-            $obj_removed = true;
823
-            $this->_model_relations[ $relationName ] = null;
824
-        } elseif ($relationship_to_model instanceof EE_Belongs_To_Relation) {
825
-            $obj_removed = $this->_model_relations[ $relationName ];
826
-            $this->_model_relations[ $relationName ] = null;
827
-        } else {
828
-            if ($object_to_remove_or_index_into_array instanceof EE_Base_Class
829
-                && $object_to_remove_or_index_into_array->ID()
830
-            ) {
831
-                $index_in_cache = $object_to_remove_or_index_into_array->ID();
832
-                if (is_array($this->_model_relations[ $relationName ])
833
-                    && ! isset($this->_model_relations[ $relationName ][ $index_in_cache ])
834
-                ) {
835
-                    $index_found_at = null;
836
-                    // find this object in the array even though it has a different key
837
-                    foreach ($this->_model_relations[ $relationName ] as $index => $obj) {
838
-                        /** @noinspection TypeUnsafeComparisonInspection */
839
-                        if ($obj instanceof EE_Base_Class
840
-                            && (
841
-                                $obj == $object_to_remove_or_index_into_array
842
-                                || $obj->ID() === $object_to_remove_or_index_into_array->ID()
843
-                            )
844
-                        ) {
845
-                            $index_found_at = $index;
846
-                            break;
847
-                        }
848
-                    }
849
-                    if ($index_found_at) {
850
-                        $index_in_cache = $index_found_at;
851
-                    } else {
852
-                        // it wasn't found. huh. well obviously it doesn't need to be removed from teh cache
853
-                        // if it wasn't in it to begin with. So we're done
854
-                        return $object_to_remove_or_index_into_array;
855
-                    }
856
-                }
857
-            } elseif ($object_to_remove_or_index_into_array instanceof EE_Base_Class) {
858
-                // so they provided a model object, but it's not yet saved to the DB... so let's go hunting for it!
859
-                foreach ($this->get_all_from_cache($relationName) as $index => $potentially_obj_we_want) {
860
-                    /** @noinspection TypeUnsafeComparisonInspection */
861
-                    if ($potentially_obj_we_want == $object_to_remove_or_index_into_array) {
862
-                        $index_in_cache = $index;
863
-                    }
864
-                }
865
-            } else {
866
-                $index_in_cache = $object_to_remove_or_index_into_array;
867
-            }
868
-            // supposedly we've found it. But it could just be that the client code
869
-            // provided a bad index/object
870
-            if (isset($this->_model_relations[ $relationName ][ $index_in_cache ])) {
871
-                $obj_removed = $this->_model_relations[ $relationName ][ $index_in_cache ];
872
-                unset($this->_model_relations[ $relationName ][ $index_in_cache ]);
873
-            } else {
874
-                // that thing was never cached anyways.
875
-                $obj_removed = null;
876
-            }
877
-        }
878
-        return $obj_removed;
879
-    }
880
-
881
-
882
-    /**
883
-     * update_cache_after_object_save
884
-     * Allows a cached item to have it's cache ID (within the array of cached items) reset using the new ID it has
885
-     * obtained after being saved to the db
886
-     *
887
-     * @param string        $relationName       - the type of object that is cached
888
-     * @param EE_Base_Class $newly_saved_object - the newly saved object to be re-cached
889
-     * @param string        $current_cache_id   - the ID that was used when originally caching the object
890
-     * @return boolean TRUE on success, FALSE on fail
891
-     * @throws ReflectionException
892
-     * @throws InvalidArgumentException
893
-     * @throws InvalidInterfaceException
894
-     * @throws InvalidDataTypeException
895
-     * @throws EE_Error
896
-     */
897
-    public function update_cache_after_object_save(
898
-        $relationName,
899
-        EE_Base_Class $newly_saved_object,
900
-        $current_cache_id = ''
901
-    ) {
902
-        // verify that incoming object is of the correct type
903
-        $obj_class = 'EE_' . $relationName;
904
-        if ($newly_saved_object instanceof $obj_class) {
905
-            /* @type EE_Base_Class $newly_saved_object */
906
-            // now get the type of relation
907
-            $relationship_to_model = $this->get_model()->related_settings_for($relationName);
908
-            // if this is a 1:1 relationship
909
-            if ($relationship_to_model instanceof EE_Belongs_To_Relation) {
910
-                // then just replace the cached object with the newly saved object
911
-                $this->_model_relations[ $relationName ] = $newly_saved_object;
912
-                return true;
913
-                // or if it's some kind of sordid feral polyamorous relationship...
914
-            }
915
-            if (is_array($this->_model_relations[ $relationName ])
916
-                && isset($this->_model_relations[ $relationName ][ $current_cache_id ])
917
-            ) {
918
-                // then remove the current cached item
919
-                unset($this->_model_relations[ $relationName ][ $current_cache_id ]);
920
-                // and cache the newly saved object using it's new ID
921
-                $this->_model_relations[ $relationName ][ $newly_saved_object->ID() ] = $newly_saved_object;
922
-                return true;
923
-            }
924
-        }
925
-        return false;
926
-    }
927
-
928
-
929
-    /**
930
-     * Fetches a single EE_Base_Class on that relation. (If the relation is of type
931
-     * BelongsTo, it will only ever have 1 object. However, other relations could have an array of objects)
932
-     *
933
-     * @param string $relationName
934
-     * @return EE_Base_Class
935
-     */
936
-    public function get_one_from_cache($relationName)
937
-    {
938
-        $cached_array_or_object = isset($this->_model_relations[ $relationName ])
939
-            ? $this->_model_relations[ $relationName ]
940
-            : null;
941
-        if (is_array($cached_array_or_object)) {
942
-            return array_shift($cached_array_or_object);
943
-        }
944
-        return $cached_array_or_object;
945
-    }
946
-
947
-
948
-    /**
949
-     * Fetches a single EE_Base_Class on that relation. (If the relation is of type
950
-     * BelongsTo, it will only ever have 1 object. However, other relations could have an array of objects)
951
-     *
952
-     * @param string $relationName
953
-     * @throws ReflectionException
954
-     * @throws InvalidArgumentException
955
-     * @throws InvalidInterfaceException
956
-     * @throws InvalidDataTypeException
957
-     * @throws EE_Error
958
-     * @return EE_Base_Class[] NOT necessarily indexed by primary keys
959
-     */
960
-    public function get_all_from_cache($relationName)
961
-    {
962
-        $objects = isset($this->_model_relations[ $relationName ]) ? $this->_model_relations[ $relationName ] : array();
963
-        // if the result is not an array, but exists, make it an array
964
-        $objects = is_array($objects) ? $objects : array($objects);
965
-        // bugfix for https://events.codebasehq.com/projects/event-espresso/tickets/7143
966
-        // basically, if this model object was stored in the session, and these cached model objects
967
-        // already have IDs, let's make sure they're in their model's entity mapper
968
-        // otherwise we will have duplicates next time we call
969
-        // EE_Registry::instance()->load_model( $relationName )->get_one_by_ID( $result->ID() );
970
-        $model = EE_Registry::instance()->load_model($relationName);
971
-        foreach ($objects as $model_object) {
972
-            if ($model instanceof EEM_Base && $model_object instanceof EE_Base_Class) {
973
-                // ensure its in the map if it has an ID; otherwise it will be added to the map when its saved
974
-                if ($model_object->ID()) {
975
-                    $model->add_to_entity_map($model_object);
976
-                }
977
-            } else {
978
-                throw new EE_Error(
979
-                    sprintf(
980
-                        esc_html__(
981
-                            'Error retrieving related model objects. Either $1%s is not a model or $2%s is not a model object',
982
-                            'event_espresso'
983
-                        ),
984
-                        $relationName,
985
-                        gettype($model_object)
986
-                    )
987
-                );
988
-            }
989
-        }
990
-        return $objects;
991
-    }
992
-
993
-
994
-    /**
995
-     * Returns the next x number of EE_Base_Class objects in sequence from this object as found in the database
996
-     * matching the given query conditions.
997
-     *
998
-     * @param null  $field_to_order_by  What field is being used as the reference point.
999
-     * @param int   $limit              How many objects to return.
1000
-     * @param array $query_params       Any additional conditions on the query.
1001
-     * @param null  $columns_to_select  If left null, then an array of EE_Base_Class objects is returned, otherwise
1002
-     *                                  you can indicate just the columns you want returned
1003
-     * @return array|EE_Base_Class[]
1004
-     * @throws ReflectionException
1005
-     * @throws InvalidArgumentException
1006
-     * @throws InvalidInterfaceException
1007
-     * @throws InvalidDataTypeException
1008
-     * @throws EE_Error
1009
-     */
1010
-    public function next_x($field_to_order_by = null, $limit = 1, $query_params = array(), $columns_to_select = null)
1011
-    {
1012
-        $model = $this->get_model();
1013
-        $field = empty($field_to_order_by) && $model->has_primary_key_field()
1014
-            ? $model->get_primary_key_field()->get_name()
1015
-            : $field_to_order_by;
1016
-        $current_value = ! empty($field) ? $this->get($field) : null;
1017
-        if (empty($field) || empty($current_value)) {
1018
-            return array();
1019
-        }
1020
-        return $model->next_x($current_value, $field, $limit, $query_params, $columns_to_select);
1021
-    }
1022
-
1023
-
1024
-    /**
1025
-     * Returns the previous x number of EE_Base_Class objects in sequence from this object as found in the database
1026
-     * matching the given query conditions.
1027
-     *
1028
-     * @param null  $field_to_order_by  What field is being used as the reference point.
1029
-     * @param int   $limit              How many objects to return.
1030
-     * @param array $query_params       Any additional conditions on the query.
1031
-     * @param null  $columns_to_select  If left null, then an array of EE_Base_Class objects is returned, otherwise
1032
-     *                                  you can indicate just the columns you want returned
1033
-     * @return array|EE_Base_Class[]
1034
-     * @throws ReflectionException
1035
-     * @throws InvalidArgumentException
1036
-     * @throws InvalidInterfaceException
1037
-     * @throws InvalidDataTypeException
1038
-     * @throws EE_Error
1039
-     */
1040
-    public function previous_x(
1041
-        $field_to_order_by = null,
1042
-        $limit = 1,
1043
-        $query_params = array(),
1044
-        $columns_to_select = null
1045
-    ) {
1046
-        $model = $this->get_model();
1047
-        $field = empty($field_to_order_by) && $model->has_primary_key_field()
1048
-            ? $model->get_primary_key_field()->get_name()
1049
-            : $field_to_order_by;
1050
-        $current_value = ! empty($field) ? $this->get($field) : null;
1051
-        if (empty($field) || empty($current_value)) {
1052
-            return array();
1053
-        }
1054
-        return $model->previous_x($current_value, $field, $limit, $query_params, $columns_to_select);
1055
-    }
1056
-
1057
-
1058
-    /**
1059
-     * Returns the next EE_Base_Class object in sequence from this object as found in the database
1060
-     * matching the given query conditions.
1061
-     *
1062
-     * @param null  $field_to_order_by  What field is being used as the reference point.
1063
-     * @param array $query_params       Any additional conditions on the query.
1064
-     * @param null  $columns_to_select  If left null, then an array of EE_Base_Class objects is returned, otherwise
1065
-     *                                  you can indicate just the columns you want returned
1066
-     * @return array|EE_Base_Class
1067
-     * @throws ReflectionException
1068
-     * @throws InvalidArgumentException
1069
-     * @throws InvalidInterfaceException
1070
-     * @throws InvalidDataTypeException
1071
-     * @throws EE_Error
1072
-     */
1073
-    public function next($field_to_order_by = null, $query_params = array(), $columns_to_select = null)
1074
-    {
1075
-        $model = $this->get_model();
1076
-        $field = empty($field_to_order_by) && $model->has_primary_key_field()
1077
-            ? $model->get_primary_key_field()->get_name()
1078
-            : $field_to_order_by;
1079
-        $current_value = ! empty($field) ? $this->get($field) : null;
1080
-        if (empty($field) || empty($current_value)) {
1081
-            return array();
1082
-        }
1083
-        return $model->next($current_value, $field, $query_params, $columns_to_select);
1084
-    }
1085
-
1086
-
1087
-    /**
1088
-     * Returns the previous EE_Base_Class object in sequence from this object as found in the database
1089
-     * matching the given query conditions.
1090
-     *
1091
-     * @param null  $field_to_order_by  What field is being used as the reference point.
1092
-     * @param array $query_params       Any additional conditions on the query.
1093
-     * @param null  $columns_to_select  If left null, then an EE_Base_Class object is returned, otherwise
1094
-     *                                  you can indicate just the column you want returned
1095
-     * @return array|EE_Base_Class
1096
-     * @throws ReflectionException
1097
-     * @throws InvalidArgumentException
1098
-     * @throws InvalidInterfaceException
1099
-     * @throws InvalidDataTypeException
1100
-     * @throws EE_Error
1101
-     */
1102
-    public function previous($field_to_order_by = null, $query_params = array(), $columns_to_select = null)
1103
-    {
1104
-        $model = $this->get_model();
1105
-        $field = empty($field_to_order_by) && $model->has_primary_key_field()
1106
-            ? $model->get_primary_key_field()->get_name()
1107
-            : $field_to_order_by;
1108
-        $current_value = ! empty($field) ? $this->get($field) : null;
1109
-        if (empty($field) || empty($current_value)) {
1110
-            return array();
1111
-        }
1112
-        return $model->previous($current_value, $field, $query_params, $columns_to_select);
1113
-    }
1114
-
1115
-
1116
-    /**
1117
-     * Overrides parent because parent expects old models.
1118
-     * This also doesn't do any validation, and won't work for serialized arrays
1119
-     *
1120
-     * @param string $field_name
1121
-     * @param mixed  $field_value_from_db
1122
-     * @throws ReflectionException
1123
-     * @throws InvalidArgumentException
1124
-     * @throws InvalidInterfaceException
1125
-     * @throws InvalidDataTypeException
1126
-     * @throws EE_Error
1127
-     */
1128
-    public function set_from_db($field_name, $field_value_from_db)
1129
-    {
1130
-        $field_obj = $this->get_model()->field_settings_for($field_name);
1131
-        if ($field_obj instanceof EE_Model_Field_Base) {
1132
-            // you would think the DB has no NULLs for non-null label fields right? wrong!
1133
-            // eg, a CPT model object could have an entry in the posts table, but no
1134
-            // entry in the meta table. Meaning that all its columns in the meta table
1135
-            // are null! yikes! so when we find one like that, use defaults for its meta columns
1136
-            if ($field_value_from_db === null) {
1137
-                if ($field_obj->is_nullable()) {
1138
-                    // if the field allows nulls, then let it be null
1139
-                    $field_value = null;
1140
-                } else {
1141
-                    $field_value = $field_obj->get_default_value();
1142
-                }
1143
-            } else {
1144
-                $field_value = $field_obj->prepare_for_set_from_db($field_value_from_db);
1145
-            }
1146
-            $this->_fields[ $field_name ] = $field_value;
1147
-            $this->_clear_cached_property($field_name);
1148
-        }
1149
-    }
1150
-
1151
-
1152
-    /**
1153
-     * verifies that the specified field is of the correct type
1154
-     *
1155
-     * @param string $field_name
1156
-     * @param string $extra_cache_ref This allows the user to specify an extra cache ref for the given property
1157
-     *                                (in cases where the same property may be used for different outputs
1158
-     *                                - i.e. datetime, money etc.)
1159
-     * @return mixed
1160
-     * @throws ReflectionException
1161
-     * @throws InvalidArgumentException
1162
-     * @throws InvalidInterfaceException
1163
-     * @throws InvalidDataTypeException
1164
-     * @throws EE_Error
1165
-     */
1166
-    public function get($field_name, $extra_cache_ref = null)
1167
-    {
1168
-        return $this->_get_cached_property($field_name, false, $extra_cache_ref);
1169
-    }
1170
-
1171
-
1172
-    /**
1173
-     * This method simply returns the RAW unprocessed value for the given property in this class
1174
-     *
1175
-     * @param  string $field_name A valid fieldname
1176
-     * @return mixed              Whatever the raw value stored on the property is.
1177
-     * @throws ReflectionException
1178
-     * @throws InvalidArgumentException
1179
-     * @throws InvalidInterfaceException
1180
-     * @throws InvalidDataTypeException
1181
-     * @throws EE_Error if fieldSettings is misconfigured or the field doesn't exist.
1182
-     */
1183
-    public function get_raw($field_name)
1184
-    {
1185
-        $field_settings = $this->get_model()->field_settings_for($field_name);
1186
-        return $field_settings instanceof EE_Datetime_Field && $this->_fields[ $field_name ] instanceof DateTime
1187
-            ? $this->_fields[ $field_name ]->format('U')
1188
-            : $this->_fields[ $field_name ];
1189
-    }
1190
-
1191
-
1192
-    /**
1193
-     * This is used to return the internal DateTime object used for a field that is a
1194
-     * EE_Datetime_Field.
1195
-     *
1196
-     * @param string $field_name               The field name retrieving the DateTime object.
1197
-     * @return mixed null | false | DateTime  If the requested field is NOT a EE_Datetime_Field then
1198
-     * @throws EE_Error an error is set and false returned.  If the field IS an
1199
-     *                                         EE_Datetime_Field and but the field value is null, then
1200
-     *                                         just null is returned (because that indicates that likely
1201
-     *                                         this field is nullable).
1202
-     * @throws InvalidArgumentException
1203
-     * @throws InvalidDataTypeException
1204
-     * @throws InvalidInterfaceException
1205
-     * @throws ReflectionException
1206
-     */
1207
-    public function get_DateTime_object($field_name)
1208
-    {
1209
-        $field_settings = $this->get_model()->field_settings_for($field_name);
1210
-        if (! $field_settings instanceof EE_Datetime_Field) {
1211
-            EE_Error::add_error(
1212
-                sprintf(
1213
-                    esc_html__(
1214
-                        'The field %s is not an EE_Datetime_Field field.  There is no DateTime object stored on this field type.',
1215
-                        'event_espresso'
1216
-                    ),
1217
-                    $field_name
1218
-                ),
1219
-                __FILE__,
1220
-                __FUNCTION__,
1221
-                __LINE__
1222
-            );
1223
-            return false;
1224
-        }
1225
-        return isset($this->_fields[ $field_name ]) && $this->_fields[ $field_name ] instanceof DateTime
1226
-            ? clone $this->_fields[ $field_name ]
1227
-            : null;
1228
-    }
1229
-
1230
-
1231
-    /**
1232
-     * To be used in template to immediately echo out the value, and format it for output.
1233
-     * Eg, should call stripslashes and whatnot before echoing
1234
-     *
1235
-     * @param string $field_name      the name of the field as it appears in the DB
1236
-     * @param string $extra_cache_ref This allows the user to specify an extra cache ref for the given property
1237
-     *                                (in cases where the same property may be used for different outputs
1238
-     *                                - i.e. datetime, money etc.)
1239
-     * @return void
1240
-     * @throws ReflectionException
1241
-     * @throws InvalidArgumentException
1242
-     * @throws InvalidInterfaceException
1243
-     * @throws InvalidDataTypeException
1244
-     * @throws EE_Error
1245
-     */
1246
-    public function e($field_name, $extra_cache_ref = null)
1247
-    {
1248
-        echo $this->get_pretty($field_name, $extra_cache_ref);
1249
-    }
1250
-
1251
-
1252
-    /**
1253
-     * Exactly like e(), echoes out the field, but sets its schema to 'form_input', so that it
1254
-     * can be easily used as the value of form input.
1255
-     *
1256
-     * @param string $field_name
1257
-     * @return void
1258
-     * @throws ReflectionException
1259
-     * @throws InvalidArgumentException
1260
-     * @throws InvalidInterfaceException
1261
-     * @throws InvalidDataTypeException
1262
-     * @throws EE_Error
1263
-     */
1264
-    public function f($field_name)
1265
-    {
1266
-        $this->e($field_name, 'form_input');
1267
-    }
1268
-
1269
-
1270
-    /**
1271
-     * Same as `f()` but just returns the value instead of echoing it
1272
-     *
1273
-     * @param string $field_name
1274
-     * @return string
1275
-     * @throws ReflectionException
1276
-     * @throws InvalidArgumentException
1277
-     * @throws InvalidInterfaceException
1278
-     * @throws InvalidDataTypeException
1279
-     * @throws EE_Error
1280
-     */
1281
-    public function get_f($field_name)
1282
-    {
1283
-        return (string) $this->get_pretty($field_name, 'form_input');
1284
-    }
1285
-
1286
-
1287
-    /**
1288
-     * Gets a pretty view of the field's value. $extra_cache_ref can specify different formats for this.
1289
-     * The $extra_cache_ref will be passed to the model field's prepare_for_pretty_echoing, so consult the field's class
1290
-     * to see what options are available.
1291
-     *
1292
-     * @param string $field_name
1293
-     * @param string $extra_cache_ref This allows the user to specify an extra cache ref for the given property
1294
-     *                                (in cases where the same property may be used for different outputs
1295
-     *                                - i.e. datetime, money etc.)
1296
-     * @return mixed
1297
-     * @throws ReflectionException
1298
-     * @throws InvalidArgumentException
1299
-     * @throws InvalidInterfaceException
1300
-     * @throws InvalidDataTypeException
1301
-     * @throws EE_Error
1302
-     */
1303
-    public function get_pretty($field_name, $extra_cache_ref = null)
1304
-    {
1305
-        return $this->_get_cached_property($field_name, true, $extra_cache_ref);
1306
-    }
1307
-
1308
-
1309
-    /**
1310
-     * This simply returns the datetime for the given field name
1311
-     * Note: this protected function is called by the wrapper get_date or get_time or get_datetime functions
1312
-     * (and the equivalent e_date, e_time, e_datetime).
1313
-     *
1314
-     * @access   protected
1315
-     * @param string   $field_name   Field on the instantiated EE_Base_Class child object
1316
-     * @param string   $dt_frmt      valid datetime format used for date
1317
-     *                               (if '' then we just use the default on the field,
1318
-     *                               if NULL we use the last-used format)
1319
-     * @param string   $tm_frmt      Same as above except this is for time format
1320
-     * @param string   $date_or_time if NULL then both are returned, otherwise "D" = only date and "T" = only time.
1321
-     * @param  boolean $echo         Whether the dtt is echoing using pretty echoing or just returned using vanilla get
1322
-     * @return string|bool|EE_Error string on success, FALSE on fail, or EE_Error Exception is thrown
1323
-     *                               if field is not a valid dtt field, or void if echoing
1324
-     * @throws ReflectionException
1325
-     * @throws InvalidArgumentException
1326
-     * @throws InvalidInterfaceException
1327
-     * @throws InvalidDataTypeException
1328
-     * @throws EE_Error
1329
-     */
1330
-    protected function _get_datetime($field_name, $dt_frmt = '', $tm_frmt = '', $date_or_time = '', $echo = false)
1331
-    {
1332
-        // clear cached property
1333
-        $this->_clear_cached_property($field_name);
1334
-        // reset format properties because they are used in get()
1335
-        $this->_dt_frmt = $dt_frmt !== '' ? $dt_frmt : $this->_dt_frmt;
1336
-        $this->_tm_frmt = $tm_frmt !== '' ? $tm_frmt : $this->_tm_frmt;
1337
-        if ($echo) {
1338
-            $this->e($field_name, $date_or_time);
1339
-            return '';
1340
-        }
1341
-        return $this->get($field_name, $date_or_time);
1342
-    }
1343
-
1344
-
1345
-    /**
1346
-     * below are wrapper functions for the various datetime outputs that can be obtained for JUST returning the date
1347
-     * portion of a datetime value. (note the only difference between get_ and e_ is one returns the value and the
1348
-     * other echoes the pretty value for dtt)
1349
-     *
1350
-     * @param  string $field_name name of model object datetime field holding the value
1351
-     * @param  string $format     format for the date returned (if NULL we use default in dt_frmt property)
1352
-     * @return string            datetime value formatted
1353
-     * @throws ReflectionException
1354
-     * @throws InvalidArgumentException
1355
-     * @throws InvalidInterfaceException
1356
-     * @throws InvalidDataTypeException
1357
-     * @throws EE_Error
1358
-     */
1359
-    public function get_date($field_name, $format = '')
1360
-    {
1361
-        return $this->_get_datetime($field_name, $format, null, 'D');
1362
-    }
1363
-
1364
-
1365
-    /**
1366
-     * @param        $field_name
1367
-     * @param string $format
1368
-     * @throws ReflectionException
1369
-     * @throws InvalidArgumentException
1370
-     * @throws InvalidInterfaceException
1371
-     * @throws InvalidDataTypeException
1372
-     * @throws EE_Error
1373
-     */
1374
-    public function e_date($field_name, $format = '')
1375
-    {
1376
-        $this->_get_datetime($field_name, $format, null, 'D', true);
1377
-    }
1378
-
1379
-
1380
-    /**
1381
-     * below are wrapper functions for the various datetime outputs that can be obtained for JUST returning the time
1382
-     * portion of a datetime value. (note the only difference between get_ and e_ is one returns the value and the
1383
-     * other echoes the pretty value for dtt)
1384
-     *
1385
-     * @param  string $field_name name of model object datetime field holding the value
1386
-     * @param  string $format     format for the time returned ( if NULL we use default in tm_frmt property)
1387
-     * @return string             datetime value formatted
1388
-     * @throws ReflectionException
1389
-     * @throws InvalidArgumentException
1390
-     * @throws InvalidInterfaceException
1391
-     * @throws InvalidDataTypeException
1392
-     * @throws EE_Error
1393
-     */
1394
-    public function get_time($field_name, $format = '')
1395
-    {
1396
-        return $this->_get_datetime($field_name, null, $format, 'T');
1397
-    }
1398
-
1399
-
1400
-    /**
1401
-     * @param        $field_name
1402
-     * @param string $format
1403
-     * @throws ReflectionException
1404
-     * @throws InvalidArgumentException
1405
-     * @throws InvalidInterfaceException
1406
-     * @throws InvalidDataTypeException
1407
-     * @throws EE_Error
1408
-     */
1409
-    public function e_time($field_name, $format = '')
1410
-    {
1411
-        $this->_get_datetime($field_name, null, $format, 'T', true);
1412
-    }
1413
-
1414
-
1415
-    /**
1416
-     * below are wrapper functions for the various datetime outputs that can be obtained for returning the date AND
1417
-     * time portion of a datetime value. (note the only difference between get_ and e_ is one returns the value and the
1418
-     * other echoes the pretty value for dtt)
1419
-     *
1420
-     * @param  string $field_name name of model object datetime field holding the value
1421
-     * @param  string $dt_frmt    format for the date returned (if NULL we use default in dt_frmt property)
1422
-     * @param  string $tm_frmt    format for the time returned (if NULL we use default in tm_frmt property)
1423
-     * @return string             datetime value formatted
1424
-     * @throws ReflectionException
1425
-     * @throws InvalidArgumentException
1426
-     * @throws InvalidInterfaceException
1427
-     * @throws InvalidDataTypeException
1428
-     * @throws EE_Error
1429
-     */
1430
-    public function get_datetime($field_name, $dt_frmt = '', $tm_frmt = '')
1431
-    {
1432
-        return $this->_get_datetime($field_name, $dt_frmt, $tm_frmt);
1433
-    }
1434
-
1435
-
1436
-    /**
1437
-     * @param string $field_name
1438
-     * @param string $dt_frmt
1439
-     * @param string $tm_frmt
1440
-     * @throws ReflectionException
1441
-     * @throws InvalidArgumentException
1442
-     * @throws InvalidInterfaceException
1443
-     * @throws InvalidDataTypeException
1444
-     * @throws EE_Error
1445
-     */
1446
-    public function e_datetime($field_name, $dt_frmt = '', $tm_frmt = '')
1447
-    {
1448
-        $this->_get_datetime($field_name, $dt_frmt, $tm_frmt, null, true);
1449
-    }
1450
-
1451
-
1452
-    /**
1453
-     * Get the i8ln value for a date using the WordPress @see date_i18n function.
1454
-     *
1455
-     * @param string $field_name The EE_Datetime_Field reference for the date being retrieved.
1456
-     * @param string $format     PHP valid date/time string format.  If none is provided then the internal set format
1457
-     *                           on the object will be used.
1458
-     * @return string Date and time string in set locale or false if no field exists for the given
1459
-     * @throws ReflectionException
1460
-     * @throws InvalidArgumentException
1461
-     * @throws InvalidInterfaceException
1462
-     * @throws InvalidDataTypeException
1463
-     * @throws EE_Error
1464
-     *                           field name.
1465
-     */
1466
-    public function get_i18n_datetime($field_name, $format = '')
1467
-    {
1468
-        $format = empty($format) ? $this->_dt_frmt . ' ' . $this->_tm_frmt : $format;
1469
-        return date_i18n(
1470
-            $format,
1471
-            EEH_DTT_Helper::get_timestamp_with_offset(
1472
-                $this->get_raw($field_name),
1473
-                $this->_timezone
1474
-            )
1475
-        );
1476
-    }
1477
-
1478
-
1479
-    /**
1480
-     * This method validates whether the given field name is a valid field on the model object as well as it is of a
1481
-     * type EE_Datetime_Field.  On success there will be returned the field settings.  On fail an EE_Error exception is
1482
-     * thrown.
1483
-     *
1484
-     * @param  string $field_name The field name being checked
1485
-     * @throws ReflectionException
1486
-     * @throws InvalidArgumentException
1487
-     * @throws InvalidInterfaceException
1488
-     * @throws InvalidDataTypeException
1489
-     * @throws EE_Error
1490
-     * @return EE_Datetime_Field
1491
-     */
1492
-    protected function _get_dtt_field_settings($field_name)
1493
-    {
1494
-        $field = $this->get_model()->field_settings_for($field_name);
1495
-        // check if field is dtt
1496
-        if ($field instanceof EE_Datetime_Field) {
1497
-            return $field;
1498
-        }
1499
-        throw new EE_Error(
1500
-            sprintf(
1501
-                esc_html__(
1502
-                    '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',
1503
-                    'event_espresso'
1504
-                ),
1505
-                $field_name,
1506
-                self::_get_model_classname(get_class($this))
1507
-            )
1508
-        );
1509
-    }
1510
-
1511
-
1512
-
1513
-
1514
-    /**
1515
-     * NOTE ABOUT BELOW:
1516
-     * These convenience date and time setters are for setting date and time independently.  In other words you might
1517
-     * want to change the time on a datetime_field but leave the date the same (or vice versa). IF on the other hand
1518
-     * you want to set both date and time at the same time, you can just use the models default set($fieldname,$value)
1519
-     * method and make sure you send the entire datetime value for setting.
1520
-     */
1521
-    /**
1522
-     * sets the time on a datetime property
1523
-     *
1524
-     * @access protected
1525
-     * @param string|Datetime $time      a valid time string for php datetime functions (or DateTime object)
1526
-     * @param string          $fieldname the name of the field the time is being set on (must match a EE_Datetime_Field)
1527
-     * @throws ReflectionException
1528
-     * @throws InvalidArgumentException
1529
-     * @throws InvalidInterfaceException
1530
-     * @throws InvalidDataTypeException
1531
-     * @throws EE_Error
1532
-     */
1533
-    protected function _set_time_for($time, $fieldname)
1534
-    {
1535
-        $this->_set_date_time('T', $time, $fieldname);
1536
-    }
1537
-
1538
-
1539
-    /**
1540
-     * sets the date on a datetime property
1541
-     *
1542
-     * @access protected
1543
-     * @param string|DateTime $date      a valid date string for php datetime functions ( or DateTime object)
1544
-     * @param string          $fieldname the name of the field the date is being set on (must match a EE_Datetime_Field)
1545
-     * @throws ReflectionException
1546
-     * @throws InvalidArgumentException
1547
-     * @throws InvalidInterfaceException
1548
-     * @throws InvalidDataTypeException
1549
-     * @throws EE_Error
1550
-     */
1551
-    protected function _set_date_for($date, $fieldname)
1552
-    {
1553
-        $this->_set_date_time('D', $date, $fieldname);
1554
-    }
1555
-
1556
-
1557
-    /**
1558
-     * This takes care of setting a date or time independently on a given model object property. This method also
1559
-     * verifies that the given fieldname matches a model object property and is for a EE_Datetime_Field field
1560
-     *
1561
-     * @access protected
1562
-     * @param string          $what           "T" for time, 'B' for both, 'D' for Date.
1563
-     * @param string|DateTime $datetime_value A valid Date or Time string (or DateTime object)
1564
-     * @param string          $fieldname      the name of the field the date OR time is being set on (must match a
1565
-     *                                        EE_Datetime_Field property)
1566
-     * @throws ReflectionException
1567
-     * @throws InvalidArgumentException
1568
-     * @throws InvalidInterfaceException
1569
-     * @throws InvalidDataTypeException
1570
-     * @throws EE_Error
1571
-     */
1572
-    protected function _set_date_time($what = 'T', $datetime_value, $fieldname)
1573
-    {
1574
-        $field = $this->_get_dtt_field_settings($fieldname);
1575
-        $field->set_timezone($this->_timezone);
1576
-        $field->set_date_format($this->_dt_frmt);
1577
-        $field->set_time_format($this->_tm_frmt);
1578
-        switch ($what) {
1579
-            case 'T':
1580
-                $this->_fields[ $fieldname ] = $field->prepare_for_set_with_new_time(
1581
-                    $datetime_value,
1582
-                    $this->_fields[ $fieldname ]
1583
-                );
1584
-                $this->_has_changes = true;
1585
-                break;
1586
-            case 'D':
1587
-                $this->_fields[ $fieldname ] = $field->prepare_for_set_with_new_date(
1588
-                    $datetime_value,
1589
-                    $this->_fields[ $fieldname ]
1590
-                );
1591
-                $this->_has_changes = true;
1592
-                break;
1593
-            case 'B':
1594
-                $this->_fields[ $fieldname ] = $field->prepare_for_set($datetime_value);
1595
-                $this->_has_changes = true;
1596
-                break;
1597
-        }
1598
-        $this->_clear_cached_property($fieldname);
1599
-    }
1600
-
1601
-
1602
-    /**
1603
-     * This will return a timestamp for the website timezone but ONLY when the current website timezone is different
1604
-     * than the timezone set for the website. NOTE, this currently only works well with methods that return values.  If
1605
-     * you use it with methods that echo values the $_timestamp property may not get reset to its original value and
1606
-     * that could lead to some unexpected results!
1607
-     *
1608
-     * @access public
1609
-     * @param string $field_name               This is the name of the field on the object that contains the date/time
1610
-     *                                         value being returned.
1611
-     * @param string $callback                 must match a valid method in this class (defaults to get_datetime)
1612
-     * @param mixed (array|string) $args       This is the arguments that will be passed to the callback.
1613
-     * @param string $prepend                  You can include something to prepend on the timestamp
1614
-     * @param string $append                   You can include something to append on the timestamp
1615
-     * @throws ReflectionException
1616
-     * @throws InvalidArgumentException
1617
-     * @throws InvalidInterfaceException
1618
-     * @throws InvalidDataTypeException
1619
-     * @throws EE_Error
1620
-     * @return string timestamp
1621
-     */
1622
-    public function display_in_my_timezone(
1623
-        $field_name,
1624
-        $callback = 'get_datetime',
1625
-        $args = null,
1626
-        $prepend = '',
1627
-        $append = ''
1628
-    ) {
1629
-        $timezone = EEH_DTT_Helper::get_timezone();
1630
-        if ($timezone === $this->_timezone) {
1631
-            return '';
1632
-        }
1633
-        $original_timezone = $this->_timezone;
1634
-        $this->set_timezone($timezone);
1635
-        $fn = (array) $field_name;
1636
-        $args = array_merge($fn, (array) $args);
1637
-        if (! method_exists($this, $callback)) {
1638
-            throw new EE_Error(
1639
-                sprintf(
1640
-                    esc_html__(
1641
-                        'The method named "%s" given as the callback param in "display_in_my_timezone" does not exist.  Please check your spelling',
1642
-                        'event_espresso'
1643
-                    ),
1644
-                    $callback
1645
-                )
1646
-            );
1647
-        }
1648
-        $args = (array) $args;
1649
-        $return = $prepend . call_user_func_array(array($this, $callback), $args) . $append;
1650
-        $this->set_timezone($original_timezone);
1651
-        return $return;
1652
-    }
1653
-
1654
-
1655
-    /**
1656
-     * Deletes this model object.
1657
-     * This calls the `EE_Base_Class::_delete` method.  Child classes wishing to change default behaviour should
1658
-     * override
1659
-     * `EE_Base_Class::_delete` NOT this class.
1660
-     *
1661
-     * @return boolean | int
1662
-     * @throws ReflectionException
1663
-     * @throws InvalidArgumentException
1664
-     * @throws InvalidInterfaceException
1665
-     * @throws InvalidDataTypeException
1666
-     * @throws EE_Error
1667
-     */
1668
-    public function delete()
1669
-    {
1670
-        /**
1671
-         * Called just before the `EE_Base_Class::_delete` method call.
1672
-         * Note:
1673
-         * `EE_Base_Class::_delete` might be overridden by child classes so any client code hooking into these actions
1674
-         * should be aware that `_delete` may not always result in a permanent delete.
1675
-         * For example, `EE_Soft_Delete_Base_Class::_delete`
1676
-         * soft deletes (trash) the object and does not permanently delete it.
1677
-         *
1678
-         * @param EE_Base_Class $model_object about to be 'deleted'
1679
-         */
1680
-        do_action('AHEE__EE_Base_Class__delete__before', $this);
1681
-        $result = $this->_delete();
1682
-        /**
1683
-         * Called just after the `EE_Base_Class::_delete` method call.
1684
-         * Note:
1685
-         * `EE_Base_Class::_delete` might be overridden by child classes so any client code hooking into these actions
1686
-         * should be aware that `_delete` may not always result in a permanent delete.
1687
-         * For example `EE_Soft_Base_Class::_delete`
1688
-         * soft deletes (trash) the object and does not permanently delete it.
1689
-         *
1690
-         * @param EE_Base_Class $model_object that was just 'deleted'
1691
-         * @param boolean       $result
1692
-         */
1693
-        do_action('AHEE__EE_Base_Class__delete__end', $this, $result);
1694
-        return $result;
1695
-    }
1696
-
1697
-
1698
-    /**
1699
-     * Calls the specific delete method for the instantiated class.
1700
-     * This method is called by the public `EE_Base_Class::delete` method.  Any child classes desiring to override
1701
-     * default functionality for "delete" (which is to call `permanently_delete`) should override this method NOT
1702
-     * `EE_Base_Class::delete`
1703
-     *
1704
-     * @return bool|int
1705
-     * @throws ReflectionException
1706
-     * @throws InvalidArgumentException
1707
-     * @throws InvalidInterfaceException
1708
-     * @throws InvalidDataTypeException
1709
-     * @throws EE_Error
1710
-     */
1711
-    protected function _delete()
1712
-    {
1713
-        return $this->delete_permanently();
1714
-    }
1715
-
1716
-
1717
-    /**
1718
-     * Deletes this model object permanently from db
1719
-     * (but keep in mind related models may block the delete and return an error)
1720
-     *
1721
-     * @return bool | int
1722
-     * @throws ReflectionException
1723
-     * @throws InvalidArgumentException
1724
-     * @throws InvalidInterfaceException
1725
-     * @throws InvalidDataTypeException
1726
-     * @throws EE_Error
1727
-     */
1728
-    public function delete_permanently()
1729
-    {
1730
-        /**
1731
-         * Called just before HARD deleting a model object
1732
-         *
1733
-         * @param EE_Base_Class $model_object about to be 'deleted'
1734
-         */
1735
-        do_action('AHEE__EE_Base_Class__delete_permanently__before', $this);
1736
-        $model = $this->get_model();
1737
-        $result = $model->delete_permanently_by_ID($this->ID());
1738
-        $this->refresh_cache_of_related_objects();
1739
-        /**
1740
-         * Called just after HARD deleting a model object
1741
-         *
1742
-         * @param EE_Base_Class $model_object that was just 'deleted'
1743
-         * @param boolean       $result
1744
-         */
1745
-        do_action('AHEE__EE_Base_Class__delete_permanently__end', $this, $result);
1746
-        return $result;
1747
-    }
1748
-
1749
-
1750
-    /**
1751
-     * When this model object is deleted, it may still be cached on related model objects. This clears the cache of
1752
-     * related model objects
1753
-     *
1754
-     * @throws ReflectionException
1755
-     * @throws InvalidArgumentException
1756
-     * @throws InvalidInterfaceException
1757
-     * @throws InvalidDataTypeException
1758
-     * @throws EE_Error
1759
-     */
1760
-    public function refresh_cache_of_related_objects()
1761
-    {
1762
-        $model = $this->get_model();
1763
-        foreach ($model->relation_settings() as $relation_name => $relation_obj) {
1764
-            if (! empty($this->_model_relations[ $relation_name ])) {
1765
-                $related_objects = $this->_model_relations[ $relation_name ];
1766
-                if ($relation_obj instanceof EE_Belongs_To_Relation) {
1767
-                    // this relation only stores a single model object, not an array
1768
-                    // but let's make it consistent
1769
-                    $related_objects = array($related_objects);
1770
-                }
1771
-                foreach ($related_objects as $related_object) {
1772
-                    // only refresh their cache if they're in memory
1773
-                    if ($related_object instanceof EE_Base_Class) {
1774
-                        $related_object->clear_cache(
1775
-                            $model->get_this_model_name(),
1776
-                            $this
1777
-                        );
1778
-                    }
1779
-                }
1780
-            }
1781
-        }
1782
-    }
1783
-
1784
-
1785
-    /**
1786
-     *        Saves this object to the database. An array may be supplied to set some values on this
1787
-     * object just before saving.
1788
-     *
1789
-     * @access public
1790
-     * @param array $set_cols_n_values keys are field names, values are their new values,
1791
-     *                                 if provided during the save() method (often client code will change the fields'
1792
-     *                                 values before calling save)
1793
-     * @throws InvalidArgumentException
1794
-     * @throws InvalidInterfaceException
1795
-     * @throws InvalidDataTypeException
1796
-     * @throws EE_Error
1797
-     * @return int , 1 on a successful update, the ID of the new entry on insert; 0 on failure or if the model object
1798
-     *                                 isn't allowed to persist (as determined by EE_Base_Class::allow_persist())
1799
-     * @throws ReflectionException
1800
-     * @throws ReflectionException
1801
-     * @throws ReflectionException
1802
-     */
1803
-    public function save($set_cols_n_values = array())
1804
-    {
1805
-        $model = $this->get_model();
1806
-        /**
1807
-         * Filters the fields we're about to save on the model object
1808
-         *
1809
-         * @param array         $set_cols_n_values
1810
-         * @param EE_Base_Class $model_object
1811
-         */
1812
-        $set_cols_n_values = (array) apply_filters(
1813
-            'FHEE__EE_Base_Class__save__set_cols_n_values',
1814
-            $set_cols_n_values,
1815
-            $this
1816
-        );
1817
-        // set attributes as provided in $set_cols_n_values
1818
-        foreach ($set_cols_n_values as $column => $value) {
1819
-            $this->set($column, $value);
1820
-        }
1821
-        // no changes ? then don't do anything
1822
-        if (! $this->_has_changes && $this->ID() && $model->get_primary_key_field()->is_auto_increment()) {
1823
-            return 0;
1824
-        }
1825
-        /**
1826
-         * Saving a model object.
1827
-         * Before we perform a save, this action is fired.
1828
-         *
1829
-         * @param EE_Base_Class $model_object the model object about to be saved.
1830
-         */
1831
-        do_action('AHEE__EE_Base_Class__save__begin', $this);
1832
-        if (! $this->allow_persist()) {
1833
-            return 0;
1834
-        }
1835
-        // now get current attribute values
1836
-        $save_cols_n_values = $this->_fields;
1837
-        // if the object already has an ID, update it. Otherwise, insert it
1838
-        // also: change the assumption about values passed to the model NOT being prepare dby the model object.
1839
-        // They have been
1840
-        $old_assumption_concerning_value_preparation = $model
1841
-            ->get_assumption_concerning_values_already_prepared_by_model_object();
1842
-        $model->assume_values_already_prepared_by_model_object(true);
1843
-        // does this model have an autoincrement PK?
1844
-        if ($model->has_primary_key_field()) {
1845
-            if ($model->get_primary_key_field()->is_auto_increment()) {
1846
-                // ok check if it's set, if so: update; if not, insert
1847
-                if (! empty($save_cols_n_values[ $model->primary_key_name() ])) {
1848
-                    $results = $model->update_by_ID($save_cols_n_values, $this->ID());
1849
-                } else {
1850
-                    unset($save_cols_n_values[ $model->primary_key_name() ]);
1851
-                    $results = $model->insert($save_cols_n_values);
1852
-                    if ($results) {
1853
-                        // if successful, set the primary key
1854
-                        // but don't use the normal SET method, because it will check if
1855
-                        // an item with the same ID exists in the mapper & db, then
1856
-                        // will find it in the db (because we just added it) and THAT object
1857
-                        // will get added to the mapper before we can add this one!
1858
-                        // but if we just avoid using the SET method, all that headache can be avoided
1859
-                        $pk_field_name = $model->primary_key_name();
1860
-                        $this->_fields[ $pk_field_name ] = $results;
1861
-                        $this->_clear_cached_property($pk_field_name);
1862
-                        $model->add_to_entity_map($this);
1863
-                        $this->_update_cached_related_model_objs_fks();
1864
-                    }
1865
-                }
1866
-            } else {// PK is NOT auto-increment
1867
-                // so check if one like it already exists in the db
1868
-                if ($model->exists_by_ID($this->ID())) {
1869
-                    if (WP_DEBUG && ! $this->in_entity_map()) {
1870
-                        throw new EE_Error(
1871
-                            sprintf(
1872
-                                esc_html__(
1873
-                                    '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',
1874
-                                    'event_espresso'
1875
-                                ),
1876
-                                get_class($this),
1877
-                                get_class($model) . '::instance()->add_to_entity_map()',
1878
-                                get_class($model) . '::instance()->get_one_by_ID()',
1879
-                                '<br />'
1880
-                            )
1881
-                        );
1882
-                    }
1883
-                    $results = $model->update_by_ID($save_cols_n_values, $this->ID());
1884
-                } else {
1885
-                    $results = $model->insert($save_cols_n_values);
1886
-                    $this->_update_cached_related_model_objs_fks();
1887
-                }
1888
-            }
1889
-        } else {// there is NO primary key
1890
-            $already_in_db = false;
1891
-            foreach ($model->unique_indexes() as $index) {
1892
-                $uniqueness_where_params = array_intersect_key($save_cols_n_values, $index->fields());
1893
-                if ($model->exists(array($uniqueness_where_params))) {
1894
-                    $already_in_db = true;
1895
-                }
1896
-            }
1897
-            if ($already_in_db) {
1898
-                $combined_pk_fields_n_values = array_intersect_key(
1899
-                    $save_cols_n_values,
1900
-                    $model->get_combined_primary_key_fields()
1901
-                );
1902
-                $results = $model->update(
1903
-                    $save_cols_n_values,
1904
-                    $combined_pk_fields_n_values
1905
-                );
1906
-            } else {
1907
-                $results = $model->insert($save_cols_n_values);
1908
-            }
1909
-        }
1910
-        // restore the old assumption about values being prepared by the model object
1911
-        $model->assume_values_already_prepared_by_model_object(
1912
-            $old_assumption_concerning_value_preparation
1913
-        );
1914
-        /**
1915
-         * After saving the model object this action is called
1916
-         *
1917
-         * @param EE_Base_Class $model_object which was just saved
1918
-         * @param boolean|int   $results      if it were updated, TRUE or FALSE; if it were newly inserted
1919
-         *                                    the new ID (or 0 if an error occurred and it wasn't updated)
1920
-         */
1921
-        do_action('AHEE__EE_Base_Class__save__end', $this, $results);
1922
-        $this->_has_changes = false;
1923
-        return $results;
1924
-    }
1925
-
1926
-
1927
-    /**
1928
-     * Updates the foreign key on related models objects pointing to this to have this model object's ID
1929
-     * as their foreign key.  If the cached related model objects already exist in the db, saves them (so that the DB
1930
-     * is consistent) Especially useful in case we JUST added this model object ot the database and we want to let its
1931
-     * cached relations with foreign keys to it know about that change. Eg: we've created a transaction but haven't
1932
-     * 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
1933
-     * transaction. Now, when we save the transaction, the registration's TXN_ID will be automatically updated, whether
1934
-     * or not they exist in the DB (if they do, their DB records will be automatically updated)
1935
-     *
1936
-     * @return void
1937
-     * @throws ReflectionException
1938
-     * @throws InvalidArgumentException
1939
-     * @throws InvalidInterfaceException
1940
-     * @throws InvalidDataTypeException
1941
-     * @throws EE_Error
1942
-     */
1943
-    protected function _update_cached_related_model_objs_fks()
1944
-    {
1945
-        $model = $this->get_model();
1946
-        foreach ($model->relation_settings() as $relation_name => $relation_obj) {
1947
-            if ($relation_obj instanceof EE_Has_Many_Relation) {
1948
-                foreach ($this->get_all_from_cache($relation_name) as $related_model_obj_in_cache) {
1949
-                    $fk_to_this = $related_model_obj_in_cache->get_model()->get_foreign_key_to(
1950
-                        $model->get_this_model_name()
1951
-                    );
1952
-                    $related_model_obj_in_cache->set($fk_to_this->get_name(), $this->ID());
1953
-                    if ($related_model_obj_in_cache->ID()) {
1954
-                        $related_model_obj_in_cache->save();
1955
-                    }
1956
-                }
1957
-            }
1958
-        }
1959
-    }
1960
-
1961
-
1962
-    /**
1963
-     * Saves this model object and its NEW cached relations to the database.
1964
-     * (Meaning, for now, IT DOES NOT WORK if the cached items already exist in the DB.
1965
-     * In order for that to work, we would need to mark model objects as dirty/clean...
1966
-     * because otherwise, there's a potential for infinite looping of saving
1967
-     * Saves the cached related model objects, and ensures the relation between them
1968
-     * and this object and properly setup
1969
-     *
1970
-     * @return int ID of new model object on save; 0 on failure+
1971
-     * @throws ReflectionException
1972
-     * @throws InvalidArgumentException
1973
-     * @throws InvalidInterfaceException
1974
-     * @throws InvalidDataTypeException
1975
-     * @throws EE_Error
1976
-     */
1977
-    public function save_new_cached_related_model_objs()
1978
-    {
1979
-        // make sure this has been saved
1980
-        if (! $this->ID()) {
1981
-            $id = $this->save();
1982
-        } else {
1983
-            $id = $this->ID();
1984
-        }
1985
-        // now save all the NEW cached model objects  (ie they don't exist in the DB)
1986
-        foreach ($this->get_model()->relation_settings() as $relationName => $relationObj) {
1987
-            if ($this->_model_relations[ $relationName ]) {
1988
-                // is this a relation where we should expect just ONE related object (ie, EE_Belongs_To_relation)
1989
-                // or MANY related objects (ie, EE_HABTM_Relation or EE_Has_Many_Relation)?
1990
-                /* @var $related_model_obj EE_Base_Class */
1991
-                if ($relationObj instanceof EE_Belongs_To_Relation) {
1992
-                    // add a relation to that relation type (which saves the appropriate thing in the process)
1993
-                    // but ONLY if it DOES NOT exist in the DB
1994
-                    $related_model_obj = $this->_model_relations[ $relationName ];
1995
-                    // if( ! $related_model_obj->ID()){
1996
-                    $this->_add_relation_to($related_model_obj, $relationName);
1997
-                    $related_model_obj->save_new_cached_related_model_objs();
1998
-                    // }
1999
-                } else {
2000
-                    foreach ($this->_model_relations[ $relationName ] as $related_model_obj) {
2001
-                        // add a relation to that relation type (which saves the appropriate thing in the process)
2002
-                        // but ONLY if it DOES NOT exist in the DB
2003
-                        // if( ! $related_model_obj->ID()){
2004
-                        $this->_add_relation_to($related_model_obj, $relationName);
2005
-                        $related_model_obj->save_new_cached_related_model_objs();
2006
-                        // }
2007
-                    }
2008
-                }
2009
-            }
2010
-        }
2011
-        return $id;
2012
-    }
2013
-
2014
-
2015
-    /**
2016
-     * for getting a model while instantiated.
2017
-     *
2018
-     * @return EEM_Base | EEM_CPT_Base
2019
-     * @throws ReflectionException
2020
-     * @throws InvalidArgumentException
2021
-     * @throws InvalidInterfaceException
2022
-     * @throws InvalidDataTypeException
2023
-     * @throws EE_Error
2024
-     */
2025
-    public function get_model()
2026
-    {
2027
-        if (! $this->_model) {
2028
-            $modelName = self::_get_model_classname(get_class($this));
2029
-            $this->_model = self::_get_model_instance_with_name($modelName, $this->_timezone);
2030
-        } else {
2031
-            $this->_model->set_timezone($this->_timezone);
2032
-        }
2033
-        return $this->_model;
2034
-    }
2035
-
2036
-
2037
-    /**
2038
-     * @param $props_n_values
2039
-     * @param $classname
2040
-     * @return mixed bool|EE_Base_Class|EEM_CPT_Base
2041
-     * @throws ReflectionException
2042
-     * @throws InvalidArgumentException
2043
-     * @throws InvalidInterfaceException
2044
-     * @throws InvalidDataTypeException
2045
-     * @throws EE_Error
2046
-     */
2047
-    protected static function _get_object_from_entity_mapper($props_n_values, $classname)
2048
-    {
2049
-        // TODO: will not work for Term_Relationships because they have no PK!
2050
-        $primary_id_ref = self::_get_primary_key_name($classname);
2051
-        if (array_key_exists($primary_id_ref, $props_n_values)
2052
-            && ! empty($props_n_values[ $primary_id_ref ])
2053
-        ) {
2054
-            $id = $props_n_values[ $primary_id_ref ];
2055
-            return self::_get_model($classname)->get_from_entity_map($id);
2056
-        }
2057
-        return false;
2058
-    }
2059
-
2060
-
2061
-    /**
2062
-     * This is called by child static "new_instance" method and we'll check to see if there is an existing db entry for
2063
-     * the primary key (if present in incoming values). If there is a key in the incoming array that matches the
2064
-     * 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
2065
-     * we return false.
2066
-     *
2067
-     * @param  array  $props_n_values   incoming array of properties and their values
2068
-     * @param  string $classname        the classname of the child class
2069
-     * @param null    $timezone
2070
-     * @param array   $date_formats     incoming date_formats in an array where the first value is the
2071
-     *                                  date_format and the second value is the time format
2072
-     * @return mixed (EE_Base_Class|bool)
2073
-     * @throws InvalidArgumentException
2074
-     * @throws InvalidInterfaceException
2075
-     * @throws InvalidDataTypeException
2076
-     * @throws EE_Error
2077
-     * @throws ReflectionException
2078
-     * @throws ReflectionException
2079
-     * @throws ReflectionException
2080
-     */
2081
-    protected static function _check_for_object($props_n_values, $classname, $timezone = null, $date_formats = array())
2082
-    {
2083
-        $existing = null;
2084
-        $model = self::_get_model($classname, $timezone);
2085
-        if ($model->has_primary_key_field()) {
2086
-            $primary_id_ref = self::_get_primary_key_name($classname);
2087
-            if (array_key_exists($primary_id_ref, $props_n_values)
2088
-                && ! empty($props_n_values[ $primary_id_ref ])
2089
-            ) {
2090
-                $existing = $model->get_one_by_ID(
2091
-                    $props_n_values[ $primary_id_ref ]
2092
-                );
2093
-            }
2094
-        } elseif ($model->has_all_combined_primary_key_fields($props_n_values)) {
2095
-            // no primary key on this model, but there's still a matching item in the DB
2096
-            $existing = self::_get_model($classname, $timezone)->get_one_by_ID(
2097
-                self::_get_model($classname, $timezone)
2098
-                    ->get_index_primary_key_string($props_n_values)
2099
-            );
2100
-        }
2101
-        if ($existing) {
2102
-            // set date formats if present before setting values
2103
-            if (! empty($date_formats) && is_array($date_formats)) {
2104
-                $existing->set_date_format($date_formats[0]);
2105
-                $existing->set_time_format($date_formats[1]);
2106
-            } else {
2107
-                // set default formats for date and time
2108
-                $existing->set_date_format(get_option('date_format'));
2109
-                $existing->set_time_format(get_option('time_format'));
2110
-            }
2111
-            foreach ($props_n_values as $property => $field_value) {
2112
-                $existing->set($property, $field_value);
2113
-            }
2114
-            return $existing;
2115
-        }
2116
-        return false;
2117
-    }
2118
-
2119
-
2120
-    /**
2121
-     * Gets the EEM_*_Model for this class
2122
-     *
2123
-     * @access public now, as this is more convenient
2124
-     * @param      $classname
2125
-     * @param null $timezone
2126
-     * @throws ReflectionException
2127
-     * @throws InvalidArgumentException
2128
-     * @throws InvalidInterfaceException
2129
-     * @throws InvalidDataTypeException
2130
-     * @throws EE_Error
2131
-     * @return EEM_Base
2132
-     */
2133
-    protected static function _get_model($classname, $timezone = null)
2134
-    {
2135
-        // find model for this class
2136
-        if (! $classname) {
2137
-            throw new EE_Error(
2138
-                sprintf(
2139
-                    esc_html__(
2140
-                        'What were you thinking calling _get_model(%s)?? You need to specify the class name',
2141
-                        'event_espresso'
2142
-                    ),
2143
-                    $classname
2144
-                )
2145
-            );
2146
-        }
2147
-        $modelName = self::_get_model_classname($classname);
2148
-        return self::_get_model_instance_with_name($modelName, $timezone);
2149
-    }
2150
-
2151
-
2152
-    /**
2153
-     * Gets the model instance (eg instance of EEM_Attendee) given its classname (eg EE_Attendee)
2154
-     *
2155
-     * @param string $model_classname
2156
-     * @param null   $timezone
2157
-     * @return EEM_Base
2158
-     * @throws ReflectionException
2159
-     * @throws InvalidArgumentException
2160
-     * @throws InvalidInterfaceException
2161
-     * @throws InvalidDataTypeException
2162
-     * @throws EE_Error
2163
-     */
2164
-    protected static function _get_model_instance_with_name($model_classname, $timezone = null)
2165
-    {
2166
-        $model_classname = str_replace('EEM_', '', $model_classname);
2167
-        $model = EE_Registry::instance()->load_model($model_classname);
2168
-        $model->set_timezone($timezone);
2169
-        return $model;
2170
-    }
2171
-
2172
-
2173
-    /**
2174
-     * If a model name is provided (eg Registration), gets the model classname for that model.
2175
-     * Also works if a model class's classname is provided (eg EE_Registration).
2176
-     *
2177
-     * @param null $model_name
2178
-     * @return string like EEM_Attendee
2179
-     */
2180
-    private static function _get_model_classname($model_name = null)
2181
-    {
2182
-        if (strpos($model_name, 'EE_') === 0) {
2183
-            $model_classname = str_replace('EE_', 'EEM_', $model_name);
2184
-        } else {
2185
-            $model_classname = 'EEM_' . $model_name;
2186
-        }
2187
-        return $model_classname;
2188
-    }
2189
-
2190
-
2191
-    /**
2192
-     * returns the name of the primary key attribute
2193
-     *
2194
-     * @param null $classname
2195
-     * @throws ReflectionException
2196
-     * @throws InvalidArgumentException
2197
-     * @throws InvalidInterfaceException
2198
-     * @throws InvalidDataTypeException
2199
-     * @throws EE_Error
2200
-     * @return string
2201
-     */
2202
-    protected static function _get_primary_key_name($classname = null)
2203
-    {
2204
-        if (! $classname) {
2205
-            throw new EE_Error(
2206
-                sprintf(
2207
-                    esc_html__('What were you thinking calling _get_primary_key_name(%s)', 'event_espresso'),
2208
-                    $classname
2209
-                )
2210
-            );
2211
-        }
2212
-        return self::_get_model($classname)->get_primary_key_field()->get_name();
2213
-    }
2214
-
2215
-
2216
-    /**
2217
-     * Gets the value of the primary key.
2218
-     * If the object hasn't yet been saved, it should be whatever the model field's default was
2219
-     * (eg, if this were the EE_Event class, look at the primary key field on EEM_Event and see what its default value
2220
-     * is. Usually defaults for integer primary keys are 0; string primary keys are usually NULL).
2221
-     *
2222
-     * @return mixed, if the primary key is of type INT it'll be an int. Otherwise it could be a string
2223
-     * @throws ReflectionException
2224
-     * @throws InvalidArgumentException
2225
-     * @throws InvalidInterfaceException
2226
-     * @throws InvalidDataTypeException
2227
-     * @throws EE_Error
2228
-     */
2229
-    public function ID()
2230
-    {
2231
-        $model = $this->get_model();
2232
-        // now that we know the name of the variable, use a variable variable to get its value and return its
2233
-        if ($model->has_primary_key_field()) {
2234
-            return $this->_fields[ $model->primary_key_name() ];
2235
-        }
2236
-        return $model->get_index_primary_key_string($this->_fields);
2237
-    }
2238
-
2239
-
2240
-    /**
2241
-     * Adds a relationship to the specified EE_Base_Class object, given the relationship's name. Eg, if the current
2242
-     * model is related to a group of events, the $relationName should be 'Event', and should be a key in the EE
2243
-     * Model's $_model_relations array. If this model object doesn't exist in the DB, just caches the related thing
2244
-     *
2245
-     * @param mixed  $otherObjectModelObjectOrID       EE_Base_Class or the ID of the other object
2246
-     * @param string $relationName                     eg 'Events','Question',etc.
2247
-     *                                                 an attendee to a group, you also want to specify which role they
2248
-     *                                                 will have in that group. So you would use this parameter to
2249
-     *                                                 specify array('role-column-name'=>'role-id')
2250
-     * @param array  $extra_join_model_fields_n_values You can optionally include an array of key=>value pairs that
2251
-     *                                                 allow you to further constrict the relation to being added.
2252
-     *                                                 However, keep in mind that the columns (keys) given must match a
2253
-     *                                                 column on the JOIN table and currently only the HABTM models
2254
-     *                                                 accept these additional conditions.  Also remember that if an
2255
-     *                                                 exact match isn't found for these extra cols/val pairs, then a
2256
-     *                                                 NEW row is created in the join table.
2257
-     * @param null   $cache_id
2258
-     * @throws ReflectionException
2259
-     * @throws InvalidArgumentException
2260
-     * @throws InvalidInterfaceException
2261
-     * @throws InvalidDataTypeException
2262
-     * @throws EE_Error
2263
-     * @return EE_Base_Class the object the relation was added to
2264
-     */
2265
-    public function _add_relation_to(
2266
-        $otherObjectModelObjectOrID,
2267
-        $relationName,
2268
-        $extra_join_model_fields_n_values = array(),
2269
-        $cache_id = null
2270
-    ) {
2271
-        $model = $this->get_model();
2272
-        // if this thing exists in the DB, save the relation to the DB
2273
-        if ($this->ID()) {
2274
-            $otherObject = $model->add_relationship_to(
2275
-                $this,
2276
-                $otherObjectModelObjectOrID,
2277
-                $relationName,
2278
-                $extra_join_model_fields_n_values
2279
-            );
2280
-            // clear cache so future get_many_related and get_first_related() return new results.
2281
-            $this->clear_cache($relationName, $otherObject, true);
2282
-            if ($otherObject instanceof EE_Base_Class) {
2283
-                $otherObject->clear_cache($model->get_this_model_name(), $this);
2284
-            }
2285
-        } else {
2286
-            // this thing doesn't exist in the DB,  so just cache it
2287
-            if (! $otherObjectModelObjectOrID instanceof EE_Base_Class) {
2288
-                throw new EE_Error(
2289
-                    sprintf(
2290
-                        esc_html__(
2291
-                            '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',
2292
-                            'event_espresso'
2293
-                        ),
2294
-                        $otherObjectModelObjectOrID,
2295
-                        get_class($this)
2296
-                    )
2297
-                );
2298
-            }
2299
-            $otherObject = $otherObjectModelObjectOrID;
2300
-            $this->cache($relationName, $otherObjectModelObjectOrID, $cache_id);
2301
-        }
2302
-        if ($otherObject instanceof EE_Base_Class) {
2303
-            // fix the reciprocal relation too
2304
-            if ($otherObject->ID()) {
2305
-                // its saved so assumed relations exist in the DB, so we can just
2306
-                // clear the cache so future queries use the updated info in the DB
2307
-                $otherObject->clear_cache(
2308
-                    $model->get_this_model_name(),
2309
-                    null,
2310
-                    true
2311
-                );
2312
-            } else {
2313
-                // it's not saved, so it caches relations like this
2314
-                $otherObject->cache($model->get_this_model_name(), $this);
2315
-            }
2316
-        }
2317
-        return $otherObject;
2318
-    }
2319
-
2320
-
2321
-    /**
2322
-     * Removes a relationship to the specified EE_Base_Class object, given the relationships' name. Eg, if the current
2323
-     * model is related to a group of events, the $relationName should be 'Events', and should be a key in the EE
2324
-     * Model's $_model_relations array. If this model object doesn't exist in the DB, just removes the related thing
2325
-     * from the cache
2326
-     *
2327
-     * @param mixed  $otherObjectModelObjectOrID
2328
-     *                EE_Base_Class or the ID of the other object, OR an array key into the cache if this isn't saved
2329
-     *                to the DB yet
2330
-     * @param string $relationName
2331
-     * @param array  $where_query
2332
-     *                You can optionally include an array of key=>value pairs that allow you to further constrict the
2333
-     *                relation to being added. However, keep in mind that the columns (keys) given must match a column
2334
-     *                on the JOIN table and currently only the HABTM models accept these additional conditions. Also
2335
-     *                remember that if an exact match isn't found for these extra cols/val pairs, then no row is
2336
-     *                deleted.
2337
-     * @return EE_Base_Class the relation was removed from
2338
-     * @throws ReflectionException
2339
-     * @throws InvalidArgumentException
2340
-     * @throws InvalidInterfaceException
2341
-     * @throws InvalidDataTypeException
2342
-     * @throws EE_Error
2343
-     */
2344
-    public function _remove_relation_to($otherObjectModelObjectOrID, $relationName, $where_query = array())
2345
-    {
2346
-        if ($this->ID()) {
2347
-            // if this exists in the DB, save the relation change to the DB too
2348
-            $otherObject = $this->get_model()->remove_relationship_to(
2349
-                $this,
2350
-                $otherObjectModelObjectOrID,
2351
-                $relationName,
2352
-                $where_query
2353
-            );
2354
-            $this->clear_cache(
2355
-                $relationName,
2356
-                $otherObject
2357
-            );
2358
-        } else {
2359
-            // this doesn't exist in the DB, just remove it from the cache
2360
-            $otherObject = $this->clear_cache(
2361
-                $relationName,
2362
-                $otherObjectModelObjectOrID
2363
-            );
2364
-        }
2365
-        if ($otherObject instanceof EE_Base_Class) {
2366
-            $otherObject->clear_cache(
2367
-                $this->get_model()->get_this_model_name(),
2368
-                $this
2369
-            );
2370
-        }
2371
-        return $otherObject;
2372
-    }
2373
-
2374
-
2375
-    /**
2376
-     * Removes ALL the related things for the $relationName.
2377
-     *
2378
-     * @param string $relationName
2379
-     * @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
2380
-     * @return EE_Base_Class
2381
-     * @throws ReflectionException
2382
-     * @throws InvalidArgumentException
2383
-     * @throws InvalidInterfaceException
2384
-     * @throws InvalidDataTypeException
2385
-     * @throws EE_Error
2386
-     */
2387
-    public function _remove_relations($relationName, $where_query_params = array())
2388
-    {
2389
-        if ($this->ID()) {
2390
-            // if this exists in the DB, save the relation change to the DB too
2391
-            $otherObjects = $this->get_model()->remove_relations(
2392
-                $this,
2393
-                $relationName,
2394
-                $where_query_params
2395
-            );
2396
-            $this->clear_cache(
2397
-                $relationName,
2398
-                null,
2399
-                true
2400
-            );
2401
-        } else {
2402
-            // this doesn't exist in the DB, just remove it from the cache
2403
-            $otherObjects = $this->clear_cache(
2404
-                $relationName,
2405
-                null,
2406
-                true
2407
-            );
2408
-        }
2409
-        if (is_array($otherObjects)) {
2410
-            foreach ($otherObjects as $otherObject) {
2411
-                $otherObject->clear_cache(
2412
-                    $this->get_model()->get_this_model_name(),
2413
-                    $this
2414
-                );
2415
-            }
2416
-        }
2417
-        return $otherObjects;
2418
-    }
2419
-
2420
-
2421
-    /**
2422
-     * Gets all the related model objects of the specified type. Eg, if the current class if
2423
-     * EE_Event, you could call $this->get_many_related('Registration') to get an array of all the
2424
-     * EE_Registration objects which related to this event. Note: by default, we remove the "default query params"
2425
-     * because we want to get even deleted items etc.
2426
-     *
2427
-     * @param string $relationName key in the model's _model_relations array
2428
-     * @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
2429
-     * @return EE_Base_Class[]     Results not necessarily indexed by IDs, because some results might not have primary
2430
-     *                             keys or might not be saved yet. Consider using EEM_Base::get_IDs() on these
2431
-     *                             results if you want IDs
2432
-     * @throws ReflectionException
2433
-     * @throws InvalidArgumentException
2434
-     * @throws InvalidInterfaceException
2435
-     * @throws InvalidDataTypeException
2436
-     * @throws EE_Error
2437
-     */
2438
-    public function get_many_related($relationName, $query_params = array())
2439
-    {
2440
-        if ($this->ID()) {
2441
-            // this exists in the DB, so get the related things from either the cache or the DB
2442
-            // if there are query parameters, forget about caching the related model objects.
2443
-            if ($query_params) {
2444
-                $related_model_objects = $this->get_model()->get_all_related(
2445
-                    $this,
2446
-                    $relationName,
2447
-                    $query_params
2448
-                );
2449
-            } else {
2450
-                // did we already cache the result of this query?
2451
-                $cached_results = $this->get_all_from_cache($relationName);
2452
-                if (! $cached_results) {
2453
-                    $related_model_objects = $this->get_model()->get_all_related(
2454
-                        $this,
2455
-                        $relationName,
2456
-                        $query_params
2457
-                    );
2458
-                    // if no query parameters were passed, then we got all the related model objects
2459
-                    // for that relation. We can cache them then.
2460
-                    foreach ($related_model_objects as $related_model_object) {
2461
-                        $this->cache($relationName, $related_model_object);
2462
-                    }
2463
-                } else {
2464
-                    $related_model_objects = $cached_results;
2465
-                }
2466
-            }
2467
-        } else {
2468
-            // this doesn't exist in the DB, so just get the related things from the cache
2469
-            $related_model_objects = $this->get_all_from_cache($relationName);
2470
-        }
2471
-        return $related_model_objects;
2472
-    }
2473
-
2474
-
2475
-    /**
2476
-     * Instead of getting the related model objects, simply counts them. Ignores default_where_conditions by default,
2477
-     * unless otherwise specified in the $query_params
2478
-     *
2479
-     * @param string $relation_name  model_name like 'Event', or 'Registration'
2480
-     * @param array  $query_params   @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2481
-     * @param string $field_to_count name of field to count by. By default, uses primary key
2482
-     * @param bool   $distinct       if we want to only count the distinct values for the column then you can trigger
2483
-     *                               that by the setting $distinct to TRUE;
2484
-     * @return int
2485
-     * @throws ReflectionException
2486
-     * @throws InvalidArgumentException
2487
-     * @throws InvalidInterfaceException
2488
-     * @throws InvalidDataTypeException
2489
-     * @throws EE_Error
2490
-     */
2491
-    public function count_related($relation_name, $query_params = array(), $field_to_count = null, $distinct = false)
2492
-    {
2493
-        return $this->get_model()->count_related(
2494
-            $this,
2495
-            $relation_name,
2496
-            $query_params,
2497
-            $field_to_count,
2498
-            $distinct
2499
-        );
2500
-    }
2501
-
2502
-
2503
-    /**
2504
-     * Instead of getting the related model objects, simply sums up the values of the specified field.
2505
-     * Note: ignores default_where_conditions by default, unless otherwise specified in the $query_params
2506
-     *
2507
-     * @param string $relation_name model_name like 'Event', or 'Registration'
2508
-     * @param array  $query_params  @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2509
-     * @param string $field_to_sum  name of field to count by.
2510
-     *                              By default, uses primary key
2511
-     *                              (which doesn't make much sense, so you should probably change it)
2512
-     * @return int
2513
-     * @throws ReflectionException
2514
-     * @throws InvalidArgumentException
2515
-     * @throws InvalidInterfaceException
2516
-     * @throws InvalidDataTypeException
2517
-     * @throws EE_Error
2518
-     */
2519
-    public function sum_related($relation_name, $query_params = array(), $field_to_sum = null)
2520
-    {
2521
-        return $this->get_model()->sum_related(
2522
-            $this,
2523
-            $relation_name,
2524
-            $query_params,
2525
-            $field_to_sum
2526
-        );
2527
-    }
2528
-
2529
-
2530
-    /**
2531
-     * Gets the first (ie, one) related model object of the specified type.
2532
-     *
2533
-     * @param string $relationName key in the model's _model_relations array
2534
-     * @param array  $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2535
-     * @return EE_Base_Class (not an array, a single object)
2536
-     * @throws ReflectionException
2537
-     * @throws InvalidArgumentException
2538
-     * @throws InvalidInterfaceException
2539
-     * @throws InvalidDataTypeException
2540
-     * @throws EE_Error
2541
-     */
2542
-    public function get_first_related($relationName, $query_params = array())
2543
-    {
2544
-        $model = $this->get_model();
2545
-        if ($this->ID()) {// this exists in the DB, get from the cache OR the DB
2546
-            // if they've provided some query parameters, don't bother trying to cache the result
2547
-            // also make sure we're not caching the result of get_first_related
2548
-            // on a relation which should have an array of objects (because the cache might have an array of objects)
2549
-            if ($query_params
2550
-                || ! $model->related_settings_for($relationName)
2551
-                     instanceof
2552
-                     EE_Belongs_To_Relation
2553
-            ) {
2554
-                $related_model_object = $model->get_first_related(
2555
-                    $this,
2556
-                    $relationName,
2557
-                    $query_params
2558
-                );
2559
-            } else {
2560
-                // first, check if we've already cached the result of this query
2561
-                $cached_result = $this->get_one_from_cache($relationName);
2562
-                if (! $cached_result) {
2563
-                    $related_model_object = $model->get_first_related(
2564
-                        $this,
2565
-                        $relationName,
2566
-                        $query_params
2567
-                    );
2568
-                    $this->cache($relationName, $related_model_object);
2569
-                } else {
2570
-                    $related_model_object = $cached_result;
2571
-                }
2572
-            }
2573
-        } else {
2574
-            $related_model_object = null;
2575
-            // this doesn't exist in the Db,
2576
-            // but maybe the relation is of type belongs to, and so the related thing might
2577
-            if ($model->related_settings_for($relationName) instanceof EE_Belongs_To_Relation) {
2578
-                $related_model_object = $model->get_first_related(
2579
-                    $this,
2580
-                    $relationName,
2581
-                    $query_params
2582
-                );
2583
-            }
2584
-            // this doesn't exist in the DB and apparently the thing it belongs to doesn't either,
2585
-            // just get what's cached on this object
2586
-            if (! $related_model_object) {
2587
-                $related_model_object = $this->get_one_from_cache($relationName);
2588
-            }
2589
-        }
2590
-        return $related_model_object;
2591
-    }
2592
-
2593
-
2594
-    /**
2595
-     * Does a delete on all related objects of type $relationName and removes
2596
-     * the current model object's relation to them. If they can't be deleted (because
2597
-     * of blocking related model objects) does nothing. If the related model objects are
2598
-     * soft-deletable, they will be soft-deleted regardless of related blocking model objects.
2599
-     * If this model object doesn't exist yet in the DB, just removes its related things
2600
-     *
2601
-     * @param string $relationName
2602
-     * @param array  $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2603
-     * @return int how many deleted
2604
-     * @throws ReflectionException
2605
-     * @throws InvalidArgumentException
2606
-     * @throws InvalidInterfaceException
2607
-     * @throws InvalidDataTypeException
2608
-     * @throws EE_Error
2609
-     */
2610
-    public function delete_related($relationName, $query_params = array())
2611
-    {
2612
-        if ($this->ID()) {
2613
-            $count = $this->get_model()->delete_related(
2614
-                $this,
2615
-                $relationName,
2616
-                $query_params
2617
-            );
2618
-        } else {
2619
-            $count = count($this->get_all_from_cache($relationName));
2620
-            $this->clear_cache($relationName, null, true);
2621
-        }
2622
-        return $count;
2623
-    }
2624
-
2625
-
2626
-    /**
2627
-     * Does a hard delete (ie, removes the DB row) 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) just does a soft delete on it instead, if possible.
2630
-     * If the related thing isn't a soft-deletable model object, this function is identical
2631
-     * to delete_related(). If this model object doesn't exist in the DB, just remove 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 (including those soft deleted)
2636
-     * @throws ReflectionException
2637
-     * @throws InvalidArgumentException
2638
-     * @throws InvalidInterfaceException
2639
-     * @throws InvalidDataTypeException
2640
-     * @throws EE_Error
2641
-     */
2642
-    public function delete_related_permanently($relationName, $query_params = array())
2643
-    {
2644
-        if ($this->ID()) {
2645
-            $count = $this->get_model()->delete_related_permanently(
2646
-                $this,
2647
-                $relationName,
2648
-                $query_params
2649
-            );
2650
-        } else {
2651
-            $count = count($this->get_all_from_cache($relationName));
2652
-        }
2653
-        $this->clear_cache($relationName, null, true);
2654
-        return $count;
2655
-    }
2656
-
2657
-
2658
-    /**
2659
-     * is_set
2660
-     * Just a simple utility function children can use for checking if property exists
2661
-     *
2662
-     * @access  public
2663
-     * @param  string $field_name property to check
2664
-     * @return bool                              TRUE if existing,FALSE if not.
2665
-     */
2666
-    public function is_set($field_name)
2667
-    {
2668
-        return isset($this->_fields[ $field_name ]);
2669
-    }
2670
-
2671
-
2672
-    /**
2673
-     * Just a simple utility function children can use for checking if property (or properties) exists and throwing an
2674
-     * EE_Error exception if they don't
2675
-     *
2676
-     * @param  mixed (string|array) $properties properties to check
2677
-     * @throws EE_Error
2678
-     * @return bool                              TRUE if existing, throw EE_Error if not.
2679
-     */
2680
-    protected function _property_exists($properties)
2681
-    {
2682
-        foreach ((array) $properties as $property_name) {
2683
-            // first make sure this property exists
2684
-            if (! $this->_fields[ $property_name ]) {
2685
-                throw new EE_Error(
2686
-                    sprintf(
2687
-                        esc_html__(
2688
-                            'Trying to retrieve a non-existent property (%s).  Double check the spelling please',
2689
-                            'event_espresso'
2690
-                        ),
2691
-                        $property_name
2692
-                    )
2693
-                );
2694
-            }
2695
-        }
2696
-        return true;
2697
-    }
2698
-
2699
-
2700
-    /**
2701
-     * This simply returns an array of model fields for this object
2702
-     *
2703
-     * @return array
2704
-     * @throws ReflectionException
2705
-     * @throws InvalidArgumentException
2706
-     * @throws InvalidInterfaceException
2707
-     * @throws InvalidDataTypeException
2708
-     * @throws EE_Error
2709
-     */
2710
-    public function model_field_array()
2711
-    {
2712
-        $fields = $this->get_model()->field_settings(false);
2713
-        $properties = array();
2714
-        // remove prepended underscore
2715
-        foreach ($fields as $field_name => $settings) {
2716
-            $properties[ $field_name ] = $this->get($field_name);
2717
-        }
2718
-        return $properties;
2719
-    }
2720
-
2721
-
2722
-    /**
2723
-     * Very handy general function to allow for plugins to extend any child of EE_Base_Class.
2724
-     * If a method is called on a child of EE_Base_Class that doesn't exist, this function is called
2725
-     * (http://www.garfieldtech.com/blog/php-magic-call) and passed the method's name and arguments.
2726
-     * Instead of requiring a plugin to extend the EE_Base_Class
2727
-     * (which works fine is there's only 1 plugin, but when will that happen?)
2728
-     * they can add a hook onto 'filters_hook_espresso__{className}__{methodName}'
2729
-     * (eg, filters_hook_espresso__EE_Answer__my_great_function)
2730
-     * and accepts 2 arguments: the object on which the function was called,
2731
-     * and an array of the original arguments passed to the function.
2732
-     * Whatever their callback function returns will be returned by this function.
2733
-     * Example: in functions.php (or in a plugin):
2734
-     *      add_filter('FHEE__EE_Answer__my_callback','my_callback',10,3);
2735
-     *      function my_callback($previousReturnValue,EE_Base_Class $object,$argsArray){
2736
-     *          $returnString= "you called my_callback! and passed args:".implode(",",$argsArray);
2737
-     *          return $previousReturnValue.$returnString;
2738
-     *      }
2739
-     * require('EE_Answer.class.php');
2740
-     * $answer= EE_Answer::new_instance(array('REG_ID' => 2,'QST_ID' => 3,'ANS_value' => The answer is 42'));
2741
-     * echo $answer->my_callback('monkeys',100);
2742
-     * //will output "you called my_callback! and passed args:monkeys,100"
2743
-     *
2744
-     * @param string $methodName name of method which was called on a child of EE_Base_Class, but which
2745
-     * @param array  $args       array of original arguments passed to the function
2746
-     * @throws EE_Error
2747
-     * @return mixed whatever the plugin which calls add_filter decides
2748
-     */
2749
-    public function __call($methodName, $args)
2750
-    {
2751
-        $className = get_class($this);
2752
-        $tagName = "FHEE__{$className}__{$methodName}";
2753
-        if (! has_filter($tagName)) {
2754
-            throw new EE_Error(
2755
-                sprintf(
2756
-                    esc_html__(
2757
-                        "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;}",
2758
-                        'event_espresso'
2759
-                    ),
2760
-                    $methodName,
2761
-                    $className,
2762
-                    $tagName
2763
-                )
2764
-            );
2765
-        }
2766
-        return apply_filters($tagName, null, $this, $args);
2767
-    }
2768
-
2769
-
2770
-    /**
2771
-     * Similar to insert_post_meta, adds a record in the Extra_Meta model's table with the given key and value.
2772
-     * A $previous_value can be specified in case there are many meta rows with the same key
2773
-     *
2774
-     * @param string $meta_key
2775
-     * @param mixed  $meta_value
2776
-     * @param mixed  $previous_value
2777
-     * @return bool|int # of records updated (or BOOLEAN if we actually ended up inserting the extra meta row)
2778
-     *                  NOTE: if the values haven't changed, returns 0
2779
-     * @throws InvalidArgumentException
2780
-     * @throws InvalidInterfaceException
2781
-     * @throws InvalidDataTypeException
2782
-     * @throws EE_Error
2783
-     * @throws ReflectionException
2784
-     */
2785
-    public function update_extra_meta($meta_key, $meta_value, $previous_value = null)
2786
-    {
2787
-        $query_params = array(
2788
-            array(
2789
-                'EXM_key'  => $meta_key,
2790
-                'OBJ_ID'   => $this->ID(),
2791
-                'EXM_type' => $this->get_model()->get_this_model_name(),
2792
-            ),
2793
-        );
2794
-        if ($previous_value !== null) {
2795
-            $query_params[0]['EXM_value'] = $meta_value;
2796
-        }
2797
-        $existing_rows_like_that = EEM_Extra_Meta::instance()->get_all($query_params);
2798
-        if (! $existing_rows_like_that) {
2799
-            return $this->add_extra_meta($meta_key, $meta_value);
2800
-        }
2801
-        foreach ($existing_rows_like_that as $existing_row) {
2802
-            $existing_row->save(array('EXM_value' => $meta_value));
2803
-        }
2804
-        return count($existing_rows_like_that);
2805
-    }
2806
-
2807
-
2808
-    /**
2809
-     * Adds a new extra meta record. If $unique is set to TRUE, we'll first double-check
2810
-     * no other extra meta for this model object have the same key. Returns TRUE if the
2811
-     * extra meta row was entered, false if not
2812
-     *
2813
-     * @param string  $meta_key
2814
-     * @param mixed   $meta_value
2815
-     * @param boolean $unique
2816
-     * @return boolean
2817
-     * @throws InvalidArgumentException
2818
-     * @throws InvalidInterfaceException
2819
-     * @throws InvalidDataTypeException
2820
-     * @throws EE_Error
2821
-     * @throws ReflectionException
2822
-     * @throws ReflectionException
2823
-     */
2824
-    public function add_extra_meta($meta_key, $meta_value, $unique = false)
2825
-    {
2826
-        if ($unique) {
2827
-            $existing_extra_meta = EEM_Extra_Meta::instance()->get_one(
2828
-                array(
2829
-                    array(
2830
-                        'EXM_key'  => $meta_key,
2831
-                        'OBJ_ID'   => $this->ID(),
2832
-                        'EXM_type' => $this->get_model()->get_this_model_name(),
2833
-                    ),
2834
-                )
2835
-            );
2836
-            if ($existing_extra_meta) {
2837
-                return false;
2838
-            }
2839
-        }
2840
-        $new_extra_meta = EE_Extra_Meta::new_instance(
2841
-            array(
2842
-                'EXM_key'   => $meta_key,
2843
-                'EXM_value' => $meta_value,
2844
-                'OBJ_ID'    => $this->ID(),
2845
-                'EXM_type'  => $this->get_model()->get_this_model_name(),
2846
-            )
2847
-        );
2848
-        $new_extra_meta->save();
2849
-        return true;
2850
-    }
2851
-
2852
-
2853
-    /**
2854
-     * Deletes all the extra meta rows for this record as specified by key. If $meta_value
2855
-     * is specified, only deletes extra meta records with that value.
2856
-     *
2857
-     * @param string $meta_key
2858
-     * @param mixed  $meta_value
2859
-     * @return int number of extra meta rows deleted
2860
-     * @throws InvalidArgumentException
2861
-     * @throws InvalidInterfaceException
2862
-     * @throws InvalidDataTypeException
2863
-     * @throws EE_Error
2864
-     * @throws ReflectionException
2865
-     */
2866
-    public function delete_extra_meta($meta_key, $meta_value = null)
2867
-    {
2868
-        $query_params = array(
2869
-            array(
2870
-                'EXM_key'  => $meta_key,
2871
-                'OBJ_ID'   => $this->ID(),
2872
-                'EXM_type' => $this->get_model()->get_this_model_name(),
2873
-            ),
2874
-        );
2875
-        if ($meta_value !== null) {
2876
-            $query_params[0]['EXM_value'] = $meta_value;
2877
-        }
2878
-        return EEM_Extra_Meta::instance()->delete($query_params);
2879
-    }
2880
-
2881
-
2882
-    /**
2883
-     * Gets the extra meta with the given meta key. If you specify "single" we just return 1, otherwise
2884
-     * an array of everything found. Requires that this model actually have a relation of type EE_Has_Many_Any_Relation.
2885
-     * You can specify $default is case you haven't found the extra meta
2886
-     *
2887
-     * @param string  $meta_key
2888
-     * @param boolean $single
2889
-     * @param mixed   $default if we don't find anything, what should we return?
2890
-     * @return mixed single value if $single; array if ! $single
2891
-     * @throws ReflectionException
2892
-     * @throws InvalidArgumentException
2893
-     * @throws InvalidInterfaceException
2894
-     * @throws InvalidDataTypeException
2895
-     * @throws EE_Error
2896
-     */
2897
-    public function get_extra_meta($meta_key, $single = false, $default = null)
2898
-    {
2899
-        if ($single) {
2900
-            $result = $this->get_first_related(
2901
-                'Extra_Meta',
2902
-                array(array('EXM_key' => $meta_key))
2903
-            );
2904
-            if ($result instanceof EE_Extra_Meta) {
2905
-                return $result->value();
2906
-            }
2907
-        } else {
2908
-            $results = $this->get_many_related(
2909
-                'Extra_Meta',
2910
-                array(array('EXM_key' => $meta_key))
2911
-            );
2912
-            if ($results) {
2913
-                $values = array();
2914
-                foreach ($results as $result) {
2915
-                    if ($result instanceof EE_Extra_Meta) {
2916
-                        $values[ $result->ID() ] = $result->value();
2917
-                    }
2918
-                }
2919
-                return $values;
2920
-            }
2921
-        }
2922
-        // if nothing discovered yet return default.
2923
-        return apply_filters(
2924
-            'FHEE__EE_Base_Class__get_extra_meta__default_value',
2925
-            $default,
2926
-            $meta_key,
2927
-            $single,
2928
-            $this
2929
-        );
2930
-    }
2931
-
2932
-
2933
-    /**
2934
-     * Returns a simple array of all the extra meta associated with this model object.
2935
-     * If $one_of_each_key is true (Default), it will be an array of simple key-value pairs, keys being the
2936
-     * extra meta's key, and teh value being its value. However, if there are duplicate extra meta rows with
2937
-     * the same key, only one will be used. (eg array('foo'=>'bar','monkey'=>123))
2938
-     * If $one_of_each_key is false, it will return an array with the top-level keys being
2939
-     * the extra meta keys, but their values are also arrays, which have the extra-meta's ID as their sub-key, and
2940
-     * finally the extra meta's value as each sub-value. (eg
2941
-     * array('foo'=>array(1=>'bar',2=>'bill'),'monkey'=>array(3=>123)))
2942
-     *
2943
-     * @param boolean $one_of_each_key
2944
-     * @return array
2945
-     * @throws ReflectionException
2946
-     * @throws InvalidArgumentException
2947
-     * @throws InvalidInterfaceException
2948
-     * @throws InvalidDataTypeException
2949
-     * @throws EE_Error
2950
-     */
2951
-    public function all_extra_meta_array($one_of_each_key = true)
2952
-    {
2953
-        $return_array = array();
2954
-        if ($one_of_each_key) {
2955
-            $extra_meta_objs = $this->get_many_related(
2956
-                'Extra_Meta',
2957
-                array('group_by' => 'EXM_key')
2958
-            );
2959
-            foreach ($extra_meta_objs as $extra_meta_obj) {
2960
-                if ($extra_meta_obj instanceof EE_Extra_Meta) {
2961
-                    $return_array[ $extra_meta_obj->key() ] = $extra_meta_obj->value();
2962
-                }
2963
-            }
2964
-        } else {
2965
-            $extra_meta_objs = $this->get_many_related('Extra_Meta');
2966
-            foreach ($extra_meta_objs as $extra_meta_obj) {
2967
-                if ($extra_meta_obj instanceof EE_Extra_Meta) {
2968
-                    if (! isset($return_array[ $extra_meta_obj->key() ])) {
2969
-                        $return_array[ $extra_meta_obj->key() ] = array();
2970
-                    }
2971
-                    $return_array[ $extra_meta_obj->key() ][ $extra_meta_obj->ID() ] = $extra_meta_obj->value();
2972
-                }
2973
-            }
2974
-        }
2975
-        return $return_array;
2976
-    }
2977
-
2978
-
2979
-    /**
2980
-     * Gets a pretty nice displayable nice for this model object. Often overridden
2981
-     *
2982
-     * @return string
2983
-     * @throws ReflectionException
2984
-     * @throws InvalidArgumentException
2985
-     * @throws InvalidInterfaceException
2986
-     * @throws InvalidDataTypeException
2987
-     * @throws EE_Error
2988
-     */
2989
-    public function name()
2990
-    {
2991
-        // find a field that's not a text field
2992
-        $field_we_can_use = $this->get_model()->get_a_field_of_type('EE_Text_Field_Base');
2993
-        if ($field_we_can_use) {
2994
-            return $this->get($field_we_can_use->get_name());
2995
-        }
2996
-        $first_few_properties = $this->model_field_array();
2997
-        $first_few_properties = array_slice($first_few_properties, 0, 3);
2998
-        $name_parts = array();
2999
-        foreach ($first_few_properties as $name => $value) {
3000
-            $name_parts[] = "$name:$value";
3001
-        }
3002
-        return implode(',', $name_parts);
3003
-    }
3004
-
3005
-
3006
-    /**
3007
-     * in_entity_map
3008
-     * Checks if this model object has been proven to already be in the entity map
3009
-     *
3010
-     * @return boolean
3011
-     * @throws ReflectionException
3012
-     * @throws InvalidArgumentException
3013
-     * @throws InvalidInterfaceException
3014
-     * @throws InvalidDataTypeException
3015
-     * @throws EE_Error
3016
-     */
3017
-    public function in_entity_map()
3018
-    {
3019
-        // well, if we looked, did we find it in the entity map?
3020
-        return $this->ID() && $this->get_model()->get_from_entity_map($this->ID()) === $this;
3021
-    }
3022
-
3023
-
3024
-    /**
3025
-     * refresh_from_db
3026
-     * Makes sure the fields and values on this model object are in-sync with what's in the database.
3027
-     *
3028
-     * @throws ReflectionException
3029
-     * @throws InvalidArgumentException
3030
-     * @throws InvalidInterfaceException
3031
-     * @throws InvalidDataTypeException
3032
-     * @throws EE_Error if this model object isn't in the entity mapper (because then you should
3033
-     * just use what's in the entity mapper and refresh it) and WP_DEBUG is TRUE
3034
-     */
3035
-    public function refresh_from_db()
3036
-    {
3037
-        if ($this->ID() && $this->in_entity_map()) {
3038
-            $this->get_model()->refresh_entity_map_from_db($this->ID());
3039
-        } else {
3040
-            // if it doesn't have ID, you shouldn't be asking to refresh it from teh database (because its not in the database)
3041
-            // if it has an ID but it's not in the map, and you're asking me to refresh it
3042
-            // that's kinda dangerous. You should just use what's in the entity map, or add this to the entity map if there's
3043
-            // absolutely nothing in it for this ID
3044
-            if (WP_DEBUG) {
3045
-                throw new EE_Error(
3046
-                    sprintf(
3047
-                        esc_html__(
3048
-                            '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.',
3049
-                            'event_espresso'
3050
-                        ),
3051
-                        $this->ID(),
3052
-                        get_class($this->get_model()) . '::instance()->add_to_entity_map()',
3053
-                        get_class($this->get_model()) . '::instance()->refresh_entity_map()'
3054
-                    )
3055
-                );
3056
-            }
3057
-        }
3058
-    }
3059
-
3060
-
3061
-    /**
3062
-     * Change $fields' values to $new_value_sql (which is a string of raw SQL)
3063
-     *
3064
-     * @since 4.9.80.p
3065
-     * @param EE_Model_Field_Base[] $fields
3066
-     * @param string $new_value_sql
3067
-     *      example: 'column_name=123',
3068
-     *      or 'column_name=column_name+1',
3069
-     *      or 'column_name= CASE
3070
-     *          WHEN (`column_name` + `other_column` + 5) <= `yet_another_column`
3071
-     *          THEN `column_name` + 5
3072
-     *          ELSE `column_name`
3073
-     *      END'
3074
-     *      Also updates $field on this model object with the latest value from the database.
3075
-     * @return bool
3076
-     * @throws EE_Error
3077
-     * @throws InvalidArgumentException
3078
-     * @throws InvalidDataTypeException
3079
-     * @throws InvalidInterfaceException
3080
-     * @throws ReflectionException
3081
-     */
3082
-    protected function updateFieldsInDB($fields, $new_value_sql)
3083
-    {
3084
-        // First make sure this model object actually exists in the DB. It would be silly to try to update it in the DB
3085
-        // if it wasn't even there to start off.
3086
-        if (! $this->ID()) {
3087
-            $this->save();
3088
-        }
3089
-        global $wpdb;
3090
-        if (empty($fields)) {
3091
-            throw new InvalidArgumentException(
3092
-                esc_html__(
3093
-                    'EE_Base_Class::updateFieldsInDB was passed an empty array of fields.',
3094
-                    'event_espresso'
3095
-                )
3096
-            );
3097
-        }
3098
-        $first_field = reset($fields);
3099
-        $table_alias = $first_field->get_table_alias();
3100
-        foreach ($fields as $field) {
3101
-            if ($table_alias !== $field->get_table_alias()) {
3102
-                throw new InvalidArgumentException(
3103
-                    sprintf(
3104
-                        esc_html__(
3105
-                            // @codingStandardsIgnoreStart
3106
-                            '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.',
3107
-                            // @codingStandardsIgnoreEnd
3108
-                            'event_espresso'
3109
-                        ),
3110
-                        $table_alias,
3111
-                        $field->get_table_alias()
3112
-                    )
3113
-                );
3114
-            }
3115
-        }
3116
-        // Ok the fields are now known to all be for the same table. Proceed with creating the SQL to update it.
3117
-        $table_obj = $this->get_model()->get_table_obj_by_alias($table_alias);
3118
-        $table_pk_value = $this->ID();
3119
-        $table_name = $table_obj->get_table_name();
3120
-        if ($table_obj instanceof EE_Secondary_Table) {
3121
-            $table_pk_field_name = $table_obj->get_fk_on_table();
3122
-        } else {
3123
-            $table_pk_field_name = $table_obj->get_pk_column();
3124
-        }
3125
-
3126
-        $query =
3127
-            "UPDATE `{$table_name}`
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
+			list($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 (isset($this->_props_n_values_provided_in_constructor[ $field_name ])
254
+			&& $field_settings = $this->get_model()->field_settings_for($field_name)
255
+		) {
256
+			return $field_settings->prepare_for_get($this->_props_n_values_provided_in_constructor[ $field_name ]);
257
+		}
258
+		return null;
259
+	}
260
+
261
+
262
+	/**
263
+	 * @param EE_Base_Class $obj
264
+	 * @return string
265
+	 */
266
+	public function get_class($obj)
267
+	{
268
+		return get_class($obj);
269
+	}
270
+
271
+
272
+	/**
273
+	 * Overrides parent because parent expects old models.
274
+	 * This also doesn't do any validation, and won't work for serialized arrays
275
+	 *
276
+	 * @param    string $field_name
277
+	 * @param    mixed  $field_value
278
+	 * @param bool      $use_default
279
+	 * @throws InvalidArgumentException
280
+	 * @throws InvalidInterfaceException
281
+	 * @throws InvalidDataTypeException
282
+	 * @throws EE_Error
283
+	 * @throws ReflectionException
284
+	 * @throws ReflectionException
285
+	 * @throws ReflectionException
286
+	 */
287
+	public function set($field_name, $field_value, $use_default = false)
288
+	{
289
+		// if not using default and nothing has changed, and object has already been setup (has ID),
290
+		// then don't do anything
291
+		if (! $use_default
292
+			&& $this->_fields[ $field_name ] === $field_value
293
+			&& $this->ID()
294
+		) {
295
+			return;
296
+		}
297
+		$model = $this->get_model();
298
+		$this->_has_changes = true;
299
+		$field_obj = $model->field_settings_for($field_name);
300
+		if ($field_obj instanceof EE_Model_Field_Base) {
301
+			// if ( method_exists( $field_obj, 'set_timezone' )) {
302
+			if ($field_obj instanceof EE_Datetime_Field) {
303
+				$field_obj->set_timezone($this->_timezone);
304
+				$field_obj->set_date_format($this->_dt_frmt);
305
+				$field_obj->set_time_format($this->_tm_frmt);
306
+			}
307
+			$holder_of_value = $field_obj->prepare_for_set($field_value);
308
+			// should the value be null?
309
+			if (($field_value === null || $holder_of_value === null || $holder_of_value === '') && $use_default) {
310
+				$this->_fields[ $field_name ] = $field_obj->get_default_value();
311
+				/**
312
+				 * To save having to refactor all the models, if a default value is used for a
313
+				 * EE_Datetime_Field, and that value is not null nor is it a DateTime
314
+				 * object.  Then let's do a set again to ensure that it becomes a DateTime
315
+				 * object.
316
+				 *
317
+				 * @since 4.6.10+
318
+				 */
319
+				if ($field_obj instanceof EE_Datetime_Field
320
+					&& $this->_fields[ $field_name ] !== null
321
+					&& ! $this->_fields[ $field_name ] instanceof DateTime
322
+				) {
323
+					empty($this->_fields[ $field_name ])
324
+						? $this->set($field_name, time())
325
+						: $this->set($field_name, $this->_fields[ $field_name ]);
326
+				}
327
+			} else {
328
+				$this->_fields[ $field_name ] = $holder_of_value;
329
+			}
330
+			// if we're not in the constructor...
331
+			// now check if what we set was a primary key
332
+			if (// note: props_n_values_provided_in_constructor is only set at the END of the constructor
333
+				$this->_props_n_values_provided_in_constructor
334
+				&& $field_value
335
+				&& $field_name === $model->primary_key_name()
336
+			) {
337
+				// if so, we want all this object's fields to be filled either with
338
+				// what we've explicitly set on this model
339
+				// or what we have in the db
340
+				// echo "setting primary key!";
341
+				$fields_on_model = self::_get_model(get_class($this))->field_settings();
342
+				$obj_in_db = self::_get_model(get_class($this))->get_one_by_ID($field_value);
343
+				foreach ($fields_on_model as $field_obj) {
344
+					if (! array_key_exists($field_obj->get_name(), $this->_props_n_values_provided_in_constructor)
345
+						&& $field_obj->get_name() !== $field_name
346
+					) {
347
+						$this->set($field_obj->get_name(), $obj_in_db->get($field_obj->get_name()));
348
+					}
349
+				}
350
+				// oh this model object has an ID? well make sure its in the entity mapper
351
+				$model->add_to_entity_map($this);
352
+			}
353
+			// let's unset any cache for this field_name from the $_cached_properties property.
354
+			$this->_clear_cached_property($field_name);
355
+		} else {
356
+			throw new EE_Error(
357
+				sprintf(
358
+					esc_html__(
359
+						'A valid EE_Model_Field_Base could not be found for the given field name: %s',
360
+						'event_espresso'
361
+					),
362
+					$field_name
363
+				)
364
+			);
365
+		}
366
+	}
367
+
368
+
369
+	/**
370
+	 * Set custom select values for model.
371
+	 *
372
+	 * @param array $custom_select_values
373
+	 */
374
+	public function setCustomSelectsValues(array $custom_select_values)
375
+	{
376
+		$this->custom_selection_results = $custom_select_values;
377
+	}
378
+
379
+
380
+	/**
381
+	 * Returns the custom select value for the provided alias if its set.
382
+	 * If not set, returns null.
383
+	 *
384
+	 * @param string $alias
385
+	 * @return string|int|float|null
386
+	 */
387
+	public function getCustomSelect($alias)
388
+	{
389
+		return isset($this->custom_selection_results[ $alias ])
390
+			? $this->custom_selection_results[ $alias ]
391
+			: null;
392
+	}
393
+
394
+
395
+	/**
396
+	 * This sets the field value on the db column if it exists for the given $column_name or
397
+	 * saves it to EE_Extra_Meta if the given $column_name does not match a db column.
398
+	 *
399
+	 * @see EE_message::get_column_value for related documentation on the necessity of this method.
400
+	 * @param string $field_name  Must be the exact column name.
401
+	 * @param mixed  $field_value The value to set.
402
+	 * @return int|bool @see EE_Base_Class::update_extra_meta() for return docs.
403
+	 * @throws InvalidArgumentException
404
+	 * @throws InvalidInterfaceException
405
+	 * @throws InvalidDataTypeException
406
+	 * @throws EE_Error
407
+	 * @throws ReflectionException
408
+	 */
409
+	public function set_field_or_extra_meta($field_name, $field_value)
410
+	{
411
+		if ($this->get_model()->has_field($field_name)) {
412
+			$this->set($field_name, $field_value);
413
+			return true;
414
+		}
415
+		// ensure this object is saved first so that extra meta can be properly related.
416
+		$this->save();
417
+		return $this->update_extra_meta($field_name, $field_value);
418
+	}
419
+
420
+
421
+	/**
422
+	 * This retrieves the value of the db column set on this class or if that's not present
423
+	 * it will attempt to retrieve from extra_meta if found.
424
+	 * Example Usage:
425
+	 * Via EE_Message child class:
426
+	 * Due to the dynamic nature of the EE_messages system, EE_messengers will always have a "to",
427
+	 * "from", "subject", and "content" field (as represented in the EE_Message schema), however they may
428
+	 * also have additional main fields specific to the messenger.  The system accommodates those extra
429
+	 * fields through the EE_Extra_Meta table.  This method allows for EE_messengers to retrieve the
430
+	 * value for those extra fields dynamically via the EE_message object.
431
+	 *
432
+	 * @param  string $field_name expecting the fully qualified field name.
433
+	 * @return mixed|null  value for the field if found.  null if not found.
434
+	 * @throws ReflectionException
435
+	 * @throws InvalidArgumentException
436
+	 * @throws InvalidInterfaceException
437
+	 * @throws InvalidDataTypeException
438
+	 * @throws EE_Error
439
+	 */
440
+	public function get_field_or_extra_meta($field_name)
441
+	{
442
+		if ($this->get_model()->has_field($field_name)) {
443
+			$column_value = $this->get($field_name);
444
+		} else {
445
+			// This isn't a column in the main table, let's see if it is in the extra meta.
446
+			$column_value = $this->get_extra_meta($field_name, true, null);
447
+		}
448
+		return $column_value;
449
+	}
450
+
451
+
452
+	/**
453
+	 * See $_timezone property for description of what the timezone property is for.  This SETS the timezone internally
454
+	 * for being able to reference what timezone we are running conversions on when converting TO the internal timezone
455
+	 * (UTC Unix Timestamp) for the object OR when converting FROM the internal timezone (UTC Unix Timestamp). This is
456
+	 * available to all child classes that may be using the EE_Datetime_Field for a field data type.
457
+	 *
458
+	 * @access public
459
+	 * @param string $timezone A valid timezone string as described by @link http://www.php.net/manual/en/timezones.php
460
+	 * @return void
461
+	 * @throws InvalidArgumentException
462
+	 * @throws InvalidInterfaceException
463
+	 * @throws InvalidDataTypeException
464
+	 * @throws EE_Error
465
+	 * @throws ReflectionException
466
+	 */
467
+	public function set_timezone($timezone = '')
468
+	{
469
+		$this->_timezone = EEH_DTT_Helper::get_valid_timezone_string($timezone);
470
+		// make sure we clear all cached properties because they won't be relevant now
471
+		$this->_clear_cached_properties();
472
+		// make sure we update field settings and the date for all EE_Datetime_Fields
473
+		$model_fields = $this->get_model()->field_settings(false);
474
+		foreach ($model_fields as $field_name => $field_obj) {
475
+			if ($field_obj instanceof EE_Datetime_Field) {
476
+				$field_obj->set_timezone($this->_timezone);
477
+				if (isset($this->_fields[ $field_name ]) && $this->_fields[ $field_name ] instanceof DateTime) {
478
+					EEH_DTT_Helper::setTimezone($this->_fields[ $field_name ], new DateTimeZone($this->_timezone));
479
+				}
480
+			}
481
+		}
482
+	}
483
+
484
+
485
+	/**
486
+	 * This just returns whatever is set for the current timezone.
487
+	 *
488
+	 * @access public
489
+	 * @return string timezone string
490
+	 */
491
+	public function get_timezone()
492
+	{
493
+		return $this->_timezone;
494
+	}
495
+
496
+
497
+	/**
498
+	 * This sets the internal date format to what is sent in to be used as the new default for the class
499
+	 * internally instead of wp set date format options
500
+	 *
501
+	 * @since 4.6
502
+	 * @param string $format should be a format recognizable by PHP date() functions.
503
+	 */
504
+	public function set_date_format($format)
505
+	{
506
+		$this->_dt_frmt = $format;
507
+		// clear cached_properties because they won't be relevant now.
508
+		$this->_clear_cached_properties();
509
+	}
510
+
511
+
512
+	/**
513
+	 * This sets the internal time format string to what is sent in to be used as the new default for the
514
+	 * class internally instead of wp set time format options.
515
+	 *
516
+	 * @since 4.6
517
+	 * @param string $format should be a format recognizable by PHP date() functions.
518
+	 */
519
+	public function set_time_format($format)
520
+	{
521
+		$this->_tm_frmt = $format;
522
+		// clear cached_properties because they won't be relevant now.
523
+		$this->_clear_cached_properties();
524
+	}
525
+
526
+
527
+	/**
528
+	 * This returns the current internal set format for the date and time formats.
529
+	 *
530
+	 * @param bool $full           if true (default), then return the full format.  Otherwise will return an array
531
+	 *                             where the first value is the date format and the second value is the time format.
532
+	 * @return mixed string|array
533
+	 */
534
+	public function get_format($full = true)
535
+	{
536
+		return $full ? $this->_dt_frmt . ' ' . $this->_tm_frmt : array($this->_dt_frmt, $this->_tm_frmt);
537
+	}
538
+
539
+
540
+	/**
541
+	 * cache
542
+	 * stores the passed model object on the current model object.
543
+	 * In certain circumstances, we can use this cached model object instead of querying for another one entirely.
544
+	 *
545
+	 * @param string        $relationName    one of the keys in the _model_relations array on the model. Eg
546
+	 *                                       'Registration' associated with this model object
547
+	 * @param EE_Base_Class $object_to_cache that has a relation to this model object. (Eg, if this is a Transaction,
548
+	 *                                       that could be a payment or a registration)
549
+	 * @param null          $cache_id        a string or number that will be used as the key for any Belongs_To_Many
550
+	 *                                       items which will be stored in an array on this object
551
+	 * @throws ReflectionException
552
+	 * @throws InvalidArgumentException
553
+	 * @throws InvalidInterfaceException
554
+	 * @throws InvalidDataTypeException
555
+	 * @throws EE_Error
556
+	 * @return mixed    index into cache, or just TRUE if the relation is of type Belongs_To (because there's only one
557
+	 *                                       related thing, no array)
558
+	 */
559
+	public function cache($relationName = '', $object_to_cache = null, $cache_id = null)
560
+	{
561
+		// its entirely possible that there IS no related object yet in which case there is nothing to cache.
562
+		if (! $object_to_cache instanceof EE_Base_Class) {
563
+			return false;
564
+		}
565
+		// also get "how" the object is related, or throw an error
566
+		if (! $relationship_to_model = $this->get_model()->related_settings_for($relationName)) {
567
+			throw new EE_Error(
568
+				sprintf(
569
+					esc_html__('There is no relationship to %s on a %s. Cannot cache it', 'event_espresso'),
570
+					$relationName,
571
+					get_class($this)
572
+				)
573
+			);
574
+		}
575
+		// how many things are related ?
576
+		if ($relationship_to_model instanceof EE_Belongs_To_Relation) {
577
+			// if it's a "belongs to" relationship, then there's only one related model object
578
+			// eg, if this is a registration, there's only 1 attendee for it
579
+			// so for these model objects just set it to be cached
580
+			$this->_model_relations[ $relationName ] = $object_to_cache;
581
+			$return = true;
582
+		} else {
583
+			// otherwise, this is the "many" side of a one to many relationship,
584
+			// so we'll add the object to the array of related objects for that type.
585
+			// eg: if this is an event, there are many registrations for that event,
586
+			// so we cache the registrations in an array
587
+			if (! is_array($this->_model_relations[ $relationName ])) {
588
+				// if for some reason, the cached item is a model object,
589
+				// then stick that in the array, otherwise start with an empty array
590
+				$this->_model_relations[ $relationName ] = $this->_model_relations[ $relationName ]
591
+														   instanceof
592
+														   EE_Base_Class
593
+					? array($this->_model_relations[ $relationName ]) : array();
594
+			}
595
+			// first check for a cache_id which is normally empty
596
+			if (! empty($cache_id)) {
597
+				// if the cache_id exists, then it means we are purposely trying to cache this
598
+				// with a known key that can then be used to retrieve the object later on
599
+				$this->_model_relations[ $relationName ][ $cache_id ] = $object_to_cache;
600
+				$return = $cache_id;
601
+			} elseif ($object_to_cache->ID()) {
602
+				// OR the cached object originally came from the db, so let's just use it's PK for an ID
603
+				$this->_model_relations[ $relationName ][ $object_to_cache->ID() ] = $object_to_cache;
604
+				$return = $object_to_cache->ID();
605
+			} else {
606
+				// OR it's a new object with no ID, so just throw it in the array with an auto-incremented ID
607
+				$this->_model_relations[ $relationName ][] = $object_to_cache;
608
+				// move the internal pointer to the end of the array
609
+				end($this->_model_relations[ $relationName ]);
610
+				// and grab the key so that we can return it
611
+				$return = key($this->_model_relations[ $relationName ]);
612
+			}
613
+		}
614
+		return $return;
615
+	}
616
+
617
+
618
+	/**
619
+	 * For adding an item to the cached_properties property.
620
+	 *
621
+	 * @access protected
622
+	 * @param string      $fieldname the property item the corresponding value is for.
623
+	 * @param mixed       $value     The value we are caching.
624
+	 * @param string|null $cache_type
625
+	 * @return void
626
+	 * @throws ReflectionException
627
+	 * @throws InvalidArgumentException
628
+	 * @throws InvalidInterfaceException
629
+	 * @throws InvalidDataTypeException
630
+	 * @throws EE_Error
631
+	 */
632
+	protected function _set_cached_property($fieldname, $value, $cache_type = null)
633
+	{
634
+		// first make sure this property exists
635
+		$this->get_model()->field_settings_for($fieldname);
636
+		$cache_type = empty($cache_type) ? 'standard' : $cache_type;
637
+		$this->_cached_properties[ $fieldname ][ $cache_type ] = $value;
638
+	}
639
+
640
+
641
+	/**
642
+	 * This returns the value cached property if it exists OR the actual property value if the cache doesn't exist.
643
+	 * This also SETS the cache if we return the actual property!
644
+	 *
645
+	 * @param string $fieldname        the name of the property we're trying to retrieve
646
+	 * @param bool   $pretty
647
+	 * @param string $extra_cache_ref  This allows the user to specify an extra cache ref for the given property
648
+	 *                                 (in cases where the same property may be used for different outputs
649
+	 *                                 - i.e. datetime, money etc.)
650
+	 *                                 It can also accept certain pre-defined "schema" strings
651
+	 *                                 to define how to output the property.
652
+	 *                                 see the field's prepare_for_pretty_echoing for what strings can be used
653
+	 * @return mixed                   whatever the value for the property is we're retrieving
654
+	 * @throws ReflectionException
655
+	 * @throws InvalidArgumentException
656
+	 * @throws InvalidInterfaceException
657
+	 * @throws InvalidDataTypeException
658
+	 * @throws EE_Error
659
+	 */
660
+	protected function _get_cached_property($fieldname, $pretty = false, $extra_cache_ref = null)
661
+	{
662
+		// verify the field exists
663
+		$model = $this->get_model();
664
+		$model->field_settings_for($fieldname);
665
+		$cache_type = $pretty ? 'pretty' : 'standard';
666
+		$cache_type .= ! empty($extra_cache_ref) ? '_' . $extra_cache_ref : '';
667
+		if (isset($this->_cached_properties[ $fieldname ][ $cache_type ])) {
668
+			return $this->_cached_properties[ $fieldname ][ $cache_type ];
669
+		}
670
+		$value = $this->_get_fresh_property($fieldname, $pretty, $extra_cache_ref);
671
+		$this->_set_cached_property($fieldname, $value, $cache_type);
672
+		return $value;
673
+	}
674
+
675
+
676
+	/**
677
+	 * If the cache didn't fetch the needed item, this fetches it.
678
+	 *
679
+	 * @param string $fieldname
680
+	 * @param bool   $pretty
681
+	 * @param string $extra_cache_ref
682
+	 * @return mixed
683
+	 * @throws InvalidArgumentException
684
+	 * @throws InvalidInterfaceException
685
+	 * @throws InvalidDataTypeException
686
+	 * @throws EE_Error
687
+	 * @throws ReflectionException
688
+	 */
689
+	protected function _get_fresh_property($fieldname, $pretty = false, $extra_cache_ref = null)
690
+	{
691
+		$field_obj = $this->get_model()->field_settings_for($fieldname);
692
+		// If this is an EE_Datetime_Field we need to make sure timezone, formats, and output are correct
693
+		if ($field_obj instanceof EE_Datetime_Field) {
694
+			$this->_prepare_datetime_field($field_obj, $pretty, $extra_cache_ref);
695
+		}
696
+		if (! isset($this->_fields[ $fieldname ])) {
697
+			$this->_fields[ $fieldname ] = null;
698
+		}
699
+		$value = $pretty
700
+			? $field_obj->prepare_for_pretty_echoing($this->_fields[ $fieldname ], $extra_cache_ref)
701
+			: $field_obj->prepare_for_get($this->_fields[ $fieldname ]);
702
+		return $value;
703
+	}
704
+
705
+
706
+	/**
707
+	 * set timezone, formats, and output for EE_Datetime_Field objects
708
+	 *
709
+	 * @param \EE_Datetime_Field $datetime_field
710
+	 * @param bool               $pretty
711
+	 * @param null               $date_or_time
712
+	 * @return void
713
+	 * @throws InvalidArgumentException
714
+	 * @throws InvalidInterfaceException
715
+	 * @throws InvalidDataTypeException
716
+	 * @throws EE_Error
717
+	 */
718
+	protected function _prepare_datetime_field(
719
+		EE_Datetime_Field $datetime_field,
720
+		$pretty = false,
721
+		$date_or_time = null
722
+	) {
723
+		$datetime_field->set_timezone($this->_timezone);
724
+		$datetime_field->set_date_format($this->_dt_frmt, $pretty);
725
+		$datetime_field->set_time_format($this->_tm_frmt, $pretty);
726
+		// set the output returned
727
+		switch ($date_or_time) {
728
+			case 'D':
729
+				$datetime_field->set_date_time_output('date');
730
+				break;
731
+			case 'T':
732
+				$datetime_field->set_date_time_output('time');
733
+				break;
734
+			default:
735
+				$datetime_field->set_date_time_output();
736
+		}
737
+	}
738
+
739
+
740
+	/**
741
+	 * This just takes care of clearing out the cached_properties
742
+	 *
743
+	 * @return void
744
+	 */
745
+	protected function _clear_cached_properties()
746
+	{
747
+		$this->_cached_properties = array();
748
+	}
749
+
750
+
751
+	/**
752
+	 * This just clears out ONE property if it exists in the cache
753
+	 *
754
+	 * @param  string $property_name the property to remove if it exists (from the _cached_properties array)
755
+	 * @return void
756
+	 */
757
+	protected function _clear_cached_property($property_name)
758
+	{
759
+		if (isset($this->_cached_properties[ $property_name ])) {
760
+			unset($this->_cached_properties[ $property_name ]);
761
+		}
762
+	}
763
+
764
+
765
+	/**
766
+	 * Ensures that this related thing is a model object.
767
+	 *
768
+	 * @param mixed  $object_or_id EE_base_Class/int/string either a related model object, or its ID
769
+	 * @param string $model_name   name of the related thing, eg 'Attendee',
770
+	 * @return EE_Base_Class
771
+	 * @throws ReflectionException
772
+	 * @throws InvalidArgumentException
773
+	 * @throws InvalidInterfaceException
774
+	 * @throws InvalidDataTypeException
775
+	 * @throws EE_Error
776
+	 */
777
+	protected function ensure_related_thing_is_model_obj($object_or_id, $model_name)
778
+	{
779
+		$other_model_instance = self::_get_model_instance_with_name(
780
+			self::_get_model_classname($model_name),
781
+			$this->_timezone
782
+		);
783
+		return $other_model_instance->ensure_is_obj($object_or_id);
784
+	}
785
+
786
+
787
+	/**
788
+	 * Forgets the cached model of the given relation Name. So the next time we request it,
789
+	 * we will fetch it again from the database. (Handy if you know it's changed somehow).
790
+	 * If a specific object is supplied, and the relationship to it is either a HasMany or HABTM,
791
+	 * then only remove that one object from our cached array. Otherwise, clear the entire list
792
+	 *
793
+	 * @param string $relationName                         one of the keys in the _model_relations array on the model.
794
+	 *                                                     Eg 'Registration'
795
+	 * @param mixed  $object_to_remove_or_index_into_array or an index into the array of cached things, or NULL
796
+	 *                                                     if you intend to use $clear_all = TRUE, or the relation only
797
+	 *                                                     has 1 object anyways (ie, it's a BelongsToRelation)
798
+	 * @param bool   $clear_all                            This flags clearing the entire cache relation property if
799
+	 *                                                     this is HasMany or HABTM.
800
+	 * @throws ReflectionException
801
+	 * @throws InvalidArgumentException
802
+	 * @throws InvalidInterfaceException
803
+	 * @throws InvalidDataTypeException
804
+	 * @throws EE_Error
805
+	 * @return EE_Base_Class | boolean from which was cleared from the cache, or true if we requested to remove a
806
+	 *                                                     relation from all
807
+	 */
808
+	public function clear_cache($relationName, $object_to_remove_or_index_into_array = null, $clear_all = false)
809
+	{
810
+		$relationship_to_model = $this->get_model()->related_settings_for($relationName);
811
+		$index_in_cache = '';
812
+		if (! $relationship_to_model) {
813
+			throw new EE_Error(
814
+				sprintf(
815
+					esc_html__('There is no relationship to %s on a %s. Cannot clear that cache', 'event_espresso'),
816
+					$relationName,
817
+					get_class($this)
818
+				)
819
+			);
820
+		}
821
+		if ($clear_all) {
822
+			$obj_removed = true;
823
+			$this->_model_relations[ $relationName ] = null;
824
+		} elseif ($relationship_to_model instanceof EE_Belongs_To_Relation) {
825
+			$obj_removed = $this->_model_relations[ $relationName ];
826
+			$this->_model_relations[ $relationName ] = null;
827
+		} else {
828
+			if ($object_to_remove_or_index_into_array instanceof EE_Base_Class
829
+				&& $object_to_remove_or_index_into_array->ID()
830
+			) {
831
+				$index_in_cache = $object_to_remove_or_index_into_array->ID();
832
+				if (is_array($this->_model_relations[ $relationName ])
833
+					&& ! isset($this->_model_relations[ $relationName ][ $index_in_cache ])
834
+				) {
835
+					$index_found_at = null;
836
+					// find this object in the array even though it has a different key
837
+					foreach ($this->_model_relations[ $relationName ] as $index => $obj) {
838
+						/** @noinspection TypeUnsafeComparisonInspection */
839
+						if ($obj instanceof EE_Base_Class
840
+							&& (
841
+								$obj == $object_to_remove_or_index_into_array
842
+								|| $obj->ID() === $object_to_remove_or_index_into_array->ID()
843
+							)
844
+						) {
845
+							$index_found_at = $index;
846
+							break;
847
+						}
848
+					}
849
+					if ($index_found_at) {
850
+						$index_in_cache = $index_found_at;
851
+					} else {
852
+						// it wasn't found. huh. well obviously it doesn't need to be removed from teh cache
853
+						// if it wasn't in it to begin with. So we're done
854
+						return $object_to_remove_or_index_into_array;
855
+					}
856
+				}
857
+			} elseif ($object_to_remove_or_index_into_array instanceof EE_Base_Class) {
858
+				// so they provided a model object, but it's not yet saved to the DB... so let's go hunting for it!
859
+				foreach ($this->get_all_from_cache($relationName) as $index => $potentially_obj_we_want) {
860
+					/** @noinspection TypeUnsafeComparisonInspection */
861
+					if ($potentially_obj_we_want == $object_to_remove_or_index_into_array) {
862
+						$index_in_cache = $index;
863
+					}
864
+				}
865
+			} else {
866
+				$index_in_cache = $object_to_remove_or_index_into_array;
867
+			}
868
+			// supposedly we've found it. But it could just be that the client code
869
+			// provided a bad index/object
870
+			if (isset($this->_model_relations[ $relationName ][ $index_in_cache ])) {
871
+				$obj_removed = $this->_model_relations[ $relationName ][ $index_in_cache ];
872
+				unset($this->_model_relations[ $relationName ][ $index_in_cache ]);
873
+			} else {
874
+				// that thing was never cached anyways.
875
+				$obj_removed = null;
876
+			}
877
+		}
878
+		return $obj_removed;
879
+	}
880
+
881
+
882
+	/**
883
+	 * update_cache_after_object_save
884
+	 * Allows a cached item to have it's cache ID (within the array of cached items) reset using the new ID it has
885
+	 * obtained after being saved to the db
886
+	 *
887
+	 * @param string        $relationName       - the type of object that is cached
888
+	 * @param EE_Base_Class $newly_saved_object - the newly saved object to be re-cached
889
+	 * @param string        $current_cache_id   - the ID that was used when originally caching the object
890
+	 * @return boolean TRUE on success, FALSE on fail
891
+	 * @throws ReflectionException
892
+	 * @throws InvalidArgumentException
893
+	 * @throws InvalidInterfaceException
894
+	 * @throws InvalidDataTypeException
895
+	 * @throws EE_Error
896
+	 */
897
+	public function update_cache_after_object_save(
898
+		$relationName,
899
+		EE_Base_Class $newly_saved_object,
900
+		$current_cache_id = ''
901
+	) {
902
+		// verify that incoming object is of the correct type
903
+		$obj_class = 'EE_' . $relationName;
904
+		if ($newly_saved_object instanceof $obj_class) {
905
+			/* @type EE_Base_Class $newly_saved_object */
906
+			// now get the type of relation
907
+			$relationship_to_model = $this->get_model()->related_settings_for($relationName);
908
+			// if this is a 1:1 relationship
909
+			if ($relationship_to_model instanceof EE_Belongs_To_Relation) {
910
+				// then just replace the cached object with the newly saved object
911
+				$this->_model_relations[ $relationName ] = $newly_saved_object;
912
+				return true;
913
+				// or if it's some kind of sordid feral polyamorous relationship...
914
+			}
915
+			if (is_array($this->_model_relations[ $relationName ])
916
+				&& isset($this->_model_relations[ $relationName ][ $current_cache_id ])
917
+			) {
918
+				// then remove the current cached item
919
+				unset($this->_model_relations[ $relationName ][ $current_cache_id ]);
920
+				// and cache the newly saved object using it's new ID
921
+				$this->_model_relations[ $relationName ][ $newly_saved_object->ID() ] = $newly_saved_object;
922
+				return true;
923
+			}
924
+		}
925
+		return false;
926
+	}
927
+
928
+
929
+	/**
930
+	 * Fetches a single EE_Base_Class on that relation. (If the relation is of type
931
+	 * BelongsTo, it will only ever have 1 object. However, other relations could have an array of objects)
932
+	 *
933
+	 * @param string $relationName
934
+	 * @return EE_Base_Class
935
+	 */
936
+	public function get_one_from_cache($relationName)
937
+	{
938
+		$cached_array_or_object = isset($this->_model_relations[ $relationName ])
939
+			? $this->_model_relations[ $relationName ]
940
+			: null;
941
+		if (is_array($cached_array_or_object)) {
942
+			return array_shift($cached_array_or_object);
943
+		}
944
+		return $cached_array_or_object;
945
+	}
946
+
947
+
948
+	/**
949
+	 * Fetches a single EE_Base_Class on that relation. (If the relation is of type
950
+	 * BelongsTo, it will only ever have 1 object. However, other relations could have an array of objects)
951
+	 *
952
+	 * @param string $relationName
953
+	 * @throws ReflectionException
954
+	 * @throws InvalidArgumentException
955
+	 * @throws InvalidInterfaceException
956
+	 * @throws InvalidDataTypeException
957
+	 * @throws EE_Error
958
+	 * @return EE_Base_Class[] NOT necessarily indexed by primary keys
959
+	 */
960
+	public function get_all_from_cache($relationName)
961
+	{
962
+		$objects = isset($this->_model_relations[ $relationName ]) ? $this->_model_relations[ $relationName ] : array();
963
+		// if the result is not an array, but exists, make it an array
964
+		$objects = is_array($objects) ? $objects : array($objects);
965
+		// bugfix for https://events.codebasehq.com/projects/event-espresso/tickets/7143
966
+		// basically, if this model object was stored in the session, and these cached model objects
967
+		// already have IDs, let's make sure they're in their model's entity mapper
968
+		// otherwise we will have duplicates next time we call
969
+		// EE_Registry::instance()->load_model( $relationName )->get_one_by_ID( $result->ID() );
970
+		$model = EE_Registry::instance()->load_model($relationName);
971
+		foreach ($objects as $model_object) {
972
+			if ($model instanceof EEM_Base && $model_object instanceof EE_Base_Class) {
973
+				// ensure its in the map if it has an ID; otherwise it will be added to the map when its saved
974
+				if ($model_object->ID()) {
975
+					$model->add_to_entity_map($model_object);
976
+				}
977
+			} else {
978
+				throw new EE_Error(
979
+					sprintf(
980
+						esc_html__(
981
+							'Error retrieving related model objects. Either $1%s is not a model or $2%s is not a model object',
982
+							'event_espresso'
983
+						),
984
+						$relationName,
985
+						gettype($model_object)
986
+					)
987
+				);
988
+			}
989
+		}
990
+		return $objects;
991
+	}
992
+
993
+
994
+	/**
995
+	 * Returns the next x number of EE_Base_Class objects in sequence from this object as found in the database
996
+	 * matching the given query conditions.
997
+	 *
998
+	 * @param null  $field_to_order_by  What field is being used as the reference point.
999
+	 * @param int   $limit              How many objects to return.
1000
+	 * @param array $query_params       Any additional conditions on the query.
1001
+	 * @param null  $columns_to_select  If left null, then an array of EE_Base_Class objects is returned, otherwise
1002
+	 *                                  you can indicate just the columns you want returned
1003
+	 * @return array|EE_Base_Class[]
1004
+	 * @throws ReflectionException
1005
+	 * @throws InvalidArgumentException
1006
+	 * @throws InvalidInterfaceException
1007
+	 * @throws InvalidDataTypeException
1008
+	 * @throws EE_Error
1009
+	 */
1010
+	public function next_x($field_to_order_by = null, $limit = 1, $query_params = array(), $columns_to_select = null)
1011
+	{
1012
+		$model = $this->get_model();
1013
+		$field = empty($field_to_order_by) && $model->has_primary_key_field()
1014
+			? $model->get_primary_key_field()->get_name()
1015
+			: $field_to_order_by;
1016
+		$current_value = ! empty($field) ? $this->get($field) : null;
1017
+		if (empty($field) || empty($current_value)) {
1018
+			return array();
1019
+		}
1020
+		return $model->next_x($current_value, $field, $limit, $query_params, $columns_to_select);
1021
+	}
1022
+
1023
+
1024
+	/**
1025
+	 * Returns the previous x number of EE_Base_Class objects in sequence from this object as found in the database
1026
+	 * matching the given query conditions.
1027
+	 *
1028
+	 * @param null  $field_to_order_by  What field is being used as the reference point.
1029
+	 * @param int   $limit              How many objects to return.
1030
+	 * @param array $query_params       Any additional conditions on the query.
1031
+	 * @param null  $columns_to_select  If left null, then an array of EE_Base_Class objects is returned, otherwise
1032
+	 *                                  you can indicate just the columns you want returned
1033
+	 * @return array|EE_Base_Class[]
1034
+	 * @throws ReflectionException
1035
+	 * @throws InvalidArgumentException
1036
+	 * @throws InvalidInterfaceException
1037
+	 * @throws InvalidDataTypeException
1038
+	 * @throws EE_Error
1039
+	 */
1040
+	public function previous_x(
1041
+		$field_to_order_by = null,
1042
+		$limit = 1,
1043
+		$query_params = array(),
1044
+		$columns_to_select = null
1045
+	) {
1046
+		$model = $this->get_model();
1047
+		$field = empty($field_to_order_by) && $model->has_primary_key_field()
1048
+			? $model->get_primary_key_field()->get_name()
1049
+			: $field_to_order_by;
1050
+		$current_value = ! empty($field) ? $this->get($field) : null;
1051
+		if (empty($field) || empty($current_value)) {
1052
+			return array();
1053
+		}
1054
+		return $model->previous_x($current_value, $field, $limit, $query_params, $columns_to_select);
1055
+	}
1056
+
1057
+
1058
+	/**
1059
+	 * Returns the next EE_Base_Class object in sequence from this object as found in the database
1060
+	 * matching the given query conditions.
1061
+	 *
1062
+	 * @param null  $field_to_order_by  What field is being used as the reference point.
1063
+	 * @param array $query_params       Any additional conditions on the query.
1064
+	 * @param null  $columns_to_select  If left null, then an array of EE_Base_Class objects is returned, otherwise
1065
+	 *                                  you can indicate just the columns you want returned
1066
+	 * @return array|EE_Base_Class
1067
+	 * @throws ReflectionException
1068
+	 * @throws InvalidArgumentException
1069
+	 * @throws InvalidInterfaceException
1070
+	 * @throws InvalidDataTypeException
1071
+	 * @throws EE_Error
1072
+	 */
1073
+	public function next($field_to_order_by = null, $query_params = array(), $columns_to_select = null)
1074
+	{
1075
+		$model = $this->get_model();
1076
+		$field = empty($field_to_order_by) && $model->has_primary_key_field()
1077
+			? $model->get_primary_key_field()->get_name()
1078
+			: $field_to_order_by;
1079
+		$current_value = ! empty($field) ? $this->get($field) : null;
1080
+		if (empty($field) || empty($current_value)) {
1081
+			return array();
1082
+		}
1083
+		return $model->next($current_value, $field, $query_params, $columns_to_select);
1084
+	}
1085
+
1086
+
1087
+	/**
1088
+	 * Returns the previous EE_Base_Class object in sequence from this object as found in the database
1089
+	 * matching the given query conditions.
1090
+	 *
1091
+	 * @param null  $field_to_order_by  What field is being used as the reference point.
1092
+	 * @param array $query_params       Any additional conditions on the query.
1093
+	 * @param null  $columns_to_select  If left null, then an EE_Base_Class object is returned, otherwise
1094
+	 *                                  you can indicate just the column you want returned
1095
+	 * @return array|EE_Base_Class
1096
+	 * @throws ReflectionException
1097
+	 * @throws InvalidArgumentException
1098
+	 * @throws InvalidInterfaceException
1099
+	 * @throws InvalidDataTypeException
1100
+	 * @throws EE_Error
1101
+	 */
1102
+	public function previous($field_to_order_by = null, $query_params = array(), $columns_to_select = null)
1103
+	{
1104
+		$model = $this->get_model();
1105
+		$field = empty($field_to_order_by) && $model->has_primary_key_field()
1106
+			? $model->get_primary_key_field()->get_name()
1107
+			: $field_to_order_by;
1108
+		$current_value = ! empty($field) ? $this->get($field) : null;
1109
+		if (empty($field) || empty($current_value)) {
1110
+			return array();
1111
+		}
1112
+		return $model->previous($current_value, $field, $query_params, $columns_to_select);
1113
+	}
1114
+
1115
+
1116
+	/**
1117
+	 * Overrides parent because parent expects old models.
1118
+	 * This also doesn't do any validation, and won't work for serialized arrays
1119
+	 *
1120
+	 * @param string $field_name
1121
+	 * @param mixed  $field_value_from_db
1122
+	 * @throws ReflectionException
1123
+	 * @throws InvalidArgumentException
1124
+	 * @throws InvalidInterfaceException
1125
+	 * @throws InvalidDataTypeException
1126
+	 * @throws EE_Error
1127
+	 */
1128
+	public function set_from_db($field_name, $field_value_from_db)
1129
+	{
1130
+		$field_obj = $this->get_model()->field_settings_for($field_name);
1131
+		if ($field_obj instanceof EE_Model_Field_Base) {
1132
+			// you would think the DB has no NULLs for non-null label fields right? wrong!
1133
+			// eg, a CPT model object could have an entry in the posts table, but no
1134
+			// entry in the meta table. Meaning that all its columns in the meta table
1135
+			// are null! yikes! so when we find one like that, use defaults for its meta columns
1136
+			if ($field_value_from_db === null) {
1137
+				if ($field_obj->is_nullable()) {
1138
+					// if the field allows nulls, then let it be null
1139
+					$field_value = null;
1140
+				} else {
1141
+					$field_value = $field_obj->get_default_value();
1142
+				}
1143
+			} else {
1144
+				$field_value = $field_obj->prepare_for_set_from_db($field_value_from_db);
1145
+			}
1146
+			$this->_fields[ $field_name ] = $field_value;
1147
+			$this->_clear_cached_property($field_name);
1148
+		}
1149
+	}
1150
+
1151
+
1152
+	/**
1153
+	 * verifies that the specified field is of the correct type
1154
+	 *
1155
+	 * @param string $field_name
1156
+	 * @param string $extra_cache_ref This allows the user to specify an extra cache ref for the given property
1157
+	 *                                (in cases where the same property may be used for different outputs
1158
+	 *                                - i.e. datetime, money etc.)
1159
+	 * @return mixed
1160
+	 * @throws ReflectionException
1161
+	 * @throws InvalidArgumentException
1162
+	 * @throws InvalidInterfaceException
1163
+	 * @throws InvalidDataTypeException
1164
+	 * @throws EE_Error
1165
+	 */
1166
+	public function get($field_name, $extra_cache_ref = null)
1167
+	{
1168
+		return $this->_get_cached_property($field_name, false, $extra_cache_ref);
1169
+	}
1170
+
1171
+
1172
+	/**
1173
+	 * This method simply returns the RAW unprocessed value for the given property in this class
1174
+	 *
1175
+	 * @param  string $field_name A valid fieldname
1176
+	 * @return mixed              Whatever the raw value stored on the property is.
1177
+	 * @throws ReflectionException
1178
+	 * @throws InvalidArgumentException
1179
+	 * @throws InvalidInterfaceException
1180
+	 * @throws InvalidDataTypeException
1181
+	 * @throws EE_Error if fieldSettings is misconfigured or the field doesn't exist.
1182
+	 */
1183
+	public function get_raw($field_name)
1184
+	{
1185
+		$field_settings = $this->get_model()->field_settings_for($field_name);
1186
+		return $field_settings instanceof EE_Datetime_Field && $this->_fields[ $field_name ] instanceof DateTime
1187
+			? $this->_fields[ $field_name ]->format('U')
1188
+			: $this->_fields[ $field_name ];
1189
+	}
1190
+
1191
+
1192
+	/**
1193
+	 * This is used to return the internal DateTime object used for a field that is a
1194
+	 * EE_Datetime_Field.
1195
+	 *
1196
+	 * @param string $field_name               The field name retrieving the DateTime object.
1197
+	 * @return mixed null | false | DateTime  If the requested field is NOT a EE_Datetime_Field then
1198
+	 * @throws EE_Error an error is set and false returned.  If the field IS an
1199
+	 *                                         EE_Datetime_Field and but the field value is null, then
1200
+	 *                                         just null is returned (because that indicates that likely
1201
+	 *                                         this field is nullable).
1202
+	 * @throws InvalidArgumentException
1203
+	 * @throws InvalidDataTypeException
1204
+	 * @throws InvalidInterfaceException
1205
+	 * @throws ReflectionException
1206
+	 */
1207
+	public function get_DateTime_object($field_name)
1208
+	{
1209
+		$field_settings = $this->get_model()->field_settings_for($field_name);
1210
+		if (! $field_settings instanceof EE_Datetime_Field) {
1211
+			EE_Error::add_error(
1212
+				sprintf(
1213
+					esc_html__(
1214
+						'The field %s is not an EE_Datetime_Field field.  There is no DateTime object stored on this field type.',
1215
+						'event_espresso'
1216
+					),
1217
+					$field_name
1218
+				),
1219
+				__FILE__,
1220
+				__FUNCTION__,
1221
+				__LINE__
1222
+			);
1223
+			return false;
1224
+		}
1225
+		return isset($this->_fields[ $field_name ]) && $this->_fields[ $field_name ] instanceof DateTime
1226
+			? clone $this->_fields[ $field_name ]
1227
+			: null;
1228
+	}
1229
+
1230
+
1231
+	/**
1232
+	 * To be used in template to immediately echo out the value, and format it for output.
1233
+	 * Eg, should call stripslashes and whatnot before echoing
1234
+	 *
1235
+	 * @param string $field_name      the name of the field as it appears in the DB
1236
+	 * @param string $extra_cache_ref This allows the user to specify an extra cache ref for the given property
1237
+	 *                                (in cases where the same property may be used for different outputs
1238
+	 *                                - i.e. datetime, money etc.)
1239
+	 * @return void
1240
+	 * @throws ReflectionException
1241
+	 * @throws InvalidArgumentException
1242
+	 * @throws InvalidInterfaceException
1243
+	 * @throws InvalidDataTypeException
1244
+	 * @throws EE_Error
1245
+	 */
1246
+	public function e($field_name, $extra_cache_ref = null)
1247
+	{
1248
+		echo $this->get_pretty($field_name, $extra_cache_ref);
1249
+	}
1250
+
1251
+
1252
+	/**
1253
+	 * Exactly like e(), echoes out the field, but sets its schema to 'form_input', so that it
1254
+	 * can be easily used as the value of form input.
1255
+	 *
1256
+	 * @param string $field_name
1257
+	 * @return void
1258
+	 * @throws ReflectionException
1259
+	 * @throws InvalidArgumentException
1260
+	 * @throws InvalidInterfaceException
1261
+	 * @throws InvalidDataTypeException
1262
+	 * @throws EE_Error
1263
+	 */
1264
+	public function f($field_name)
1265
+	{
1266
+		$this->e($field_name, 'form_input');
1267
+	}
1268
+
1269
+
1270
+	/**
1271
+	 * Same as `f()` but just returns the value instead of echoing it
1272
+	 *
1273
+	 * @param string $field_name
1274
+	 * @return string
1275
+	 * @throws ReflectionException
1276
+	 * @throws InvalidArgumentException
1277
+	 * @throws InvalidInterfaceException
1278
+	 * @throws InvalidDataTypeException
1279
+	 * @throws EE_Error
1280
+	 */
1281
+	public function get_f($field_name)
1282
+	{
1283
+		return (string) $this->get_pretty($field_name, 'form_input');
1284
+	}
1285
+
1286
+
1287
+	/**
1288
+	 * Gets a pretty view of the field's value. $extra_cache_ref can specify different formats for this.
1289
+	 * The $extra_cache_ref will be passed to the model field's prepare_for_pretty_echoing, so consult the field's class
1290
+	 * to see what options are available.
1291
+	 *
1292
+	 * @param string $field_name
1293
+	 * @param string $extra_cache_ref This allows the user to specify an extra cache ref for the given property
1294
+	 *                                (in cases where the same property may be used for different outputs
1295
+	 *                                - i.e. datetime, money etc.)
1296
+	 * @return mixed
1297
+	 * @throws ReflectionException
1298
+	 * @throws InvalidArgumentException
1299
+	 * @throws InvalidInterfaceException
1300
+	 * @throws InvalidDataTypeException
1301
+	 * @throws EE_Error
1302
+	 */
1303
+	public function get_pretty($field_name, $extra_cache_ref = null)
1304
+	{
1305
+		return $this->_get_cached_property($field_name, true, $extra_cache_ref);
1306
+	}
1307
+
1308
+
1309
+	/**
1310
+	 * This simply returns the datetime for the given field name
1311
+	 * Note: this protected function is called by the wrapper get_date or get_time or get_datetime functions
1312
+	 * (and the equivalent e_date, e_time, e_datetime).
1313
+	 *
1314
+	 * @access   protected
1315
+	 * @param string   $field_name   Field on the instantiated EE_Base_Class child object
1316
+	 * @param string   $dt_frmt      valid datetime format used for date
1317
+	 *                               (if '' then we just use the default on the field,
1318
+	 *                               if NULL we use the last-used format)
1319
+	 * @param string   $tm_frmt      Same as above except this is for time format
1320
+	 * @param string   $date_or_time if NULL then both are returned, otherwise "D" = only date and "T" = only time.
1321
+	 * @param  boolean $echo         Whether the dtt is echoing using pretty echoing or just returned using vanilla get
1322
+	 * @return string|bool|EE_Error string on success, FALSE on fail, or EE_Error Exception is thrown
1323
+	 *                               if field is not a valid dtt field, or void if echoing
1324
+	 * @throws ReflectionException
1325
+	 * @throws InvalidArgumentException
1326
+	 * @throws InvalidInterfaceException
1327
+	 * @throws InvalidDataTypeException
1328
+	 * @throws EE_Error
1329
+	 */
1330
+	protected function _get_datetime($field_name, $dt_frmt = '', $tm_frmt = '', $date_or_time = '', $echo = false)
1331
+	{
1332
+		// clear cached property
1333
+		$this->_clear_cached_property($field_name);
1334
+		// reset format properties because they are used in get()
1335
+		$this->_dt_frmt = $dt_frmt !== '' ? $dt_frmt : $this->_dt_frmt;
1336
+		$this->_tm_frmt = $tm_frmt !== '' ? $tm_frmt : $this->_tm_frmt;
1337
+		if ($echo) {
1338
+			$this->e($field_name, $date_or_time);
1339
+			return '';
1340
+		}
1341
+		return $this->get($field_name, $date_or_time);
1342
+	}
1343
+
1344
+
1345
+	/**
1346
+	 * below are wrapper functions for the various datetime outputs that can be obtained for JUST returning the date
1347
+	 * portion of a datetime value. (note the only difference between get_ and e_ is one returns the value and the
1348
+	 * other echoes the pretty value for dtt)
1349
+	 *
1350
+	 * @param  string $field_name name of model object datetime field holding the value
1351
+	 * @param  string $format     format for the date returned (if NULL we use default in dt_frmt property)
1352
+	 * @return string            datetime value formatted
1353
+	 * @throws ReflectionException
1354
+	 * @throws InvalidArgumentException
1355
+	 * @throws InvalidInterfaceException
1356
+	 * @throws InvalidDataTypeException
1357
+	 * @throws EE_Error
1358
+	 */
1359
+	public function get_date($field_name, $format = '')
1360
+	{
1361
+		return $this->_get_datetime($field_name, $format, null, 'D');
1362
+	}
1363
+
1364
+
1365
+	/**
1366
+	 * @param        $field_name
1367
+	 * @param string $format
1368
+	 * @throws ReflectionException
1369
+	 * @throws InvalidArgumentException
1370
+	 * @throws InvalidInterfaceException
1371
+	 * @throws InvalidDataTypeException
1372
+	 * @throws EE_Error
1373
+	 */
1374
+	public function e_date($field_name, $format = '')
1375
+	{
1376
+		$this->_get_datetime($field_name, $format, null, 'D', true);
1377
+	}
1378
+
1379
+
1380
+	/**
1381
+	 * below are wrapper functions for the various datetime outputs that can be obtained for JUST returning the time
1382
+	 * portion of a datetime value. (note the only difference between get_ and e_ is one returns the value and the
1383
+	 * other echoes the pretty value for dtt)
1384
+	 *
1385
+	 * @param  string $field_name name of model object datetime field holding the value
1386
+	 * @param  string $format     format for the time returned ( if NULL we use default in tm_frmt property)
1387
+	 * @return string             datetime value formatted
1388
+	 * @throws ReflectionException
1389
+	 * @throws InvalidArgumentException
1390
+	 * @throws InvalidInterfaceException
1391
+	 * @throws InvalidDataTypeException
1392
+	 * @throws EE_Error
1393
+	 */
1394
+	public function get_time($field_name, $format = '')
1395
+	{
1396
+		return $this->_get_datetime($field_name, null, $format, 'T');
1397
+	}
1398
+
1399
+
1400
+	/**
1401
+	 * @param        $field_name
1402
+	 * @param string $format
1403
+	 * @throws ReflectionException
1404
+	 * @throws InvalidArgumentException
1405
+	 * @throws InvalidInterfaceException
1406
+	 * @throws InvalidDataTypeException
1407
+	 * @throws EE_Error
1408
+	 */
1409
+	public function e_time($field_name, $format = '')
1410
+	{
1411
+		$this->_get_datetime($field_name, null, $format, 'T', true);
1412
+	}
1413
+
1414
+
1415
+	/**
1416
+	 * below are wrapper functions for the various datetime outputs that can be obtained for returning the date AND
1417
+	 * time portion of a datetime value. (note the only difference between get_ and e_ is one returns the value and the
1418
+	 * other echoes the pretty value for dtt)
1419
+	 *
1420
+	 * @param  string $field_name name of model object datetime field holding the value
1421
+	 * @param  string $dt_frmt    format for the date returned (if NULL we use default in dt_frmt property)
1422
+	 * @param  string $tm_frmt    format for the time returned (if NULL we use default in tm_frmt property)
1423
+	 * @return string             datetime value formatted
1424
+	 * @throws ReflectionException
1425
+	 * @throws InvalidArgumentException
1426
+	 * @throws InvalidInterfaceException
1427
+	 * @throws InvalidDataTypeException
1428
+	 * @throws EE_Error
1429
+	 */
1430
+	public function get_datetime($field_name, $dt_frmt = '', $tm_frmt = '')
1431
+	{
1432
+		return $this->_get_datetime($field_name, $dt_frmt, $tm_frmt);
1433
+	}
1434
+
1435
+
1436
+	/**
1437
+	 * @param string $field_name
1438
+	 * @param string $dt_frmt
1439
+	 * @param string $tm_frmt
1440
+	 * @throws ReflectionException
1441
+	 * @throws InvalidArgumentException
1442
+	 * @throws InvalidInterfaceException
1443
+	 * @throws InvalidDataTypeException
1444
+	 * @throws EE_Error
1445
+	 */
1446
+	public function e_datetime($field_name, $dt_frmt = '', $tm_frmt = '')
1447
+	{
1448
+		$this->_get_datetime($field_name, $dt_frmt, $tm_frmt, null, true);
1449
+	}
1450
+
1451
+
1452
+	/**
1453
+	 * Get the i8ln value for a date using the WordPress @see date_i18n function.
1454
+	 *
1455
+	 * @param string $field_name The EE_Datetime_Field reference for the date being retrieved.
1456
+	 * @param string $format     PHP valid date/time string format.  If none is provided then the internal set format
1457
+	 *                           on the object will be used.
1458
+	 * @return string Date and time string in set locale or false if no field exists for the given
1459
+	 * @throws ReflectionException
1460
+	 * @throws InvalidArgumentException
1461
+	 * @throws InvalidInterfaceException
1462
+	 * @throws InvalidDataTypeException
1463
+	 * @throws EE_Error
1464
+	 *                           field name.
1465
+	 */
1466
+	public function get_i18n_datetime($field_name, $format = '')
1467
+	{
1468
+		$format = empty($format) ? $this->_dt_frmt . ' ' . $this->_tm_frmt : $format;
1469
+		return date_i18n(
1470
+			$format,
1471
+			EEH_DTT_Helper::get_timestamp_with_offset(
1472
+				$this->get_raw($field_name),
1473
+				$this->_timezone
1474
+			)
1475
+		);
1476
+	}
1477
+
1478
+
1479
+	/**
1480
+	 * This method validates whether the given field name is a valid field on the model object as well as it is of a
1481
+	 * type EE_Datetime_Field.  On success there will be returned the field settings.  On fail an EE_Error exception is
1482
+	 * thrown.
1483
+	 *
1484
+	 * @param  string $field_name The field name being checked
1485
+	 * @throws ReflectionException
1486
+	 * @throws InvalidArgumentException
1487
+	 * @throws InvalidInterfaceException
1488
+	 * @throws InvalidDataTypeException
1489
+	 * @throws EE_Error
1490
+	 * @return EE_Datetime_Field
1491
+	 */
1492
+	protected function _get_dtt_field_settings($field_name)
1493
+	{
1494
+		$field = $this->get_model()->field_settings_for($field_name);
1495
+		// check if field is dtt
1496
+		if ($field instanceof EE_Datetime_Field) {
1497
+			return $field;
1498
+		}
1499
+		throw new EE_Error(
1500
+			sprintf(
1501
+				esc_html__(
1502
+					'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',
1503
+					'event_espresso'
1504
+				),
1505
+				$field_name,
1506
+				self::_get_model_classname(get_class($this))
1507
+			)
1508
+		);
1509
+	}
1510
+
1511
+
1512
+
1513
+
1514
+	/**
1515
+	 * NOTE ABOUT BELOW:
1516
+	 * These convenience date and time setters are for setting date and time independently.  In other words you might
1517
+	 * want to change the time on a datetime_field but leave the date the same (or vice versa). IF on the other hand
1518
+	 * you want to set both date and time at the same time, you can just use the models default set($fieldname,$value)
1519
+	 * method and make sure you send the entire datetime value for setting.
1520
+	 */
1521
+	/**
1522
+	 * sets the time on a datetime property
1523
+	 *
1524
+	 * @access protected
1525
+	 * @param string|Datetime $time      a valid time string for php datetime functions (or DateTime object)
1526
+	 * @param string          $fieldname the name of the field the time is being set on (must match a EE_Datetime_Field)
1527
+	 * @throws ReflectionException
1528
+	 * @throws InvalidArgumentException
1529
+	 * @throws InvalidInterfaceException
1530
+	 * @throws InvalidDataTypeException
1531
+	 * @throws EE_Error
1532
+	 */
1533
+	protected function _set_time_for($time, $fieldname)
1534
+	{
1535
+		$this->_set_date_time('T', $time, $fieldname);
1536
+	}
1537
+
1538
+
1539
+	/**
1540
+	 * sets the date on a datetime property
1541
+	 *
1542
+	 * @access protected
1543
+	 * @param string|DateTime $date      a valid date string for php datetime functions ( or DateTime object)
1544
+	 * @param string          $fieldname the name of the field the date is being set on (must match a EE_Datetime_Field)
1545
+	 * @throws ReflectionException
1546
+	 * @throws InvalidArgumentException
1547
+	 * @throws InvalidInterfaceException
1548
+	 * @throws InvalidDataTypeException
1549
+	 * @throws EE_Error
1550
+	 */
1551
+	protected function _set_date_for($date, $fieldname)
1552
+	{
1553
+		$this->_set_date_time('D', $date, $fieldname);
1554
+	}
1555
+
1556
+
1557
+	/**
1558
+	 * This takes care of setting a date or time independently on a given model object property. This method also
1559
+	 * verifies that the given fieldname matches a model object property and is for a EE_Datetime_Field field
1560
+	 *
1561
+	 * @access protected
1562
+	 * @param string          $what           "T" for time, 'B' for both, 'D' for Date.
1563
+	 * @param string|DateTime $datetime_value A valid Date or Time string (or DateTime object)
1564
+	 * @param string          $fieldname      the name of the field the date OR time is being set on (must match a
1565
+	 *                                        EE_Datetime_Field property)
1566
+	 * @throws ReflectionException
1567
+	 * @throws InvalidArgumentException
1568
+	 * @throws InvalidInterfaceException
1569
+	 * @throws InvalidDataTypeException
1570
+	 * @throws EE_Error
1571
+	 */
1572
+	protected function _set_date_time($what = 'T', $datetime_value, $fieldname)
1573
+	{
1574
+		$field = $this->_get_dtt_field_settings($fieldname);
1575
+		$field->set_timezone($this->_timezone);
1576
+		$field->set_date_format($this->_dt_frmt);
1577
+		$field->set_time_format($this->_tm_frmt);
1578
+		switch ($what) {
1579
+			case 'T':
1580
+				$this->_fields[ $fieldname ] = $field->prepare_for_set_with_new_time(
1581
+					$datetime_value,
1582
+					$this->_fields[ $fieldname ]
1583
+				);
1584
+				$this->_has_changes = true;
1585
+				break;
1586
+			case 'D':
1587
+				$this->_fields[ $fieldname ] = $field->prepare_for_set_with_new_date(
1588
+					$datetime_value,
1589
+					$this->_fields[ $fieldname ]
1590
+				);
1591
+				$this->_has_changes = true;
1592
+				break;
1593
+			case 'B':
1594
+				$this->_fields[ $fieldname ] = $field->prepare_for_set($datetime_value);
1595
+				$this->_has_changes = true;
1596
+				break;
1597
+		}
1598
+		$this->_clear_cached_property($fieldname);
1599
+	}
1600
+
1601
+
1602
+	/**
1603
+	 * This will return a timestamp for the website timezone but ONLY when the current website timezone is different
1604
+	 * than the timezone set for the website. NOTE, this currently only works well with methods that return values.  If
1605
+	 * you use it with methods that echo values the $_timestamp property may not get reset to its original value and
1606
+	 * that could lead to some unexpected results!
1607
+	 *
1608
+	 * @access public
1609
+	 * @param string $field_name               This is the name of the field on the object that contains the date/time
1610
+	 *                                         value being returned.
1611
+	 * @param string $callback                 must match a valid method in this class (defaults to get_datetime)
1612
+	 * @param mixed (array|string) $args       This is the arguments that will be passed to the callback.
1613
+	 * @param string $prepend                  You can include something to prepend on the timestamp
1614
+	 * @param string $append                   You can include something to append on the timestamp
1615
+	 * @throws ReflectionException
1616
+	 * @throws InvalidArgumentException
1617
+	 * @throws InvalidInterfaceException
1618
+	 * @throws InvalidDataTypeException
1619
+	 * @throws EE_Error
1620
+	 * @return string timestamp
1621
+	 */
1622
+	public function display_in_my_timezone(
1623
+		$field_name,
1624
+		$callback = 'get_datetime',
1625
+		$args = null,
1626
+		$prepend = '',
1627
+		$append = ''
1628
+	) {
1629
+		$timezone = EEH_DTT_Helper::get_timezone();
1630
+		if ($timezone === $this->_timezone) {
1631
+			return '';
1632
+		}
1633
+		$original_timezone = $this->_timezone;
1634
+		$this->set_timezone($timezone);
1635
+		$fn = (array) $field_name;
1636
+		$args = array_merge($fn, (array) $args);
1637
+		if (! method_exists($this, $callback)) {
1638
+			throw new EE_Error(
1639
+				sprintf(
1640
+					esc_html__(
1641
+						'The method named "%s" given as the callback param in "display_in_my_timezone" does not exist.  Please check your spelling',
1642
+						'event_espresso'
1643
+					),
1644
+					$callback
1645
+				)
1646
+			);
1647
+		}
1648
+		$args = (array) $args;
1649
+		$return = $prepend . call_user_func_array(array($this, $callback), $args) . $append;
1650
+		$this->set_timezone($original_timezone);
1651
+		return $return;
1652
+	}
1653
+
1654
+
1655
+	/**
1656
+	 * Deletes this model object.
1657
+	 * This calls the `EE_Base_Class::_delete` method.  Child classes wishing to change default behaviour should
1658
+	 * override
1659
+	 * `EE_Base_Class::_delete` NOT this class.
1660
+	 *
1661
+	 * @return boolean | int
1662
+	 * @throws ReflectionException
1663
+	 * @throws InvalidArgumentException
1664
+	 * @throws InvalidInterfaceException
1665
+	 * @throws InvalidDataTypeException
1666
+	 * @throws EE_Error
1667
+	 */
1668
+	public function delete()
1669
+	{
1670
+		/**
1671
+		 * Called just before the `EE_Base_Class::_delete` method call.
1672
+		 * Note:
1673
+		 * `EE_Base_Class::_delete` might be overridden by child classes so any client code hooking into these actions
1674
+		 * should be aware that `_delete` may not always result in a permanent delete.
1675
+		 * For example, `EE_Soft_Delete_Base_Class::_delete`
1676
+		 * soft deletes (trash) the object and does not permanently delete it.
1677
+		 *
1678
+		 * @param EE_Base_Class $model_object about to be 'deleted'
1679
+		 */
1680
+		do_action('AHEE__EE_Base_Class__delete__before', $this);
1681
+		$result = $this->_delete();
1682
+		/**
1683
+		 * Called just after the `EE_Base_Class::_delete` method call.
1684
+		 * Note:
1685
+		 * `EE_Base_Class::_delete` might be overridden by child classes so any client code hooking into these actions
1686
+		 * should be aware that `_delete` may not always result in a permanent delete.
1687
+		 * For example `EE_Soft_Base_Class::_delete`
1688
+		 * soft deletes (trash) the object and does not permanently delete it.
1689
+		 *
1690
+		 * @param EE_Base_Class $model_object that was just 'deleted'
1691
+		 * @param boolean       $result
1692
+		 */
1693
+		do_action('AHEE__EE_Base_Class__delete__end', $this, $result);
1694
+		return $result;
1695
+	}
1696
+
1697
+
1698
+	/**
1699
+	 * Calls the specific delete method for the instantiated class.
1700
+	 * This method is called by the public `EE_Base_Class::delete` method.  Any child classes desiring to override
1701
+	 * default functionality for "delete" (which is to call `permanently_delete`) should override this method NOT
1702
+	 * `EE_Base_Class::delete`
1703
+	 *
1704
+	 * @return bool|int
1705
+	 * @throws ReflectionException
1706
+	 * @throws InvalidArgumentException
1707
+	 * @throws InvalidInterfaceException
1708
+	 * @throws InvalidDataTypeException
1709
+	 * @throws EE_Error
1710
+	 */
1711
+	protected function _delete()
1712
+	{
1713
+		return $this->delete_permanently();
1714
+	}
1715
+
1716
+
1717
+	/**
1718
+	 * Deletes this model object permanently from db
1719
+	 * (but keep in mind related models may block the delete and return an error)
1720
+	 *
1721
+	 * @return bool | int
1722
+	 * @throws ReflectionException
1723
+	 * @throws InvalidArgumentException
1724
+	 * @throws InvalidInterfaceException
1725
+	 * @throws InvalidDataTypeException
1726
+	 * @throws EE_Error
1727
+	 */
1728
+	public function delete_permanently()
1729
+	{
1730
+		/**
1731
+		 * Called just before HARD deleting a model object
1732
+		 *
1733
+		 * @param EE_Base_Class $model_object about to be 'deleted'
1734
+		 */
1735
+		do_action('AHEE__EE_Base_Class__delete_permanently__before', $this);
1736
+		$model = $this->get_model();
1737
+		$result = $model->delete_permanently_by_ID($this->ID());
1738
+		$this->refresh_cache_of_related_objects();
1739
+		/**
1740
+		 * Called just after HARD deleting a model object
1741
+		 *
1742
+		 * @param EE_Base_Class $model_object that was just 'deleted'
1743
+		 * @param boolean       $result
1744
+		 */
1745
+		do_action('AHEE__EE_Base_Class__delete_permanently__end', $this, $result);
1746
+		return $result;
1747
+	}
1748
+
1749
+
1750
+	/**
1751
+	 * When this model object is deleted, it may still be cached on related model objects. This clears the cache of
1752
+	 * related model objects
1753
+	 *
1754
+	 * @throws ReflectionException
1755
+	 * @throws InvalidArgumentException
1756
+	 * @throws InvalidInterfaceException
1757
+	 * @throws InvalidDataTypeException
1758
+	 * @throws EE_Error
1759
+	 */
1760
+	public function refresh_cache_of_related_objects()
1761
+	{
1762
+		$model = $this->get_model();
1763
+		foreach ($model->relation_settings() as $relation_name => $relation_obj) {
1764
+			if (! empty($this->_model_relations[ $relation_name ])) {
1765
+				$related_objects = $this->_model_relations[ $relation_name ];
1766
+				if ($relation_obj instanceof EE_Belongs_To_Relation) {
1767
+					// this relation only stores a single model object, not an array
1768
+					// but let's make it consistent
1769
+					$related_objects = array($related_objects);
1770
+				}
1771
+				foreach ($related_objects as $related_object) {
1772
+					// only refresh their cache if they're in memory
1773
+					if ($related_object instanceof EE_Base_Class) {
1774
+						$related_object->clear_cache(
1775
+							$model->get_this_model_name(),
1776
+							$this
1777
+						);
1778
+					}
1779
+				}
1780
+			}
1781
+		}
1782
+	}
1783
+
1784
+
1785
+	/**
1786
+	 *        Saves this object to the database. An array may be supplied to set some values on this
1787
+	 * object just before saving.
1788
+	 *
1789
+	 * @access public
1790
+	 * @param array $set_cols_n_values keys are field names, values are their new values,
1791
+	 *                                 if provided during the save() method (often client code will change the fields'
1792
+	 *                                 values before calling save)
1793
+	 * @throws InvalidArgumentException
1794
+	 * @throws InvalidInterfaceException
1795
+	 * @throws InvalidDataTypeException
1796
+	 * @throws EE_Error
1797
+	 * @return int , 1 on a successful update, the ID of the new entry on insert; 0 on failure or if the model object
1798
+	 *                                 isn't allowed to persist (as determined by EE_Base_Class::allow_persist())
1799
+	 * @throws ReflectionException
1800
+	 * @throws ReflectionException
1801
+	 * @throws ReflectionException
1802
+	 */
1803
+	public function save($set_cols_n_values = array())
1804
+	{
1805
+		$model = $this->get_model();
1806
+		/**
1807
+		 * Filters the fields we're about to save on the model object
1808
+		 *
1809
+		 * @param array         $set_cols_n_values
1810
+		 * @param EE_Base_Class $model_object
1811
+		 */
1812
+		$set_cols_n_values = (array) apply_filters(
1813
+			'FHEE__EE_Base_Class__save__set_cols_n_values',
1814
+			$set_cols_n_values,
1815
+			$this
1816
+		);
1817
+		// set attributes as provided in $set_cols_n_values
1818
+		foreach ($set_cols_n_values as $column => $value) {
1819
+			$this->set($column, $value);
1820
+		}
1821
+		// no changes ? then don't do anything
1822
+		if (! $this->_has_changes && $this->ID() && $model->get_primary_key_field()->is_auto_increment()) {
1823
+			return 0;
1824
+		}
1825
+		/**
1826
+		 * Saving a model object.
1827
+		 * Before we perform a save, this action is fired.
1828
+		 *
1829
+		 * @param EE_Base_Class $model_object the model object about to be saved.
1830
+		 */
1831
+		do_action('AHEE__EE_Base_Class__save__begin', $this);
1832
+		if (! $this->allow_persist()) {
1833
+			return 0;
1834
+		}
1835
+		// now get current attribute values
1836
+		$save_cols_n_values = $this->_fields;
1837
+		// if the object already has an ID, update it. Otherwise, insert it
1838
+		// also: change the assumption about values passed to the model NOT being prepare dby the model object.
1839
+		// They have been
1840
+		$old_assumption_concerning_value_preparation = $model
1841
+			->get_assumption_concerning_values_already_prepared_by_model_object();
1842
+		$model->assume_values_already_prepared_by_model_object(true);
1843
+		// does this model have an autoincrement PK?
1844
+		if ($model->has_primary_key_field()) {
1845
+			if ($model->get_primary_key_field()->is_auto_increment()) {
1846
+				// ok check if it's set, if so: update; if not, insert
1847
+				if (! empty($save_cols_n_values[ $model->primary_key_name() ])) {
1848
+					$results = $model->update_by_ID($save_cols_n_values, $this->ID());
1849
+				} else {
1850
+					unset($save_cols_n_values[ $model->primary_key_name() ]);
1851
+					$results = $model->insert($save_cols_n_values);
1852
+					if ($results) {
1853
+						// if successful, set the primary key
1854
+						// but don't use the normal SET method, because it will check if
1855
+						// an item with the same ID exists in the mapper & db, then
1856
+						// will find it in the db (because we just added it) and THAT object
1857
+						// will get added to the mapper before we can add this one!
1858
+						// but if we just avoid using the SET method, all that headache can be avoided
1859
+						$pk_field_name = $model->primary_key_name();
1860
+						$this->_fields[ $pk_field_name ] = $results;
1861
+						$this->_clear_cached_property($pk_field_name);
1862
+						$model->add_to_entity_map($this);
1863
+						$this->_update_cached_related_model_objs_fks();
1864
+					}
1865
+				}
1866
+			} else {// PK is NOT auto-increment
1867
+				// so check if one like it already exists in the db
1868
+				if ($model->exists_by_ID($this->ID())) {
1869
+					if (WP_DEBUG && ! $this->in_entity_map()) {
1870
+						throw new EE_Error(
1871
+							sprintf(
1872
+								esc_html__(
1873
+									'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',
1874
+									'event_espresso'
1875
+								),
1876
+								get_class($this),
1877
+								get_class($model) . '::instance()->add_to_entity_map()',
1878
+								get_class($model) . '::instance()->get_one_by_ID()',
1879
+								'<br />'
1880
+							)
1881
+						);
1882
+					}
1883
+					$results = $model->update_by_ID($save_cols_n_values, $this->ID());
1884
+				} else {
1885
+					$results = $model->insert($save_cols_n_values);
1886
+					$this->_update_cached_related_model_objs_fks();
1887
+				}
1888
+			}
1889
+		} else {// there is NO primary key
1890
+			$already_in_db = false;
1891
+			foreach ($model->unique_indexes() as $index) {
1892
+				$uniqueness_where_params = array_intersect_key($save_cols_n_values, $index->fields());
1893
+				if ($model->exists(array($uniqueness_where_params))) {
1894
+					$already_in_db = true;
1895
+				}
1896
+			}
1897
+			if ($already_in_db) {
1898
+				$combined_pk_fields_n_values = array_intersect_key(
1899
+					$save_cols_n_values,
1900
+					$model->get_combined_primary_key_fields()
1901
+				);
1902
+				$results = $model->update(
1903
+					$save_cols_n_values,
1904
+					$combined_pk_fields_n_values
1905
+				);
1906
+			} else {
1907
+				$results = $model->insert($save_cols_n_values);
1908
+			}
1909
+		}
1910
+		// restore the old assumption about values being prepared by the model object
1911
+		$model->assume_values_already_prepared_by_model_object(
1912
+			$old_assumption_concerning_value_preparation
1913
+		);
1914
+		/**
1915
+		 * After saving the model object this action is called
1916
+		 *
1917
+		 * @param EE_Base_Class $model_object which was just saved
1918
+		 * @param boolean|int   $results      if it were updated, TRUE or FALSE; if it were newly inserted
1919
+		 *                                    the new ID (or 0 if an error occurred and it wasn't updated)
1920
+		 */
1921
+		do_action('AHEE__EE_Base_Class__save__end', $this, $results);
1922
+		$this->_has_changes = false;
1923
+		return $results;
1924
+	}
1925
+
1926
+
1927
+	/**
1928
+	 * Updates the foreign key on related models objects pointing to this to have this model object's ID
1929
+	 * as their foreign key.  If the cached related model objects already exist in the db, saves them (so that the DB
1930
+	 * is consistent) Especially useful in case we JUST added this model object ot the database and we want to let its
1931
+	 * cached relations with foreign keys to it know about that change. Eg: we've created a transaction but haven't
1932
+	 * 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
1933
+	 * transaction. Now, when we save the transaction, the registration's TXN_ID will be automatically updated, whether
1934
+	 * or not they exist in the DB (if they do, their DB records will be automatically updated)
1935
+	 *
1936
+	 * @return void
1937
+	 * @throws ReflectionException
1938
+	 * @throws InvalidArgumentException
1939
+	 * @throws InvalidInterfaceException
1940
+	 * @throws InvalidDataTypeException
1941
+	 * @throws EE_Error
1942
+	 */
1943
+	protected function _update_cached_related_model_objs_fks()
1944
+	{
1945
+		$model = $this->get_model();
1946
+		foreach ($model->relation_settings() as $relation_name => $relation_obj) {
1947
+			if ($relation_obj instanceof EE_Has_Many_Relation) {
1948
+				foreach ($this->get_all_from_cache($relation_name) as $related_model_obj_in_cache) {
1949
+					$fk_to_this = $related_model_obj_in_cache->get_model()->get_foreign_key_to(
1950
+						$model->get_this_model_name()
1951
+					);
1952
+					$related_model_obj_in_cache->set($fk_to_this->get_name(), $this->ID());
1953
+					if ($related_model_obj_in_cache->ID()) {
1954
+						$related_model_obj_in_cache->save();
1955
+					}
1956
+				}
1957
+			}
1958
+		}
1959
+	}
1960
+
1961
+
1962
+	/**
1963
+	 * Saves this model object and its NEW cached relations to the database.
1964
+	 * (Meaning, for now, IT DOES NOT WORK if the cached items already exist in the DB.
1965
+	 * In order for that to work, we would need to mark model objects as dirty/clean...
1966
+	 * because otherwise, there's a potential for infinite looping of saving
1967
+	 * Saves the cached related model objects, and ensures the relation between them
1968
+	 * and this object and properly setup
1969
+	 *
1970
+	 * @return int ID of new model object on save; 0 on failure+
1971
+	 * @throws ReflectionException
1972
+	 * @throws InvalidArgumentException
1973
+	 * @throws InvalidInterfaceException
1974
+	 * @throws InvalidDataTypeException
1975
+	 * @throws EE_Error
1976
+	 */
1977
+	public function save_new_cached_related_model_objs()
1978
+	{
1979
+		// make sure this has been saved
1980
+		if (! $this->ID()) {
1981
+			$id = $this->save();
1982
+		} else {
1983
+			$id = $this->ID();
1984
+		}
1985
+		// now save all the NEW cached model objects  (ie they don't exist in the DB)
1986
+		foreach ($this->get_model()->relation_settings() as $relationName => $relationObj) {
1987
+			if ($this->_model_relations[ $relationName ]) {
1988
+				// is this a relation where we should expect just ONE related object (ie, EE_Belongs_To_relation)
1989
+				// or MANY related objects (ie, EE_HABTM_Relation or EE_Has_Many_Relation)?
1990
+				/* @var $related_model_obj EE_Base_Class */
1991
+				if ($relationObj instanceof EE_Belongs_To_Relation) {
1992
+					// add a relation to that relation type (which saves the appropriate thing in the process)
1993
+					// but ONLY if it DOES NOT exist in the DB
1994
+					$related_model_obj = $this->_model_relations[ $relationName ];
1995
+					// if( ! $related_model_obj->ID()){
1996
+					$this->_add_relation_to($related_model_obj, $relationName);
1997
+					$related_model_obj->save_new_cached_related_model_objs();
1998
+					// }
1999
+				} else {
2000
+					foreach ($this->_model_relations[ $relationName ] as $related_model_obj) {
2001
+						// add a relation to that relation type (which saves the appropriate thing in the process)
2002
+						// but ONLY if it DOES NOT exist in the DB
2003
+						// if( ! $related_model_obj->ID()){
2004
+						$this->_add_relation_to($related_model_obj, $relationName);
2005
+						$related_model_obj->save_new_cached_related_model_objs();
2006
+						// }
2007
+					}
2008
+				}
2009
+			}
2010
+		}
2011
+		return $id;
2012
+	}
2013
+
2014
+
2015
+	/**
2016
+	 * for getting a model while instantiated.
2017
+	 *
2018
+	 * @return EEM_Base | EEM_CPT_Base
2019
+	 * @throws ReflectionException
2020
+	 * @throws InvalidArgumentException
2021
+	 * @throws InvalidInterfaceException
2022
+	 * @throws InvalidDataTypeException
2023
+	 * @throws EE_Error
2024
+	 */
2025
+	public function get_model()
2026
+	{
2027
+		if (! $this->_model) {
2028
+			$modelName = self::_get_model_classname(get_class($this));
2029
+			$this->_model = self::_get_model_instance_with_name($modelName, $this->_timezone);
2030
+		} else {
2031
+			$this->_model->set_timezone($this->_timezone);
2032
+		}
2033
+		return $this->_model;
2034
+	}
2035
+
2036
+
2037
+	/**
2038
+	 * @param $props_n_values
2039
+	 * @param $classname
2040
+	 * @return mixed bool|EE_Base_Class|EEM_CPT_Base
2041
+	 * @throws ReflectionException
2042
+	 * @throws InvalidArgumentException
2043
+	 * @throws InvalidInterfaceException
2044
+	 * @throws InvalidDataTypeException
2045
+	 * @throws EE_Error
2046
+	 */
2047
+	protected static function _get_object_from_entity_mapper($props_n_values, $classname)
2048
+	{
2049
+		// TODO: will not work for Term_Relationships because they have no PK!
2050
+		$primary_id_ref = self::_get_primary_key_name($classname);
2051
+		if (array_key_exists($primary_id_ref, $props_n_values)
2052
+			&& ! empty($props_n_values[ $primary_id_ref ])
2053
+		) {
2054
+			$id = $props_n_values[ $primary_id_ref ];
2055
+			return self::_get_model($classname)->get_from_entity_map($id);
2056
+		}
2057
+		return false;
2058
+	}
2059
+
2060
+
2061
+	/**
2062
+	 * This is called by child static "new_instance" method and we'll check to see if there is an existing db entry for
2063
+	 * the primary key (if present in incoming values). If there is a key in the incoming array that matches the
2064
+	 * 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
2065
+	 * we return false.
2066
+	 *
2067
+	 * @param  array  $props_n_values   incoming array of properties and their values
2068
+	 * @param  string $classname        the classname of the child class
2069
+	 * @param null    $timezone
2070
+	 * @param array   $date_formats     incoming date_formats in an array where the first value is the
2071
+	 *                                  date_format and the second value is the time format
2072
+	 * @return mixed (EE_Base_Class|bool)
2073
+	 * @throws InvalidArgumentException
2074
+	 * @throws InvalidInterfaceException
2075
+	 * @throws InvalidDataTypeException
2076
+	 * @throws EE_Error
2077
+	 * @throws ReflectionException
2078
+	 * @throws ReflectionException
2079
+	 * @throws ReflectionException
2080
+	 */
2081
+	protected static function _check_for_object($props_n_values, $classname, $timezone = null, $date_formats = array())
2082
+	{
2083
+		$existing = null;
2084
+		$model = self::_get_model($classname, $timezone);
2085
+		if ($model->has_primary_key_field()) {
2086
+			$primary_id_ref = self::_get_primary_key_name($classname);
2087
+			if (array_key_exists($primary_id_ref, $props_n_values)
2088
+				&& ! empty($props_n_values[ $primary_id_ref ])
2089
+			) {
2090
+				$existing = $model->get_one_by_ID(
2091
+					$props_n_values[ $primary_id_ref ]
2092
+				);
2093
+			}
2094
+		} elseif ($model->has_all_combined_primary_key_fields($props_n_values)) {
2095
+			// no primary key on this model, but there's still a matching item in the DB
2096
+			$existing = self::_get_model($classname, $timezone)->get_one_by_ID(
2097
+				self::_get_model($classname, $timezone)
2098
+					->get_index_primary_key_string($props_n_values)
2099
+			);
2100
+		}
2101
+		if ($existing) {
2102
+			// set date formats if present before setting values
2103
+			if (! empty($date_formats) && is_array($date_formats)) {
2104
+				$existing->set_date_format($date_formats[0]);
2105
+				$existing->set_time_format($date_formats[1]);
2106
+			} else {
2107
+				// set default formats for date and time
2108
+				$existing->set_date_format(get_option('date_format'));
2109
+				$existing->set_time_format(get_option('time_format'));
2110
+			}
2111
+			foreach ($props_n_values as $property => $field_value) {
2112
+				$existing->set($property, $field_value);
2113
+			}
2114
+			return $existing;
2115
+		}
2116
+		return false;
2117
+	}
2118
+
2119
+
2120
+	/**
2121
+	 * Gets the EEM_*_Model for this class
2122
+	 *
2123
+	 * @access public now, as this is more convenient
2124
+	 * @param      $classname
2125
+	 * @param null $timezone
2126
+	 * @throws ReflectionException
2127
+	 * @throws InvalidArgumentException
2128
+	 * @throws InvalidInterfaceException
2129
+	 * @throws InvalidDataTypeException
2130
+	 * @throws EE_Error
2131
+	 * @return EEM_Base
2132
+	 */
2133
+	protected static function _get_model($classname, $timezone = null)
2134
+	{
2135
+		// find model for this class
2136
+		if (! $classname) {
2137
+			throw new EE_Error(
2138
+				sprintf(
2139
+					esc_html__(
2140
+						'What were you thinking calling _get_model(%s)?? You need to specify the class name',
2141
+						'event_espresso'
2142
+					),
2143
+					$classname
2144
+				)
2145
+			);
2146
+		}
2147
+		$modelName = self::_get_model_classname($classname);
2148
+		return self::_get_model_instance_with_name($modelName, $timezone);
2149
+	}
2150
+
2151
+
2152
+	/**
2153
+	 * Gets the model instance (eg instance of EEM_Attendee) given its classname (eg EE_Attendee)
2154
+	 *
2155
+	 * @param string $model_classname
2156
+	 * @param null   $timezone
2157
+	 * @return EEM_Base
2158
+	 * @throws ReflectionException
2159
+	 * @throws InvalidArgumentException
2160
+	 * @throws InvalidInterfaceException
2161
+	 * @throws InvalidDataTypeException
2162
+	 * @throws EE_Error
2163
+	 */
2164
+	protected static function _get_model_instance_with_name($model_classname, $timezone = null)
2165
+	{
2166
+		$model_classname = str_replace('EEM_', '', $model_classname);
2167
+		$model = EE_Registry::instance()->load_model($model_classname);
2168
+		$model->set_timezone($timezone);
2169
+		return $model;
2170
+	}
2171
+
2172
+
2173
+	/**
2174
+	 * If a model name is provided (eg Registration), gets the model classname for that model.
2175
+	 * Also works if a model class's classname is provided (eg EE_Registration).
2176
+	 *
2177
+	 * @param null $model_name
2178
+	 * @return string like EEM_Attendee
2179
+	 */
2180
+	private static function _get_model_classname($model_name = null)
2181
+	{
2182
+		if (strpos($model_name, 'EE_') === 0) {
2183
+			$model_classname = str_replace('EE_', 'EEM_', $model_name);
2184
+		} else {
2185
+			$model_classname = 'EEM_' . $model_name;
2186
+		}
2187
+		return $model_classname;
2188
+	}
2189
+
2190
+
2191
+	/**
2192
+	 * returns the name of the primary key attribute
2193
+	 *
2194
+	 * @param null $classname
2195
+	 * @throws ReflectionException
2196
+	 * @throws InvalidArgumentException
2197
+	 * @throws InvalidInterfaceException
2198
+	 * @throws InvalidDataTypeException
2199
+	 * @throws EE_Error
2200
+	 * @return string
2201
+	 */
2202
+	protected static function _get_primary_key_name($classname = null)
2203
+	{
2204
+		if (! $classname) {
2205
+			throw new EE_Error(
2206
+				sprintf(
2207
+					esc_html__('What were you thinking calling _get_primary_key_name(%s)', 'event_espresso'),
2208
+					$classname
2209
+				)
2210
+			);
2211
+		}
2212
+		return self::_get_model($classname)->get_primary_key_field()->get_name();
2213
+	}
2214
+
2215
+
2216
+	/**
2217
+	 * Gets the value of the primary key.
2218
+	 * If the object hasn't yet been saved, it should be whatever the model field's default was
2219
+	 * (eg, if this were the EE_Event class, look at the primary key field on EEM_Event and see what its default value
2220
+	 * is. Usually defaults for integer primary keys are 0; string primary keys are usually NULL).
2221
+	 *
2222
+	 * @return mixed, if the primary key is of type INT it'll be an int. Otherwise it could be a string
2223
+	 * @throws ReflectionException
2224
+	 * @throws InvalidArgumentException
2225
+	 * @throws InvalidInterfaceException
2226
+	 * @throws InvalidDataTypeException
2227
+	 * @throws EE_Error
2228
+	 */
2229
+	public function ID()
2230
+	{
2231
+		$model = $this->get_model();
2232
+		// now that we know the name of the variable, use a variable variable to get its value and return its
2233
+		if ($model->has_primary_key_field()) {
2234
+			return $this->_fields[ $model->primary_key_name() ];
2235
+		}
2236
+		return $model->get_index_primary_key_string($this->_fields);
2237
+	}
2238
+
2239
+
2240
+	/**
2241
+	 * Adds a relationship to the specified EE_Base_Class object, given the relationship's name. Eg, if the current
2242
+	 * model is related to a group of events, the $relationName should be 'Event', and should be a key in the EE
2243
+	 * Model's $_model_relations array. If this model object doesn't exist in the DB, just caches the related thing
2244
+	 *
2245
+	 * @param mixed  $otherObjectModelObjectOrID       EE_Base_Class or the ID of the other object
2246
+	 * @param string $relationName                     eg 'Events','Question',etc.
2247
+	 *                                                 an attendee to a group, you also want to specify which role they
2248
+	 *                                                 will have in that group. So you would use this parameter to
2249
+	 *                                                 specify array('role-column-name'=>'role-id')
2250
+	 * @param array  $extra_join_model_fields_n_values You can optionally include an array of key=>value pairs that
2251
+	 *                                                 allow you to further constrict the relation to being added.
2252
+	 *                                                 However, keep in mind that the columns (keys) given must match a
2253
+	 *                                                 column on the JOIN table and currently only the HABTM models
2254
+	 *                                                 accept these additional conditions.  Also remember that if an
2255
+	 *                                                 exact match isn't found for these extra cols/val pairs, then a
2256
+	 *                                                 NEW row is created in the join table.
2257
+	 * @param null   $cache_id
2258
+	 * @throws ReflectionException
2259
+	 * @throws InvalidArgumentException
2260
+	 * @throws InvalidInterfaceException
2261
+	 * @throws InvalidDataTypeException
2262
+	 * @throws EE_Error
2263
+	 * @return EE_Base_Class the object the relation was added to
2264
+	 */
2265
+	public function _add_relation_to(
2266
+		$otherObjectModelObjectOrID,
2267
+		$relationName,
2268
+		$extra_join_model_fields_n_values = array(),
2269
+		$cache_id = null
2270
+	) {
2271
+		$model = $this->get_model();
2272
+		// if this thing exists in the DB, save the relation to the DB
2273
+		if ($this->ID()) {
2274
+			$otherObject = $model->add_relationship_to(
2275
+				$this,
2276
+				$otherObjectModelObjectOrID,
2277
+				$relationName,
2278
+				$extra_join_model_fields_n_values
2279
+			);
2280
+			// clear cache so future get_many_related and get_first_related() return new results.
2281
+			$this->clear_cache($relationName, $otherObject, true);
2282
+			if ($otherObject instanceof EE_Base_Class) {
2283
+				$otherObject->clear_cache($model->get_this_model_name(), $this);
2284
+			}
2285
+		} else {
2286
+			// this thing doesn't exist in the DB,  so just cache it
2287
+			if (! $otherObjectModelObjectOrID instanceof EE_Base_Class) {
2288
+				throw new EE_Error(
2289
+					sprintf(
2290
+						esc_html__(
2291
+							'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',
2292
+							'event_espresso'
2293
+						),
2294
+						$otherObjectModelObjectOrID,
2295
+						get_class($this)
2296
+					)
2297
+				);
2298
+			}
2299
+			$otherObject = $otherObjectModelObjectOrID;
2300
+			$this->cache($relationName, $otherObjectModelObjectOrID, $cache_id);
2301
+		}
2302
+		if ($otherObject instanceof EE_Base_Class) {
2303
+			// fix the reciprocal relation too
2304
+			if ($otherObject->ID()) {
2305
+				// its saved so assumed relations exist in the DB, so we can just
2306
+				// clear the cache so future queries use the updated info in the DB
2307
+				$otherObject->clear_cache(
2308
+					$model->get_this_model_name(),
2309
+					null,
2310
+					true
2311
+				);
2312
+			} else {
2313
+				// it's not saved, so it caches relations like this
2314
+				$otherObject->cache($model->get_this_model_name(), $this);
2315
+			}
2316
+		}
2317
+		return $otherObject;
2318
+	}
2319
+
2320
+
2321
+	/**
2322
+	 * Removes a relationship to the specified EE_Base_Class object, given the relationships' name. Eg, if the current
2323
+	 * model is related to a group of events, the $relationName should be 'Events', and should be a key in the EE
2324
+	 * Model's $_model_relations array. If this model object doesn't exist in the DB, just removes the related thing
2325
+	 * from the cache
2326
+	 *
2327
+	 * @param mixed  $otherObjectModelObjectOrID
2328
+	 *                EE_Base_Class or the ID of the other object, OR an array key into the cache if this isn't saved
2329
+	 *                to the DB yet
2330
+	 * @param string $relationName
2331
+	 * @param array  $where_query
2332
+	 *                You can optionally include an array of key=>value pairs that allow you to further constrict the
2333
+	 *                relation to being added. However, keep in mind that the columns (keys) given must match a column
2334
+	 *                on the JOIN table and currently only the HABTM models accept these additional conditions. Also
2335
+	 *                remember that if an exact match isn't found for these extra cols/val pairs, then no row is
2336
+	 *                deleted.
2337
+	 * @return EE_Base_Class the relation was removed from
2338
+	 * @throws ReflectionException
2339
+	 * @throws InvalidArgumentException
2340
+	 * @throws InvalidInterfaceException
2341
+	 * @throws InvalidDataTypeException
2342
+	 * @throws EE_Error
2343
+	 */
2344
+	public function _remove_relation_to($otherObjectModelObjectOrID, $relationName, $where_query = array())
2345
+	{
2346
+		if ($this->ID()) {
2347
+			// if this exists in the DB, save the relation change to the DB too
2348
+			$otherObject = $this->get_model()->remove_relationship_to(
2349
+				$this,
2350
+				$otherObjectModelObjectOrID,
2351
+				$relationName,
2352
+				$where_query
2353
+			);
2354
+			$this->clear_cache(
2355
+				$relationName,
2356
+				$otherObject
2357
+			);
2358
+		} else {
2359
+			// this doesn't exist in the DB, just remove it from the cache
2360
+			$otherObject = $this->clear_cache(
2361
+				$relationName,
2362
+				$otherObjectModelObjectOrID
2363
+			);
2364
+		}
2365
+		if ($otherObject instanceof EE_Base_Class) {
2366
+			$otherObject->clear_cache(
2367
+				$this->get_model()->get_this_model_name(),
2368
+				$this
2369
+			);
2370
+		}
2371
+		return $otherObject;
2372
+	}
2373
+
2374
+
2375
+	/**
2376
+	 * Removes ALL the related things for the $relationName.
2377
+	 *
2378
+	 * @param string $relationName
2379
+	 * @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
2380
+	 * @return EE_Base_Class
2381
+	 * @throws ReflectionException
2382
+	 * @throws InvalidArgumentException
2383
+	 * @throws InvalidInterfaceException
2384
+	 * @throws InvalidDataTypeException
2385
+	 * @throws EE_Error
2386
+	 */
2387
+	public function _remove_relations($relationName, $where_query_params = array())
2388
+	{
2389
+		if ($this->ID()) {
2390
+			// if this exists in the DB, save the relation change to the DB too
2391
+			$otherObjects = $this->get_model()->remove_relations(
2392
+				$this,
2393
+				$relationName,
2394
+				$where_query_params
2395
+			);
2396
+			$this->clear_cache(
2397
+				$relationName,
2398
+				null,
2399
+				true
2400
+			);
2401
+		} else {
2402
+			// this doesn't exist in the DB, just remove it from the cache
2403
+			$otherObjects = $this->clear_cache(
2404
+				$relationName,
2405
+				null,
2406
+				true
2407
+			);
2408
+		}
2409
+		if (is_array($otherObjects)) {
2410
+			foreach ($otherObjects as $otherObject) {
2411
+				$otherObject->clear_cache(
2412
+					$this->get_model()->get_this_model_name(),
2413
+					$this
2414
+				);
2415
+			}
2416
+		}
2417
+		return $otherObjects;
2418
+	}
2419
+
2420
+
2421
+	/**
2422
+	 * Gets all the related model objects of the specified type. Eg, if the current class if
2423
+	 * EE_Event, you could call $this->get_many_related('Registration') to get an array of all the
2424
+	 * EE_Registration objects which related to this event. Note: by default, we remove the "default query params"
2425
+	 * because we want to get even deleted items etc.
2426
+	 *
2427
+	 * @param string $relationName key in the model's _model_relations array
2428
+	 * @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
2429
+	 * @return EE_Base_Class[]     Results not necessarily indexed by IDs, because some results might not have primary
2430
+	 *                             keys or might not be saved yet. Consider using EEM_Base::get_IDs() on these
2431
+	 *                             results if you want IDs
2432
+	 * @throws ReflectionException
2433
+	 * @throws InvalidArgumentException
2434
+	 * @throws InvalidInterfaceException
2435
+	 * @throws InvalidDataTypeException
2436
+	 * @throws EE_Error
2437
+	 */
2438
+	public function get_many_related($relationName, $query_params = array())
2439
+	{
2440
+		if ($this->ID()) {
2441
+			// this exists in the DB, so get the related things from either the cache or the DB
2442
+			// if there are query parameters, forget about caching the related model objects.
2443
+			if ($query_params) {
2444
+				$related_model_objects = $this->get_model()->get_all_related(
2445
+					$this,
2446
+					$relationName,
2447
+					$query_params
2448
+				);
2449
+			} else {
2450
+				// did we already cache the result of this query?
2451
+				$cached_results = $this->get_all_from_cache($relationName);
2452
+				if (! $cached_results) {
2453
+					$related_model_objects = $this->get_model()->get_all_related(
2454
+						$this,
2455
+						$relationName,
2456
+						$query_params
2457
+					);
2458
+					// if no query parameters were passed, then we got all the related model objects
2459
+					// for that relation. We can cache them then.
2460
+					foreach ($related_model_objects as $related_model_object) {
2461
+						$this->cache($relationName, $related_model_object);
2462
+					}
2463
+				} else {
2464
+					$related_model_objects = $cached_results;
2465
+				}
2466
+			}
2467
+		} else {
2468
+			// this doesn't exist in the DB, so just get the related things from the cache
2469
+			$related_model_objects = $this->get_all_from_cache($relationName);
2470
+		}
2471
+		return $related_model_objects;
2472
+	}
2473
+
2474
+
2475
+	/**
2476
+	 * Instead of getting the related model objects, simply counts them. Ignores default_where_conditions by default,
2477
+	 * unless otherwise specified in the $query_params
2478
+	 *
2479
+	 * @param string $relation_name  model_name like 'Event', or 'Registration'
2480
+	 * @param array  $query_params   @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2481
+	 * @param string $field_to_count name of field to count by. By default, uses primary key
2482
+	 * @param bool   $distinct       if we want to only count the distinct values for the column then you can trigger
2483
+	 *                               that by the setting $distinct to TRUE;
2484
+	 * @return int
2485
+	 * @throws ReflectionException
2486
+	 * @throws InvalidArgumentException
2487
+	 * @throws InvalidInterfaceException
2488
+	 * @throws InvalidDataTypeException
2489
+	 * @throws EE_Error
2490
+	 */
2491
+	public function count_related($relation_name, $query_params = array(), $field_to_count = null, $distinct = false)
2492
+	{
2493
+		return $this->get_model()->count_related(
2494
+			$this,
2495
+			$relation_name,
2496
+			$query_params,
2497
+			$field_to_count,
2498
+			$distinct
2499
+		);
2500
+	}
2501
+
2502
+
2503
+	/**
2504
+	 * Instead of getting the related model objects, simply sums up the values of the specified field.
2505
+	 * Note: ignores default_where_conditions by default, unless otherwise specified in the $query_params
2506
+	 *
2507
+	 * @param string $relation_name model_name like 'Event', or 'Registration'
2508
+	 * @param array  $query_params  @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2509
+	 * @param string $field_to_sum  name of field to count by.
2510
+	 *                              By default, uses primary key
2511
+	 *                              (which doesn't make much sense, so you should probably change it)
2512
+	 * @return int
2513
+	 * @throws ReflectionException
2514
+	 * @throws InvalidArgumentException
2515
+	 * @throws InvalidInterfaceException
2516
+	 * @throws InvalidDataTypeException
2517
+	 * @throws EE_Error
2518
+	 */
2519
+	public function sum_related($relation_name, $query_params = array(), $field_to_sum = null)
2520
+	{
2521
+		return $this->get_model()->sum_related(
2522
+			$this,
2523
+			$relation_name,
2524
+			$query_params,
2525
+			$field_to_sum
2526
+		);
2527
+	}
2528
+
2529
+
2530
+	/**
2531
+	 * Gets the first (ie, one) related model object of the specified type.
2532
+	 *
2533
+	 * @param string $relationName key in the model's _model_relations array
2534
+	 * @param array  $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2535
+	 * @return EE_Base_Class (not an array, a single object)
2536
+	 * @throws ReflectionException
2537
+	 * @throws InvalidArgumentException
2538
+	 * @throws InvalidInterfaceException
2539
+	 * @throws InvalidDataTypeException
2540
+	 * @throws EE_Error
2541
+	 */
2542
+	public function get_first_related($relationName, $query_params = array())
2543
+	{
2544
+		$model = $this->get_model();
2545
+		if ($this->ID()) {// this exists in the DB, get from the cache OR the DB
2546
+			// if they've provided some query parameters, don't bother trying to cache the result
2547
+			// also make sure we're not caching the result of get_first_related
2548
+			// on a relation which should have an array of objects (because the cache might have an array of objects)
2549
+			if ($query_params
2550
+				|| ! $model->related_settings_for($relationName)
2551
+					 instanceof
2552
+					 EE_Belongs_To_Relation
2553
+			) {
2554
+				$related_model_object = $model->get_first_related(
2555
+					$this,
2556
+					$relationName,
2557
+					$query_params
2558
+				);
2559
+			} else {
2560
+				// first, check if we've already cached the result of this query
2561
+				$cached_result = $this->get_one_from_cache($relationName);
2562
+				if (! $cached_result) {
2563
+					$related_model_object = $model->get_first_related(
2564
+						$this,
2565
+						$relationName,
2566
+						$query_params
2567
+					);
2568
+					$this->cache($relationName, $related_model_object);
2569
+				} else {
2570
+					$related_model_object = $cached_result;
2571
+				}
2572
+			}
2573
+		} else {
2574
+			$related_model_object = null;
2575
+			// this doesn't exist in the Db,
2576
+			// but maybe the relation is of type belongs to, and so the related thing might
2577
+			if ($model->related_settings_for($relationName) instanceof EE_Belongs_To_Relation) {
2578
+				$related_model_object = $model->get_first_related(
2579
+					$this,
2580
+					$relationName,
2581
+					$query_params
2582
+				);
2583
+			}
2584
+			// this doesn't exist in the DB and apparently the thing it belongs to doesn't either,
2585
+			// just get what's cached on this object
2586
+			if (! $related_model_object) {
2587
+				$related_model_object = $this->get_one_from_cache($relationName);
2588
+			}
2589
+		}
2590
+		return $related_model_object;
2591
+	}
2592
+
2593
+
2594
+	/**
2595
+	 * Does a delete on all related objects of type $relationName and removes
2596
+	 * the current model object's relation to them. If they can't be deleted (because
2597
+	 * of blocking related model objects) does nothing. If the related model objects are
2598
+	 * soft-deletable, they will be soft-deleted regardless of related blocking model objects.
2599
+	 * If this model object doesn't exist yet in the DB, just removes its related things
2600
+	 *
2601
+	 * @param string $relationName
2602
+	 * @param array  $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2603
+	 * @return int how many deleted
2604
+	 * @throws ReflectionException
2605
+	 * @throws InvalidArgumentException
2606
+	 * @throws InvalidInterfaceException
2607
+	 * @throws InvalidDataTypeException
2608
+	 * @throws EE_Error
2609
+	 */
2610
+	public function delete_related($relationName, $query_params = array())
2611
+	{
2612
+		if ($this->ID()) {
2613
+			$count = $this->get_model()->delete_related(
2614
+				$this,
2615
+				$relationName,
2616
+				$query_params
2617
+			);
2618
+		} else {
2619
+			$count = count($this->get_all_from_cache($relationName));
2620
+			$this->clear_cache($relationName, null, true);
2621
+		}
2622
+		return $count;
2623
+	}
2624
+
2625
+
2626
+	/**
2627
+	 * Does a hard delete (ie, removes the DB row) 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) just does a soft delete on it instead, if possible.
2630
+	 * If the related thing isn't a soft-deletable model object, this function is identical
2631
+	 * to delete_related(). If this model object doesn't exist in the DB, just remove 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 (including those soft deleted)
2636
+	 * @throws ReflectionException
2637
+	 * @throws InvalidArgumentException
2638
+	 * @throws InvalidInterfaceException
2639
+	 * @throws InvalidDataTypeException
2640
+	 * @throws EE_Error
2641
+	 */
2642
+	public function delete_related_permanently($relationName, $query_params = array())
2643
+	{
2644
+		if ($this->ID()) {
2645
+			$count = $this->get_model()->delete_related_permanently(
2646
+				$this,
2647
+				$relationName,
2648
+				$query_params
2649
+			);
2650
+		} else {
2651
+			$count = count($this->get_all_from_cache($relationName));
2652
+		}
2653
+		$this->clear_cache($relationName, null, true);
2654
+		return $count;
2655
+	}
2656
+
2657
+
2658
+	/**
2659
+	 * is_set
2660
+	 * Just a simple utility function children can use for checking if property exists
2661
+	 *
2662
+	 * @access  public
2663
+	 * @param  string $field_name property to check
2664
+	 * @return bool                              TRUE if existing,FALSE if not.
2665
+	 */
2666
+	public function is_set($field_name)
2667
+	{
2668
+		return isset($this->_fields[ $field_name ]);
2669
+	}
2670
+
2671
+
2672
+	/**
2673
+	 * Just a simple utility function children can use for checking if property (or properties) exists and throwing an
2674
+	 * EE_Error exception if they don't
2675
+	 *
2676
+	 * @param  mixed (string|array) $properties properties to check
2677
+	 * @throws EE_Error
2678
+	 * @return bool                              TRUE if existing, throw EE_Error if not.
2679
+	 */
2680
+	protected function _property_exists($properties)
2681
+	{
2682
+		foreach ((array) $properties as $property_name) {
2683
+			// first make sure this property exists
2684
+			if (! $this->_fields[ $property_name ]) {
2685
+				throw new EE_Error(
2686
+					sprintf(
2687
+						esc_html__(
2688
+							'Trying to retrieve a non-existent property (%s).  Double check the spelling please',
2689
+							'event_espresso'
2690
+						),
2691
+						$property_name
2692
+					)
2693
+				);
2694
+			}
2695
+		}
2696
+		return true;
2697
+	}
2698
+
2699
+
2700
+	/**
2701
+	 * This simply returns an array of model fields for this object
2702
+	 *
2703
+	 * @return array
2704
+	 * @throws ReflectionException
2705
+	 * @throws InvalidArgumentException
2706
+	 * @throws InvalidInterfaceException
2707
+	 * @throws InvalidDataTypeException
2708
+	 * @throws EE_Error
2709
+	 */
2710
+	public function model_field_array()
2711
+	{
2712
+		$fields = $this->get_model()->field_settings(false);
2713
+		$properties = array();
2714
+		// remove prepended underscore
2715
+		foreach ($fields as $field_name => $settings) {
2716
+			$properties[ $field_name ] = $this->get($field_name);
2717
+		}
2718
+		return $properties;
2719
+	}
2720
+
2721
+
2722
+	/**
2723
+	 * Very handy general function to allow for plugins to extend any child of EE_Base_Class.
2724
+	 * If a method is called on a child of EE_Base_Class that doesn't exist, this function is called
2725
+	 * (http://www.garfieldtech.com/blog/php-magic-call) and passed the method's name and arguments.
2726
+	 * Instead of requiring a plugin to extend the EE_Base_Class
2727
+	 * (which works fine is there's only 1 plugin, but when will that happen?)
2728
+	 * they can add a hook onto 'filters_hook_espresso__{className}__{methodName}'
2729
+	 * (eg, filters_hook_espresso__EE_Answer__my_great_function)
2730
+	 * and accepts 2 arguments: the object on which the function was called,
2731
+	 * and an array of the original arguments passed to the function.
2732
+	 * Whatever their callback function returns will be returned by this function.
2733
+	 * Example: in functions.php (or in a plugin):
2734
+	 *      add_filter('FHEE__EE_Answer__my_callback','my_callback',10,3);
2735
+	 *      function my_callback($previousReturnValue,EE_Base_Class $object,$argsArray){
2736
+	 *          $returnString= "you called my_callback! and passed args:".implode(",",$argsArray);
2737
+	 *          return $previousReturnValue.$returnString;
2738
+	 *      }
2739
+	 * require('EE_Answer.class.php');
2740
+	 * $answer= EE_Answer::new_instance(array('REG_ID' => 2,'QST_ID' => 3,'ANS_value' => The answer is 42'));
2741
+	 * echo $answer->my_callback('monkeys',100);
2742
+	 * //will output "you called my_callback! and passed args:monkeys,100"
2743
+	 *
2744
+	 * @param string $methodName name of method which was called on a child of EE_Base_Class, but which
2745
+	 * @param array  $args       array of original arguments passed to the function
2746
+	 * @throws EE_Error
2747
+	 * @return mixed whatever the plugin which calls add_filter decides
2748
+	 */
2749
+	public function __call($methodName, $args)
2750
+	{
2751
+		$className = get_class($this);
2752
+		$tagName = "FHEE__{$className}__{$methodName}";
2753
+		if (! has_filter($tagName)) {
2754
+			throw new EE_Error(
2755
+				sprintf(
2756
+					esc_html__(
2757
+						"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;}",
2758
+						'event_espresso'
2759
+					),
2760
+					$methodName,
2761
+					$className,
2762
+					$tagName
2763
+				)
2764
+			);
2765
+		}
2766
+		return apply_filters($tagName, null, $this, $args);
2767
+	}
2768
+
2769
+
2770
+	/**
2771
+	 * Similar to insert_post_meta, adds a record in the Extra_Meta model's table with the given key and value.
2772
+	 * A $previous_value can be specified in case there are many meta rows with the same key
2773
+	 *
2774
+	 * @param string $meta_key
2775
+	 * @param mixed  $meta_value
2776
+	 * @param mixed  $previous_value
2777
+	 * @return bool|int # of records updated (or BOOLEAN if we actually ended up inserting the extra meta row)
2778
+	 *                  NOTE: if the values haven't changed, returns 0
2779
+	 * @throws InvalidArgumentException
2780
+	 * @throws InvalidInterfaceException
2781
+	 * @throws InvalidDataTypeException
2782
+	 * @throws EE_Error
2783
+	 * @throws ReflectionException
2784
+	 */
2785
+	public function update_extra_meta($meta_key, $meta_value, $previous_value = null)
2786
+	{
2787
+		$query_params = array(
2788
+			array(
2789
+				'EXM_key'  => $meta_key,
2790
+				'OBJ_ID'   => $this->ID(),
2791
+				'EXM_type' => $this->get_model()->get_this_model_name(),
2792
+			),
2793
+		);
2794
+		if ($previous_value !== null) {
2795
+			$query_params[0]['EXM_value'] = $meta_value;
2796
+		}
2797
+		$existing_rows_like_that = EEM_Extra_Meta::instance()->get_all($query_params);
2798
+		if (! $existing_rows_like_that) {
2799
+			return $this->add_extra_meta($meta_key, $meta_value);
2800
+		}
2801
+		foreach ($existing_rows_like_that as $existing_row) {
2802
+			$existing_row->save(array('EXM_value' => $meta_value));
2803
+		}
2804
+		return count($existing_rows_like_that);
2805
+	}
2806
+
2807
+
2808
+	/**
2809
+	 * Adds a new extra meta record. If $unique is set to TRUE, we'll first double-check
2810
+	 * no other extra meta for this model object have the same key. Returns TRUE if the
2811
+	 * extra meta row was entered, false if not
2812
+	 *
2813
+	 * @param string  $meta_key
2814
+	 * @param mixed   $meta_value
2815
+	 * @param boolean $unique
2816
+	 * @return boolean
2817
+	 * @throws InvalidArgumentException
2818
+	 * @throws InvalidInterfaceException
2819
+	 * @throws InvalidDataTypeException
2820
+	 * @throws EE_Error
2821
+	 * @throws ReflectionException
2822
+	 * @throws ReflectionException
2823
+	 */
2824
+	public function add_extra_meta($meta_key, $meta_value, $unique = false)
2825
+	{
2826
+		if ($unique) {
2827
+			$existing_extra_meta = EEM_Extra_Meta::instance()->get_one(
2828
+				array(
2829
+					array(
2830
+						'EXM_key'  => $meta_key,
2831
+						'OBJ_ID'   => $this->ID(),
2832
+						'EXM_type' => $this->get_model()->get_this_model_name(),
2833
+					),
2834
+				)
2835
+			);
2836
+			if ($existing_extra_meta) {
2837
+				return false;
2838
+			}
2839
+		}
2840
+		$new_extra_meta = EE_Extra_Meta::new_instance(
2841
+			array(
2842
+				'EXM_key'   => $meta_key,
2843
+				'EXM_value' => $meta_value,
2844
+				'OBJ_ID'    => $this->ID(),
2845
+				'EXM_type'  => $this->get_model()->get_this_model_name(),
2846
+			)
2847
+		);
2848
+		$new_extra_meta->save();
2849
+		return true;
2850
+	}
2851
+
2852
+
2853
+	/**
2854
+	 * Deletes all the extra meta rows for this record as specified by key. If $meta_value
2855
+	 * is specified, only deletes extra meta records with that value.
2856
+	 *
2857
+	 * @param string $meta_key
2858
+	 * @param mixed  $meta_value
2859
+	 * @return int number of extra meta rows deleted
2860
+	 * @throws InvalidArgumentException
2861
+	 * @throws InvalidInterfaceException
2862
+	 * @throws InvalidDataTypeException
2863
+	 * @throws EE_Error
2864
+	 * @throws ReflectionException
2865
+	 */
2866
+	public function delete_extra_meta($meta_key, $meta_value = null)
2867
+	{
2868
+		$query_params = array(
2869
+			array(
2870
+				'EXM_key'  => $meta_key,
2871
+				'OBJ_ID'   => $this->ID(),
2872
+				'EXM_type' => $this->get_model()->get_this_model_name(),
2873
+			),
2874
+		);
2875
+		if ($meta_value !== null) {
2876
+			$query_params[0]['EXM_value'] = $meta_value;
2877
+		}
2878
+		return EEM_Extra_Meta::instance()->delete($query_params);
2879
+	}
2880
+
2881
+
2882
+	/**
2883
+	 * Gets the extra meta with the given meta key. If you specify "single" we just return 1, otherwise
2884
+	 * an array of everything found. Requires that this model actually have a relation of type EE_Has_Many_Any_Relation.
2885
+	 * You can specify $default is case you haven't found the extra meta
2886
+	 *
2887
+	 * @param string  $meta_key
2888
+	 * @param boolean $single
2889
+	 * @param mixed   $default if we don't find anything, what should we return?
2890
+	 * @return mixed single value if $single; array if ! $single
2891
+	 * @throws ReflectionException
2892
+	 * @throws InvalidArgumentException
2893
+	 * @throws InvalidInterfaceException
2894
+	 * @throws InvalidDataTypeException
2895
+	 * @throws EE_Error
2896
+	 */
2897
+	public function get_extra_meta($meta_key, $single = false, $default = null)
2898
+	{
2899
+		if ($single) {
2900
+			$result = $this->get_first_related(
2901
+				'Extra_Meta',
2902
+				array(array('EXM_key' => $meta_key))
2903
+			);
2904
+			if ($result instanceof EE_Extra_Meta) {
2905
+				return $result->value();
2906
+			}
2907
+		} else {
2908
+			$results = $this->get_many_related(
2909
+				'Extra_Meta',
2910
+				array(array('EXM_key' => $meta_key))
2911
+			);
2912
+			if ($results) {
2913
+				$values = array();
2914
+				foreach ($results as $result) {
2915
+					if ($result instanceof EE_Extra_Meta) {
2916
+						$values[ $result->ID() ] = $result->value();
2917
+					}
2918
+				}
2919
+				return $values;
2920
+			}
2921
+		}
2922
+		// if nothing discovered yet return default.
2923
+		return apply_filters(
2924
+			'FHEE__EE_Base_Class__get_extra_meta__default_value',
2925
+			$default,
2926
+			$meta_key,
2927
+			$single,
2928
+			$this
2929
+		);
2930
+	}
2931
+
2932
+
2933
+	/**
2934
+	 * Returns a simple array of all the extra meta associated with this model object.
2935
+	 * If $one_of_each_key is true (Default), it will be an array of simple key-value pairs, keys being the
2936
+	 * extra meta's key, and teh value being its value. However, if there are duplicate extra meta rows with
2937
+	 * the same key, only one will be used. (eg array('foo'=>'bar','monkey'=>123))
2938
+	 * If $one_of_each_key is false, it will return an array with the top-level keys being
2939
+	 * the extra meta keys, but their values are also arrays, which have the extra-meta's ID as their sub-key, and
2940
+	 * finally the extra meta's value as each sub-value. (eg
2941
+	 * array('foo'=>array(1=>'bar',2=>'bill'),'monkey'=>array(3=>123)))
2942
+	 *
2943
+	 * @param boolean $one_of_each_key
2944
+	 * @return array
2945
+	 * @throws ReflectionException
2946
+	 * @throws InvalidArgumentException
2947
+	 * @throws InvalidInterfaceException
2948
+	 * @throws InvalidDataTypeException
2949
+	 * @throws EE_Error
2950
+	 */
2951
+	public function all_extra_meta_array($one_of_each_key = true)
2952
+	{
2953
+		$return_array = array();
2954
+		if ($one_of_each_key) {
2955
+			$extra_meta_objs = $this->get_many_related(
2956
+				'Extra_Meta',
2957
+				array('group_by' => 'EXM_key')
2958
+			);
2959
+			foreach ($extra_meta_objs as $extra_meta_obj) {
2960
+				if ($extra_meta_obj instanceof EE_Extra_Meta) {
2961
+					$return_array[ $extra_meta_obj->key() ] = $extra_meta_obj->value();
2962
+				}
2963
+			}
2964
+		} else {
2965
+			$extra_meta_objs = $this->get_many_related('Extra_Meta');
2966
+			foreach ($extra_meta_objs as $extra_meta_obj) {
2967
+				if ($extra_meta_obj instanceof EE_Extra_Meta) {
2968
+					if (! isset($return_array[ $extra_meta_obj->key() ])) {
2969
+						$return_array[ $extra_meta_obj->key() ] = array();
2970
+					}
2971
+					$return_array[ $extra_meta_obj->key() ][ $extra_meta_obj->ID() ] = $extra_meta_obj->value();
2972
+				}
2973
+			}
2974
+		}
2975
+		return $return_array;
2976
+	}
2977
+
2978
+
2979
+	/**
2980
+	 * Gets a pretty nice displayable nice for this model object. Often overridden
2981
+	 *
2982
+	 * @return string
2983
+	 * @throws ReflectionException
2984
+	 * @throws InvalidArgumentException
2985
+	 * @throws InvalidInterfaceException
2986
+	 * @throws InvalidDataTypeException
2987
+	 * @throws EE_Error
2988
+	 */
2989
+	public function name()
2990
+	{
2991
+		// find a field that's not a text field
2992
+		$field_we_can_use = $this->get_model()->get_a_field_of_type('EE_Text_Field_Base');
2993
+		if ($field_we_can_use) {
2994
+			return $this->get($field_we_can_use->get_name());
2995
+		}
2996
+		$first_few_properties = $this->model_field_array();
2997
+		$first_few_properties = array_slice($first_few_properties, 0, 3);
2998
+		$name_parts = array();
2999
+		foreach ($first_few_properties as $name => $value) {
3000
+			$name_parts[] = "$name:$value";
3001
+		}
3002
+		return implode(',', $name_parts);
3003
+	}
3004
+
3005
+
3006
+	/**
3007
+	 * in_entity_map
3008
+	 * Checks if this model object has been proven to already be in the entity map
3009
+	 *
3010
+	 * @return boolean
3011
+	 * @throws ReflectionException
3012
+	 * @throws InvalidArgumentException
3013
+	 * @throws InvalidInterfaceException
3014
+	 * @throws InvalidDataTypeException
3015
+	 * @throws EE_Error
3016
+	 */
3017
+	public function in_entity_map()
3018
+	{
3019
+		// well, if we looked, did we find it in the entity map?
3020
+		return $this->ID() && $this->get_model()->get_from_entity_map($this->ID()) === $this;
3021
+	}
3022
+
3023
+
3024
+	/**
3025
+	 * refresh_from_db
3026
+	 * Makes sure the fields and values on this model object are in-sync with what's in the database.
3027
+	 *
3028
+	 * @throws ReflectionException
3029
+	 * @throws InvalidArgumentException
3030
+	 * @throws InvalidInterfaceException
3031
+	 * @throws InvalidDataTypeException
3032
+	 * @throws EE_Error if this model object isn't in the entity mapper (because then you should
3033
+	 * just use what's in the entity mapper and refresh it) and WP_DEBUG is TRUE
3034
+	 */
3035
+	public function refresh_from_db()
3036
+	{
3037
+		if ($this->ID() && $this->in_entity_map()) {
3038
+			$this->get_model()->refresh_entity_map_from_db($this->ID());
3039
+		} else {
3040
+			// if it doesn't have ID, you shouldn't be asking to refresh it from teh database (because its not in the database)
3041
+			// if it has an ID but it's not in the map, and you're asking me to refresh it
3042
+			// that's kinda dangerous. You should just use what's in the entity map, or add this to the entity map if there's
3043
+			// absolutely nothing in it for this ID
3044
+			if (WP_DEBUG) {
3045
+				throw new EE_Error(
3046
+					sprintf(
3047
+						esc_html__(
3048
+							'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.',
3049
+							'event_espresso'
3050
+						),
3051
+						$this->ID(),
3052
+						get_class($this->get_model()) . '::instance()->add_to_entity_map()',
3053
+						get_class($this->get_model()) . '::instance()->refresh_entity_map()'
3054
+					)
3055
+				);
3056
+			}
3057
+		}
3058
+	}
3059
+
3060
+
3061
+	/**
3062
+	 * Change $fields' values to $new_value_sql (which is a string of raw SQL)
3063
+	 *
3064
+	 * @since 4.9.80.p
3065
+	 * @param EE_Model_Field_Base[] $fields
3066
+	 * @param string $new_value_sql
3067
+	 *      example: 'column_name=123',
3068
+	 *      or 'column_name=column_name+1',
3069
+	 *      or 'column_name= CASE
3070
+	 *          WHEN (`column_name` + `other_column` + 5) <= `yet_another_column`
3071
+	 *          THEN `column_name` + 5
3072
+	 *          ELSE `column_name`
3073
+	 *      END'
3074
+	 *      Also updates $field on this model object with the latest value from the database.
3075
+	 * @return bool
3076
+	 * @throws EE_Error
3077
+	 * @throws InvalidArgumentException
3078
+	 * @throws InvalidDataTypeException
3079
+	 * @throws InvalidInterfaceException
3080
+	 * @throws ReflectionException
3081
+	 */
3082
+	protected function updateFieldsInDB($fields, $new_value_sql)
3083
+	{
3084
+		// First make sure this model object actually exists in the DB. It would be silly to try to update it in the DB
3085
+		// if it wasn't even there to start off.
3086
+		if (! $this->ID()) {
3087
+			$this->save();
3088
+		}
3089
+		global $wpdb;
3090
+		if (empty($fields)) {
3091
+			throw new InvalidArgumentException(
3092
+				esc_html__(
3093
+					'EE_Base_Class::updateFieldsInDB was passed an empty array of fields.',
3094
+					'event_espresso'
3095
+				)
3096
+			);
3097
+		}
3098
+		$first_field = reset($fields);
3099
+		$table_alias = $first_field->get_table_alias();
3100
+		foreach ($fields as $field) {
3101
+			if ($table_alias !== $field->get_table_alias()) {
3102
+				throw new InvalidArgumentException(
3103
+					sprintf(
3104
+						esc_html__(
3105
+							// @codingStandardsIgnoreStart
3106
+							'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.',
3107
+							// @codingStandardsIgnoreEnd
3108
+							'event_espresso'
3109
+						),
3110
+						$table_alias,
3111
+						$field->get_table_alias()
3112
+					)
3113
+				);
3114
+			}
3115
+		}
3116
+		// Ok the fields are now known to all be for the same table. Proceed with creating the SQL to update it.
3117
+		$table_obj = $this->get_model()->get_table_obj_by_alias($table_alias);
3118
+		$table_pk_value = $this->ID();
3119
+		$table_name = $table_obj->get_table_name();
3120
+		if ($table_obj instanceof EE_Secondary_Table) {
3121
+			$table_pk_field_name = $table_obj->get_fk_on_table();
3122
+		} else {
3123
+			$table_pk_field_name = $table_obj->get_pk_column();
3124
+		}
3125
+
3126
+		$query =
3127
+			"UPDATE `{$table_name}`
3128 3128
             SET "
3129
-            . $new_value_sql
3130
-            . $wpdb->prepare(
3131
-                "
3129
+			. $new_value_sql
3130
+			. $wpdb->prepare(
3131
+				"
3132 3132
             WHERE `{$table_pk_field_name}` = %d;",
3133
-                $table_pk_value
3134
-            );
3135
-        $result = $wpdb->query($query);
3136
-        foreach ($fields as $field) {
3137
-            // If it was successful, we'd like to know the new value.
3138
-            // If it failed, we'd also like to know the new value.
3139
-            $new_value = $this->get_model()->get_var(
3140
-                $this->get_model()->alter_query_params_to_restrict_by_ID(
3141
-                    $this->get_model()->get_index_primary_key_string(
3142
-                        $this->model_field_array()
3143
-                    ),
3144
-                    array(
3145
-                        'default_where_conditions' => 'minimum',
3146
-                    )
3147
-                ),
3148
-                $field->get_name()
3149
-            );
3150
-            $this->set_from_db(
3151
-                $field->get_name(),
3152
-                $new_value
3153
-            );
3154
-        }
3155
-        return (bool) $result;
3156
-    }
3157
-
3158
-
3159
-    /**
3160
-     * Nudges $field_name's value by $quantity, without any conditionals (in comparison to bumpConditionally()).
3161
-     * Does not allow negative values, however.
3162
-     *
3163
-     * @since 4.9.80.p
3164
-     * @param array $fields_n_quantities keys are the field names, and values are the amount by which to bump them
3165
-     *                                   (positive or negative). One important gotcha: all these values must be
3166
-     *                                   on the same table (eg don't pass in one field for the posts table and
3167
-     *                                   another for the event meta table.)
3168
-     * @return bool
3169
-     * @throws EE_Error
3170
-     * @throws InvalidArgumentException
3171
-     * @throws InvalidDataTypeException
3172
-     * @throws InvalidInterfaceException
3173
-     * @throws ReflectionException
3174
-     */
3175
-    public function adjustNumericFieldsInDb(array $fields_n_quantities)
3176
-    {
3177
-        global $wpdb;
3178
-        if (empty($fields_n_quantities)) {
3179
-            // No fields to update? Well sure, we updated them to that value just fine.
3180
-            return true;
3181
-        }
3182
-        $fields = [];
3183
-        $set_sql_statements = [];
3184
-        foreach ($fields_n_quantities as $field_name => $quantity) {
3185
-            $field = $this->get_model()->field_settings_for($field_name, true);
3186
-            $fields[] = $field;
3187
-            $column_name = $field->get_table_column();
3188
-
3189
-            $abs_qty = absint($quantity);
3190
-            if ($quantity > 0) {
3191
-                // don't let the value be negative as often these fields are unsigned
3192
-                $set_sql_statements[] = $wpdb->prepare(
3193
-                    "`{$column_name}` = `{$column_name}` + %d",
3194
-                    $abs_qty
3195
-                );
3196
-            } else {
3197
-                $set_sql_statements[] = $wpdb->prepare(
3198
-                    "`{$column_name}` = CASE
3133
+				$table_pk_value
3134
+			);
3135
+		$result = $wpdb->query($query);
3136
+		foreach ($fields as $field) {
3137
+			// If it was successful, we'd like to know the new value.
3138
+			// If it failed, we'd also like to know the new value.
3139
+			$new_value = $this->get_model()->get_var(
3140
+				$this->get_model()->alter_query_params_to_restrict_by_ID(
3141
+					$this->get_model()->get_index_primary_key_string(
3142
+						$this->model_field_array()
3143
+					),
3144
+					array(
3145
+						'default_where_conditions' => 'minimum',
3146
+					)
3147
+				),
3148
+				$field->get_name()
3149
+			);
3150
+			$this->set_from_db(
3151
+				$field->get_name(),
3152
+				$new_value
3153
+			);
3154
+		}
3155
+		return (bool) $result;
3156
+	}
3157
+
3158
+
3159
+	/**
3160
+	 * Nudges $field_name's value by $quantity, without any conditionals (in comparison to bumpConditionally()).
3161
+	 * Does not allow negative values, however.
3162
+	 *
3163
+	 * @since 4.9.80.p
3164
+	 * @param array $fields_n_quantities keys are the field names, and values are the amount by which to bump them
3165
+	 *                                   (positive or negative). One important gotcha: all these values must be
3166
+	 *                                   on the same table (eg don't pass in one field for the posts table and
3167
+	 *                                   another for the event meta table.)
3168
+	 * @return bool
3169
+	 * @throws EE_Error
3170
+	 * @throws InvalidArgumentException
3171
+	 * @throws InvalidDataTypeException
3172
+	 * @throws InvalidInterfaceException
3173
+	 * @throws ReflectionException
3174
+	 */
3175
+	public function adjustNumericFieldsInDb(array $fields_n_quantities)
3176
+	{
3177
+		global $wpdb;
3178
+		if (empty($fields_n_quantities)) {
3179
+			// No fields to update? Well sure, we updated them to that value just fine.
3180
+			return true;
3181
+		}
3182
+		$fields = [];
3183
+		$set_sql_statements = [];
3184
+		foreach ($fields_n_quantities as $field_name => $quantity) {
3185
+			$field = $this->get_model()->field_settings_for($field_name, true);
3186
+			$fields[] = $field;
3187
+			$column_name = $field->get_table_column();
3188
+
3189
+			$abs_qty = absint($quantity);
3190
+			if ($quantity > 0) {
3191
+				// don't let the value be negative as often these fields are unsigned
3192
+				$set_sql_statements[] = $wpdb->prepare(
3193
+					"`{$column_name}` = `{$column_name}` + %d",
3194
+					$abs_qty
3195
+				);
3196
+			} else {
3197
+				$set_sql_statements[] = $wpdb->prepare(
3198
+					"`{$column_name}` = CASE
3199 3199
                        WHEN (`{$column_name}` >= %d)
3200 3200
                        THEN `{$column_name}` - %d
3201 3201
                        ELSE 0
3202 3202
                     END",
3203
-                    $abs_qty,
3204
-                    $abs_qty
3205
-                );
3206
-            }
3207
-        }
3208
-        return $this->updateFieldsInDB(
3209
-            $fields,
3210
-            implode(', ', $set_sql_statements)
3211
-        );
3212
-    }
3213
-
3214
-
3215
-    /**
3216
-     * Increases the value of the field $field_name_to_bump by $quantity, but only if the values of
3217
-     * $field_name_to_bump plus $field_name_affecting_total and $quantity won't exceed $limit_field_name's value.
3218
-     * For example, this is useful when bumping the value of TKT_reserved, TKT_sold, DTT_reserved or DTT_sold.
3219
-     * Returns true if the value was successfully bumped, and updates the value on this model object.
3220
-     * Otherwise returns false.
3221
-     *
3222
-     * @since 4.9.80.p
3223
-     * @param string $field_name_to_bump
3224
-     * @param string $field_name_affecting_total
3225
-     * @param string $limit_field_name
3226
-     * @param int    $quantity
3227
-     * @return bool
3228
-     * @throws EE_Error
3229
-     * @throws InvalidArgumentException
3230
-     * @throws InvalidDataTypeException
3231
-     * @throws InvalidInterfaceException
3232
-     * @throws ReflectionException
3233
-     */
3234
-    public function incrementFieldConditionallyInDb($field_name_to_bump, $field_name_affecting_total, $limit_field_name, $quantity)
3235
-    {
3236
-        global $wpdb;
3237
-        $field = $this->get_model()->field_settings_for($field_name_to_bump, true);
3238
-        $column_name = $field->get_table_column();
3239
-
3240
-        $field_affecting_total = $this->get_model()->field_settings_for($field_name_affecting_total, true);
3241
-        $column_affecting_total = $field_affecting_total->get_table_column();
3242
-
3243
-        $limiting_field = $this->get_model()->field_settings_for($limit_field_name, true);
3244
-        $limiting_column = $limiting_field->get_table_column();
3245
-        return $this->updateFieldsInDB(
3246
-            [$field],
3247
-            $wpdb->prepare(
3248
-                "`{$column_name}` =
3203
+					$abs_qty,
3204
+					$abs_qty
3205
+				);
3206
+			}
3207
+		}
3208
+		return $this->updateFieldsInDB(
3209
+			$fields,
3210
+			implode(', ', $set_sql_statements)
3211
+		);
3212
+	}
3213
+
3214
+
3215
+	/**
3216
+	 * Increases the value of the field $field_name_to_bump by $quantity, but only if the values of
3217
+	 * $field_name_to_bump plus $field_name_affecting_total and $quantity won't exceed $limit_field_name's value.
3218
+	 * For example, this is useful when bumping the value of TKT_reserved, TKT_sold, DTT_reserved or DTT_sold.
3219
+	 * Returns true if the value was successfully bumped, and updates the value on this model object.
3220
+	 * Otherwise returns false.
3221
+	 *
3222
+	 * @since 4.9.80.p
3223
+	 * @param string $field_name_to_bump
3224
+	 * @param string $field_name_affecting_total
3225
+	 * @param string $limit_field_name
3226
+	 * @param int    $quantity
3227
+	 * @return bool
3228
+	 * @throws EE_Error
3229
+	 * @throws InvalidArgumentException
3230
+	 * @throws InvalidDataTypeException
3231
+	 * @throws InvalidInterfaceException
3232
+	 * @throws ReflectionException
3233
+	 */
3234
+	public function incrementFieldConditionallyInDb($field_name_to_bump, $field_name_affecting_total, $limit_field_name, $quantity)
3235
+	{
3236
+		global $wpdb;
3237
+		$field = $this->get_model()->field_settings_for($field_name_to_bump, true);
3238
+		$column_name = $field->get_table_column();
3239
+
3240
+		$field_affecting_total = $this->get_model()->field_settings_for($field_name_affecting_total, true);
3241
+		$column_affecting_total = $field_affecting_total->get_table_column();
3242
+
3243
+		$limiting_field = $this->get_model()->field_settings_for($limit_field_name, true);
3244
+		$limiting_column = $limiting_field->get_table_column();
3245
+		return $this->updateFieldsInDB(
3246
+			[$field],
3247
+			$wpdb->prepare(
3248
+				"`{$column_name}` =
3249 3249
             CASE
3250 3250
                WHEN ((`{$column_name}` + `{$column_affecting_total}` + %d) <= `{$limiting_column}`) OR `{$limiting_column}` = %d
3251 3251
                THEN `{$column_name}` + %d
3252 3252
                ELSE `{$column_name}`
3253 3253
             END",
3254
-                $quantity,
3255
-                EE_INF_IN_DB,
3256
-                $quantity
3257
-            )
3258
-        );
3259
-    }
3260
-
3261
-
3262
-    /**
3263
-     * Because some other plugins, like Advanced Cron Manager, expect all objects to have this method
3264
-     * (probably a bad assumption they have made, oh well)
3265
-     *
3266
-     * @return string
3267
-     */
3268
-    public function __toString()
3269
-    {
3270
-        try {
3271
-            return sprintf('%s (%s)', $this->name(), $this->ID());
3272
-        } catch (Exception $e) {
3273
-            EE_Error::add_error($e->getMessage(), __FILE__, __FUNCTION__, __LINE__);
3274
-            return '';
3275
-        }
3276
-    }
3277
-
3278
-
3279
-    /**
3280
-     * Clear related model objects if they're already in the DB, because otherwise when we
3281
-     * UN-serialize this model object we'll need to be careful to add them to the entity map.
3282
-     * This means if we have made changes to those related model objects, and want to unserialize
3283
-     * the this model object on a subsequent request, changes to those related model objects will be lost.
3284
-     * Instead, those related model objects should be directly serialized and stored.
3285
-     * Eg, the following won't work:
3286
-     * $reg = EEM_Registration::instance()->get_one_by_ID( 123 );
3287
-     * $att = $reg->attendee();
3288
-     * $att->set( 'ATT_fname', 'Dirk' );
3289
-     * update_option( 'my_option', serialize( $reg ) );
3290
-     * //END REQUEST
3291
-     * //START NEXT REQUEST
3292
-     * $reg = get_option( 'my_option' );
3293
-     * $reg->attendee()->save();
3294
-     * And would need to be replace with:
3295
-     * $reg = EEM_Registration::instance()->get_one_by_ID( 123 );
3296
-     * $att = $reg->attendee();
3297
-     * $att->set( 'ATT_fname', 'Dirk' );
3298
-     * update_option( 'my_option', serialize( $reg ) );
3299
-     * //END REQUEST
3300
-     * //START NEXT REQUEST
3301
-     * $att = get_option( 'my_option' );
3302
-     * $att->save();
3303
-     *
3304
-     * @return array
3305
-     * @throws ReflectionException
3306
-     * @throws InvalidArgumentException
3307
-     * @throws InvalidInterfaceException
3308
-     * @throws InvalidDataTypeException
3309
-     * @throws EE_Error
3310
-     */
3311
-    public function __sleep()
3312
-    {
3313
-        $model = $this->get_model();
3314
-        foreach ($model->relation_settings() as $relation_name => $relation_obj) {
3315
-            if ($relation_obj instanceof EE_Belongs_To_Relation) {
3316
-                $classname = 'EE_' . $model->get_this_model_name();
3317
-                if ($this->get_one_from_cache($relation_name) instanceof $classname
3318
-                    && $this->get_one_from_cache($relation_name)->ID()
3319
-                ) {
3320
-                    $this->clear_cache(
3321
-                        $relation_name,
3322
-                        $this->get_one_from_cache($relation_name)->ID()
3323
-                    );
3324
-                }
3325
-            }
3326
-        }
3327
-        $this->_props_n_values_provided_in_constructor = array();
3328
-        $properties_to_serialize = get_object_vars($this);
3329
-        // don't serialize the model. It's big and that risks recursion
3330
-        unset($properties_to_serialize['_model']);
3331
-        return array_keys($properties_to_serialize);
3332
-    }
3333
-
3334
-
3335
-    /**
3336
-     * restore _props_n_values_provided_in_constructor
3337
-     * PLZ NOTE: this will reset the array to whatever fields values were present prior to serialization,
3338
-     * and therefore should NOT be used to determine if state change has occurred since initial construction.
3339
-     * At best, you would only be able to detect if state change has occurred during THIS request.
3340
-     */
3341
-    public function __wakeup()
3342
-    {
3343
-        $this->_props_n_values_provided_in_constructor = $this->_fields;
3344
-    }
3345
-
3346
-
3347
-    /**
3348
-     * Usage of this magic method is to ensure any internally cached references to object instances that must remain
3349
-     * distinct with the clone host instance are also cloned.
3350
-     */
3351
-    public function __clone()
3352
-    {
3353
-        // handle DateTimes (this is handled in here because there's no one specific child class that uses datetimes).
3354
-        foreach ($this->_fields as $field => $value) {
3355
-            if ($value instanceof DateTime) {
3356
-                $this->_fields[ $field ] = clone $value;
3357
-            }
3358
-        }
3359
-    }
3254
+				$quantity,
3255
+				EE_INF_IN_DB,
3256
+				$quantity
3257
+			)
3258
+		);
3259
+	}
3260
+
3261
+
3262
+	/**
3263
+	 * Because some other plugins, like Advanced Cron Manager, expect all objects to have this method
3264
+	 * (probably a bad assumption they have made, oh well)
3265
+	 *
3266
+	 * @return string
3267
+	 */
3268
+	public function __toString()
3269
+	{
3270
+		try {
3271
+			return sprintf('%s (%s)', $this->name(), $this->ID());
3272
+		} catch (Exception $e) {
3273
+			EE_Error::add_error($e->getMessage(), __FILE__, __FUNCTION__, __LINE__);
3274
+			return '';
3275
+		}
3276
+	}
3277
+
3278
+
3279
+	/**
3280
+	 * Clear related model objects if they're already in the DB, because otherwise when we
3281
+	 * UN-serialize this model object we'll need to be careful to add them to the entity map.
3282
+	 * This means if we have made changes to those related model objects, and want to unserialize
3283
+	 * the this model object on a subsequent request, changes to those related model objects will be lost.
3284
+	 * Instead, those related model objects should be directly serialized and stored.
3285
+	 * Eg, the following won't work:
3286
+	 * $reg = EEM_Registration::instance()->get_one_by_ID( 123 );
3287
+	 * $att = $reg->attendee();
3288
+	 * $att->set( 'ATT_fname', 'Dirk' );
3289
+	 * update_option( 'my_option', serialize( $reg ) );
3290
+	 * //END REQUEST
3291
+	 * //START NEXT REQUEST
3292
+	 * $reg = get_option( 'my_option' );
3293
+	 * $reg->attendee()->save();
3294
+	 * And would need to be replace with:
3295
+	 * $reg = EEM_Registration::instance()->get_one_by_ID( 123 );
3296
+	 * $att = $reg->attendee();
3297
+	 * $att->set( 'ATT_fname', 'Dirk' );
3298
+	 * update_option( 'my_option', serialize( $reg ) );
3299
+	 * //END REQUEST
3300
+	 * //START NEXT REQUEST
3301
+	 * $att = get_option( 'my_option' );
3302
+	 * $att->save();
3303
+	 *
3304
+	 * @return array
3305
+	 * @throws ReflectionException
3306
+	 * @throws InvalidArgumentException
3307
+	 * @throws InvalidInterfaceException
3308
+	 * @throws InvalidDataTypeException
3309
+	 * @throws EE_Error
3310
+	 */
3311
+	public function __sleep()
3312
+	{
3313
+		$model = $this->get_model();
3314
+		foreach ($model->relation_settings() as $relation_name => $relation_obj) {
3315
+			if ($relation_obj instanceof EE_Belongs_To_Relation) {
3316
+				$classname = 'EE_' . $model->get_this_model_name();
3317
+				if ($this->get_one_from_cache($relation_name) instanceof $classname
3318
+					&& $this->get_one_from_cache($relation_name)->ID()
3319
+				) {
3320
+					$this->clear_cache(
3321
+						$relation_name,
3322
+						$this->get_one_from_cache($relation_name)->ID()
3323
+					);
3324
+				}
3325
+			}
3326
+		}
3327
+		$this->_props_n_values_provided_in_constructor = array();
3328
+		$properties_to_serialize = get_object_vars($this);
3329
+		// don't serialize the model. It's big and that risks recursion
3330
+		unset($properties_to_serialize['_model']);
3331
+		return array_keys($properties_to_serialize);
3332
+	}
3333
+
3334
+
3335
+	/**
3336
+	 * restore _props_n_values_provided_in_constructor
3337
+	 * PLZ NOTE: this will reset the array to whatever fields values were present prior to serialization,
3338
+	 * and therefore should NOT be used to determine if state change has occurred since initial construction.
3339
+	 * At best, you would only be able to detect if state change has occurred during THIS request.
3340
+	 */
3341
+	public function __wakeup()
3342
+	{
3343
+		$this->_props_n_values_provided_in_constructor = $this->_fields;
3344
+	}
3345
+
3346
+
3347
+	/**
3348
+	 * Usage of this magic method is to ensure any internally cached references to object instances that must remain
3349
+	 * distinct with the clone host instance are also cloned.
3350
+	 */
3351
+	public function __clone()
3352
+	{
3353
+		// handle DateTimes (this is handled in here because there's no one specific child class that uses datetimes).
3354
+		foreach ($this->_fields as $field => $value) {
3355
+			if ($value instanceof DateTime) {
3356
+				$this->_fields[ $field ] = clone $value;
3357
+			}
3358
+		}
3359
+	}
3360 3360
 }
Please login to merge, or discard this patch.
Spacing   +121 added lines, -121 removed lines patch added patch discarded remove patch
@@ -146,7 +146,7 @@  discard block
 block discarded – undo
146 146
         $fieldValues = is_array($fieldValues) ? $fieldValues : array($fieldValues);
147 147
         // verify client code has not passed any invalid field names
148 148
         foreach ($fieldValues as $field_name => $field_value) {
149
-            if (! isset($model_fields[ $field_name ])) {
149
+            if ( ! isset($model_fields[$field_name])) {
150 150
                 throw new EE_Error(
151 151
                     sprintf(
152 152
                         esc_html__(
@@ -161,7 +161,7 @@  discard block
 block discarded – undo
161 161
             }
162 162
         }
163 163
         $this->_timezone = EEH_DTT_Helper::get_valid_timezone_string($timezone);
164
-        if (! empty($date_formats) && is_array($date_formats)) {
164
+        if ( ! empty($date_formats) && is_array($date_formats)) {
165 165
             list($this->_dt_frmt, $this->_tm_frmt) = $date_formats;
166 166
         } else {
167 167
             // set default formats for date and time
@@ -174,7 +174,7 @@  discard block
 block discarded – undo
174 174
             foreach ($model_fields as $fieldName => $field) {
175 175
                 $this->set_from_db(
176 176
                     $fieldName,
177
-                    isset($fieldValues[ $fieldName ]) ? $fieldValues[ $fieldName ] : null
177
+                    isset($fieldValues[$fieldName]) ? $fieldValues[$fieldName] : null
178 178
                 );
179 179
             }
180 180
         } else {
@@ -183,7 +183,7 @@  discard block
 block discarded – undo
183 183
             foreach ($model_fields as $fieldName => $field) {
184 184
                 $this->set(
185 185
                     $fieldName,
186
-                    isset($fieldValues[ $fieldName ]) ? $fieldValues[ $fieldName ] : null,
186
+                    isset($fieldValues[$fieldName]) ? $fieldValues[$fieldName] : null,
187 187
                     true
188 188
                 );
189 189
             }
@@ -191,15 +191,15 @@  discard block
 block discarded – undo
191 191
         // remember what values were passed to this constructor
192 192
         $this->_props_n_values_provided_in_constructor = $fieldValues;
193 193
         // remember in entity mapper
194
-        if (! $bydb && $model->has_primary_key_field() && $this->ID()) {
194
+        if ( ! $bydb && $model->has_primary_key_field() && $this->ID()) {
195 195
             $model->add_to_entity_map($this);
196 196
         }
197 197
         // setup all the relations
198 198
         foreach ($model->relation_settings() as $relation_name => $relation_obj) {
199 199
             if ($relation_obj instanceof EE_Belongs_To_Relation) {
200
-                $this->_model_relations[ $relation_name ] = null;
200
+                $this->_model_relations[$relation_name] = null;
201 201
             } else {
202
-                $this->_model_relations[ $relation_name ] = array();
202
+                $this->_model_relations[$relation_name] = array();
203 203
             }
204 204
         }
205 205
         /**
@@ -250,10 +250,10 @@  discard block
 block discarded – undo
250 250
      */
251 251
     public function get_original($field_name)
252 252
     {
253
-        if (isset($this->_props_n_values_provided_in_constructor[ $field_name ])
253
+        if (isset($this->_props_n_values_provided_in_constructor[$field_name])
254 254
             && $field_settings = $this->get_model()->field_settings_for($field_name)
255 255
         ) {
256
-            return $field_settings->prepare_for_get($this->_props_n_values_provided_in_constructor[ $field_name ]);
256
+            return $field_settings->prepare_for_get($this->_props_n_values_provided_in_constructor[$field_name]);
257 257
         }
258 258
         return null;
259 259
     }
@@ -288,8 +288,8 @@  discard block
 block discarded – undo
288 288
     {
289 289
         // if not using default and nothing has changed, and object has already been setup (has ID),
290 290
         // then don't do anything
291
-        if (! $use_default
292
-            && $this->_fields[ $field_name ] === $field_value
291
+        if ( ! $use_default
292
+            && $this->_fields[$field_name] === $field_value
293 293
             && $this->ID()
294 294
         ) {
295 295
             return;
@@ -307,7 +307,7 @@  discard block
 block discarded – undo
307 307
             $holder_of_value = $field_obj->prepare_for_set($field_value);
308 308
             // should the value be null?
309 309
             if (($field_value === null || $holder_of_value === null || $holder_of_value === '') && $use_default) {
310
-                $this->_fields[ $field_name ] = $field_obj->get_default_value();
310
+                $this->_fields[$field_name] = $field_obj->get_default_value();
311 311
                 /**
312 312
                  * To save having to refactor all the models, if a default value is used for a
313 313
                  * EE_Datetime_Field, and that value is not null nor is it a DateTime
@@ -317,15 +317,15 @@  discard block
 block discarded – undo
317 317
                  * @since 4.6.10+
318 318
                  */
319 319
                 if ($field_obj instanceof EE_Datetime_Field
320
-                    && $this->_fields[ $field_name ] !== null
321
-                    && ! $this->_fields[ $field_name ] instanceof DateTime
320
+                    && $this->_fields[$field_name] !== null
321
+                    && ! $this->_fields[$field_name] instanceof DateTime
322 322
                 ) {
323
-                    empty($this->_fields[ $field_name ])
323
+                    empty($this->_fields[$field_name])
324 324
                         ? $this->set($field_name, time())
325
-                        : $this->set($field_name, $this->_fields[ $field_name ]);
325
+                        : $this->set($field_name, $this->_fields[$field_name]);
326 326
                 }
327 327
             } else {
328
-                $this->_fields[ $field_name ] = $holder_of_value;
328
+                $this->_fields[$field_name] = $holder_of_value;
329 329
             }
330 330
             // if we're not in the constructor...
331 331
             // now check if what we set was a primary key
@@ -341,7 +341,7 @@  discard block
 block discarded – undo
341 341
                 $fields_on_model = self::_get_model(get_class($this))->field_settings();
342 342
                 $obj_in_db = self::_get_model(get_class($this))->get_one_by_ID($field_value);
343 343
                 foreach ($fields_on_model as $field_obj) {
344
-                    if (! array_key_exists($field_obj->get_name(), $this->_props_n_values_provided_in_constructor)
344
+                    if ( ! array_key_exists($field_obj->get_name(), $this->_props_n_values_provided_in_constructor)
345 345
                         && $field_obj->get_name() !== $field_name
346 346
                     ) {
347 347
                         $this->set($field_obj->get_name(), $obj_in_db->get($field_obj->get_name()));
@@ -386,8 +386,8 @@  discard block
 block discarded – undo
386 386
      */
387 387
     public function getCustomSelect($alias)
388 388
     {
389
-        return isset($this->custom_selection_results[ $alias ])
390
-            ? $this->custom_selection_results[ $alias ]
389
+        return isset($this->custom_selection_results[$alias])
390
+            ? $this->custom_selection_results[$alias]
391 391
             : null;
392 392
     }
393 393
 
@@ -474,8 +474,8 @@  discard block
 block discarded – undo
474 474
         foreach ($model_fields as $field_name => $field_obj) {
475 475
             if ($field_obj instanceof EE_Datetime_Field) {
476 476
                 $field_obj->set_timezone($this->_timezone);
477
-                if (isset($this->_fields[ $field_name ]) && $this->_fields[ $field_name ] instanceof DateTime) {
478
-                    EEH_DTT_Helper::setTimezone($this->_fields[ $field_name ], new DateTimeZone($this->_timezone));
477
+                if (isset($this->_fields[$field_name]) && $this->_fields[$field_name] instanceof DateTime) {
478
+                    EEH_DTT_Helper::setTimezone($this->_fields[$field_name], new DateTimeZone($this->_timezone));
479 479
                 }
480 480
             }
481 481
         }
@@ -533,7 +533,7 @@  discard block
 block discarded – undo
533 533
      */
534 534
     public function get_format($full = true)
535 535
     {
536
-        return $full ? $this->_dt_frmt . ' ' . $this->_tm_frmt : array($this->_dt_frmt, $this->_tm_frmt);
536
+        return $full ? $this->_dt_frmt.' '.$this->_tm_frmt : array($this->_dt_frmt, $this->_tm_frmt);
537 537
     }
538 538
 
539 539
 
@@ -559,11 +559,11 @@  discard block
 block discarded – undo
559 559
     public function cache($relationName = '', $object_to_cache = null, $cache_id = null)
560 560
     {
561 561
         // its entirely possible that there IS no related object yet in which case there is nothing to cache.
562
-        if (! $object_to_cache instanceof EE_Base_Class) {
562
+        if ( ! $object_to_cache instanceof EE_Base_Class) {
563 563
             return false;
564 564
         }
565 565
         // also get "how" the object is related, or throw an error
566
-        if (! $relationship_to_model = $this->get_model()->related_settings_for($relationName)) {
566
+        if ( ! $relationship_to_model = $this->get_model()->related_settings_for($relationName)) {
567 567
             throw new EE_Error(
568 568
                 sprintf(
569 569
                     esc_html__('There is no relationship to %s on a %s. Cannot cache it', 'event_espresso'),
@@ -577,38 +577,38 @@  discard block
 block discarded – undo
577 577
             // if it's a "belongs to" relationship, then there's only one related model object
578 578
             // eg, if this is a registration, there's only 1 attendee for it
579 579
             // so for these model objects just set it to be cached
580
-            $this->_model_relations[ $relationName ] = $object_to_cache;
580
+            $this->_model_relations[$relationName] = $object_to_cache;
581 581
             $return = true;
582 582
         } else {
583 583
             // otherwise, this is the "many" side of a one to many relationship,
584 584
             // so we'll add the object to the array of related objects for that type.
585 585
             // eg: if this is an event, there are many registrations for that event,
586 586
             // so we cache the registrations in an array
587
-            if (! is_array($this->_model_relations[ $relationName ])) {
587
+            if ( ! is_array($this->_model_relations[$relationName])) {
588 588
                 // if for some reason, the cached item is a model object,
589 589
                 // then stick that in the array, otherwise start with an empty array
590
-                $this->_model_relations[ $relationName ] = $this->_model_relations[ $relationName ]
590
+                $this->_model_relations[$relationName] = $this->_model_relations[$relationName]
591 591
                                                            instanceof
592 592
                                                            EE_Base_Class
593
-                    ? array($this->_model_relations[ $relationName ]) : array();
593
+                    ? array($this->_model_relations[$relationName]) : array();
594 594
             }
595 595
             // first check for a cache_id which is normally empty
596
-            if (! empty($cache_id)) {
596
+            if ( ! empty($cache_id)) {
597 597
                 // if the cache_id exists, then it means we are purposely trying to cache this
598 598
                 // with a known key that can then be used to retrieve the object later on
599
-                $this->_model_relations[ $relationName ][ $cache_id ] = $object_to_cache;
599
+                $this->_model_relations[$relationName][$cache_id] = $object_to_cache;
600 600
                 $return = $cache_id;
601 601
             } elseif ($object_to_cache->ID()) {
602 602
                 // OR the cached object originally came from the db, so let's just use it's PK for an ID
603
-                $this->_model_relations[ $relationName ][ $object_to_cache->ID() ] = $object_to_cache;
603
+                $this->_model_relations[$relationName][$object_to_cache->ID()] = $object_to_cache;
604 604
                 $return = $object_to_cache->ID();
605 605
             } else {
606 606
                 // OR it's a new object with no ID, so just throw it in the array with an auto-incremented ID
607
-                $this->_model_relations[ $relationName ][] = $object_to_cache;
607
+                $this->_model_relations[$relationName][] = $object_to_cache;
608 608
                 // move the internal pointer to the end of the array
609
-                end($this->_model_relations[ $relationName ]);
609
+                end($this->_model_relations[$relationName]);
610 610
                 // and grab the key so that we can return it
611
-                $return = key($this->_model_relations[ $relationName ]);
611
+                $return = key($this->_model_relations[$relationName]);
612 612
             }
613 613
         }
614 614
         return $return;
@@ -634,7 +634,7 @@  discard block
 block discarded – undo
634 634
         // first make sure this property exists
635 635
         $this->get_model()->field_settings_for($fieldname);
636 636
         $cache_type = empty($cache_type) ? 'standard' : $cache_type;
637
-        $this->_cached_properties[ $fieldname ][ $cache_type ] = $value;
637
+        $this->_cached_properties[$fieldname][$cache_type] = $value;
638 638
     }
639 639
 
640 640
 
@@ -663,9 +663,9 @@  discard block
 block discarded – undo
663 663
         $model = $this->get_model();
664 664
         $model->field_settings_for($fieldname);
665 665
         $cache_type = $pretty ? 'pretty' : 'standard';
666
-        $cache_type .= ! empty($extra_cache_ref) ? '_' . $extra_cache_ref : '';
667
-        if (isset($this->_cached_properties[ $fieldname ][ $cache_type ])) {
668
-            return $this->_cached_properties[ $fieldname ][ $cache_type ];
666
+        $cache_type .= ! empty($extra_cache_ref) ? '_'.$extra_cache_ref : '';
667
+        if (isset($this->_cached_properties[$fieldname][$cache_type])) {
668
+            return $this->_cached_properties[$fieldname][$cache_type];
669 669
         }
670 670
         $value = $this->_get_fresh_property($fieldname, $pretty, $extra_cache_ref);
671 671
         $this->_set_cached_property($fieldname, $value, $cache_type);
@@ -693,12 +693,12 @@  discard block
 block discarded – undo
693 693
         if ($field_obj instanceof EE_Datetime_Field) {
694 694
             $this->_prepare_datetime_field($field_obj, $pretty, $extra_cache_ref);
695 695
         }
696
-        if (! isset($this->_fields[ $fieldname ])) {
697
-            $this->_fields[ $fieldname ] = null;
696
+        if ( ! isset($this->_fields[$fieldname])) {
697
+            $this->_fields[$fieldname] = null;
698 698
         }
699 699
         $value = $pretty
700
-            ? $field_obj->prepare_for_pretty_echoing($this->_fields[ $fieldname ], $extra_cache_ref)
701
-            : $field_obj->prepare_for_get($this->_fields[ $fieldname ]);
700
+            ? $field_obj->prepare_for_pretty_echoing($this->_fields[$fieldname], $extra_cache_ref)
701
+            : $field_obj->prepare_for_get($this->_fields[$fieldname]);
702 702
         return $value;
703 703
     }
704 704
 
@@ -756,8 +756,8 @@  discard block
 block discarded – undo
756 756
      */
757 757
     protected function _clear_cached_property($property_name)
758 758
     {
759
-        if (isset($this->_cached_properties[ $property_name ])) {
760
-            unset($this->_cached_properties[ $property_name ]);
759
+        if (isset($this->_cached_properties[$property_name])) {
760
+            unset($this->_cached_properties[$property_name]);
761 761
         }
762 762
     }
763 763
 
@@ -809,7 +809,7 @@  discard block
 block discarded – undo
809 809
     {
810 810
         $relationship_to_model = $this->get_model()->related_settings_for($relationName);
811 811
         $index_in_cache = '';
812
-        if (! $relationship_to_model) {
812
+        if ( ! $relationship_to_model) {
813 813
             throw new EE_Error(
814 814
                 sprintf(
815 815
                     esc_html__('There is no relationship to %s on a %s. Cannot clear that cache', 'event_espresso'),
@@ -820,21 +820,21 @@  discard block
 block discarded – undo
820 820
         }
821 821
         if ($clear_all) {
822 822
             $obj_removed = true;
823
-            $this->_model_relations[ $relationName ] = null;
823
+            $this->_model_relations[$relationName] = null;
824 824
         } elseif ($relationship_to_model instanceof EE_Belongs_To_Relation) {
825
-            $obj_removed = $this->_model_relations[ $relationName ];
826
-            $this->_model_relations[ $relationName ] = null;
825
+            $obj_removed = $this->_model_relations[$relationName];
826
+            $this->_model_relations[$relationName] = null;
827 827
         } else {
828 828
             if ($object_to_remove_or_index_into_array instanceof EE_Base_Class
829 829
                 && $object_to_remove_or_index_into_array->ID()
830 830
             ) {
831 831
                 $index_in_cache = $object_to_remove_or_index_into_array->ID();
832
-                if (is_array($this->_model_relations[ $relationName ])
833
-                    && ! isset($this->_model_relations[ $relationName ][ $index_in_cache ])
832
+                if (is_array($this->_model_relations[$relationName])
833
+                    && ! isset($this->_model_relations[$relationName][$index_in_cache])
834 834
                 ) {
835 835
                     $index_found_at = null;
836 836
                     // find this object in the array even though it has a different key
837
-                    foreach ($this->_model_relations[ $relationName ] as $index => $obj) {
837
+                    foreach ($this->_model_relations[$relationName] as $index => $obj) {
838 838
                         /** @noinspection TypeUnsafeComparisonInspection */
839 839
                         if ($obj instanceof EE_Base_Class
840 840
                             && (
@@ -867,9 +867,9 @@  discard block
 block discarded – undo
867 867
             }
868 868
             // supposedly we've found it. But it could just be that the client code
869 869
             // provided a bad index/object
870
-            if (isset($this->_model_relations[ $relationName ][ $index_in_cache ])) {
871
-                $obj_removed = $this->_model_relations[ $relationName ][ $index_in_cache ];
872
-                unset($this->_model_relations[ $relationName ][ $index_in_cache ]);
870
+            if (isset($this->_model_relations[$relationName][$index_in_cache])) {
871
+                $obj_removed = $this->_model_relations[$relationName][$index_in_cache];
872
+                unset($this->_model_relations[$relationName][$index_in_cache]);
873 873
             } else {
874 874
                 // that thing was never cached anyways.
875 875
                 $obj_removed = null;
@@ -900,7 +900,7 @@  discard block
 block discarded – undo
900 900
         $current_cache_id = ''
901 901
     ) {
902 902
         // verify that incoming object is of the correct type
903
-        $obj_class = 'EE_' . $relationName;
903
+        $obj_class = 'EE_'.$relationName;
904 904
         if ($newly_saved_object instanceof $obj_class) {
905 905
             /* @type EE_Base_Class $newly_saved_object */
906 906
             // now get the type of relation
@@ -908,17 +908,17 @@  discard block
 block discarded – undo
908 908
             // if this is a 1:1 relationship
909 909
             if ($relationship_to_model instanceof EE_Belongs_To_Relation) {
910 910
                 // then just replace the cached object with the newly saved object
911
-                $this->_model_relations[ $relationName ] = $newly_saved_object;
911
+                $this->_model_relations[$relationName] = $newly_saved_object;
912 912
                 return true;
913 913
                 // or if it's some kind of sordid feral polyamorous relationship...
914 914
             }
915
-            if (is_array($this->_model_relations[ $relationName ])
916
-                && isset($this->_model_relations[ $relationName ][ $current_cache_id ])
915
+            if (is_array($this->_model_relations[$relationName])
916
+                && isset($this->_model_relations[$relationName][$current_cache_id])
917 917
             ) {
918 918
                 // then remove the current cached item
919
-                unset($this->_model_relations[ $relationName ][ $current_cache_id ]);
919
+                unset($this->_model_relations[$relationName][$current_cache_id]);
920 920
                 // and cache the newly saved object using it's new ID
921
-                $this->_model_relations[ $relationName ][ $newly_saved_object->ID() ] = $newly_saved_object;
921
+                $this->_model_relations[$relationName][$newly_saved_object->ID()] = $newly_saved_object;
922 922
                 return true;
923 923
             }
924 924
         }
@@ -935,8 +935,8 @@  discard block
 block discarded – undo
935 935
      */
936 936
     public function get_one_from_cache($relationName)
937 937
     {
938
-        $cached_array_or_object = isset($this->_model_relations[ $relationName ])
939
-            ? $this->_model_relations[ $relationName ]
938
+        $cached_array_or_object = isset($this->_model_relations[$relationName])
939
+            ? $this->_model_relations[$relationName]
940 940
             : null;
941 941
         if (is_array($cached_array_or_object)) {
942 942
             return array_shift($cached_array_or_object);
@@ -959,7 +959,7 @@  discard block
 block discarded – undo
959 959
      */
960 960
     public function get_all_from_cache($relationName)
961 961
     {
962
-        $objects = isset($this->_model_relations[ $relationName ]) ? $this->_model_relations[ $relationName ] : array();
962
+        $objects = isset($this->_model_relations[$relationName]) ? $this->_model_relations[$relationName] : array();
963 963
         // if the result is not an array, but exists, make it an array
964 964
         $objects = is_array($objects) ? $objects : array($objects);
965 965
         // bugfix for https://events.codebasehq.com/projects/event-espresso/tickets/7143
@@ -1143,7 +1143,7 @@  discard block
 block discarded – undo
1143 1143
             } else {
1144 1144
                 $field_value = $field_obj->prepare_for_set_from_db($field_value_from_db);
1145 1145
             }
1146
-            $this->_fields[ $field_name ] = $field_value;
1146
+            $this->_fields[$field_name] = $field_value;
1147 1147
             $this->_clear_cached_property($field_name);
1148 1148
         }
1149 1149
     }
@@ -1183,9 +1183,9 @@  discard block
 block discarded – undo
1183 1183
     public function get_raw($field_name)
1184 1184
     {
1185 1185
         $field_settings = $this->get_model()->field_settings_for($field_name);
1186
-        return $field_settings instanceof EE_Datetime_Field && $this->_fields[ $field_name ] instanceof DateTime
1187
-            ? $this->_fields[ $field_name ]->format('U')
1188
-            : $this->_fields[ $field_name ];
1186
+        return $field_settings instanceof EE_Datetime_Field && $this->_fields[$field_name] instanceof DateTime
1187
+            ? $this->_fields[$field_name]->format('U')
1188
+            : $this->_fields[$field_name];
1189 1189
     }
1190 1190
 
1191 1191
 
@@ -1207,7 +1207,7 @@  discard block
 block discarded – undo
1207 1207
     public function get_DateTime_object($field_name)
1208 1208
     {
1209 1209
         $field_settings = $this->get_model()->field_settings_for($field_name);
1210
-        if (! $field_settings instanceof EE_Datetime_Field) {
1210
+        if ( ! $field_settings instanceof EE_Datetime_Field) {
1211 1211
             EE_Error::add_error(
1212 1212
                 sprintf(
1213 1213
                     esc_html__(
@@ -1222,8 +1222,8 @@  discard block
 block discarded – undo
1222 1222
             );
1223 1223
             return false;
1224 1224
         }
1225
-        return isset($this->_fields[ $field_name ]) && $this->_fields[ $field_name ] instanceof DateTime
1226
-            ? clone $this->_fields[ $field_name ]
1225
+        return isset($this->_fields[$field_name]) && $this->_fields[$field_name] instanceof DateTime
1226
+            ? clone $this->_fields[$field_name]
1227 1227
             : null;
1228 1228
     }
1229 1229
 
@@ -1465,7 +1465,7 @@  discard block
 block discarded – undo
1465 1465
      */
1466 1466
     public function get_i18n_datetime($field_name, $format = '')
1467 1467
     {
1468
-        $format = empty($format) ? $this->_dt_frmt . ' ' . $this->_tm_frmt : $format;
1468
+        $format = empty($format) ? $this->_dt_frmt.' '.$this->_tm_frmt : $format;
1469 1469
         return date_i18n(
1470 1470
             $format,
1471 1471
             EEH_DTT_Helper::get_timestamp_with_offset(
@@ -1577,21 +1577,21 @@  discard block
 block discarded – undo
1577 1577
         $field->set_time_format($this->_tm_frmt);
1578 1578
         switch ($what) {
1579 1579
             case 'T':
1580
-                $this->_fields[ $fieldname ] = $field->prepare_for_set_with_new_time(
1580
+                $this->_fields[$fieldname] = $field->prepare_for_set_with_new_time(
1581 1581
                     $datetime_value,
1582
-                    $this->_fields[ $fieldname ]
1582
+                    $this->_fields[$fieldname]
1583 1583
                 );
1584 1584
                 $this->_has_changes = true;
1585 1585
                 break;
1586 1586
             case 'D':
1587
-                $this->_fields[ $fieldname ] = $field->prepare_for_set_with_new_date(
1587
+                $this->_fields[$fieldname] = $field->prepare_for_set_with_new_date(
1588 1588
                     $datetime_value,
1589
-                    $this->_fields[ $fieldname ]
1589
+                    $this->_fields[$fieldname]
1590 1590
                 );
1591 1591
                 $this->_has_changes = true;
1592 1592
                 break;
1593 1593
             case 'B':
1594
-                $this->_fields[ $fieldname ] = $field->prepare_for_set($datetime_value);
1594
+                $this->_fields[$fieldname] = $field->prepare_for_set($datetime_value);
1595 1595
                 $this->_has_changes = true;
1596 1596
                 break;
1597 1597
         }
@@ -1634,7 +1634,7 @@  discard block
 block discarded – undo
1634 1634
         $this->set_timezone($timezone);
1635 1635
         $fn = (array) $field_name;
1636 1636
         $args = array_merge($fn, (array) $args);
1637
-        if (! method_exists($this, $callback)) {
1637
+        if ( ! method_exists($this, $callback)) {
1638 1638
             throw new EE_Error(
1639 1639
                 sprintf(
1640 1640
                     esc_html__(
@@ -1646,7 +1646,7 @@  discard block
 block discarded – undo
1646 1646
             );
1647 1647
         }
1648 1648
         $args = (array) $args;
1649
-        $return = $prepend . call_user_func_array(array($this, $callback), $args) . $append;
1649
+        $return = $prepend.call_user_func_array(array($this, $callback), $args).$append;
1650 1650
         $this->set_timezone($original_timezone);
1651 1651
         return $return;
1652 1652
     }
@@ -1761,8 +1761,8 @@  discard block
 block discarded – undo
1761 1761
     {
1762 1762
         $model = $this->get_model();
1763 1763
         foreach ($model->relation_settings() as $relation_name => $relation_obj) {
1764
-            if (! empty($this->_model_relations[ $relation_name ])) {
1765
-                $related_objects = $this->_model_relations[ $relation_name ];
1764
+            if ( ! empty($this->_model_relations[$relation_name])) {
1765
+                $related_objects = $this->_model_relations[$relation_name];
1766 1766
                 if ($relation_obj instanceof EE_Belongs_To_Relation) {
1767 1767
                     // this relation only stores a single model object, not an array
1768 1768
                     // but let's make it consistent
@@ -1819,7 +1819,7 @@  discard block
 block discarded – undo
1819 1819
             $this->set($column, $value);
1820 1820
         }
1821 1821
         // no changes ? then don't do anything
1822
-        if (! $this->_has_changes && $this->ID() && $model->get_primary_key_field()->is_auto_increment()) {
1822
+        if ( ! $this->_has_changes && $this->ID() && $model->get_primary_key_field()->is_auto_increment()) {
1823 1823
             return 0;
1824 1824
         }
1825 1825
         /**
@@ -1829,7 +1829,7 @@  discard block
 block discarded – undo
1829 1829
          * @param EE_Base_Class $model_object the model object about to be saved.
1830 1830
          */
1831 1831
         do_action('AHEE__EE_Base_Class__save__begin', $this);
1832
-        if (! $this->allow_persist()) {
1832
+        if ( ! $this->allow_persist()) {
1833 1833
             return 0;
1834 1834
         }
1835 1835
         // now get current attribute values
@@ -1844,10 +1844,10 @@  discard block
 block discarded – undo
1844 1844
         if ($model->has_primary_key_field()) {
1845 1845
             if ($model->get_primary_key_field()->is_auto_increment()) {
1846 1846
                 // ok check if it's set, if so: update; if not, insert
1847
-                if (! empty($save_cols_n_values[ $model->primary_key_name() ])) {
1847
+                if ( ! empty($save_cols_n_values[$model->primary_key_name()])) {
1848 1848
                     $results = $model->update_by_ID($save_cols_n_values, $this->ID());
1849 1849
                 } else {
1850
-                    unset($save_cols_n_values[ $model->primary_key_name() ]);
1850
+                    unset($save_cols_n_values[$model->primary_key_name()]);
1851 1851
                     $results = $model->insert($save_cols_n_values);
1852 1852
                     if ($results) {
1853 1853
                         // if successful, set the primary key
@@ -1857,7 +1857,7 @@  discard block
 block discarded – undo
1857 1857
                         // will get added to the mapper before we can add this one!
1858 1858
                         // but if we just avoid using the SET method, all that headache can be avoided
1859 1859
                         $pk_field_name = $model->primary_key_name();
1860
-                        $this->_fields[ $pk_field_name ] = $results;
1860
+                        $this->_fields[$pk_field_name] = $results;
1861 1861
                         $this->_clear_cached_property($pk_field_name);
1862 1862
                         $model->add_to_entity_map($this);
1863 1863
                         $this->_update_cached_related_model_objs_fks();
@@ -1874,8 +1874,8 @@  discard block
 block discarded – undo
1874 1874
                                     'event_espresso'
1875 1875
                                 ),
1876 1876
                                 get_class($this),
1877
-                                get_class($model) . '::instance()->add_to_entity_map()',
1878
-                                get_class($model) . '::instance()->get_one_by_ID()',
1877
+                                get_class($model).'::instance()->add_to_entity_map()',
1878
+                                get_class($model).'::instance()->get_one_by_ID()',
1879 1879
                                 '<br />'
1880 1880
                             )
1881 1881
                         );
@@ -1977,27 +1977,27 @@  discard block
 block discarded – undo
1977 1977
     public function save_new_cached_related_model_objs()
1978 1978
     {
1979 1979
         // make sure this has been saved
1980
-        if (! $this->ID()) {
1980
+        if ( ! $this->ID()) {
1981 1981
             $id = $this->save();
1982 1982
         } else {
1983 1983
             $id = $this->ID();
1984 1984
         }
1985 1985
         // now save all the NEW cached model objects  (ie they don't exist in the DB)
1986 1986
         foreach ($this->get_model()->relation_settings() as $relationName => $relationObj) {
1987
-            if ($this->_model_relations[ $relationName ]) {
1987
+            if ($this->_model_relations[$relationName]) {
1988 1988
                 // is this a relation where we should expect just ONE related object (ie, EE_Belongs_To_relation)
1989 1989
                 // or MANY related objects (ie, EE_HABTM_Relation or EE_Has_Many_Relation)?
1990 1990
                 /* @var $related_model_obj EE_Base_Class */
1991 1991
                 if ($relationObj instanceof EE_Belongs_To_Relation) {
1992 1992
                     // add a relation to that relation type (which saves the appropriate thing in the process)
1993 1993
                     // but ONLY if it DOES NOT exist in the DB
1994
-                    $related_model_obj = $this->_model_relations[ $relationName ];
1994
+                    $related_model_obj = $this->_model_relations[$relationName];
1995 1995
                     // if( ! $related_model_obj->ID()){
1996 1996
                     $this->_add_relation_to($related_model_obj, $relationName);
1997 1997
                     $related_model_obj->save_new_cached_related_model_objs();
1998 1998
                     // }
1999 1999
                 } else {
2000
-                    foreach ($this->_model_relations[ $relationName ] as $related_model_obj) {
2000
+                    foreach ($this->_model_relations[$relationName] as $related_model_obj) {
2001 2001
                         // add a relation to that relation type (which saves the appropriate thing in the process)
2002 2002
                         // but ONLY if it DOES NOT exist in the DB
2003 2003
                         // if( ! $related_model_obj->ID()){
@@ -2024,7 +2024,7 @@  discard block
 block discarded – undo
2024 2024
      */
2025 2025
     public function get_model()
2026 2026
     {
2027
-        if (! $this->_model) {
2027
+        if ( ! $this->_model) {
2028 2028
             $modelName = self::_get_model_classname(get_class($this));
2029 2029
             $this->_model = self::_get_model_instance_with_name($modelName, $this->_timezone);
2030 2030
         } else {
@@ -2049,9 +2049,9 @@  discard block
 block discarded – undo
2049 2049
         // TODO: will not work for Term_Relationships because they have no PK!
2050 2050
         $primary_id_ref = self::_get_primary_key_name($classname);
2051 2051
         if (array_key_exists($primary_id_ref, $props_n_values)
2052
-            && ! empty($props_n_values[ $primary_id_ref ])
2052
+            && ! empty($props_n_values[$primary_id_ref])
2053 2053
         ) {
2054
-            $id = $props_n_values[ $primary_id_ref ];
2054
+            $id = $props_n_values[$primary_id_ref];
2055 2055
             return self::_get_model($classname)->get_from_entity_map($id);
2056 2056
         }
2057 2057
         return false;
@@ -2085,10 +2085,10 @@  discard block
 block discarded – undo
2085 2085
         if ($model->has_primary_key_field()) {
2086 2086
             $primary_id_ref = self::_get_primary_key_name($classname);
2087 2087
             if (array_key_exists($primary_id_ref, $props_n_values)
2088
-                && ! empty($props_n_values[ $primary_id_ref ])
2088
+                && ! empty($props_n_values[$primary_id_ref])
2089 2089
             ) {
2090 2090
                 $existing = $model->get_one_by_ID(
2091
-                    $props_n_values[ $primary_id_ref ]
2091
+                    $props_n_values[$primary_id_ref]
2092 2092
                 );
2093 2093
             }
2094 2094
         } elseif ($model->has_all_combined_primary_key_fields($props_n_values)) {
@@ -2100,7 +2100,7 @@  discard block
 block discarded – undo
2100 2100
         }
2101 2101
         if ($existing) {
2102 2102
             // set date formats if present before setting values
2103
-            if (! empty($date_formats) && is_array($date_formats)) {
2103
+            if ( ! empty($date_formats) && is_array($date_formats)) {
2104 2104
                 $existing->set_date_format($date_formats[0]);
2105 2105
                 $existing->set_time_format($date_formats[1]);
2106 2106
             } else {
@@ -2133,7 +2133,7 @@  discard block
 block discarded – undo
2133 2133
     protected static function _get_model($classname, $timezone = null)
2134 2134
     {
2135 2135
         // find model for this class
2136
-        if (! $classname) {
2136
+        if ( ! $classname) {
2137 2137
             throw new EE_Error(
2138 2138
                 sprintf(
2139 2139
                     esc_html__(
@@ -2182,7 +2182,7 @@  discard block
 block discarded – undo
2182 2182
         if (strpos($model_name, 'EE_') === 0) {
2183 2183
             $model_classname = str_replace('EE_', 'EEM_', $model_name);
2184 2184
         } else {
2185
-            $model_classname = 'EEM_' . $model_name;
2185
+            $model_classname = 'EEM_'.$model_name;
2186 2186
         }
2187 2187
         return $model_classname;
2188 2188
     }
@@ -2201,7 +2201,7 @@  discard block
 block discarded – undo
2201 2201
      */
2202 2202
     protected static function _get_primary_key_name($classname = null)
2203 2203
     {
2204
-        if (! $classname) {
2204
+        if ( ! $classname) {
2205 2205
             throw new EE_Error(
2206 2206
                 sprintf(
2207 2207
                     esc_html__('What were you thinking calling _get_primary_key_name(%s)', 'event_espresso'),
@@ -2231,7 +2231,7 @@  discard block
 block discarded – undo
2231 2231
         $model = $this->get_model();
2232 2232
         // now that we know the name of the variable, use a variable variable to get its value and return its
2233 2233
         if ($model->has_primary_key_field()) {
2234
-            return $this->_fields[ $model->primary_key_name() ];
2234
+            return $this->_fields[$model->primary_key_name()];
2235 2235
         }
2236 2236
         return $model->get_index_primary_key_string($this->_fields);
2237 2237
     }
@@ -2284,7 +2284,7 @@  discard block
 block discarded – undo
2284 2284
             }
2285 2285
         } else {
2286 2286
             // this thing doesn't exist in the DB,  so just cache it
2287
-            if (! $otherObjectModelObjectOrID instanceof EE_Base_Class) {
2287
+            if ( ! $otherObjectModelObjectOrID instanceof EE_Base_Class) {
2288 2288
                 throw new EE_Error(
2289 2289
                     sprintf(
2290 2290
                         esc_html__(
@@ -2449,7 +2449,7 @@  discard block
 block discarded – undo
2449 2449
             } else {
2450 2450
                 // did we already cache the result of this query?
2451 2451
                 $cached_results = $this->get_all_from_cache($relationName);
2452
-                if (! $cached_results) {
2452
+                if ( ! $cached_results) {
2453 2453
                     $related_model_objects = $this->get_model()->get_all_related(
2454 2454
                         $this,
2455 2455
                         $relationName,
@@ -2559,7 +2559,7 @@  discard block
 block discarded – undo
2559 2559
             } else {
2560 2560
                 // first, check if we've already cached the result of this query
2561 2561
                 $cached_result = $this->get_one_from_cache($relationName);
2562
-                if (! $cached_result) {
2562
+                if ( ! $cached_result) {
2563 2563
                     $related_model_object = $model->get_first_related(
2564 2564
                         $this,
2565 2565
                         $relationName,
@@ -2583,7 +2583,7 @@  discard block
 block discarded – undo
2583 2583
             }
2584 2584
             // this doesn't exist in the DB and apparently the thing it belongs to doesn't either,
2585 2585
             // just get what's cached on this object
2586
-            if (! $related_model_object) {
2586
+            if ( ! $related_model_object) {
2587 2587
                 $related_model_object = $this->get_one_from_cache($relationName);
2588 2588
             }
2589 2589
         }
@@ -2665,7 +2665,7 @@  discard block
 block discarded – undo
2665 2665
      */
2666 2666
     public function is_set($field_name)
2667 2667
     {
2668
-        return isset($this->_fields[ $field_name ]);
2668
+        return isset($this->_fields[$field_name]);
2669 2669
     }
2670 2670
 
2671 2671
 
@@ -2681,7 +2681,7 @@  discard block
 block discarded – undo
2681 2681
     {
2682 2682
         foreach ((array) $properties as $property_name) {
2683 2683
             // first make sure this property exists
2684
-            if (! $this->_fields[ $property_name ]) {
2684
+            if ( ! $this->_fields[$property_name]) {
2685 2685
                 throw new EE_Error(
2686 2686
                     sprintf(
2687 2687
                         esc_html__(
@@ -2713,7 +2713,7 @@  discard block
 block discarded – undo
2713 2713
         $properties = array();
2714 2714
         // remove prepended underscore
2715 2715
         foreach ($fields as $field_name => $settings) {
2716
-            $properties[ $field_name ] = $this->get($field_name);
2716
+            $properties[$field_name] = $this->get($field_name);
2717 2717
         }
2718 2718
         return $properties;
2719 2719
     }
@@ -2750,7 +2750,7 @@  discard block
 block discarded – undo
2750 2750
     {
2751 2751
         $className = get_class($this);
2752 2752
         $tagName = "FHEE__{$className}__{$methodName}";
2753
-        if (! has_filter($tagName)) {
2753
+        if ( ! has_filter($tagName)) {
2754 2754
             throw new EE_Error(
2755 2755
                 sprintf(
2756 2756
                     esc_html__(
@@ -2795,7 +2795,7 @@  discard block
 block discarded – undo
2795 2795
             $query_params[0]['EXM_value'] = $meta_value;
2796 2796
         }
2797 2797
         $existing_rows_like_that = EEM_Extra_Meta::instance()->get_all($query_params);
2798
-        if (! $existing_rows_like_that) {
2798
+        if ( ! $existing_rows_like_that) {
2799 2799
             return $this->add_extra_meta($meta_key, $meta_value);
2800 2800
         }
2801 2801
         foreach ($existing_rows_like_that as $existing_row) {
@@ -2913,7 +2913,7 @@  discard block
 block discarded – undo
2913 2913
                 $values = array();
2914 2914
                 foreach ($results as $result) {
2915 2915
                     if ($result instanceof EE_Extra_Meta) {
2916
-                        $values[ $result->ID() ] = $result->value();
2916
+                        $values[$result->ID()] = $result->value();
2917 2917
                     }
2918 2918
                 }
2919 2919
                 return $values;
@@ -2958,17 +2958,17 @@  discard block
 block discarded – undo
2958 2958
             );
2959 2959
             foreach ($extra_meta_objs as $extra_meta_obj) {
2960 2960
                 if ($extra_meta_obj instanceof EE_Extra_Meta) {
2961
-                    $return_array[ $extra_meta_obj->key() ] = $extra_meta_obj->value();
2961
+                    $return_array[$extra_meta_obj->key()] = $extra_meta_obj->value();
2962 2962
                 }
2963 2963
             }
2964 2964
         } else {
2965 2965
             $extra_meta_objs = $this->get_many_related('Extra_Meta');
2966 2966
             foreach ($extra_meta_objs as $extra_meta_obj) {
2967 2967
                 if ($extra_meta_obj instanceof EE_Extra_Meta) {
2968
-                    if (! isset($return_array[ $extra_meta_obj->key() ])) {
2969
-                        $return_array[ $extra_meta_obj->key() ] = array();
2968
+                    if ( ! isset($return_array[$extra_meta_obj->key()])) {
2969
+                        $return_array[$extra_meta_obj->key()] = array();
2970 2970
                     }
2971
-                    $return_array[ $extra_meta_obj->key() ][ $extra_meta_obj->ID() ] = $extra_meta_obj->value();
2971
+                    $return_array[$extra_meta_obj->key()][$extra_meta_obj->ID()] = $extra_meta_obj->value();
2972 2972
                 }
2973 2973
             }
2974 2974
         }
@@ -3049,8 +3049,8 @@  discard block
 block discarded – undo
3049 3049
                             'event_espresso'
3050 3050
                         ),
3051 3051
                         $this->ID(),
3052
-                        get_class($this->get_model()) . '::instance()->add_to_entity_map()',
3053
-                        get_class($this->get_model()) . '::instance()->refresh_entity_map()'
3052
+                        get_class($this->get_model()).'::instance()->add_to_entity_map()',
3053
+                        get_class($this->get_model()).'::instance()->refresh_entity_map()'
3054 3054
                     )
3055 3055
                 );
3056 3056
             }
@@ -3083,7 +3083,7 @@  discard block
 block discarded – undo
3083 3083
     {
3084 3084
         // First make sure this model object actually exists in the DB. It would be silly to try to update it in the DB
3085 3085
         // if it wasn't even there to start off.
3086
-        if (! $this->ID()) {
3086
+        if ( ! $this->ID()) {
3087 3087
             $this->save();
3088 3088
         }
3089 3089
         global $wpdb;
@@ -3313,7 +3313,7 @@  discard block
 block discarded – undo
3313 3313
         $model = $this->get_model();
3314 3314
         foreach ($model->relation_settings() as $relation_name => $relation_obj) {
3315 3315
             if ($relation_obj instanceof EE_Belongs_To_Relation) {
3316
-                $classname = 'EE_' . $model->get_this_model_name();
3316
+                $classname = 'EE_'.$model->get_this_model_name();
3317 3317
                 if ($this->get_one_from_cache($relation_name) instanceof $classname
3318 3318
                     && $this->get_one_from_cache($relation_name)->ID()
3319 3319
                 ) {
@@ -3353,7 +3353,7 @@  discard block
 block discarded – undo
3353 3353
         // handle DateTimes (this is handled in here because there's no one specific child class that uses datetimes).
3354 3354
         foreach ($this->_fields as $field => $value) {
3355 3355
             if ($value instanceof DateTime) {
3356
-                $this->_fields[ $field ] = clone $value;
3356
+                $this->_fields[$field] = clone $value;
3357 3357
             }
3358 3358
         }
3359 3359
     }
Please login to merge, or discard this patch.
core/domain/entities/GenericAddress.php 2 patches
Doc Comments   +4 added lines, -2 removed lines patch added patch discarded remove patch
@@ -37,6 +37,8 @@  discard block
 block discarded – undo
37 37
      * @param \EE_State | string   $state
38 38
      * @param string               $zip
39 39
      * @param \EE_Country | string $country
40
+     * @param integer $state
41
+     * @param string $country
40 42
      * @return GenericAddress
41 43
      */
42 44
     public function __construct($address, $address2, $city, $state, $zip, $country)
@@ -130,7 +132,7 @@  discard block
 block discarded – undo
130 132
 
131 133
 
132 134
     /**
133
-     * @return \EE_State
135
+     * @return string
134 136
      */
135 137
     public function state_obj()
136 138
     {
@@ -183,7 +185,7 @@  discard block
 block discarded – undo
183 185
 
184 186
 
185 187
     /**
186
-     * @return \EE_Country
188
+     * @return string
187 189
      */
188 190
     public function country_obj()
189 191
     {
Please login to merge, or discard this patch.
Indentation   +201 added lines, -201 removed lines patch added patch discarded remove patch
@@ -12,205 +12,205 @@
 block discarded – undo
12 12
  */
13 13
 class GenericAddress implements \EEI_Address
14 14
 {
15
-    // phpcs:disable PSR2.Classes.PropertyDeclaration.Underscore
16
-    private $_address = '';
17
-
18
-    private $_address2 = '';
19
-
20
-    private $_city = '';
21
-
22
-    private $_state_ID = '';
23
-
24
-    private $_state_obj = '';
25
-
26
-    private $_zip = '';
27
-
28
-    private $_country_ID = '';
29
-
30
-    private $_country_obj = '';
31
-    // phpcs:enable
32
-
33
-    // phpcs:disable PSR2.Methods.MethodDeclaration.Underscore
34
-    /**
35
-     * @param string               $address
36
-     * @param string               $address2
37
-     * @param string               $city
38
-     * @param \EE_State | string   $state
39
-     * @param string               $zip
40
-     * @param \EE_Country | string $country
41
-     * @return GenericAddress
42
-     */
43
-    public function __construct($address, $address2, $city, $state, $zip, $country)
44
-    {
45
-        $this->_address = $address;
46
-        $this->_address2 = $address2;
47
-        $this->_city = $city;
48
-        if ($state instanceof \EE_State) {
49
-            $this->_state_obj = $state;
50
-        } else {
51
-            $this->_state_ID = $state;
52
-            $this->_state_obj = $this->_get_state_obj();
53
-        }
54
-        $this->_zip = $zip;
55
-        if ($country instanceof \EE_Country) {
56
-            $this->_country_obj = $country;
57
-        } else {
58
-            $this->_country_ID = $country;
59
-            $this->_country_obj = $this->_get_country_obj();
60
-        }
61
-    }
62
-
63
-
64
-    /**
65
-     * @return string
66
-     */
67
-    public function address()
68
-    {
69
-        return $this->_address;
70
-    }
71
-
72
-
73
-    /**
74
-     * @return string
75
-     */
76
-    public function address2()
77
-    {
78
-        return $this->_address2;
79
-    }
80
-
81
-
82
-    /**
83
-     * @return string
84
-     */
85
-    public function city()
86
-    {
87
-        return $this->_city;
88
-    }
89
-
90
-    // phpcs:disable PSR1.Methods.CamelCapsMethodName.NotCamelCaps
91
-
92
-    /**
93
-     * @return \EE_State
94
-     */
95
-    private function _get_state_obj()
96
-    {
97
-        return $this->_state_obj instanceof \EE_State
98
-            ? $this->_state_obj
99
-            : \EE_Registry::instance()->load_model('State')->get_one_by_ID($this->_state_ID);
100
-    }
101
-
102
-
103
-    /**
104
-     * @return string
105
-     */
106
-    public function state_ID()
107
-    {
108
-        return $this->_state_ID;
109
-    }
110
-
111
-
112
-    /**
113
-     * @return string
114
-     */
115
-    public function state_abbrev()
116
-    {
117
-        return $this->state_obj() instanceof \EE_State
118
-            ? $this->state_obj()->abbrev()
119
-            : '';
120
-    }
121
-
122
-
123
-    /**
124
-     * @return string
125
-     */
126
-    public function state_name()
127
-    {
128
-        return $this->state_obj() instanceof \EE_State
129
-            ? $this->state_obj()->name()
130
-            : '';
131
-    }
132
-
133
-
134
-    /**
135
-     * @return \EE_State
136
-     */
137
-    public function state_obj()
138
-    {
139
-        return $this->_state_obj;
140
-    }
141
-
142
-
143
-    /**
144
-     * @return string
145
-     */
146
-    public function state()
147
-    {
148
-        if (apply_filters('FHEE__EEI_Address__state__use_abbreviation', true, $this->state_obj())) {
149
-            return $this->state_obj()->abbrev();
150
-        } else {
151
-            return $this->state_name();
152
-        }
153
-    }
154
-
155
-
156
-    /**
157
-     * @return \EE_Country
158
-     */
159
-    private function _get_country_obj()
160
-    {
161
-        return $this->_country_obj instanceof \EE_Country
162
-            ? $this->_country_obj
163
-            : \EE_Registry::instance()->load_model('Country')->get_one_by_ID($this->_country_ID);
164
-    }
165
-
166
-
167
-    /**
168
-     * @return string
169
-     */
170
-    public function country_ID()
171
-    {
172
-        return $this->_country_ID;
173
-    }
174
-
175
-
176
-    /**
177
-     * @return string
178
-     */
179
-    public function country_name()
180
-    {
181
-        return $this->country_obj() instanceof \EE_Country
182
-            ? $this->country_obj()->name()
183
-            : '';
184
-    }
185
-
186
-
187
-    /**
188
-     * @return \EE_Country
189
-     */
190
-    public function country_obj()
191
-    {
192
-        return $this->_country_obj;
193
-    }
194
-
195
-
196
-    /**
197
-     * @return string
198
-     */
199
-    public function country()
200
-    {
201
-        if (apply_filters('FHEE__EEI_Address__country__use_abbreviation', true, $this->country_obj())) {
202
-            return $this->country_ID();
203
-        } else {
204
-            return $this->country_name();
205
-        }
206
-    }
207
-
208
-
209
-    /**
210
-     * @return string
211
-     */
212
-    public function zip()
213
-    {
214
-        return $this->_zip;
215
-    }
15
+	// phpcs:disable PSR2.Classes.PropertyDeclaration.Underscore
16
+	private $_address = '';
17
+
18
+	private $_address2 = '';
19
+
20
+	private $_city = '';
21
+
22
+	private $_state_ID = '';
23
+
24
+	private $_state_obj = '';
25
+
26
+	private $_zip = '';
27
+
28
+	private $_country_ID = '';
29
+
30
+	private $_country_obj = '';
31
+	// phpcs:enable
32
+
33
+	// phpcs:disable PSR2.Methods.MethodDeclaration.Underscore
34
+	/**
35
+	 * @param string               $address
36
+	 * @param string               $address2
37
+	 * @param string               $city
38
+	 * @param \EE_State | string   $state
39
+	 * @param string               $zip
40
+	 * @param \EE_Country | string $country
41
+	 * @return GenericAddress
42
+	 */
43
+	public function __construct($address, $address2, $city, $state, $zip, $country)
44
+	{
45
+		$this->_address = $address;
46
+		$this->_address2 = $address2;
47
+		$this->_city = $city;
48
+		if ($state instanceof \EE_State) {
49
+			$this->_state_obj = $state;
50
+		} else {
51
+			$this->_state_ID = $state;
52
+			$this->_state_obj = $this->_get_state_obj();
53
+		}
54
+		$this->_zip = $zip;
55
+		if ($country instanceof \EE_Country) {
56
+			$this->_country_obj = $country;
57
+		} else {
58
+			$this->_country_ID = $country;
59
+			$this->_country_obj = $this->_get_country_obj();
60
+		}
61
+	}
62
+
63
+
64
+	/**
65
+	 * @return string
66
+	 */
67
+	public function address()
68
+	{
69
+		return $this->_address;
70
+	}
71
+
72
+
73
+	/**
74
+	 * @return string
75
+	 */
76
+	public function address2()
77
+	{
78
+		return $this->_address2;
79
+	}
80
+
81
+
82
+	/**
83
+	 * @return string
84
+	 */
85
+	public function city()
86
+	{
87
+		return $this->_city;
88
+	}
89
+
90
+	// phpcs:disable PSR1.Methods.CamelCapsMethodName.NotCamelCaps
91
+
92
+	/**
93
+	 * @return \EE_State
94
+	 */
95
+	private function _get_state_obj()
96
+	{
97
+		return $this->_state_obj instanceof \EE_State
98
+			? $this->_state_obj
99
+			: \EE_Registry::instance()->load_model('State')->get_one_by_ID($this->_state_ID);
100
+	}
101
+
102
+
103
+	/**
104
+	 * @return string
105
+	 */
106
+	public function state_ID()
107
+	{
108
+		return $this->_state_ID;
109
+	}
110
+
111
+
112
+	/**
113
+	 * @return string
114
+	 */
115
+	public function state_abbrev()
116
+	{
117
+		return $this->state_obj() instanceof \EE_State
118
+			? $this->state_obj()->abbrev()
119
+			: '';
120
+	}
121
+
122
+
123
+	/**
124
+	 * @return string
125
+	 */
126
+	public function state_name()
127
+	{
128
+		return $this->state_obj() instanceof \EE_State
129
+			? $this->state_obj()->name()
130
+			: '';
131
+	}
132
+
133
+
134
+	/**
135
+	 * @return \EE_State
136
+	 */
137
+	public function state_obj()
138
+	{
139
+		return $this->_state_obj;
140
+	}
141
+
142
+
143
+	/**
144
+	 * @return string
145
+	 */
146
+	public function state()
147
+	{
148
+		if (apply_filters('FHEE__EEI_Address__state__use_abbreviation', true, $this->state_obj())) {
149
+			return $this->state_obj()->abbrev();
150
+		} else {
151
+			return $this->state_name();
152
+		}
153
+	}
154
+
155
+
156
+	/**
157
+	 * @return \EE_Country
158
+	 */
159
+	private function _get_country_obj()
160
+	{
161
+		return $this->_country_obj instanceof \EE_Country
162
+			? $this->_country_obj
163
+			: \EE_Registry::instance()->load_model('Country')->get_one_by_ID($this->_country_ID);
164
+	}
165
+
166
+
167
+	/**
168
+	 * @return string
169
+	 */
170
+	public function country_ID()
171
+	{
172
+		return $this->_country_ID;
173
+	}
174
+
175
+
176
+	/**
177
+	 * @return string
178
+	 */
179
+	public function country_name()
180
+	{
181
+		return $this->country_obj() instanceof \EE_Country
182
+			? $this->country_obj()->name()
183
+			: '';
184
+	}
185
+
186
+
187
+	/**
188
+	 * @return \EE_Country
189
+	 */
190
+	public function country_obj()
191
+	{
192
+		return $this->_country_obj;
193
+	}
194
+
195
+
196
+	/**
197
+	 * @return string
198
+	 */
199
+	public function country()
200
+	{
201
+		if (apply_filters('FHEE__EEI_Address__country__use_abbreviation', true, $this->country_obj())) {
202
+			return $this->country_ID();
203
+		} else {
204
+			return $this->country_name();
205
+		}
206
+	}
207
+
208
+
209
+	/**
210
+	 * @return string
211
+	 */
212
+	public function zip()
213
+	{
214
+		return $this->_zip;
215
+	}
216 216
 }
Please login to merge, or discard this patch.
core/libraries/batch/JobHandlers/AttendeesReport.php 3 patches
Doc Comments   +4 added lines patch added patch discarded remove patch
@@ -90,6 +90,10 @@
 block discarded – undo
90 90
         return \EEM_Attendee::instance()->count(array('caps' => \EEM_Base::caps_read_admin));
91 91
     }
92 92
 
93
+    /**
94
+     * @param integer $offset
95
+     * @param integer $limit
96
+     */
93 97
     public function get_csv_data($offset, $limit)
94 98
     {
95 99
         $attendee_rows = \EEM_Attendee::instance()->get_all_wpdb_results(
Please login to merge, or discard this patch.
Indentation   +96 added lines, -96 removed lines patch added patch discarded remove patch
@@ -19,106 +19,106 @@
 block discarded – undo
19 19
 class AttendeesReport extends JobHandlerFile
20 20
 {
21 21
 
22
-    // phpcs:disable PSR1.Methods.CamelCapsMethodName.NotCamelCaps
23
-    public function create_job(JobParameters $job_parameters)
24
-    {
25
-        if (! \EE_Capabilities::instance()->current_user_can('ee_read_contacts', 'generating_report')) {
26
-            throw new BatchRequestException(
27
-                __('You do not have permission to view contacts', 'event_espresso')
28
-            );
29
-        }
30
-        $filepath = $this->create_file_from_job_with_name(
31
-            $job_parameters->job_id(),
32
-            __('contact-list-report.csv', 'event_espresso')
33
-        );
34
-        $job_parameters->add_extra_data('filepath', $filepath);
35
-        $job_parameters->set_job_size($this->count_units_to_process());
36
-        // we should also set the header columns
37
-        $csv_data_for_row = $this->get_csv_data(0, 1);
38
-        \EEH_Export::write_data_array_to_csv($filepath, $csv_data_for_row, true);
39
-        // if we actually processed a row there, record it
40
-        if ($job_parameters->job_size()) {
41
-            $job_parameters->mark_processed(1);
42
-        }
43
-        return new JobStepResponse(
44
-            $job_parameters,
45
-            __('Contacts report started successfully...', 'event_espresso')
46
-        );
47
-    }
22
+	// phpcs:disable PSR1.Methods.CamelCapsMethodName.NotCamelCaps
23
+	public function create_job(JobParameters $job_parameters)
24
+	{
25
+		if (! \EE_Capabilities::instance()->current_user_can('ee_read_contacts', 'generating_report')) {
26
+			throw new BatchRequestException(
27
+				__('You do not have permission to view contacts', 'event_espresso')
28
+			);
29
+		}
30
+		$filepath = $this->create_file_from_job_with_name(
31
+			$job_parameters->job_id(),
32
+			__('contact-list-report.csv', 'event_espresso')
33
+		);
34
+		$job_parameters->add_extra_data('filepath', $filepath);
35
+		$job_parameters->set_job_size($this->count_units_to_process());
36
+		// we should also set the header columns
37
+		$csv_data_for_row = $this->get_csv_data(0, 1);
38
+		\EEH_Export::write_data_array_to_csv($filepath, $csv_data_for_row, true);
39
+		// if we actually processed a row there, record it
40
+		if ($job_parameters->job_size()) {
41
+			$job_parameters->mark_processed(1);
42
+		}
43
+		return new JobStepResponse(
44
+			$job_parameters,
45
+			__('Contacts report started successfully...', 'event_espresso')
46
+		);
47
+	}
48 48
 
49 49
 
50
-    public function continue_job(JobParameters $job_parameters, $batch_size = 50)
51
-    {
52
-        $csv_data = $this->get_csv_data($job_parameters->units_processed(), $batch_size);
53
-        \EEH_Export::write_data_array_to_csv(
54
-            $job_parameters->extra_datum('filepath'),
55
-            $csv_data,
56
-            false
57
-        );
58
-        $units_processed = count($csv_data);
59
-        $job_parameters->mark_processed($units_processed);
60
-        $extra_response_data = array(
61
-            'file_url' => '',
62
-        );
63
-        if ($units_processed < $batch_size) {
64
-            $job_parameters->set_status(JobParameters::status_complete);
65
-            $extra_response_data['file_url'] = $this->get_url_to_file($job_parameters->extra_datum('filepath'));
66
-        }
67
-        return new JobStepResponse(
68
-            $job_parameters,
69
-            sprintf(
70
-                __('Wrote %1$s rows to report CSV file...', 'event_espresso'),
71
-                count($csv_data)
72
-            ),
73
-            $extra_response_data
74
-        );
75
-    }
50
+	public function continue_job(JobParameters $job_parameters, $batch_size = 50)
51
+	{
52
+		$csv_data = $this->get_csv_data($job_parameters->units_processed(), $batch_size);
53
+		\EEH_Export::write_data_array_to_csv(
54
+			$job_parameters->extra_datum('filepath'),
55
+			$csv_data,
56
+			false
57
+		);
58
+		$units_processed = count($csv_data);
59
+		$job_parameters->mark_processed($units_processed);
60
+		$extra_response_data = array(
61
+			'file_url' => '',
62
+		);
63
+		if ($units_processed < $batch_size) {
64
+			$job_parameters->set_status(JobParameters::status_complete);
65
+			$extra_response_data['file_url'] = $this->get_url_to_file($job_parameters->extra_datum('filepath'));
66
+		}
67
+		return new JobStepResponse(
68
+			$job_parameters,
69
+			sprintf(
70
+				__('Wrote %1$s rows to report CSV file...', 'event_espresso'),
71
+				count($csv_data)
72
+			),
73
+			$extra_response_data
74
+		);
75
+	}
76 76
 
77 77
 
78
-    public function cleanup_job(JobParameters $job_parameters)
79
-    {
80
-        $this->_file_helper->delete(
81
-            \EEH_File::remove_filename_from_filepath($job_parameters->extra_datum('filepath')),
82
-            true,
83
-            'd'
84
-        );
85
-        return new JobStepResponse($job_parameters, __('Cleaned up temporary file', 'event_espresso'));
86
-    }
78
+	public function cleanup_job(JobParameters $job_parameters)
79
+	{
80
+		$this->_file_helper->delete(
81
+			\EEH_File::remove_filename_from_filepath($job_parameters->extra_datum('filepath')),
82
+			true,
83
+			'd'
84
+		);
85
+		return new JobStepResponse($job_parameters, __('Cleaned up temporary file', 'event_espresso'));
86
+	}
87 87
 
88
-    public function count_units_to_process()
89
-    {
90
-        return \EEM_Attendee::instance()->count(array('caps' => \EEM_Base::caps_read_admin));
91
-    }
88
+	public function count_units_to_process()
89
+	{
90
+		return \EEM_Attendee::instance()->count(array('caps' => \EEM_Base::caps_read_admin));
91
+	}
92 92
 
93
-    public function get_csv_data($offset, $limit)
94
-    {
95
-        $attendee_rows = \EEM_Attendee::instance()->get_all_wpdb_results(
96
-            array(
97
-                'limit'      => array($offset, $limit),
98
-                'force_join' => array('State', 'Country'),
99
-                'caps'       => \EEM_Base::caps_read_admin,
100
-            )
101
-        );
102
-        $csv_data = array();
103
-        foreach ($attendee_rows as $attendee_row) {
104
-            $csv_row = array();
105
-            foreach (\EEM_Attendee::instance()->field_settings() as $field_name => $field_obj) {
106
-                if ($field_name == 'STA_ID') {
107
-                    $state_name_field = \EEM_State::instance()->field_settings_for('STA_name');
108
-                    $csv_row[ __('State', 'event_espresso') ] = $attendee_row[ $state_name_field->get_qualified_column() ];
109
-                } elseif ($field_name == 'CNT_ISO') {
110
-                    $country_name_field = \EEM_Country::instance()->field_settings_for('CNT_name');
111
-                    $csv_row[ __('Country', 'event_espresso') ] = $attendee_row[ $country_name_field->get_qualified_column() ];
112
-                } else {
113
-                    $csv_row[ wp_specialchars_decode($field_obj->get_nicename(), ENT_QUOTES) ] = $attendee_row[ $field_obj->get_qualified_column() ];
114
-                }
115
-            }
116
-            $csv_data[] = apply_filters(
117
-                'FHEE___EventEspresso_core_libraries_batch_JobHandlers_AttendeesReport__get_csv_data__row',
118
-                $csv_row,
119
-                $attendee_row
120
-            );
121
-        }
122
-        return $csv_data;
123
-    }
93
+	public function get_csv_data($offset, $limit)
94
+	{
95
+		$attendee_rows = \EEM_Attendee::instance()->get_all_wpdb_results(
96
+			array(
97
+				'limit'      => array($offset, $limit),
98
+				'force_join' => array('State', 'Country'),
99
+				'caps'       => \EEM_Base::caps_read_admin,
100
+			)
101
+		);
102
+		$csv_data = array();
103
+		foreach ($attendee_rows as $attendee_row) {
104
+			$csv_row = array();
105
+			foreach (\EEM_Attendee::instance()->field_settings() as $field_name => $field_obj) {
106
+				if ($field_name == 'STA_ID') {
107
+					$state_name_field = \EEM_State::instance()->field_settings_for('STA_name');
108
+					$csv_row[ __('State', 'event_espresso') ] = $attendee_row[ $state_name_field->get_qualified_column() ];
109
+				} elseif ($field_name == 'CNT_ISO') {
110
+					$country_name_field = \EEM_Country::instance()->field_settings_for('CNT_name');
111
+					$csv_row[ __('Country', 'event_espresso') ] = $attendee_row[ $country_name_field->get_qualified_column() ];
112
+				} else {
113
+					$csv_row[ wp_specialchars_decode($field_obj->get_nicename(), ENT_QUOTES) ] = $attendee_row[ $field_obj->get_qualified_column() ];
114
+				}
115
+			}
116
+			$csv_data[] = apply_filters(
117
+				'FHEE___EventEspresso_core_libraries_batch_JobHandlers_AttendeesReport__get_csv_data__row',
118
+				$csv_row,
119
+				$attendee_row
120
+			);
121
+		}
122
+		return $csv_data;
123
+	}
124 124
 }
Please login to merge, or discard this patch.
Spacing   +4 added lines, -4 removed lines patch added patch discarded remove patch
@@ -22,7 +22,7 @@  discard block
 block discarded – undo
22 22
     // phpcs:disable PSR1.Methods.CamelCapsMethodName.NotCamelCaps
23 23
     public function create_job(JobParameters $job_parameters)
24 24
     {
25
-        if (! \EE_Capabilities::instance()->current_user_can('ee_read_contacts', 'generating_report')) {
25
+        if ( ! \EE_Capabilities::instance()->current_user_can('ee_read_contacts', 'generating_report')) {
26 26
             throw new BatchRequestException(
27 27
                 __('You do not have permission to view contacts', 'event_espresso')
28 28
             );
@@ -105,12 +105,12 @@  discard block
 block discarded – undo
105 105
             foreach (\EEM_Attendee::instance()->field_settings() as $field_name => $field_obj) {
106 106
                 if ($field_name == 'STA_ID') {
107 107
                     $state_name_field = \EEM_State::instance()->field_settings_for('STA_name');
108
-                    $csv_row[ __('State', 'event_espresso') ] = $attendee_row[ $state_name_field->get_qualified_column() ];
108
+                    $csv_row[__('State', 'event_espresso')] = $attendee_row[$state_name_field->get_qualified_column()];
109 109
                 } elseif ($field_name == 'CNT_ISO') {
110 110
                     $country_name_field = \EEM_Country::instance()->field_settings_for('CNT_name');
111
-                    $csv_row[ __('Country', 'event_espresso') ] = $attendee_row[ $country_name_field->get_qualified_column() ];
111
+                    $csv_row[__('Country', 'event_espresso')] = $attendee_row[$country_name_field->get_qualified_column()];
112 112
                 } else {
113
-                    $csv_row[ wp_specialchars_decode($field_obj->get_nicename(), ENT_QUOTES) ] = $attendee_row[ $field_obj->get_qualified_column() ];
113
+                    $csv_row[wp_specialchars_decode($field_obj->get_nicename(), ENT_QUOTES)] = $attendee_row[$field_obj->get_qualified_column()];
114 114
                 }
115 115
             }
116 116
             $csv_data[] = apply_filters(
Please login to merge, or discard this patch.
core/libraries/form_sections/inputs/EE_Form_Input_Base.input.php 3 patches
Doc Comments   +2 added lines, -2 removed lines patch added patch discarded remove patch
@@ -356,7 +356,7 @@  discard block
 block discarded – undo
356 356
      * Sets sensitive_data_removal_strategy
357 357
      *
358 358
      * @param EE_Sensitive_Data_Removal_Base $sensitive_data_removal_strategy
359
-     * @return boolean
359
+     * @return boolean|null
360 360
      */
361 361
     public function set_sensitive_data_removal_strategy($sensitive_data_removal_strategy)
362 362
     {
@@ -476,7 +476,7 @@  discard block
 block discarded – undo
476 476
     /**
477 477
      * returns true if input employs any of the validation strategy defined by the supplied array of classnames
478 478
      *
479
-     * @param array $validation_strategy_classnames
479
+     * @param string[] $validation_strategy_classnames
480 480
      * @return bool
481 481
      */
482 482
     public function has_validation_strategy($validation_strategy_classnames)
Please login to merge, or discard this patch.
Spacing   +20 added lines, -20 removed lines patch added patch discarded remove patch
@@ -202,7 +202,7 @@  discard block
 block discarded – undo
202 202
         if (isset($input_args['validation_strategies'])) {
203 203
             foreach ((array) $input_args['validation_strategies'] as $validation_strategy) {
204 204
                 if ($validation_strategy instanceof EE_Validation_Strategy_Base && empty($input_args['ignore_input'])) {
205
-                    $this->_validation_strategies[ get_class($validation_strategy) ] = $validation_strategy;
205
+                    $this->_validation_strategies[get_class($validation_strategy)] = $validation_strategy;
206 206
                 }
207 207
             }
208 208
             unset($input_args['validation_strategies']);
@@ -213,7 +213,7 @@  discard block
 block discarded – undo
213 213
         // loop thru incoming options
214 214
         foreach ($input_args as $key => $value) {
215 215
             // add underscore to $key to match property names
216
-            $_key = '_' . $key;
216
+            $_key = '_'.$key;
217 217
             if (property_exists($this, $_key)) {
218 218
                 $this->{$_key} = $value;
219 219
             }
@@ -233,7 +233,7 @@  discard block
 block discarded – undo
233 233
         if (isset($input_args['ignore_input'])) {
234 234
             $this->_normalization_strategy = new EE_Null_Normalization();
235 235
         }
236
-        if (! $this->_normalization_strategy) {
236
+        if ( ! $this->_normalization_strategy) {
237 237
                 $this->_normalization_strategy = new EE_Text_Normalization();
238 238
         }
239 239
         $this->_normalization_strategy->_construct_finalize($this);
@@ -242,7 +242,7 @@  discard block
 block discarded – undo
242 242
             $this->set_default($input_args['default']);
243 243
             unset($input_args['default']);
244 244
         }
245
-        if (! $this->_sensitive_data_removal_strategy) {
245
+        if ( ! $this->_sensitive_data_removal_strategy) {
246 246
             $this->_sensitive_data_removal_strategy = new EE_No_Sensitive_Data_Removal();
247 247
         }
248 248
         $this->_sensitive_data_removal_strategy->_construct_finalize($this);
@@ -259,10 +259,10 @@  discard block
 block discarded – undo
259 259
      */
260 260
     protected function _set_default_html_name_if_empty()
261 261
     {
262
-        if (! $this->_html_name) {
262
+        if ( ! $this->_html_name) {
263 263
             $this->_html_name = $this->name();
264 264
             if ($this->_parent_section && $this->_parent_section instanceof EE_Form_Section_Proper) {
265
-                $this->_html_name = $this->_parent_section->html_name_prefix() . "[{$this->name()}]";
265
+                $this->_html_name = $this->_parent_section->html_name_prefix()."[{$this->name()}]";
266 266
             }
267 267
         }
268 268
     }
@@ -294,7 +294,7 @@  discard block
 block discarded – undo
294 294
     protected function _get_display_strategy()
295 295
     {
296 296
         $this->ensure_construct_finalized_called();
297
-        if (! $this->_display_strategy || ! $this->_display_strategy instanceof EE_Display_Strategy_Base) {
297
+        if ( ! $this->_display_strategy || ! $this->_display_strategy instanceof EE_Display_Strategy_Base) {
298 298
             throw new EE_Error(
299 299
                 sprintf(
300 300
                     __(
@@ -461,7 +461,7 @@  discard block
 block discarded – undo
461 461
             if ($validation_strategy instanceof $validation_strategy_classname
462 462
                 || is_subclass_of($validation_strategy, $validation_strategy_classname)
463 463
             ) {
464
-                unset($this->_validation_strategies[ $key ]);
464
+                unset($this->_validation_strategies[$key]);
465 465
             }
466 466
         }
467 467
     }
@@ -526,7 +526,7 @@  discard block
 block discarded – undo
526 526
      */
527 527
     public function html_other_attributes()
528 528
     {
529
-        return ! empty($this->_html_other_attributes) ? ' ' . $this->_html_other_attributes : '';
529
+        return ! empty($this->_html_other_attributes) ? ' '.$this->_html_other_attributes : '';
530 530
     }
531 531
 
532 532
 
@@ -648,7 +648,7 @@  discard block
 block discarded – undo
648 648
             if (is_array($raw_input)) {
649 649
                 $raw_value = array();
650 650
                 foreach ($raw_input as $key => $value) {
651
-                    $raw_value[ $key ] = $this->_sanitize($value);
651
+                    $raw_value[$key] = $this->_sanitize($value);
652 652
                 }
653 653
                 $this->_set_raw_value($raw_value);
654 654
             } else {
@@ -681,7 +681,7 @@  discard block
 block discarded – undo
681 681
      */
682 682
     public function html_label_id()
683 683
     {
684
-        return ! empty($this->_html_label_id) ? $this->_html_label_id : $this->html_id() . '-lbl';
684
+        return ! empty($this->_html_label_id) ? $this->_html_label_id : $this->html_id().'-lbl';
685 685
     }
686 686
 
687 687
 
@@ -831,9 +831,9 @@  discard block
 block discarded – undo
831 831
                 $validation_strategy->get_jquery_validation_rule_array()
832 832
             );
833 833
         }
834
-        if (! empty($jquery_validation_rules)) {
834
+        if ( ! empty($jquery_validation_rules)) {
835 835
             foreach ($this->get_display_strategy()->get_html_input_ids(true) as $html_id_with_pound_sign) {
836
-                $jquery_validation_js[ $html_id_with_pound_sign ] = $jquery_validation_rules;
836
+                $jquery_validation_js[$html_id_with_pound_sign] = $jquery_validation_rules;
837 837
             }
838 838
         }
839 839
         return $jquery_validation_js;
@@ -955,7 +955,7 @@  discard block
 block discarded – undo
955 955
     public function html_class($add_required = false)
956 956
     {
957 957
         return $add_required && $this->required()
958
-            ? $this->required_css_class() . ' ' . $this->_html_class
958
+            ? $this->required_css_class().' '.$this->_html_class
959 959
             : $this->_html_class;
960 960
     }
961 961
 
@@ -1029,7 +1029,7 @@  discard block
 block discarded – undo
1029 1029
                 $button_css_attributes .= '';
1030 1030
         }
1031 1031
         $this->_button_css_attributes .= ! empty($other_attributes)
1032
-            ? $button_css_attributes . ' ' . $other_attributes
1032
+            ? $button_css_attributes.' '.$other_attributes
1033 1033
             : $button_css_attributes;
1034 1034
     }
1035 1035
 
@@ -1067,8 +1067,8 @@  discard block
 block discarded – undo
1067 1067
         // now get the value for the input
1068 1068
         $value = $this->findRequestForSectionUsingNameParts($name_parts, $req_data);
1069 1069
         // check if this thing's name is at the TOP level of the request data
1070
-        if ($value === null && isset($req_data[ $this->name() ])) {
1071
-            $value = $req_data[ $this->name() ];
1070
+        if ($value === null && isset($req_data[$this->name()])) {
1071
+            $value = $req_data[$this->name()];
1072 1072
         }
1073 1073
         return $value;
1074 1074
     }
@@ -1109,13 +1109,13 @@  discard block
 block discarded – undo
1109 1109
     public function findRequestForSectionUsingNameParts($html_name_parts, $req_data)
1110 1110
     {
1111 1111
         $first_part_to_consider = array_shift($html_name_parts);
1112
-        if (isset($req_data[ $first_part_to_consider ])) {
1112
+        if (isset($req_data[$first_part_to_consider])) {
1113 1113
             if (empty($html_name_parts)) {
1114
-                return $req_data[ $first_part_to_consider ];
1114
+                return $req_data[$first_part_to_consider];
1115 1115
             } else {
1116 1116
                 return $this->findRequestForSectionUsingNameParts(
1117 1117
                     $html_name_parts,
1118
-                    $req_data[ $first_part_to_consider ]
1118
+                    $req_data[$first_part_to_consider]
1119 1119
                 );
1120 1120
             }
1121 1121
         } else {
Please login to merge, or discard this patch.
Indentation   +1236 added lines, -1236 removed lines patch added patch discarded remove patch
@@ -11,1240 +11,1240 @@
 block discarded – undo
11 11
 abstract class EE_Form_Input_Base extends EE_Form_Section_Validatable
12 12
 {
13 13
 
14
-    /**
15
-     * the input's name attribute
16
-     *
17
-     * @var string
18
-     */
19
-    protected $_html_name;
20
-
21
-    /**
22
-     * id for the html label tag
23
-     *
24
-     * @var string
25
-     */
26
-    protected $_html_label_id;
27
-
28
-    /**
29
-     * class for teh html label tag
30
-     *
31
-     * @var string
32
-     */
33
-    protected $_html_label_class;
34
-
35
-    /**
36
-     * any additional html attributes that you may want to add
37
-     *
38
-     * @var string
39
-     */
40
-    protected $_html_other_attributes;
41
-
42
-    /**
43
-     * style for teh html label tag
44
-     *
45
-     * @var string
46
-     */
47
-    protected $_html_label_style;
48
-
49
-    /**
50
-     * text to be placed in the html label
51
-     *
52
-     * @var string
53
-     */
54
-    protected $_html_label_text;
55
-
56
-    /**
57
-     * the full html label. If used, all other html_label_* properties are invalid
58
-     *
59
-     * @var string
60
-     */
61
-    protected $_html_label;
62
-
63
-    /**
64
-     * HTML to use for help text (normally placed below form input), in a span which normally
65
-     * has a class of 'description'
66
-     *
67
-     * @var string
68
-     */
69
-    protected $_html_help_text;
70
-
71
-    /**
72
-     * CSS classes for displaying the help span
73
-     *
74
-     * @var string
75
-     */
76
-    protected $_html_help_class = 'description';
77
-
78
-    /**
79
-     * CSS to put in the style attribute on the help span
80
-     *
81
-     * @var string
82
-     */
83
-    protected $_html_help_style;
84
-
85
-    /**
86
-     * Stores whether or not this input's response is required.
87
-     * Because certain styling elements may also want to know that this
88
-     * input is required etc.
89
-     *
90
-     * @var boolean
91
-     */
92
-    protected $_required;
93
-
94
-    /**
95
-     * css class added to required inputs
96
-     *
97
-     * @var string
98
-     */
99
-    protected $_required_css_class = 'ee-required';
100
-
101
-    /**
102
-     * css styles applied to button type inputs
103
-     *
104
-     * @var string
105
-     */
106
-    protected $_button_css_attributes;
107
-
108
-    /**
109
-     * The raw data submitted for this, like in the $_POST super global.
110
-     * Generally unsafe for usage in client code
111
-     *
112
-     * @var mixed string or array
113
-     */
114
-    protected $_raw_value;
115
-
116
-    /**
117
-     * Value normalized according to the input's normalization strategy.
118
-     * The normalization strategy dictates whether this is a string, int, float,
119
-     * boolean, or array of any of those.
120
-     *
121
-     * @var mixed
122
-     */
123
-    protected $_normalized_value;
124
-
125
-
126
-    /**
127
-     * Normalized default value either initially set on the input, or provided by calling
128
-     * set_default().
129
-     * @var mixed
130
-     */
131
-    protected $_default;
132
-
133
-    /**
134
-     * Strategy used for displaying this field.
135
-     * Child classes must use _get_display_strategy to access it.
136
-     *
137
-     * @var EE_Display_Strategy_Base
138
-     */
139
-    private $_display_strategy;
140
-
141
-    /**
142
-     * Gets all the validation strategies used on this field
143
-     *
144
-     * @var EE_Validation_Strategy_Base[]
145
-     */
146
-    private $_validation_strategies = array();
147
-
148
-    /**
149
-     * The normalization strategy for this field
150
-     *
151
-     * @var EE_Normalization_Strategy_Base
152
-     */
153
-    private $_normalization_strategy;
154
-
155
-    /**
156
-     * Strategy for removing sensitive data after we're done with the form input
157
-     *
158
-     * @var EE_Sensitive_Data_Removal_Base
159
-     */
160
-    protected $_sensitive_data_removal_strategy;
161
-
162
-    /**
163
-     * Whether this input has been disabled or not.
164
-     * If it's disabled while rendering, an extra hidden input is added that indicates it has been knowingly disabled.
165
-     * (Client-side code that wants to dynamically disable it must also add this hidden input).
166
-     * When the form is submitted, if the input is disabled in the PHP formsection, then input is ignored.
167
-     * If the input is missing from the $_REQUEST data but the hidden input indicating the input is disabled, then the input is again ignored.
168
-     *
169
-     * @var boolean
170
-     */
171
-    protected $disabled = false;
172
-
173
-
174
-
175
-    /**
176
-     * @param array                         $input_args       {
177
-     * @type string                         $html_name        the html name for the input
178
-     * @type string                         $html_label_id    the id attribute to give to the html label tag
179
-     * @type string                         $html_label_class the class attribute to give to the html label tag
180
-     * @type string                         $html_label_style the style attribute to give ot teh label tag
181
-     * @type string                         $html_label_text  the text to put in the label tag
182
-     * @type string                         $html_label       the full html label. If used,
183
-     *                                                        all other html_label_* args are invalid
184
-     * @type string                         $html_help_text   text to put in help element
185
-     * @type string                         $html_help_style  style attribute to give to teh help element
186
-     * @type string                         $html_help_class  class attribute to give to the help element
187
-     * @type string                         $default          default value NORMALIZED (eg, if providing the default
188
-     *       for a Yes_No_Input, you should provide TRUE or FALSE, not '1' or '0')
189
-     * @type EE_Display_Strategy_Base       $display          strategy
190
-     * @type EE_Normalization_Strategy_Base $normalization_strategy
191
-     * @type EE_Validation_Strategy_Base[]  $validation_strategies
192
-     * @type boolean                        $ignore_input special argument which can be used to avoid adding any validation strategies,
193
-     *                                                    and sets the normalization strategy to the Null normalization. This is good
194
-     *                                                    when you want the input to be totally ignored server-side (like when using
195
-     *                                                    React.js form inputs)
196
-     *                                                        }
197
-     */
198
-    public function __construct($input_args = array())
199
-    {
200
-        $input_args = (array) apply_filters('FHEE__EE_Form_Input_Base___construct__input_args', $input_args, $this);
201
-        // the following properties must be cast as arrays
202
-        if (isset($input_args['validation_strategies'])) {
203
-            foreach ((array) $input_args['validation_strategies'] as $validation_strategy) {
204
-                if ($validation_strategy instanceof EE_Validation_Strategy_Base && empty($input_args['ignore_input'])) {
205
-                    $this->_validation_strategies[ get_class($validation_strategy) ] = $validation_strategy;
206
-                }
207
-            }
208
-            unset($input_args['validation_strategies']);
209
-        }
210
-        if (isset($input_args['ignore_input'])) {
211
-            $this->_validation_strategies = array();
212
-        }
213
-        // loop thru incoming options
214
-        foreach ($input_args as $key => $value) {
215
-            // add underscore to $key to match property names
216
-            $_key = '_' . $key;
217
-            if (property_exists($this, $_key)) {
218
-                $this->{$_key} = $value;
219
-            }
220
-        }
221
-        // ensure that "required" is set correctly
222
-        $this->set_required(
223
-            $this->_required,
224
-            isset($input_args['required_validation_error_message'])
225
-            ? $input_args['required_validation_error_message']
226
-            : null
227
-        );
228
-        // $this->_html_name_specified = isset( $input_args['html_name'] ) ? TRUE : FALSE;
229
-        $this->_display_strategy->_construct_finalize($this);
230
-        foreach ($this->_validation_strategies as $validation_strategy) {
231
-            $validation_strategy->_construct_finalize($this);
232
-        }
233
-        if (isset($input_args['ignore_input'])) {
234
-            $this->_normalization_strategy = new EE_Null_Normalization();
235
-        }
236
-        if (! $this->_normalization_strategy) {
237
-                $this->_normalization_strategy = new EE_Text_Normalization();
238
-        }
239
-        $this->_normalization_strategy->_construct_finalize($this);
240
-        // at least we can use the normalization strategy to populate the default
241
-        if (isset($input_args['default'])) {
242
-            $this->set_default($input_args['default']);
243
-            unset($input_args['default']);
244
-        }
245
-        if (! $this->_sensitive_data_removal_strategy) {
246
-            $this->_sensitive_data_removal_strategy = new EE_No_Sensitive_Data_Removal();
247
-        }
248
-        $this->_sensitive_data_removal_strategy->_construct_finalize($this);
249
-        parent::__construct($input_args);
250
-    }
251
-
252
-
253
-
254
-    /**
255
-     * Sets the html_name to its default value, if none was specified in teh constructor.
256
-     * Calculation involves using the name and the parent's html_name
257
-     *
258
-     * @throws \EE_Error
259
-     */
260
-    protected function _set_default_html_name_if_empty()
261
-    {
262
-        if (! $this->_html_name) {
263
-            $this->_html_name = $this->name();
264
-            if ($this->_parent_section && $this->_parent_section instanceof EE_Form_Section_Proper) {
265
-                $this->_html_name = $this->_parent_section->html_name_prefix() . "[{$this->name()}]";
266
-            }
267
-        }
268
-    }
269
-
270
-
271
-
272
-    /**
273
-     * @param $parent_form_section
274
-     * @param $name
275
-     * @throws \EE_Error
276
-     */
277
-    public function _construct_finalize($parent_form_section, $name)
278
-    {
279
-        parent::_construct_finalize($parent_form_section, $name);
280
-        if ($this->_html_label === null && $this->_html_label_text === null) {
281
-            $this->_html_label_text = ucwords(str_replace("_", " ", $name));
282
-        }
283
-        do_action('AHEE__EE_Form_Input_Base___construct_finalize__end', $this, $parent_form_section, $name);
284
-    }
285
-
286
-
287
-
288
-    /**
289
-     * Returns the strategy for displaying this form input. If none is set, throws an exception.
290
-     *
291
-     * @return EE_Display_Strategy_Base
292
-     * @throws EE_Error
293
-     */
294
-    protected function _get_display_strategy()
295
-    {
296
-        $this->ensure_construct_finalized_called();
297
-        if (! $this->_display_strategy || ! $this->_display_strategy instanceof EE_Display_Strategy_Base) {
298
-            throw new EE_Error(
299
-                sprintf(
300
-                    __(
301
-                        "Cannot get display strategy for form input with name %s and id %s, because it has not been set in the constructor",
302
-                        "event_espresso"
303
-                    ),
304
-                    $this->html_name(),
305
-                    $this->html_id()
306
-                )
307
-            );
308
-        } else {
309
-            return $this->_display_strategy;
310
-        }
311
-    }
312
-
313
-
314
-
315
-    /**
316
-     * Sets the display strategy.
317
-     *
318
-     * @param EE_Display_Strategy_Base $strategy
319
-     */
320
-    protected function _set_display_strategy(EE_Display_Strategy_Base $strategy)
321
-    {
322
-        $this->_display_strategy = $strategy;
323
-    }
324
-
325
-
326
-
327
-    /**
328
-     * Sets the sanitization strategy
329
-     *
330
-     * @param EE_Normalization_Strategy_Base $strategy
331
-     */
332
-    protected function _set_normalization_strategy(EE_Normalization_Strategy_Base $strategy)
333
-    {
334
-        $this->_normalization_strategy = $strategy;
335
-    }
336
-
337
-
338
-
339
-    /**
340
-     * Gets sensitive_data_removal_strategy
341
-     *
342
-     * @return EE_Sensitive_Data_Removal_Base
343
-     */
344
-    public function get_sensitive_data_removal_strategy()
345
-    {
346
-        return $this->_sensitive_data_removal_strategy;
347
-    }
348
-
349
-
350
-
351
-    /**
352
-     * Sets sensitive_data_removal_strategy
353
-     *
354
-     * @param EE_Sensitive_Data_Removal_Base $sensitive_data_removal_strategy
355
-     * @return boolean
356
-     */
357
-    public function set_sensitive_data_removal_strategy($sensitive_data_removal_strategy)
358
-    {
359
-        $this->_sensitive_data_removal_strategy = $sensitive_data_removal_strategy;
360
-    }
361
-
362
-
363
-
364
-    /**
365
-     * Gets the display strategy for this input
366
-     *
367
-     * @return EE_Display_Strategy_Base
368
-     */
369
-    public function get_display_strategy()
370
-    {
371
-        return $this->_display_strategy;
372
-    }
373
-
374
-
375
-
376
-    /**
377
-     * Overwrites the display strategy
378
-     *
379
-     * @param EE_Display_Strategy_Base $display_strategy
380
-     */
381
-    public function set_display_strategy($display_strategy)
382
-    {
383
-        $this->_display_strategy = $display_strategy;
384
-        $this->_display_strategy->_construct_finalize($this);
385
-    }
386
-
387
-
388
-
389
-    /**
390
-     * Gets the normalization strategy set on this input
391
-     *
392
-     * @return EE_Normalization_Strategy_Base
393
-     */
394
-    public function get_normalization_strategy()
395
-    {
396
-        return $this->_normalization_strategy;
397
-    }
398
-
399
-
400
-
401
-    /**
402
-     * Overwrites the normalization strategy
403
-     *
404
-     * @param EE_Normalization_Strategy_Base $normalization_strategy
405
-     */
406
-    public function set_normalization_strategy($normalization_strategy)
407
-    {
408
-        $this->_normalization_strategy = $normalization_strategy;
409
-        $this->_normalization_strategy->_construct_finalize($this);
410
-    }
411
-
412
-
413
-
414
-    /**
415
-     * Returns all teh validation strategies which apply to this field, numerically indexed
416
-     *
417
-     * @return EE_Validation_Strategy_Base[]
418
-     */
419
-    public function get_validation_strategies()
420
-    {
421
-        return $this->_validation_strategies;
422
-    }
423
-
424
-
425
-
426
-    /**
427
-     * Adds this strategy to the field so it will be used in both JS validation and server-side validation
428
-     *
429
-     * @param EE_Validation_Strategy_Base $validation_strategy
430
-     * @return void
431
-     */
432
-    protected function _add_validation_strategy(EE_Validation_Strategy_Base $validation_strategy)
433
-    {
434
-        $validation_strategy->_construct_finalize($this);
435
-        $this->_validation_strategies[] = $validation_strategy;
436
-    }
437
-
438
-
439
-
440
-    /**
441
-     * Adds a new validation strategy onto the form input
442
-     *
443
-     * @param EE_Validation_Strategy_Base $validation_strategy
444
-     * @return void
445
-     */
446
-    public function add_validation_strategy(EE_Validation_Strategy_Base $validation_strategy)
447
-    {
448
-        $this->_add_validation_strategy($validation_strategy);
449
-    }
450
-
451
-
452
-
453
-    /**
454
-     * The classname of the validation strategy to remove
455
-     *
456
-     * @param string $validation_strategy_classname
457
-     */
458
-    public function remove_validation_strategy($validation_strategy_classname)
459
-    {
460
-        foreach ($this->_validation_strategies as $key => $validation_strategy) {
461
-            if ($validation_strategy instanceof $validation_strategy_classname
462
-                || is_subclass_of($validation_strategy, $validation_strategy_classname)
463
-            ) {
464
-                unset($this->_validation_strategies[ $key ]);
465
-            }
466
-        }
467
-    }
468
-
469
-
470
-
471
-    /**
472
-     * returns true if input employs any of the validation strategy defined by the supplied array of classnames
473
-     *
474
-     * @param array $validation_strategy_classnames
475
-     * @return bool
476
-     */
477
-    public function has_validation_strategy($validation_strategy_classnames)
478
-    {
479
-        $validation_strategy_classnames = is_array($validation_strategy_classnames)
480
-            ? $validation_strategy_classnames
481
-            : array($validation_strategy_classnames);
482
-        foreach ($this->_validation_strategies as $key => $validation_strategy) {
483
-            if (in_array($key, $validation_strategy_classnames)) {
484
-                return true;
485
-            }
486
-        }
487
-        return false;
488
-    }
489
-
490
-
491
-
492
-    /**
493
-     * Gets the HTML
494
-     *
495
-     * @return string
496
-     */
497
-    public function get_html()
498
-    {
499
-        return $this->_parent_section->get_html_for_input($this);
500
-    }
501
-
502
-
503
-
504
-    /**
505
-     * Gets the HTML for the input itself (no label or errors) according to the
506
-     * input's display strategy
507
-     * Makes sure the JS and CSS are enqueued for it
508
-     *
509
-     * @return string
510
-     * @throws \EE_Error
511
-     */
512
-    public function get_html_for_input()
513
-    {
514
-        return $this->_form_html_filter
515
-            ? $this->_form_html_filter->filterHtml(
516
-                $this->_get_display_strategy()->display(),
517
-                $this
518
-            )
519
-            : $this->_get_display_strategy()->display();
520
-    }
521
-
522
-
523
-
524
-    /**
525
-     * @return string
526
-     */
527
-    public function html_other_attributes()
528
-    {
529
-        return ! empty($this->_html_other_attributes) ? ' ' . $this->_html_other_attributes : '';
530
-    }
531
-
532
-
533
-
534
-    /**
535
-     * @param string $html_other_attributes
536
-     */
537
-    public function set_html_other_attributes($html_other_attributes)
538
-    {
539
-        $this->_html_other_attributes = $html_other_attributes;
540
-    }
541
-
542
-
543
-
544
-    /**
545
-     * Gets the HTML for displaying the label for this form input
546
-     * according to the form section's layout strategy
547
-     *
548
-     * @return string
549
-     */
550
-    public function get_html_for_label()
551
-    {
552
-        return $this->_parent_section->get_layout_strategy()->display_label($this);
553
-    }
554
-
555
-
556
-
557
-    /**
558
-     * Gets the HTML for displaying the errors section for this form input
559
-     * according to the form section's layout strategy
560
-     *
561
-     * @return string
562
-     */
563
-    public function get_html_for_errors()
564
-    {
565
-        return $this->_parent_section->get_layout_strategy()->display_errors($this);
566
-    }
567
-
568
-
569
-
570
-    /**
571
-     * Gets the HTML for displaying the help text for this form input
572
-     * according to the form section's layout strategy
573
-     *
574
-     * @return string
575
-     */
576
-    public function get_html_for_help()
577
-    {
578
-        return $this->_parent_section->get_layout_strategy()->display_help_text($this);
579
-    }
580
-
581
-
582
-
583
-    /**
584
-     * Validates the input's sanitized value (assumes _sanitize() has already been called)
585
-     * and returns whether or not the form input's submitted value is value
586
-     *
587
-     * @return boolean
588
-     */
589
-    protected function _validate()
590
-    {
591
-        if ($this->isDisabled()) {
592
-            return true;
593
-        }
594
-        foreach ($this->_validation_strategies as $validation_strategy) {
595
-            if ($validation_strategy instanceof EE_Validation_Strategy_Base) {
596
-                try {
597
-                    $validation_strategy->validate($this->normalized_value());
598
-                } catch (EE_Validation_Error $e) {
599
-                    $this->add_validation_error($e);
600
-                }
601
-            }
602
-        }
603
-        if ($this->get_validation_errors()) {
604
-            return false;
605
-        } else {
606
-            return true;
607
-        }
608
-    }
609
-
610
-
611
-
612
-    /**
613
-     * Performs basic sanitization on this value. But what sanitization can be performed anyways?
614
-     * This value MIGHT be allowed to have tags, so we can't really remove them.
615
-     *
616
-     * @param string $value
617
-     * @return null|string
618
-     */
619
-    protected function _sanitize($value)
620
-    {
621
-        return $value !== null ? stripslashes(html_entity_decode(trim($value))) : null;
622
-    }
623
-
624
-
625
-
626
-    /**
627
-     * Picks out the form value that relates to this form input,
628
-     * and stores it as the sanitized value on the form input, and sets the normalized value.
629
-     * Returns whether or not any validation errors occurred
630
-     *
631
-     * @param array $req_data like $_POST
632
-     * @return boolean whether or not there was an error
633
-     * @throws \EE_Error
634
-     */
635
-    protected function _normalize($req_data)
636
-    {
637
-        // any existing validation errors don't apply so clear them
638
-        $this->_validation_errors = array();
639
-        // if the input is disabled, ignore whatever input was sent in
640
-        if ($this->isDisabled()) {
641
-            $this->_set_raw_value(null);
642
-            $this->_set_normalized_value($this->get_default());
643
-            return false;
644
-        }
645
-        try {
646
-            $raw_input = $this->find_form_data_for_this_section($req_data);
647
-            // super simple sanitization for now
648
-            if (is_array($raw_input)) {
649
-                $raw_value = array();
650
-                foreach ($raw_input as $key => $value) {
651
-                    $raw_value[ $key ] = $this->_sanitize($value);
652
-                }
653
-                $this->_set_raw_value($raw_value);
654
-            } else {
655
-                $this->_set_raw_value($this->_sanitize($raw_input));
656
-            }
657
-            // we want to mostly leave the input alone in case we need to re-display it to the user
658
-            $this->_set_normalized_value($this->_normalization_strategy->normalize($this->raw_value()));
659
-            return false;
660
-        } catch (EE_Validation_Error $e) {
661
-            $this->add_validation_error($e);
662
-            return true;
663
-        }
664
-    }
665
-
666
-
667
-
668
-    /**
669
-     * @return string
670
-     */
671
-    public function html_name()
672
-    {
673
-        $this->_set_default_html_name_if_empty();
674
-        return $this->_html_name;
675
-    }
676
-
677
-
678
-
679
-    /**
680
-     * @return string
681
-     */
682
-    public function html_label_id()
683
-    {
684
-        return ! empty($this->_html_label_id) ? $this->_html_label_id : $this->html_id() . '-lbl';
685
-    }
686
-
687
-
688
-
689
-    /**
690
-     * @return string
691
-     */
692
-    public function html_label_class()
693
-    {
694
-        return $this->_html_label_class;
695
-    }
696
-
697
-
698
-
699
-    /**
700
-     * @return string
701
-     */
702
-    public function html_label_style()
703
-    {
704
-        return $this->_html_label_style;
705
-    }
706
-
707
-
708
-
709
-    /**
710
-     * @return string
711
-     */
712
-    public function html_label_text()
713
-    {
714
-        return $this->_html_label_text;
715
-    }
716
-
717
-
718
-
719
-    /**
720
-     * @return string
721
-     */
722
-    public function html_help_text()
723
-    {
724
-        return $this->_html_help_text;
725
-    }
726
-
727
-
728
-
729
-    /**
730
-     * @return string
731
-     */
732
-    public function html_help_class()
733
-    {
734
-        return $this->_html_help_class;
735
-    }
736
-
737
-
738
-
739
-    /**
740
-     * @return string
741
-     */
742
-    public function html_help_style()
743
-    {
744
-        return $this->_html_style;
745
-    }
746
-
747
-
748
-
749
-    /**
750
-     * returns the raw, UNSAFE, input, almost exactly as the user submitted it.
751
-     * Please note that almost all client code should instead use the normalized_value;
752
-     * or possibly raw_value_in_form (which prepares the string for displaying in an HTML attribute on a tag,
753
-     * mostly by escaping quotes)
754
-     * Note, we do not store the exact original value sent in the user's request because
755
-     * it may have malicious content, and we MIGHT want to store the form input in a transient or something...
756
-     * in which case, we would have stored the malicious content to our database.
757
-     *
758
-     * @return string
759
-     */
760
-    public function raw_value()
761
-    {
762
-        return $this->_raw_value;
763
-    }
764
-
765
-
766
-
767
-    /**
768
-     * Returns a string safe to usage in form inputs when displaying, because
769
-     * it escapes all html entities
770
-     *
771
-     * @return string
772
-     */
773
-    public function raw_value_in_form()
774
-    {
775
-        return htmlentities($this->raw_value(), ENT_QUOTES, 'UTF-8');
776
-    }
777
-
778
-
779
-
780
-    /**
781
-     * returns the value after it's been sanitized, and then converted into it's proper type
782
-     * in PHP. Eg, a string, an int, an array,
783
-     *
784
-     * @return mixed
785
-     */
786
-    public function normalized_value()
787
-    {
788
-        return $this->_normalized_value;
789
-    }
790
-
791
-
792
-
793
-    /**
794
-     * Returns the normalized value is a presentable way. By default this is just
795
-     * the normalized value by itself, but it can be overridden for when that's not
796
-     * the best thing to display
797
-     *
798
-     * @return string
799
-     */
800
-    public function pretty_value()
801
-    {
802
-        return $this->_normalized_value;
803
-    }
804
-
805
-
806
-
807
-    /**
808
-     * When generating the JS for the jquery validation rules like<br>
809
-     * <code>$( "#myform" ).validate({
810
-     * rules: {
811
-     * password: "required",
812
-     * password_again: {
813
-     * equalTo: "#password"
814
-     * }
815
-     * }
816
-     * });</code>
817
-     * if this field had the name 'password_again', it should return
818
-     * <br><code>password_again: {
819
-     * equalTo: "#password"
820
-     * }</code>
821
-     *
822
-     * @return array
823
-     */
824
-    public function get_jquery_validation_rules()
825
-    {
826
-        $jquery_validation_js = array();
827
-        $jquery_validation_rules = array();
828
-        foreach ($this->get_validation_strategies() as $validation_strategy) {
829
-            $jquery_validation_rules = array_replace_recursive(
830
-                $jquery_validation_rules,
831
-                $validation_strategy->get_jquery_validation_rule_array()
832
-            );
833
-        }
834
-        if (! empty($jquery_validation_rules)) {
835
-            foreach ($this->get_display_strategy()->get_html_input_ids(true) as $html_id_with_pound_sign) {
836
-                $jquery_validation_js[ $html_id_with_pound_sign ] = $jquery_validation_rules;
837
-            }
838
-        }
839
-        return $jquery_validation_js;
840
-    }
841
-
842
-
843
-
844
-    /**
845
-     * Sets the input's default value for use in displaying in the form. Note: value should be
846
-     * normalized (Eg, if providing a default of ra Yes_NO_Input you would provide TRUE or FALSE, not '1' or '0')
847
-     *
848
-     * @param mixed $value
849
-     * @return void
850
-     */
851
-    public function set_default($value)
852
-    {
853
-        $this->_default = $value;
854
-        $this->_set_normalized_value($value);
855
-        $this->_set_raw_value($value);
856
-    }
857
-
858
-
859
-
860
-    /**
861
-     * Sets the normalized value on this input
862
-     *
863
-     * @param mixed $value
864
-     */
865
-    protected function _set_normalized_value($value)
866
-    {
867
-        $this->_normalized_value = $value;
868
-    }
869
-
870
-
871
-
872
-    /**
873
-     * Sets the raw value on this input (ie, exactly as the user submitted it)
874
-     *
875
-     * @param mixed $value
876
-     */
877
-    protected function _set_raw_value($value)
878
-    {
879
-        $this->_raw_value = $this->_normalization_strategy->unnormalize($value);
880
-    }
881
-
882
-
883
-
884
-    /**
885
-     * Sets the HTML label text after it has already been defined
886
-     *
887
-     * @param string $label
888
-     * @return void
889
-     */
890
-    public function set_html_label_text($label)
891
-    {
892
-        $this->_html_label_text = $label;
893
-    }
894
-
895
-
896
-
897
-    /**
898
-     * Sets whether or not this field is required, and adjusts the validation strategy.
899
-     * If you want to use the EE_Conditionally_Required_Validation_Strategy,
900
-     * please add it as a validation strategy using add_validation_strategy as normal
901
-     *
902
-     * @param boolean $required boolean
903
-     * @param null    $required_text
904
-     */
905
-    public function set_required($required = true, $required_text = null)
906
-    {
907
-        $required = filter_var($required, FILTER_VALIDATE_BOOLEAN);
908
-        // whether $required is a string or a boolean, we want to add a required validation strategy
909
-        if ($required) {
910
-            $this->_add_validation_strategy(new EE_Required_Validation_Strategy($required_text));
911
-        } else {
912
-            $this->remove_validation_strategy('EE_Required_Validation_Strategy');
913
-        }
914
-        $this->_required = $required;
915
-    }
916
-
917
-
918
-
919
-    /**
920
-     * Returns whether or not this field is required
921
-     *
922
-     * @return boolean
923
-     */
924
-    public function required()
925
-    {
926
-        return $this->_required;
927
-    }
928
-
929
-
930
-
931
-    /**
932
-     * @param string $required_css_class
933
-     */
934
-    public function set_required_css_class($required_css_class)
935
-    {
936
-        $this->_required_css_class = $required_css_class;
937
-    }
938
-
939
-
940
-
941
-    /**
942
-     * @return string
943
-     */
944
-    public function required_css_class()
945
-    {
946
-        return $this->_required_css_class;
947
-    }
948
-
949
-
950
-
951
-    /**
952
-     * @param bool $add_required
953
-     * @return string
954
-     */
955
-    public function html_class($add_required = false)
956
-    {
957
-        return $add_required && $this->required()
958
-            ? $this->required_css_class() . ' ' . $this->_html_class
959
-            : $this->_html_class;
960
-    }
961
-
962
-
963
-    /**
964
-     * Sets the help text, in case
965
-     *
966
-     * @param string $text
967
-     */
968
-    public function set_html_help_text($text)
969
-    {
970
-        $this->_html_help_text = $text;
971
-    }
972
-
973
-
974
-
975
-    /**
976
-     * Uses the sensitive data removal strategy to remove the sensitive data from this
977
-     * input. If there is any kind of sensitive data removal on this input, we clear
978
-     * out the raw value completely
979
-     *
980
-     * @return void
981
-     */
982
-    public function clean_sensitive_data()
983
-    {
984
-        // if we do ANY kind of sensitive data removal on this, then just clear out the raw value
985
-        // if we need more logic than this we'll make a strategy for it
986
-        if ($this->_sensitive_data_removal_strategy
987
-            && ! $this->_sensitive_data_removal_strategy instanceof EE_No_Sensitive_Data_Removal
988
-        ) {
989
-            $this->_set_raw_value(null);
990
-        }
991
-        // and clean the normalized value according to the appropriate strategy
992
-        $this->_set_normalized_value(
993
-            $this->get_sensitive_data_removal_strategy()->remove_sensitive_data(
994
-                $this->_normalized_value
995
-            )
996
-        );
997
-    }
998
-
999
-
1000
-
1001
-    /**
1002
-     * @param bool   $primary
1003
-     * @param string $button_size
1004
-     * @param string $other_attributes
1005
-     */
1006
-    public function set_button_css_attributes($primary = true, $button_size = '', $other_attributes = '')
1007
-    {
1008
-        $button_css_attributes = 'button';
1009
-        $button_css_attributes .= $primary === true ? ' button-primary' : ' button-secondary';
1010
-        switch ($button_size) {
1011
-            case 'xs':
1012
-            case 'extra-small':
1013
-                $button_css_attributes .= ' button-xs';
1014
-                break;
1015
-            case 'sm':
1016
-            case 'small':
1017
-                $button_css_attributes .= ' button-sm';
1018
-                break;
1019
-            case 'lg':
1020
-            case 'large':
1021
-                $button_css_attributes .= ' button-lg';
1022
-                break;
1023
-            case 'block':
1024
-                $button_css_attributes .= ' button-block';
1025
-                break;
1026
-            case 'md':
1027
-            case 'medium':
1028
-            default:
1029
-                $button_css_attributes .= '';
1030
-        }
1031
-        $this->_button_css_attributes .= ! empty($other_attributes)
1032
-            ? $button_css_attributes . ' ' . $other_attributes
1033
-            : $button_css_attributes;
1034
-    }
1035
-
1036
-
1037
-
1038
-    /**
1039
-     * @return string
1040
-     */
1041
-    public function button_css_attributes()
1042
-    {
1043
-        if (empty($this->_button_css_attributes)) {
1044
-            $this->set_button_css_attributes();
1045
-        }
1046
-        return $this->_button_css_attributes;
1047
-    }
1048
-
1049
-
1050
-
1051
-    /**
1052
-     * find_form_data_for_this_section
1053
-     * using this section's name and its parents, finds the value of the form data that corresponds to it.
1054
-     * For example, if this form section's HTML name is my_form[subform][form_input_1],
1055
-     * then it's value should be in $_REQUEST at $_REQUEST['my_form']['subform']['form_input_1'].
1056
-     * (If that doesn't exist, we also check for this subsection's name
1057
-     * at the TOP LEVEL of the request data. Eg $_REQUEST['form_input_1'].)
1058
-     * This function finds its value in the form.
1059
-     *
1060
-     * @param array $req_data
1061
-     * @return mixed whatever the raw value of this form section is in the request data
1062
-     * @throws \EE_Error
1063
-     */
1064
-    public function find_form_data_for_this_section($req_data)
1065
-    {
1066
-        $name_parts = $this->getInputNameParts();
1067
-        // now get the value for the input
1068
-        $value = $this->findRequestForSectionUsingNameParts($name_parts, $req_data);
1069
-        // check if this thing's name is at the TOP level of the request data
1070
-        if ($value === null && isset($req_data[ $this->name() ])) {
1071
-            $value = $req_data[ $this->name() ];
1072
-        }
1073
-        return $value;
1074
-    }
1075
-
1076
-
1077
-
1078
-    /**
1079
-     * If this input's name is something like "foo[bar][baz]"
1080
-     * returns an array like `array('foo','bar',baz')`
1081
-     * @return array
1082
-     */
1083
-    protected function getInputNameParts()
1084
-    {
1085
-        // break up the html name by "[]"
1086
-        if (strpos($this->html_name(), '[') !== false) {
1087
-            $before_any_brackets = substr($this->html_name(), 0, strpos($this->html_name(), '['));
1088
-        } else {
1089
-            $before_any_brackets = $this->html_name();
1090
-        }
1091
-        // grab all of the segments
1092
-        preg_match_all('~\[([^]]*)\]~', $this->html_name(), $matches);
1093
-        if (isset($matches[1]) && is_array($matches[1])) {
1094
-            $name_parts = $matches[1];
1095
-            array_unshift($name_parts, $before_any_brackets);
1096
-        } else {
1097
-            $name_parts = array($before_any_brackets);
1098
-        }
1099
-        return $name_parts;
1100
-    }
1101
-
1102
-
1103
-
1104
-    /**
1105
-     * @param array $html_name_parts
1106
-     * @param array $req_data
1107
-     * @return array | NULL
1108
-     */
1109
-    public function findRequestForSectionUsingNameParts($html_name_parts, $req_data)
1110
-    {
1111
-        $first_part_to_consider = array_shift($html_name_parts);
1112
-        if (isset($req_data[ $first_part_to_consider ])) {
1113
-            if (empty($html_name_parts)) {
1114
-                return $req_data[ $first_part_to_consider ];
1115
-            } else {
1116
-                return $this->findRequestForSectionUsingNameParts(
1117
-                    $html_name_parts,
1118
-                    $req_data[ $first_part_to_consider ]
1119
-                );
1120
-            }
1121
-        } else {
1122
-            return null;
1123
-        }
1124
-    }
1125
-
1126
-
1127
-
1128
-    /**
1129
-     * Checks if this form input's data is in the request data
1130
-     *
1131
-     * @param array $req_data like $_POST
1132
-     * @return boolean
1133
-     * @throws \EE_Error
1134
-     */
1135
-    public function form_data_present_in($req_data = null)
1136
-    {
1137
-        if ($req_data === null) {
1138
-            $req_data = $_POST;
1139
-        }
1140
-        $checked_value = $this->find_form_data_for_this_section($req_data);
1141
-        if ($checked_value !== null) {
1142
-            return true;
1143
-        } else {
1144
-            return false;
1145
-        }
1146
-    }
1147
-
1148
-
1149
-
1150
-    /**
1151
-     * Overrides parent to add js data from validation and display strategies
1152
-     *
1153
-     * @param array $form_other_js_data
1154
-     * @return array
1155
-     */
1156
-    public function get_other_js_data($form_other_js_data = array())
1157
-    {
1158
-        $form_other_js_data = $this->get_other_js_data_from_strategies($form_other_js_data);
1159
-        return $form_other_js_data;
1160
-    }
1161
-
1162
-
1163
-
1164
-    /**
1165
-     * Gets other JS data for localization from this input's strategies, like
1166
-     * the validation strategies and the display strategy
1167
-     *
1168
-     * @param array $form_other_js_data
1169
-     * @return array
1170
-     */
1171
-    public function get_other_js_data_from_strategies($form_other_js_data = array())
1172
-    {
1173
-        $form_other_js_data = $this->get_display_strategy()->get_other_js_data($form_other_js_data);
1174
-        foreach ($this->get_validation_strategies() as $validation_strategy) {
1175
-            $form_other_js_data = $validation_strategy->get_other_js_data($form_other_js_data);
1176
-        }
1177
-        return $form_other_js_data;
1178
-    }
1179
-
1180
-
1181
-
1182
-    /**
1183
-     * Override parent because we want to give our strategies an opportunity to enqueue some js and css
1184
-     *
1185
-     * @return void
1186
-     */
1187
-    public function enqueue_js()
1188
-    {
1189
-        // ask our display strategy and validation strategies if they have js to enqueue
1190
-        $this->enqueue_js_from_strategies();
1191
-    }
1192
-
1193
-
1194
-
1195
-    /**
1196
-     * Tells strategies when its ok to enqueue their js and css
1197
-     *
1198
-     * @return void
1199
-     */
1200
-    public function enqueue_js_from_strategies()
1201
-    {
1202
-        $this->get_display_strategy()->enqueue_js();
1203
-        foreach ($this->get_validation_strategies() as $validation_strategy) {
1204
-            $validation_strategy->enqueue_js();
1205
-        }
1206
-    }
1207
-
1208
-
1209
-
1210
-    /**
1211
-     * Gets the default value set on the input (not the current value, which may have been
1212
-     * changed because of a form submission). If no default was set, this us null.
1213
-     * @return mixed
1214
-     */
1215
-    public function get_default()
1216
-    {
1217
-        return $this->_default;
1218
-    }
1219
-
1220
-
1221
-
1222
-    /**
1223
-     * Makes this input disabled. That means it will have the HTML attribute 'disabled="disabled"',
1224
-     * and server-side if any input was received it will be ignored
1225
-     */
1226
-    public function disable($disable = true)
1227
-    {
1228
-        $disabled_attribute = ' disabled="disabled"';
1229
-        $this->disabled = filter_var($disable, FILTER_VALIDATE_BOOLEAN);
1230
-        if ($this->disabled) {
1231
-            if (strpos($this->_other_html_attributes, $disabled_attribute) === false) {
1232
-                $this->_other_html_attributes .= $disabled_attribute;
1233
-            }
1234
-            $this->_set_normalized_value($this->get_default());
1235
-        } else {
1236
-            $this->_other_html_attributes = str_replace($disabled_attribute, '', $this->_other_html_attributes);
1237
-        }
1238
-    }
1239
-
1240
-
1241
-
1242
-    /**
1243
-     * Returns whether or not this input is currently disabled.
1244
-     * @return bool
1245
-     */
1246
-    public function isDisabled()
1247
-    {
1248
-        return $this->disabled;
1249
-    }
14
+	/**
15
+	 * the input's name attribute
16
+	 *
17
+	 * @var string
18
+	 */
19
+	protected $_html_name;
20
+
21
+	/**
22
+	 * id for the html label tag
23
+	 *
24
+	 * @var string
25
+	 */
26
+	protected $_html_label_id;
27
+
28
+	/**
29
+	 * class for teh html label tag
30
+	 *
31
+	 * @var string
32
+	 */
33
+	protected $_html_label_class;
34
+
35
+	/**
36
+	 * any additional html attributes that you may want to add
37
+	 *
38
+	 * @var string
39
+	 */
40
+	protected $_html_other_attributes;
41
+
42
+	/**
43
+	 * style for teh html label tag
44
+	 *
45
+	 * @var string
46
+	 */
47
+	protected $_html_label_style;
48
+
49
+	/**
50
+	 * text to be placed in the html label
51
+	 *
52
+	 * @var string
53
+	 */
54
+	protected $_html_label_text;
55
+
56
+	/**
57
+	 * the full html label. If used, all other html_label_* properties are invalid
58
+	 *
59
+	 * @var string
60
+	 */
61
+	protected $_html_label;
62
+
63
+	/**
64
+	 * HTML to use for help text (normally placed below form input), in a span which normally
65
+	 * has a class of 'description'
66
+	 *
67
+	 * @var string
68
+	 */
69
+	protected $_html_help_text;
70
+
71
+	/**
72
+	 * CSS classes for displaying the help span
73
+	 *
74
+	 * @var string
75
+	 */
76
+	protected $_html_help_class = 'description';
77
+
78
+	/**
79
+	 * CSS to put in the style attribute on the help span
80
+	 *
81
+	 * @var string
82
+	 */
83
+	protected $_html_help_style;
84
+
85
+	/**
86
+	 * Stores whether or not this input's response is required.
87
+	 * Because certain styling elements may also want to know that this
88
+	 * input is required etc.
89
+	 *
90
+	 * @var boolean
91
+	 */
92
+	protected $_required;
93
+
94
+	/**
95
+	 * css class added to required inputs
96
+	 *
97
+	 * @var string
98
+	 */
99
+	protected $_required_css_class = 'ee-required';
100
+
101
+	/**
102
+	 * css styles applied to button type inputs
103
+	 *
104
+	 * @var string
105
+	 */
106
+	protected $_button_css_attributes;
107
+
108
+	/**
109
+	 * The raw data submitted for this, like in the $_POST super global.
110
+	 * Generally unsafe for usage in client code
111
+	 *
112
+	 * @var mixed string or array
113
+	 */
114
+	protected $_raw_value;
115
+
116
+	/**
117
+	 * Value normalized according to the input's normalization strategy.
118
+	 * The normalization strategy dictates whether this is a string, int, float,
119
+	 * boolean, or array of any of those.
120
+	 *
121
+	 * @var mixed
122
+	 */
123
+	protected $_normalized_value;
124
+
125
+
126
+	/**
127
+	 * Normalized default value either initially set on the input, or provided by calling
128
+	 * set_default().
129
+	 * @var mixed
130
+	 */
131
+	protected $_default;
132
+
133
+	/**
134
+	 * Strategy used for displaying this field.
135
+	 * Child classes must use _get_display_strategy to access it.
136
+	 *
137
+	 * @var EE_Display_Strategy_Base
138
+	 */
139
+	private $_display_strategy;
140
+
141
+	/**
142
+	 * Gets all the validation strategies used on this field
143
+	 *
144
+	 * @var EE_Validation_Strategy_Base[]
145
+	 */
146
+	private $_validation_strategies = array();
147
+
148
+	/**
149
+	 * The normalization strategy for this field
150
+	 *
151
+	 * @var EE_Normalization_Strategy_Base
152
+	 */
153
+	private $_normalization_strategy;
154
+
155
+	/**
156
+	 * Strategy for removing sensitive data after we're done with the form input
157
+	 *
158
+	 * @var EE_Sensitive_Data_Removal_Base
159
+	 */
160
+	protected $_sensitive_data_removal_strategy;
161
+
162
+	/**
163
+	 * Whether this input has been disabled or not.
164
+	 * If it's disabled while rendering, an extra hidden input is added that indicates it has been knowingly disabled.
165
+	 * (Client-side code that wants to dynamically disable it must also add this hidden input).
166
+	 * When the form is submitted, if the input is disabled in the PHP formsection, then input is ignored.
167
+	 * If the input is missing from the $_REQUEST data but the hidden input indicating the input is disabled, then the input is again ignored.
168
+	 *
169
+	 * @var boolean
170
+	 */
171
+	protected $disabled = false;
172
+
173
+
174
+
175
+	/**
176
+	 * @param array                         $input_args       {
177
+	 * @type string                         $html_name        the html name for the input
178
+	 * @type string                         $html_label_id    the id attribute to give to the html label tag
179
+	 * @type string                         $html_label_class the class attribute to give to the html label tag
180
+	 * @type string                         $html_label_style the style attribute to give ot teh label tag
181
+	 * @type string                         $html_label_text  the text to put in the label tag
182
+	 * @type string                         $html_label       the full html label. If used,
183
+	 *                                                        all other html_label_* args are invalid
184
+	 * @type string                         $html_help_text   text to put in help element
185
+	 * @type string                         $html_help_style  style attribute to give to teh help element
186
+	 * @type string                         $html_help_class  class attribute to give to the help element
187
+	 * @type string                         $default          default value NORMALIZED (eg, if providing the default
188
+	 *       for a Yes_No_Input, you should provide TRUE or FALSE, not '1' or '0')
189
+	 * @type EE_Display_Strategy_Base       $display          strategy
190
+	 * @type EE_Normalization_Strategy_Base $normalization_strategy
191
+	 * @type EE_Validation_Strategy_Base[]  $validation_strategies
192
+	 * @type boolean                        $ignore_input special argument which can be used to avoid adding any validation strategies,
193
+	 *                                                    and sets the normalization strategy to the Null normalization. This is good
194
+	 *                                                    when you want the input to be totally ignored server-side (like when using
195
+	 *                                                    React.js form inputs)
196
+	 *                                                        }
197
+	 */
198
+	public function __construct($input_args = array())
199
+	{
200
+		$input_args = (array) apply_filters('FHEE__EE_Form_Input_Base___construct__input_args', $input_args, $this);
201
+		// the following properties must be cast as arrays
202
+		if (isset($input_args['validation_strategies'])) {
203
+			foreach ((array) $input_args['validation_strategies'] as $validation_strategy) {
204
+				if ($validation_strategy instanceof EE_Validation_Strategy_Base && empty($input_args['ignore_input'])) {
205
+					$this->_validation_strategies[ get_class($validation_strategy) ] = $validation_strategy;
206
+				}
207
+			}
208
+			unset($input_args['validation_strategies']);
209
+		}
210
+		if (isset($input_args['ignore_input'])) {
211
+			$this->_validation_strategies = array();
212
+		}
213
+		// loop thru incoming options
214
+		foreach ($input_args as $key => $value) {
215
+			// add underscore to $key to match property names
216
+			$_key = '_' . $key;
217
+			if (property_exists($this, $_key)) {
218
+				$this->{$_key} = $value;
219
+			}
220
+		}
221
+		// ensure that "required" is set correctly
222
+		$this->set_required(
223
+			$this->_required,
224
+			isset($input_args['required_validation_error_message'])
225
+			? $input_args['required_validation_error_message']
226
+			: null
227
+		);
228
+		// $this->_html_name_specified = isset( $input_args['html_name'] ) ? TRUE : FALSE;
229
+		$this->_display_strategy->_construct_finalize($this);
230
+		foreach ($this->_validation_strategies as $validation_strategy) {
231
+			$validation_strategy->_construct_finalize($this);
232
+		}
233
+		if (isset($input_args['ignore_input'])) {
234
+			$this->_normalization_strategy = new EE_Null_Normalization();
235
+		}
236
+		if (! $this->_normalization_strategy) {
237
+				$this->_normalization_strategy = new EE_Text_Normalization();
238
+		}
239
+		$this->_normalization_strategy->_construct_finalize($this);
240
+		// at least we can use the normalization strategy to populate the default
241
+		if (isset($input_args['default'])) {
242
+			$this->set_default($input_args['default']);
243
+			unset($input_args['default']);
244
+		}
245
+		if (! $this->_sensitive_data_removal_strategy) {
246
+			$this->_sensitive_data_removal_strategy = new EE_No_Sensitive_Data_Removal();
247
+		}
248
+		$this->_sensitive_data_removal_strategy->_construct_finalize($this);
249
+		parent::__construct($input_args);
250
+	}
251
+
252
+
253
+
254
+	/**
255
+	 * Sets the html_name to its default value, if none was specified in teh constructor.
256
+	 * Calculation involves using the name and the parent's html_name
257
+	 *
258
+	 * @throws \EE_Error
259
+	 */
260
+	protected function _set_default_html_name_if_empty()
261
+	{
262
+		if (! $this->_html_name) {
263
+			$this->_html_name = $this->name();
264
+			if ($this->_parent_section && $this->_parent_section instanceof EE_Form_Section_Proper) {
265
+				$this->_html_name = $this->_parent_section->html_name_prefix() . "[{$this->name()}]";
266
+			}
267
+		}
268
+	}
269
+
270
+
271
+
272
+	/**
273
+	 * @param $parent_form_section
274
+	 * @param $name
275
+	 * @throws \EE_Error
276
+	 */
277
+	public function _construct_finalize($parent_form_section, $name)
278
+	{
279
+		parent::_construct_finalize($parent_form_section, $name);
280
+		if ($this->_html_label === null && $this->_html_label_text === null) {
281
+			$this->_html_label_text = ucwords(str_replace("_", " ", $name));
282
+		}
283
+		do_action('AHEE__EE_Form_Input_Base___construct_finalize__end', $this, $parent_form_section, $name);
284
+	}
285
+
286
+
287
+
288
+	/**
289
+	 * Returns the strategy for displaying this form input. If none is set, throws an exception.
290
+	 *
291
+	 * @return EE_Display_Strategy_Base
292
+	 * @throws EE_Error
293
+	 */
294
+	protected function _get_display_strategy()
295
+	{
296
+		$this->ensure_construct_finalized_called();
297
+		if (! $this->_display_strategy || ! $this->_display_strategy instanceof EE_Display_Strategy_Base) {
298
+			throw new EE_Error(
299
+				sprintf(
300
+					__(
301
+						"Cannot get display strategy for form input with name %s and id %s, because it has not been set in the constructor",
302
+						"event_espresso"
303
+					),
304
+					$this->html_name(),
305
+					$this->html_id()
306
+				)
307
+			);
308
+		} else {
309
+			return $this->_display_strategy;
310
+		}
311
+	}
312
+
313
+
314
+
315
+	/**
316
+	 * Sets the display strategy.
317
+	 *
318
+	 * @param EE_Display_Strategy_Base $strategy
319
+	 */
320
+	protected function _set_display_strategy(EE_Display_Strategy_Base $strategy)
321
+	{
322
+		$this->_display_strategy = $strategy;
323
+	}
324
+
325
+
326
+
327
+	/**
328
+	 * Sets the sanitization strategy
329
+	 *
330
+	 * @param EE_Normalization_Strategy_Base $strategy
331
+	 */
332
+	protected function _set_normalization_strategy(EE_Normalization_Strategy_Base $strategy)
333
+	{
334
+		$this->_normalization_strategy = $strategy;
335
+	}
336
+
337
+
338
+
339
+	/**
340
+	 * Gets sensitive_data_removal_strategy
341
+	 *
342
+	 * @return EE_Sensitive_Data_Removal_Base
343
+	 */
344
+	public function get_sensitive_data_removal_strategy()
345
+	{
346
+		return $this->_sensitive_data_removal_strategy;
347
+	}
348
+
349
+
350
+
351
+	/**
352
+	 * Sets sensitive_data_removal_strategy
353
+	 *
354
+	 * @param EE_Sensitive_Data_Removal_Base $sensitive_data_removal_strategy
355
+	 * @return boolean
356
+	 */
357
+	public function set_sensitive_data_removal_strategy($sensitive_data_removal_strategy)
358
+	{
359
+		$this->_sensitive_data_removal_strategy = $sensitive_data_removal_strategy;
360
+	}
361
+
362
+
363
+
364
+	/**
365
+	 * Gets the display strategy for this input
366
+	 *
367
+	 * @return EE_Display_Strategy_Base
368
+	 */
369
+	public function get_display_strategy()
370
+	{
371
+		return $this->_display_strategy;
372
+	}
373
+
374
+
375
+
376
+	/**
377
+	 * Overwrites the display strategy
378
+	 *
379
+	 * @param EE_Display_Strategy_Base $display_strategy
380
+	 */
381
+	public function set_display_strategy($display_strategy)
382
+	{
383
+		$this->_display_strategy = $display_strategy;
384
+		$this->_display_strategy->_construct_finalize($this);
385
+	}
386
+
387
+
388
+
389
+	/**
390
+	 * Gets the normalization strategy set on this input
391
+	 *
392
+	 * @return EE_Normalization_Strategy_Base
393
+	 */
394
+	public function get_normalization_strategy()
395
+	{
396
+		return $this->_normalization_strategy;
397
+	}
398
+
399
+
400
+
401
+	/**
402
+	 * Overwrites the normalization strategy
403
+	 *
404
+	 * @param EE_Normalization_Strategy_Base $normalization_strategy
405
+	 */
406
+	public function set_normalization_strategy($normalization_strategy)
407
+	{
408
+		$this->_normalization_strategy = $normalization_strategy;
409
+		$this->_normalization_strategy->_construct_finalize($this);
410
+	}
411
+
412
+
413
+
414
+	/**
415
+	 * Returns all teh validation strategies which apply to this field, numerically indexed
416
+	 *
417
+	 * @return EE_Validation_Strategy_Base[]
418
+	 */
419
+	public function get_validation_strategies()
420
+	{
421
+		return $this->_validation_strategies;
422
+	}
423
+
424
+
425
+
426
+	/**
427
+	 * Adds this strategy to the field so it will be used in both JS validation and server-side validation
428
+	 *
429
+	 * @param EE_Validation_Strategy_Base $validation_strategy
430
+	 * @return void
431
+	 */
432
+	protected function _add_validation_strategy(EE_Validation_Strategy_Base $validation_strategy)
433
+	{
434
+		$validation_strategy->_construct_finalize($this);
435
+		$this->_validation_strategies[] = $validation_strategy;
436
+	}
437
+
438
+
439
+
440
+	/**
441
+	 * Adds a new validation strategy onto the form input
442
+	 *
443
+	 * @param EE_Validation_Strategy_Base $validation_strategy
444
+	 * @return void
445
+	 */
446
+	public function add_validation_strategy(EE_Validation_Strategy_Base $validation_strategy)
447
+	{
448
+		$this->_add_validation_strategy($validation_strategy);
449
+	}
450
+
451
+
452
+
453
+	/**
454
+	 * The classname of the validation strategy to remove
455
+	 *
456
+	 * @param string $validation_strategy_classname
457
+	 */
458
+	public function remove_validation_strategy($validation_strategy_classname)
459
+	{
460
+		foreach ($this->_validation_strategies as $key => $validation_strategy) {
461
+			if ($validation_strategy instanceof $validation_strategy_classname
462
+				|| is_subclass_of($validation_strategy, $validation_strategy_classname)
463
+			) {
464
+				unset($this->_validation_strategies[ $key ]);
465
+			}
466
+		}
467
+	}
468
+
469
+
470
+
471
+	/**
472
+	 * returns true if input employs any of the validation strategy defined by the supplied array of classnames
473
+	 *
474
+	 * @param array $validation_strategy_classnames
475
+	 * @return bool
476
+	 */
477
+	public function has_validation_strategy($validation_strategy_classnames)
478
+	{
479
+		$validation_strategy_classnames = is_array($validation_strategy_classnames)
480
+			? $validation_strategy_classnames
481
+			: array($validation_strategy_classnames);
482
+		foreach ($this->_validation_strategies as $key => $validation_strategy) {
483
+			if (in_array($key, $validation_strategy_classnames)) {
484
+				return true;
485
+			}
486
+		}
487
+		return false;
488
+	}
489
+
490
+
491
+
492
+	/**
493
+	 * Gets the HTML
494
+	 *
495
+	 * @return string
496
+	 */
497
+	public function get_html()
498
+	{
499
+		return $this->_parent_section->get_html_for_input($this);
500
+	}
501
+
502
+
503
+
504
+	/**
505
+	 * Gets the HTML for the input itself (no label or errors) according to the
506
+	 * input's display strategy
507
+	 * Makes sure the JS and CSS are enqueued for it
508
+	 *
509
+	 * @return string
510
+	 * @throws \EE_Error
511
+	 */
512
+	public function get_html_for_input()
513
+	{
514
+		return $this->_form_html_filter
515
+			? $this->_form_html_filter->filterHtml(
516
+				$this->_get_display_strategy()->display(),
517
+				$this
518
+			)
519
+			: $this->_get_display_strategy()->display();
520
+	}
521
+
522
+
523
+
524
+	/**
525
+	 * @return string
526
+	 */
527
+	public function html_other_attributes()
528
+	{
529
+		return ! empty($this->_html_other_attributes) ? ' ' . $this->_html_other_attributes : '';
530
+	}
531
+
532
+
533
+
534
+	/**
535
+	 * @param string $html_other_attributes
536
+	 */
537
+	public function set_html_other_attributes($html_other_attributes)
538
+	{
539
+		$this->_html_other_attributes = $html_other_attributes;
540
+	}
541
+
542
+
543
+
544
+	/**
545
+	 * Gets the HTML for displaying the label for this form input
546
+	 * according to the form section's layout strategy
547
+	 *
548
+	 * @return string
549
+	 */
550
+	public function get_html_for_label()
551
+	{
552
+		return $this->_parent_section->get_layout_strategy()->display_label($this);
553
+	}
554
+
555
+
556
+
557
+	/**
558
+	 * Gets the HTML for displaying the errors section for this form input
559
+	 * according to the form section's layout strategy
560
+	 *
561
+	 * @return string
562
+	 */
563
+	public function get_html_for_errors()
564
+	{
565
+		return $this->_parent_section->get_layout_strategy()->display_errors($this);
566
+	}
567
+
568
+
569
+
570
+	/**
571
+	 * Gets the HTML for displaying the help text for this form input
572
+	 * according to the form section's layout strategy
573
+	 *
574
+	 * @return string
575
+	 */
576
+	public function get_html_for_help()
577
+	{
578
+		return $this->_parent_section->get_layout_strategy()->display_help_text($this);
579
+	}
580
+
581
+
582
+
583
+	/**
584
+	 * Validates the input's sanitized value (assumes _sanitize() has already been called)
585
+	 * and returns whether or not the form input's submitted value is value
586
+	 *
587
+	 * @return boolean
588
+	 */
589
+	protected function _validate()
590
+	{
591
+		if ($this->isDisabled()) {
592
+			return true;
593
+		}
594
+		foreach ($this->_validation_strategies as $validation_strategy) {
595
+			if ($validation_strategy instanceof EE_Validation_Strategy_Base) {
596
+				try {
597
+					$validation_strategy->validate($this->normalized_value());
598
+				} catch (EE_Validation_Error $e) {
599
+					$this->add_validation_error($e);
600
+				}
601
+			}
602
+		}
603
+		if ($this->get_validation_errors()) {
604
+			return false;
605
+		} else {
606
+			return true;
607
+		}
608
+	}
609
+
610
+
611
+
612
+	/**
613
+	 * Performs basic sanitization on this value. But what sanitization can be performed anyways?
614
+	 * This value MIGHT be allowed to have tags, so we can't really remove them.
615
+	 *
616
+	 * @param string $value
617
+	 * @return null|string
618
+	 */
619
+	protected function _sanitize($value)
620
+	{
621
+		return $value !== null ? stripslashes(html_entity_decode(trim($value))) : null;
622
+	}
623
+
624
+
625
+
626
+	/**
627
+	 * Picks out the form value that relates to this form input,
628
+	 * and stores it as the sanitized value on the form input, and sets the normalized value.
629
+	 * Returns whether or not any validation errors occurred
630
+	 *
631
+	 * @param array $req_data like $_POST
632
+	 * @return boolean whether or not there was an error
633
+	 * @throws \EE_Error
634
+	 */
635
+	protected function _normalize($req_data)
636
+	{
637
+		// any existing validation errors don't apply so clear them
638
+		$this->_validation_errors = array();
639
+		// if the input is disabled, ignore whatever input was sent in
640
+		if ($this->isDisabled()) {
641
+			$this->_set_raw_value(null);
642
+			$this->_set_normalized_value($this->get_default());
643
+			return false;
644
+		}
645
+		try {
646
+			$raw_input = $this->find_form_data_for_this_section($req_data);
647
+			// super simple sanitization for now
648
+			if (is_array($raw_input)) {
649
+				$raw_value = array();
650
+				foreach ($raw_input as $key => $value) {
651
+					$raw_value[ $key ] = $this->_sanitize($value);
652
+				}
653
+				$this->_set_raw_value($raw_value);
654
+			} else {
655
+				$this->_set_raw_value($this->_sanitize($raw_input));
656
+			}
657
+			// we want to mostly leave the input alone in case we need to re-display it to the user
658
+			$this->_set_normalized_value($this->_normalization_strategy->normalize($this->raw_value()));
659
+			return false;
660
+		} catch (EE_Validation_Error $e) {
661
+			$this->add_validation_error($e);
662
+			return true;
663
+		}
664
+	}
665
+
666
+
667
+
668
+	/**
669
+	 * @return string
670
+	 */
671
+	public function html_name()
672
+	{
673
+		$this->_set_default_html_name_if_empty();
674
+		return $this->_html_name;
675
+	}
676
+
677
+
678
+
679
+	/**
680
+	 * @return string
681
+	 */
682
+	public function html_label_id()
683
+	{
684
+		return ! empty($this->_html_label_id) ? $this->_html_label_id : $this->html_id() . '-lbl';
685
+	}
686
+
687
+
688
+
689
+	/**
690
+	 * @return string
691
+	 */
692
+	public function html_label_class()
693
+	{
694
+		return $this->_html_label_class;
695
+	}
696
+
697
+
698
+
699
+	/**
700
+	 * @return string
701
+	 */
702
+	public function html_label_style()
703
+	{
704
+		return $this->_html_label_style;
705
+	}
706
+
707
+
708
+
709
+	/**
710
+	 * @return string
711
+	 */
712
+	public function html_label_text()
713
+	{
714
+		return $this->_html_label_text;
715
+	}
716
+
717
+
718
+
719
+	/**
720
+	 * @return string
721
+	 */
722
+	public function html_help_text()
723
+	{
724
+		return $this->_html_help_text;
725
+	}
726
+
727
+
728
+
729
+	/**
730
+	 * @return string
731
+	 */
732
+	public function html_help_class()
733
+	{
734
+		return $this->_html_help_class;
735
+	}
736
+
737
+
738
+
739
+	/**
740
+	 * @return string
741
+	 */
742
+	public function html_help_style()
743
+	{
744
+		return $this->_html_style;
745
+	}
746
+
747
+
748
+
749
+	/**
750
+	 * returns the raw, UNSAFE, input, almost exactly as the user submitted it.
751
+	 * Please note that almost all client code should instead use the normalized_value;
752
+	 * or possibly raw_value_in_form (which prepares the string for displaying in an HTML attribute on a tag,
753
+	 * mostly by escaping quotes)
754
+	 * Note, we do not store the exact original value sent in the user's request because
755
+	 * it may have malicious content, and we MIGHT want to store the form input in a transient or something...
756
+	 * in which case, we would have stored the malicious content to our database.
757
+	 *
758
+	 * @return string
759
+	 */
760
+	public function raw_value()
761
+	{
762
+		return $this->_raw_value;
763
+	}
764
+
765
+
766
+
767
+	/**
768
+	 * Returns a string safe to usage in form inputs when displaying, because
769
+	 * it escapes all html entities
770
+	 *
771
+	 * @return string
772
+	 */
773
+	public function raw_value_in_form()
774
+	{
775
+		return htmlentities($this->raw_value(), ENT_QUOTES, 'UTF-8');
776
+	}
777
+
778
+
779
+
780
+	/**
781
+	 * returns the value after it's been sanitized, and then converted into it's proper type
782
+	 * in PHP. Eg, a string, an int, an array,
783
+	 *
784
+	 * @return mixed
785
+	 */
786
+	public function normalized_value()
787
+	{
788
+		return $this->_normalized_value;
789
+	}
790
+
791
+
792
+
793
+	/**
794
+	 * Returns the normalized value is a presentable way. By default this is just
795
+	 * the normalized value by itself, but it can be overridden for when that's not
796
+	 * the best thing to display
797
+	 *
798
+	 * @return string
799
+	 */
800
+	public function pretty_value()
801
+	{
802
+		return $this->_normalized_value;
803
+	}
804
+
805
+
806
+
807
+	/**
808
+	 * When generating the JS for the jquery validation rules like<br>
809
+	 * <code>$( "#myform" ).validate({
810
+	 * rules: {
811
+	 * password: "required",
812
+	 * password_again: {
813
+	 * equalTo: "#password"
814
+	 * }
815
+	 * }
816
+	 * });</code>
817
+	 * if this field had the name 'password_again', it should return
818
+	 * <br><code>password_again: {
819
+	 * equalTo: "#password"
820
+	 * }</code>
821
+	 *
822
+	 * @return array
823
+	 */
824
+	public function get_jquery_validation_rules()
825
+	{
826
+		$jquery_validation_js = array();
827
+		$jquery_validation_rules = array();
828
+		foreach ($this->get_validation_strategies() as $validation_strategy) {
829
+			$jquery_validation_rules = array_replace_recursive(
830
+				$jquery_validation_rules,
831
+				$validation_strategy->get_jquery_validation_rule_array()
832
+			);
833
+		}
834
+		if (! empty($jquery_validation_rules)) {
835
+			foreach ($this->get_display_strategy()->get_html_input_ids(true) as $html_id_with_pound_sign) {
836
+				$jquery_validation_js[ $html_id_with_pound_sign ] = $jquery_validation_rules;
837
+			}
838
+		}
839
+		return $jquery_validation_js;
840
+	}
841
+
842
+
843
+
844
+	/**
845
+	 * Sets the input's default value for use in displaying in the form. Note: value should be
846
+	 * normalized (Eg, if providing a default of ra Yes_NO_Input you would provide TRUE or FALSE, not '1' or '0')
847
+	 *
848
+	 * @param mixed $value
849
+	 * @return void
850
+	 */
851
+	public function set_default($value)
852
+	{
853
+		$this->_default = $value;
854
+		$this->_set_normalized_value($value);
855
+		$this->_set_raw_value($value);
856
+	}
857
+
858
+
859
+
860
+	/**
861
+	 * Sets the normalized value on this input
862
+	 *
863
+	 * @param mixed $value
864
+	 */
865
+	protected function _set_normalized_value($value)
866
+	{
867
+		$this->_normalized_value = $value;
868
+	}
869
+
870
+
871
+
872
+	/**
873
+	 * Sets the raw value on this input (ie, exactly as the user submitted it)
874
+	 *
875
+	 * @param mixed $value
876
+	 */
877
+	protected function _set_raw_value($value)
878
+	{
879
+		$this->_raw_value = $this->_normalization_strategy->unnormalize($value);
880
+	}
881
+
882
+
883
+
884
+	/**
885
+	 * Sets the HTML label text after it has already been defined
886
+	 *
887
+	 * @param string $label
888
+	 * @return void
889
+	 */
890
+	public function set_html_label_text($label)
891
+	{
892
+		$this->_html_label_text = $label;
893
+	}
894
+
895
+
896
+
897
+	/**
898
+	 * Sets whether or not this field is required, and adjusts the validation strategy.
899
+	 * If you want to use the EE_Conditionally_Required_Validation_Strategy,
900
+	 * please add it as a validation strategy using add_validation_strategy as normal
901
+	 *
902
+	 * @param boolean $required boolean
903
+	 * @param null    $required_text
904
+	 */
905
+	public function set_required($required = true, $required_text = null)
906
+	{
907
+		$required = filter_var($required, FILTER_VALIDATE_BOOLEAN);
908
+		// whether $required is a string or a boolean, we want to add a required validation strategy
909
+		if ($required) {
910
+			$this->_add_validation_strategy(new EE_Required_Validation_Strategy($required_text));
911
+		} else {
912
+			$this->remove_validation_strategy('EE_Required_Validation_Strategy');
913
+		}
914
+		$this->_required = $required;
915
+	}
916
+
917
+
918
+
919
+	/**
920
+	 * Returns whether or not this field is required
921
+	 *
922
+	 * @return boolean
923
+	 */
924
+	public function required()
925
+	{
926
+		return $this->_required;
927
+	}
928
+
929
+
930
+
931
+	/**
932
+	 * @param string $required_css_class
933
+	 */
934
+	public function set_required_css_class($required_css_class)
935
+	{
936
+		$this->_required_css_class = $required_css_class;
937
+	}
938
+
939
+
940
+
941
+	/**
942
+	 * @return string
943
+	 */
944
+	public function required_css_class()
945
+	{
946
+		return $this->_required_css_class;
947
+	}
948
+
949
+
950
+
951
+	/**
952
+	 * @param bool $add_required
953
+	 * @return string
954
+	 */
955
+	public function html_class($add_required = false)
956
+	{
957
+		return $add_required && $this->required()
958
+			? $this->required_css_class() . ' ' . $this->_html_class
959
+			: $this->_html_class;
960
+	}
961
+
962
+
963
+	/**
964
+	 * Sets the help text, in case
965
+	 *
966
+	 * @param string $text
967
+	 */
968
+	public function set_html_help_text($text)
969
+	{
970
+		$this->_html_help_text = $text;
971
+	}
972
+
973
+
974
+
975
+	/**
976
+	 * Uses the sensitive data removal strategy to remove the sensitive data from this
977
+	 * input. If there is any kind of sensitive data removal on this input, we clear
978
+	 * out the raw value completely
979
+	 *
980
+	 * @return void
981
+	 */
982
+	public function clean_sensitive_data()
983
+	{
984
+		// if we do ANY kind of sensitive data removal on this, then just clear out the raw value
985
+		// if we need more logic than this we'll make a strategy for it
986
+		if ($this->_sensitive_data_removal_strategy
987
+			&& ! $this->_sensitive_data_removal_strategy instanceof EE_No_Sensitive_Data_Removal
988
+		) {
989
+			$this->_set_raw_value(null);
990
+		}
991
+		// and clean the normalized value according to the appropriate strategy
992
+		$this->_set_normalized_value(
993
+			$this->get_sensitive_data_removal_strategy()->remove_sensitive_data(
994
+				$this->_normalized_value
995
+			)
996
+		);
997
+	}
998
+
999
+
1000
+
1001
+	/**
1002
+	 * @param bool   $primary
1003
+	 * @param string $button_size
1004
+	 * @param string $other_attributes
1005
+	 */
1006
+	public function set_button_css_attributes($primary = true, $button_size = '', $other_attributes = '')
1007
+	{
1008
+		$button_css_attributes = 'button';
1009
+		$button_css_attributes .= $primary === true ? ' button-primary' : ' button-secondary';
1010
+		switch ($button_size) {
1011
+			case 'xs':
1012
+			case 'extra-small':
1013
+				$button_css_attributes .= ' button-xs';
1014
+				break;
1015
+			case 'sm':
1016
+			case 'small':
1017
+				$button_css_attributes .= ' button-sm';
1018
+				break;
1019
+			case 'lg':
1020
+			case 'large':
1021
+				$button_css_attributes .= ' button-lg';
1022
+				break;
1023
+			case 'block':
1024
+				$button_css_attributes .= ' button-block';
1025
+				break;
1026
+			case 'md':
1027
+			case 'medium':
1028
+			default:
1029
+				$button_css_attributes .= '';
1030
+		}
1031
+		$this->_button_css_attributes .= ! empty($other_attributes)
1032
+			? $button_css_attributes . ' ' . $other_attributes
1033
+			: $button_css_attributes;
1034
+	}
1035
+
1036
+
1037
+
1038
+	/**
1039
+	 * @return string
1040
+	 */
1041
+	public function button_css_attributes()
1042
+	{
1043
+		if (empty($this->_button_css_attributes)) {
1044
+			$this->set_button_css_attributes();
1045
+		}
1046
+		return $this->_button_css_attributes;
1047
+	}
1048
+
1049
+
1050
+
1051
+	/**
1052
+	 * find_form_data_for_this_section
1053
+	 * using this section's name and its parents, finds the value of the form data that corresponds to it.
1054
+	 * For example, if this form section's HTML name is my_form[subform][form_input_1],
1055
+	 * then it's value should be in $_REQUEST at $_REQUEST['my_form']['subform']['form_input_1'].
1056
+	 * (If that doesn't exist, we also check for this subsection's name
1057
+	 * at the TOP LEVEL of the request data. Eg $_REQUEST['form_input_1'].)
1058
+	 * This function finds its value in the form.
1059
+	 *
1060
+	 * @param array $req_data
1061
+	 * @return mixed whatever the raw value of this form section is in the request data
1062
+	 * @throws \EE_Error
1063
+	 */
1064
+	public function find_form_data_for_this_section($req_data)
1065
+	{
1066
+		$name_parts = $this->getInputNameParts();
1067
+		// now get the value for the input
1068
+		$value = $this->findRequestForSectionUsingNameParts($name_parts, $req_data);
1069
+		// check if this thing's name is at the TOP level of the request data
1070
+		if ($value === null && isset($req_data[ $this->name() ])) {
1071
+			$value = $req_data[ $this->name() ];
1072
+		}
1073
+		return $value;
1074
+	}
1075
+
1076
+
1077
+
1078
+	/**
1079
+	 * If this input's name is something like "foo[bar][baz]"
1080
+	 * returns an array like `array('foo','bar',baz')`
1081
+	 * @return array
1082
+	 */
1083
+	protected function getInputNameParts()
1084
+	{
1085
+		// break up the html name by "[]"
1086
+		if (strpos($this->html_name(), '[') !== false) {
1087
+			$before_any_brackets = substr($this->html_name(), 0, strpos($this->html_name(), '['));
1088
+		} else {
1089
+			$before_any_brackets = $this->html_name();
1090
+		}
1091
+		// grab all of the segments
1092
+		preg_match_all('~\[([^]]*)\]~', $this->html_name(), $matches);
1093
+		if (isset($matches[1]) && is_array($matches[1])) {
1094
+			$name_parts = $matches[1];
1095
+			array_unshift($name_parts, $before_any_brackets);
1096
+		} else {
1097
+			$name_parts = array($before_any_brackets);
1098
+		}
1099
+		return $name_parts;
1100
+	}
1101
+
1102
+
1103
+
1104
+	/**
1105
+	 * @param array $html_name_parts
1106
+	 * @param array $req_data
1107
+	 * @return array | NULL
1108
+	 */
1109
+	public function findRequestForSectionUsingNameParts($html_name_parts, $req_data)
1110
+	{
1111
+		$first_part_to_consider = array_shift($html_name_parts);
1112
+		if (isset($req_data[ $first_part_to_consider ])) {
1113
+			if (empty($html_name_parts)) {
1114
+				return $req_data[ $first_part_to_consider ];
1115
+			} else {
1116
+				return $this->findRequestForSectionUsingNameParts(
1117
+					$html_name_parts,
1118
+					$req_data[ $first_part_to_consider ]
1119
+				);
1120
+			}
1121
+		} else {
1122
+			return null;
1123
+		}
1124
+	}
1125
+
1126
+
1127
+
1128
+	/**
1129
+	 * Checks if this form input's data is in the request data
1130
+	 *
1131
+	 * @param array $req_data like $_POST
1132
+	 * @return boolean
1133
+	 * @throws \EE_Error
1134
+	 */
1135
+	public function form_data_present_in($req_data = null)
1136
+	{
1137
+		if ($req_data === null) {
1138
+			$req_data = $_POST;
1139
+		}
1140
+		$checked_value = $this->find_form_data_for_this_section($req_data);
1141
+		if ($checked_value !== null) {
1142
+			return true;
1143
+		} else {
1144
+			return false;
1145
+		}
1146
+	}
1147
+
1148
+
1149
+
1150
+	/**
1151
+	 * Overrides parent to add js data from validation and display strategies
1152
+	 *
1153
+	 * @param array $form_other_js_data
1154
+	 * @return array
1155
+	 */
1156
+	public function get_other_js_data($form_other_js_data = array())
1157
+	{
1158
+		$form_other_js_data = $this->get_other_js_data_from_strategies($form_other_js_data);
1159
+		return $form_other_js_data;
1160
+	}
1161
+
1162
+
1163
+
1164
+	/**
1165
+	 * Gets other JS data for localization from this input's strategies, like
1166
+	 * the validation strategies and the display strategy
1167
+	 *
1168
+	 * @param array $form_other_js_data
1169
+	 * @return array
1170
+	 */
1171
+	public function get_other_js_data_from_strategies($form_other_js_data = array())
1172
+	{
1173
+		$form_other_js_data = $this->get_display_strategy()->get_other_js_data($form_other_js_data);
1174
+		foreach ($this->get_validation_strategies() as $validation_strategy) {
1175
+			$form_other_js_data = $validation_strategy->get_other_js_data($form_other_js_data);
1176
+		}
1177
+		return $form_other_js_data;
1178
+	}
1179
+
1180
+
1181
+
1182
+	/**
1183
+	 * Override parent because we want to give our strategies an opportunity to enqueue some js and css
1184
+	 *
1185
+	 * @return void
1186
+	 */
1187
+	public function enqueue_js()
1188
+	{
1189
+		// ask our display strategy and validation strategies if they have js to enqueue
1190
+		$this->enqueue_js_from_strategies();
1191
+	}
1192
+
1193
+
1194
+
1195
+	/**
1196
+	 * Tells strategies when its ok to enqueue their js and css
1197
+	 *
1198
+	 * @return void
1199
+	 */
1200
+	public function enqueue_js_from_strategies()
1201
+	{
1202
+		$this->get_display_strategy()->enqueue_js();
1203
+		foreach ($this->get_validation_strategies() as $validation_strategy) {
1204
+			$validation_strategy->enqueue_js();
1205
+		}
1206
+	}
1207
+
1208
+
1209
+
1210
+	/**
1211
+	 * Gets the default value set on the input (not the current value, which may have been
1212
+	 * changed because of a form submission). If no default was set, this us null.
1213
+	 * @return mixed
1214
+	 */
1215
+	public function get_default()
1216
+	{
1217
+		return $this->_default;
1218
+	}
1219
+
1220
+
1221
+
1222
+	/**
1223
+	 * Makes this input disabled. That means it will have the HTML attribute 'disabled="disabled"',
1224
+	 * and server-side if any input was received it will be ignored
1225
+	 */
1226
+	public function disable($disable = true)
1227
+	{
1228
+		$disabled_attribute = ' disabled="disabled"';
1229
+		$this->disabled = filter_var($disable, FILTER_VALIDATE_BOOLEAN);
1230
+		if ($this->disabled) {
1231
+			if (strpos($this->_other_html_attributes, $disabled_attribute) === false) {
1232
+				$this->_other_html_attributes .= $disabled_attribute;
1233
+			}
1234
+			$this->_set_normalized_value($this->get_default());
1235
+		} else {
1236
+			$this->_other_html_attributes = str_replace($disabled_attribute, '', $this->_other_html_attributes);
1237
+		}
1238
+	}
1239
+
1240
+
1241
+
1242
+	/**
1243
+	 * Returns whether or not this input is currently disabled.
1244
+	 * @return bool
1245
+	 */
1246
+	public function isDisabled()
1247
+	{
1248
+		return $this->disabled;
1249
+	}
1250 1250
 }
Please login to merge, or discard this patch.
core/Psr4Autoloader.php 3 patches
Doc Comments   +2 added lines, -2 removed lines patch added patch discarded remove patch
@@ -120,7 +120,7 @@  discard block
 block discarded – undo
120 120
      * Loads the class file for a given class name.
121 121
      *
122 122
      * @param string $class The fully-qualified class name.
123
-     * @return mixed The mapped file name on success, or boolean false on
123
+     * @return string|false The mapped file name on success, or boolean false on
124 124
      *                      failure.
125 125
      */
126 126
     public function loadClass($class)
@@ -153,7 +153,7 @@  discard block
 block discarded – undo
153 153
      *
154 154
      * @param string $prefix         The namespace prefix.
155 155
      * @param string $relative_class The relative class name.
156
-     * @return mixed Boolean false if no mapped file can be loaded, or the
156
+     * @return string|false Boolean false if no mapped file can be loaded, or the
157 157
      *                               name of the mapped file that was loaded.
158 158
      */
159 159
     protected function loadMappedFile($prefix, $relative_class)
Please login to merge, or discard this patch.
Spacing   +7 added lines, -7 removed lines patch added patch discarded remove patch
@@ -67,9 +67,9 @@  discard block
 block discarded – undo
67 67
      */
68 68
     public function prefixes($prefix = '')
69 69
     {
70
-        if (! empty($prefix)) {
70
+        if ( ! empty($prefix)) {
71 71
             // are there any base directories for this namespace prefix?
72
-            return isset($this->prefixes[ $prefix ]) ? $this->prefixes[ $prefix ] : array();
72
+            return isset($this->prefixes[$prefix]) ? $this->prefixes[$prefix] : array();
73 73
         }
74 74
         return $this->prefixes;
75 75
     }
@@ -100,18 +100,18 @@  discard block
 block discarded – undo
100 100
     public function addNamespace($prefix, $base_dir, $prepend = false)
101 101
     {
102 102
         // normalize namespace prefix
103
-        $prefix = trim($prefix, Psr4Autoloader::NS) . Psr4Autoloader::NS;
103
+        $prefix = trim($prefix, Psr4Autoloader::NS).Psr4Autoloader::NS;
104 104
         // normalize the base directory with a trailing separator
105 105
         $base_dir = \EEH_File::standardise_and_end_with_directory_separator($base_dir);
106 106
         // initialize the namespace prefix array
107
-        if (isset($this->prefixes[ $prefix ]) === false) {
108
-            $this->prefixes[ $prefix ] = array();
107
+        if (isset($this->prefixes[$prefix]) === false) {
108
+            $this->prefixes[$prefix] = array();
109 109
         }
110 110
         // retain the base directory for the namespace prefix
111 111
         if ($prepend) {
112
-            array_unshift($this->prefixes[ $prefix ], $base_dir);
112
+            array_unshift($this->prefixes[$prefix], $base_dir);
113 113
         } else {
114
-            $this->prefixes[ $prefix ][] = $base_dir;
114
+            $this->prefixes[$prefix][] = $base_dir;
115 115
         }
116 116
     }
117 117
 
Please login to merge, or discard this patch.
Indentation   +146 added lines, -146 removed lines patch added patch discarded remove patch
@@ -45,150 +45,150 @@
 block discarded – undo
45 45
 class Psr4Autoloader
46 46
 {
47 47
 
48
-    /**
49
-     * namespace separator
50
-     */
51
-    const NS = '\\';
52
-
53
-    /**
54
-     * An associative array where the key is a namespace prefix and the value
55
-     * is an array of base directories for classes in that namespace.
56
-     *
57
-     * @var array
58
-     */
59
-    protected $prefixes = array();
60
-
61
-
62
-    /**
63
-     * returns an array of registered namespace prefixes
64
-     *
65
-     * @param string $prefix
66
-     * @return array
67
-     */
68
-    public function prefixes($prefix = '')
69
-    {
70
-        if (! empty($prefix)) {
71
-            // are there any base directories for this namespace prefix?
72
-            return isset($this->prefixes[ $prefix ]) ? $this->prefixes[ $prefix ] : array();
73
-        }
74
-        return $this->prefixes;
75
-    }
76
-
77
-
78
-    /**
79
-     * Register loader with SPL autoloader stack.
80
-     *
81
-     * @return void
82
-     */
83
-    public function register()
84
-    {
85
-        spl_autoload_register(array($this, 'loadClass'));
86
-    }
87
-
88
-
89
-    /**
90
-     * Adds a base directory for a namespace prefix.
91
-     *
92
-     * @param string $prefix   The namespace prefix.
93
-     * @param string $base_dir A base directory for class files in the
94
-     *                         namespace.
95
-     * @param bool   $prepend  If true, prepend the base directory to the stack
96
-     *                         instead of appending it; this causes it to be searched first rather
97
-     *                         than last.
98
-     * @return void
99
-     */
100
-    public function addNamespace($prefix, $base_dir, $prepend = false)
101
-    {
102
-        // normalize namespace prefix
103
-        $prefix = trim($prefix, Psr4Autoloader::NS) . Psr4Autoloader::NS;
104
-        // normalize the base directory with a trailing separator
105
-        $base_dir = \EEH_File::standardise_and_end_with_directory_separator($base_dir);
106
-        // initialize the namespace prefix array
107
-        if (isset($this->prefixes[ $prefix ]) === false) {
108
-            $this->prefixes[ $prefix ] = array();
109
-        }
110
-        // retain the base directory for the namespace prefix
111
-        if ($prepend) {
112
-            array_unshift($this->prefixes[ $prefix ], $base_dir);
113
-        } else {
114
-            $this->prefixes[ $prefix ][] = $base_dir;
115
-        }
116
-    }
117
-
118
-
119
-    /**
120
-     * Loads the class file for a given class name.
121
-     *
122
-     * @param string $class The fully-qualified class name.
123
-     * @return mixed The mapped file name on success, or boolean false on
124
-     *                      failure.
125
-     */
126
-    public function loadClass($class)
127
-    {
128
-        // the current namespace prefix
129
-        $prefix = $class;
130
-        // work backwards through the namespace names of the fully-qualified
131
-        // class name to find a mapped file name
132
-        while (false !== $pos = strrpos($prefix, Psr4Autoloader::NS)) {
133
-            // retain the trailing namespace separator in the prefix
134
-            $prefix = substr($class, 0, $pos + 1);
135
-            // the rest is the relative class name
136
-            $relative_class = substr($class, $pos + 1);
137
-            // try to load a mapped file for the prefix and relative class
138
-            $mapped_file = $this->loadMappedFile($prefix, $relative_class);
139
-            if ($mapped_file) {
140
-                return $mapped_file;
141
-            }
142
-            // remove the trailing namespace separator for the next iteration
143
-            // of strrpos()
144
-            $prefix = rtrim($prefix, Psr4Autoloader::NS);
145
-        }
146
-        // never found a mapped file
147
-        return false;
148
-    }
149
-
150
-
151
-    /**
152
-     * Load the mapped file for a namespace prefix and relative class.
153
-     *
154
-     * @param string $prefix         The namespace prefix.
155
-     * @param string $relative_class The relative class name.
156
-     * @return mixed Boolean false if no mapped file can be loaded, or the
157
-     *                               name of the mapped file that was loaded.
158
-     */
159
-    protected function loadMappedFile($prefix, $relative_class)
160
-    {
161
-        // look through base directories for this namespace prefix
162
-        foreach ($this->prefixes($prefix) as $base_dir) {
163
-            // replace the namespace prefix with the base directory,
164
-            // replace namespace separators with directory separators
165
-            // in the relative class name, append with .php
166
-            $file = $base_dir
167
-                    . str_replace(Psr4Autoloader::NS, '/', $relative_class)
168
-                    . '.php';
169
-            // if the mapped file exists, require it
170
-            if ($this->requireFile($file)) {
171
-                // yes, we're done
172
-                return $file;
173
-            }
174
-        }
175
-        // never found it
176
-        return false;
177
-    }
178
-
179
-
180
-    /**
181
-     * If a file exists, require it from the file system.
182
-     *
183
-     * @param string $file The file to require.
184
-     * @return bool True if the file exists, false if not.
185
-     */
186
-    protected function requireFile($file)
187
-    {
188
-        if (file_exists($file)) {
189
-            require $file;
190
-            return true;
191
-        }
192
-        return false;
193
-    }
48
+	/**
49
+	 * namespace separator
50
+	 */
51
+	const NS = '\\';
52
+
53
+	/**
54
+	 * An associative array where the key is a namespace prefix and the value
55
+	 * is an array of base directories for classes in that namespace.
56
+	 *
57
+	 * @var array
58
+	 */
59
+	protected $prefixes = array();
60
+
61
+
62
+	/**
63
+	 * returns an array of registered namespace prefixes
64
+	 *
65
+	 * @param string $prefix
66
+	 * @return array
67
+	 */
68
+	public function prefixes($prefix = '')
69
+	{
70
+		if (! empty($prefix)) {
71
+			// are there any base directories for this namespace prefix?
72
+			return isset($this->prefixes[ $prefix ]) ? $this->prefixes[ $prefix ] : array();
73
+		}
74
+		return $this->prefixes;
75
+	}
76
+
77
+
78
+	/**
79
+	 * Register loader with SPL autoloader stack.
80
+	 *
81
+	 * @return void
82
+	 */
83
+	public function register()
84
+	{
85
+		spl_autoload_register(array($this, 'loadClass'));
86
+	}
87
+
88
+
89
+	/**
90
+	 * Adds a base directory for a namespace prefix.
91
+	 *
92
+	 * @param string $prefix   The namespace prefix.
93
+	 * @param string $base_dir A base directory for class files in the
94
+	 *                         namespace.
95
+	 * @param bool   $prepend  If true, prepend the base directory to the stack
96
+	 *                         instead of appending it; this causes it to be searched first rather
97
+	 *                         than last.
98
+	 * @return void
99
+	 */
100
+	public function addNamespace($prefix, $base_dir, $prepend = false)
101
+	{
102
+		// normalize namespace prefix
103
+		$prefix = trim($prefix, Psr4Autoloader::NS) . Psr4Autoloader::NS;
104
+		// normalize the base directory with a trailing separator
105
+		$base_dir = \EEH_File::standardise_and_end_with_directory_separator($base_dir);
106
+		// initialize the namespace prefix array
107
+		if (isset($this->prefixes[ $prefix ]) === false) {
108
+			$this->prefixes[ $prefix ] = array();
109
+		}
110
+		// retain the base directory for the namespace prefix
111
+		if ($prepend) {
112
+			array_unshift($this->prefixes[ $prefix ], $base_dir);
113
+		} else {
114
+			$this->prefixes[ $prefix ][] = $base_dir;
115
+		}
116
+	}
117
+
118
+
119
+	/**
120
+	 * Loads the class file for a given class name.
121
+	 *
122
+	 * @param string $class The fully-qualified class name.
123
+	 * @return mixed The mapped file name on success, or boolean false on
124
+	 *                      failure.
125
+	 */
126
+	public function loadClass($class)
127
+	{
128
+		// the current namespace prefix
129
+		$prefix = $class;
130
+		// work backwards through the namespace names of the fully-qualified
131
+		// class name to find a mapped file name
132
+		while (false !== $pos = strrpos($prefix, Psr4Autoloader::NS)) {
133
+			// retain the trailing namespace separator in the prefix
134
+			$prefix = substr($class, 0, $pos + 1);
135
+			// the rest is the relative class name
136
+			$relative_class = substr($class, $pos + 1);
137
+			// try to load a mapped file for the prefix and relative class
138
+			$mapped_file = $this->loadMappedFile($prefix, $relative_class);
139
+			if ($mapped_file) {
140
+				return $mapped_file;
141
+			}
142
+			// remove the trailing namespace separator for the next iteration
143
+			// of strrpos()
144
+			$prefix = rtrim($prefix, Psr4Autoloader::NS);
145
+		}
146
+		// never found a mapped file
147
+		return false;
148
+	}
149
+
150
+
151
+	/**
152
+	 * Load the mapped file for a namespace prefix and relative class.
153
+	 *
154
+	 * @param string $prefix         The namespace prefix.
155
+	 * @param string $relative_class The relative class name.
156
+	 * @return mixed Boolean false if no mapped file can be loaded, or the
157
+	 *                               name of the mapped file that was loaded.
158
+	 */
159
+	protected function loadMappedFile($prefix, $relative_class)
160
+	{
161
+		// look through base directories for this namespace prefix
162
+		foreach ($this->prefixes($prefix) as $base_dir) {
163
+			// replace the namespace prefix with the base directory,
164
+			// replace namespace separators with directory separators
165
+			// in the relative class name, append with .php
166
+			$file = $base_dir
167
+					. str_replace(Psr4Autoloader::NS, '/', $relative_class)
168
+					. '.php';
169
+			// if the mapped file exists, require it
170
+			if ($this->requireFile($file)) {
171
+				// yes, we're done
172
+				return $file;
173
+			}
174
+		}
175
+		// never found it
176
+		return false;
177
+	}
178
+
179
+
180
+	/**
181
+	 * If a file exists, require it from the file system.
182
+	 *
183
+	 * @param string $file The file to require.
184
+	 * @return bool True if the file exists, false if not.
185
+	 */
186
+	protected function requireFile($file)
187
+	{
188
+		if (file_exists($file)) {
189
+			require $file;
190
+			return true;
191
+		}
192
+		return false;
193
+	}
194 194
 }
Please login to merge, or discard this patch.
core/services/container/SharedCoffeeMaker.php 2 patches
Doc Comments   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -30,7 +30,7 @@
 block discarded – undo
30 30
     /**
31 31
      * @param RecipeInterface $recipe
32 32
      * @param array           $arguments
33
-     * @return mixed
33
+     * @return boolean
34 34
      */
35 35
     public function brew(RecipeInterface $recipe, $arguments = array())
36 36
     {
Please login to merge, or discard this patch.
Indentation   +37 added lines, -37 removed lines patch added patch discarded remove patch
@@ -18,43 +18,43 @@
 block discarded – undo
18 18
 {
19 19
 
20 20
 
21
-    /**
22
-     * @return string
23
-     */
24
-    public function type()
25
-    {
26
-        return CoffeeMaker::BREW_SHARED;
27
-    }
21
+	/**
22
+	 * @return string
23
+	 */
24
+	public function type()
25
+	{
26
+		return CoffeeMaker::BREW_SHARED;
27
+	}
28 28
 
29 29
 
30
-    /**
31
-     * @param RecipeInterface $recipe
32
-     * @param array           $arguments
33
-     * @return mixed
34
-     */
35
-    public function brew(RecipeInterface $recipe, $arguments = array())
36
-    {
37
-        $this->resolveClassAndFilepath($recipe);
38
-        $reflector = $this->injector()->getReflectionClass($recipe->fqcn());
39
-        $method = $this->resolveInstantiationMethod($reflector);
40
-        switch ($method) {
41
-            case 'instance':
42
-            case 'new_instance':
43
-            case 'new_instance_from_db':
44
-                $service = call_user_func_array(
45
-                    array($reflector->getName(), $method),
46
-                    $this->injector()->resolveDependencies($recipe, $reflector, $arguments)
47
-                );
48
-                break;
49
-            case 'newInstance':
50
-                $service = $reflector->newInstance();
51
-                break;
52
-            case 'newInstanceArgs':
53
-            default:
54
-                $service = $reflector->newInstanceArgs(
55
-                    $this->injector()->resolveDependencies($recipe, $reflector, $arguments)
56
-                );
57
-        }
58
-        return $this->coffeePot()->addService($recipe->identifier(), $service);
59
-    }
30
+	/**
31
+	 * @param RecipeInterface $recipe
32
+	 * @param array           $arguments
33
+	 * @return mixed
34
+	 */
35
+	public function brew(RecipeInterface $recipe, $arguments = array())
36
+	{
37
+		$this->resolveClassAndFilepath($recipe);
38
+		$reflector = $this->injector()->getReflectionClass($recipe->fqcn());
39
+		$method = $this->resolveInstantiationMethod($reflector);
40
+		switch ($method) {
41
+			case 'instance':
42
+			case 'new_instance':
43
+			case 'new_instance_from_db':
44
+				$service = call_user_func_array(
45
+					array($reflector->getName(), $method),
46
+					$this->injector()->resolveDependencies($recipe, $reflector, $arguments)
47
+				);
48
+				break;
49
+			case 'newInstance':
50
+				$service = $reflector->newInstance();
51
+				break;
52
+			case 'newInstanceArgs':
53
+			default:
54
+				$service = $reflector->newInstanceArgs(
55
+					$this->injector()->resolveDependencies($recipe, $reflector, $arguments)
56
+				);
57
+		}
58
+		return $this->coffeePot()->addService($recipe->identifier(), $service);
59
+	}
60 60
 }
Please login to merge, or discard this patch.