2 namespace Civi\Payment
;
4 use InvalidArgumentException
;
6 use CRM_Core_PseudoConstant
;
11 * This class provides getters and setters for arguments needed by CRM_Core_Payment methods.
13 * The setters know how to validate each setting that they are responsible for.
15 * Different methods need different settings and the concept is that by passing
16 * in a property bag we can encapsulate the params needed for a particular
17 * method call, rather than setting arguments for different methods on the main
18 * CRM_Core_Payment object.
20 * This class is also supposed to help with transition away from array key naming nightmares.
23 class PropertyBag
implements \ArrayAccess
{
24 protected $props = ['default' => []];
26 protected static $propMap = [
27 'billingStreetAddress' => TRUE,
28 'billingSupplementalAddress1' => TRUE,
29 'billingSupplementalAddress2' => TRUE,
30 'billingSupplementalAddress3' => TRUE,
31 'billingCity' => TRUE,
32 'billingPostalCode' => TRUE,
33 'billingCounty' => TRUE,
34 'billingCountry' => TRUE,
36 'contact_id' => 'contactID',
37 'contributionID' => TRUE,
38 'contribution_id' => 'contributionID',
39 'contributionRecurID' => TRUE,
40 'contribution_recur_id' => 'contributionRecurID',
42 'currencyID' => 'currency',
43 'description' => TRUE,
46 'fee_amount' => 'feeAmount',
47 'first_name' => 'firstName',
50 'invoice_id' => 'invoiceID',
51 'isBackOffice' => TRUE,
52 'is_back_office' => 'isBackOffice',
54 'is_recur' => 'isRecur',
55 'last_name' => 'lastName',
57 'paymentToken' => TRUE,
58 'payment_token' => 'paymentToken',
60 'recurFrequencyInterval' => TRUE,
61 'frequency_interval' => 'recurFrequencyInterval',
62 'recurFrequencyUnit' => TRUE,
63 'frequency_unit' => 'recurFrequencyUnit',
64 'recurProcessorID' => TRUE,
65 'transactionID' => TRUE,
66 'transaction_id' => 'transactionID',
67 'trxnResultCode' => TRUE,
71 * Get the property bag.
73 * This allows us to swap a 'might be an array might be a property bag'
74 * variable for a known PropertyBag.
76 * @param \Civi\Payment\PropertyBag|array $params
78 * @return \Civi\Payment\PropertyBag
80 public static function cast($params) {
81 if ($params instanceof self
) {
84 $propertyBag = new self();
85 $propertyBag->mergeLegacyInputParams($params);
90 * Just for unit testing.
97 * Implements ArrayAccess::offsetExists
99 * @param mixed $offset
100 * @return bool TRUE if we have that value (on our default store)
102 public function offsetExists ($offset): bool {
103 $prop = $this->handleLegacyPropNames($offset);
104 return isset($this->props
['default'][$prop]);
108 * Implements ArrayAccess::offsetGet
110 * @param mixed $offset
113 public function offsetGet ($offset) {
114 $prop = $this->handleLegacyPropNames($offset);
115 return $this->get($prop, 'default');
119 * Implements ArrayAccess::offsetSet
121 * @param mixed $offset
122 * @param mixed $value
124 public function offsetSet($offset, $value) {
126 $prop = $this->handleLegacyPropNames($offset);
128 catch (InvalidArgumentException
$e) {
129 // We need to make a lot of noise here, we're being asked to merge in
130 // something we can't validate because we don't know what this property is.
131 // This is fine if it's something particular to a payment processor
132 // (which should be using setCustomProperty) however it could also lead to
133 // things like 'my_weirly_named_contact_id'.
134 $this->legacyWarning($e->getMessage() . " We have merged this in for now as a custom property. Please rewrite your code to use PropertyBag->setCustomProperty if it is a genuinely custom property, or a standardised setter like PropertyBag->setContactID for standard properties");
135 $this->setCustomProperty($offset, $value, 'default');
139 // Coerce legacy values that were in use but shouldn't be in our new way of doing things.
140 if ($prop === 'feeAmount' && $value === '') {
141 // At least the following classes pass in ZLS for feeAmount.
142 // CRM_Core_Payment_AuthorizeNetTest::testCreateSingleNowDated
143 // CRM_Core_Payment_AuthorizeNetTest::testCreateSinglePostDated
147 // These lines are here (and not in try block) because the catch must only
148 // catch the case when the prop is custom.
149 $setter = 'set' . ucfirst($prop);
150 $this->$setter($value, 'default');
154 * Implements ArrayAccess::offsetUnset
156 * @param mixed $offset
158 public function offsetUnset ($offset) {
159 $prop = $this->handleLegacyPropNames($offset);
160 unset($this->props
['default'][$prop]);
164 * @param string $message
166 protected function legacyWarning($message) {
167 $message = "Deprecated code: $message";
168 $this->lastWarning
= $message;
169 Civi
::log()->warning($message);
173 * @param string $prop
174 * @return string canonical name.
175 * @throws \InvalidArgumentException if prop name not known.
177 protected function handleLegacyPropNames($prop) {
178 $newName = static::$propMap[$prop] ??
NULL;
179 if ($newName === TRUE) {
180 // Good, modern name.
183 if ($newName === NULL) {
184 throw new \
InvalidArgumentException("Unknown property '$prop'.");
186 // Remaining case is legacy name that's been translated.
187 $this->legacyWarning("We have translated '$prop' to '$newName' for you, but please update your code to use the propper setters and getters.");
194 * @param mixed $prop Valid property name
195 * @param string $label e.g. 'default'
197 protected function get($prop, $label) {
198 if (isset($this->props
['default'][$prop])) {
199 return $this->props
[$label][$prop];
201 throw new \
BadMethodCallException("Property '$prop' has not been set.");
207 * @param mixed $prop Valid property name
208 * @param string $label e.g. 'default'
209 * @param mixed $value
211 * @return PropertyBag $this object so you can chain set setters.
213 protected function set($prop, $label = 'default', $value) {
214 $this->props
[$label][$prop] = $value;
221 protected function coercePseudoConstantStringToInt(string $baoName, string $field, $input) {
222 if (is_numeric($input)) {
223 // We've been given a numeric ID.
226 elseif (is_string($input)) {
227 // We've been given a named instrument.
228 $_ = (int) CRM_Core_PseudoConstant
::getKey($baoName, $field, $input);
231 throw new InvalidArgumentException("Expected an integer ID or a String name for $field.");
234 throw new InvalidArgumentException("Expected an integer greater than 0 for $field.");
241 public function has($prop, $label = 'default') {
242 // We do NOT translate legacy prop names since only new code should be
243 // using this method, and new code should be using canonical names.
244 // $prop = $this->handleLegacyPropNames($prop);
245 return isset($this->props
[$label][$prop]);
249 * This is used to merge values from an array.
250 * It's a transitional function and should not be used!
254 public function mergeLegacyInputParams($data) {
255 $this->legacyWarning("We have merged input params into the property bag for now but please rewrite code to not use this.");
256 foreach ($data as $key => $value) {
257 if ($value !== NULL) {
258 $this->offsetSet($key, $value);
264 * Throw an exception if any of the props is unset.
266 * @param array $props Array of proper property names (no legacy aliases allowed).
268 * @return PropertyBag
270 public function require(array $props) {
272 foreach ($props as $prop) {
273 if (!isset($this->props
['default'][$prop])) {
278 throw new \
InvalidArgumentException("Required properties missing: " . implode(', ', $missing));
283 // Public getters, setters.
286 * Get a property by its name (but still using its getter).
288 * @param string $prop valid property name, like contactID
289 * @param bool $allowUnset If TRUE, return the default value if the property is
290 * not set - normal behaviour would be to throw an exception.
291 * @param mixed $default
292 * @param string $label e.g. 'default' or 'old' or 'new'
296 public function getter($prop, $allowUnset = FALSE, $default = NULL, $label = 'default') {
298 if ((static::$propMap[$prop] ??
NULL) === TRUE) {
299 // This is a standard property that will have a getter method.
300 $getter = 'get' . ucfirst($prop);
301 return (!$allowUnset ||
$this->has($prop, $label))
302 ?
$this->$getter($label)
306 // This is not a property name we know, but they could be requesting a
308 return (!$allowUnset ||
$this->has($prop, $label))
309 ?
$this->getCustomProperty($prop, $label)
314 * Set a property by its name (but still using its setter).
316 * @param string $prop valid property name, like contactID
317 * @param mixed $value
318 * @param string $label e.g. 'default' or 'old' or 'new'
322 public function setter($prop, $value = NULL, $label = 'default') {
323 if ((static::$propMap[$prop] ??
NULL) === TRUE) {
324 // This is a standard property.
325 $setter = 'set' . ucfirst($prop);
326 return $this->$setter($value, $label);
328 // We don't allow using the setter for custom properties.
329 throw new \
BadMethodCallException("Cannot use generic setter with non-standard properties; you must use setCustomProperty for custom properties.");
333 * Get the monetary amount.
335 public function getAmount($label = 'default') {
336 return $this->get('amount', $label);
340 * Get the monetary amount.
342 public function setAmount($value, $label = 'default') {
343 if (!is_numeric($value)) {
344 throw new \
InvalidArgumentException("setAmount requires a numeric amount value");
347 return $this->set('amount', CRM_Utils_Money
::format($value, NULL, NULL, TRUE), $label);
351 * BillingStreetAddress getter.
355 public function getBillingStreetAddress($label = 'default') {
356 return $this->get('billingStreetAddress', $label);
360 * BillingStreetAddress setter.
362 * @param string $input
363 * @param string $label e.g. 'default'
365 public function setBillingStreetAddress($input, $label = 'default') {
366 return $this->set('billingStreetAddress', $label, (string) $input);
370 * BillingSupplementalAddress1 getter.
374 public function getBillingSupplementalAddress1($label = 'default') {
375 return $this->get('billingSupplementalAddress1', $label);
379 * BillingSupplementalAddress1 setter.
381 * @param string $input
382 * @param string $label e.g. 'default'
384 public function setBillingSupplementalAddress1($input, $label = 'default') {
385 return $this->set('billingSupplementalAddress1', $label, (string) $input);
389 * BillingSupplementalAddress2 getter.
393 public function getBillingSupplementalAddress2($label = 'default') {
394 return $this->get('billingSupplementalAddress2', $label);
398 * BillingSupplementalAddress2 setter.
400 * @param string $input
401 * @param string $label e.g. 'default'
403 public function setBillingSupplementalAddress2($input, $label = 'default') {
404 return $this->set('billingSupplementalAddress2', $label, (string) $input);
408 * BillingSupplementalAddress3 getter.
412 public function getBillingSupplementalAddress3($label = 'default') {
413 return $this->get('billingSupplementalAddress3', $label);
417 * BillingSupplementalAddress3 setter.
419 * @param string $input
420 * @param string $label e.g. 'default'
422 public function setBillingSupplementalAddress3($input, $label = 'default') {
423 return $this->set('billingSupplementalAddress3', $label, (string) $input);
427 * BillingCity getter.
431 public function getBillingCity($label = 'default') {
432 return $this->get('billingCity', $label);
436 * BillingCity setter.
438 * @param string $input
439 * @param string $label e.g. 'default'
441 public function setBillingCity($input, $label = 'default') {
442 return $this->set('billingCity', $label, (string) $input);
446 * BillingPostalCode getter.
450 public function getBillingPostalCode($label = 'default') {
451 return $this->get('billingPostalCode', $label);
455 * BillingPostalCode setter.
457 * @param string $input
458 * @param string $label e.g. 'default'
460 public function setBillingPostalCode($input, $label = 'default') {
461 return $this->set('billingPostalCode', $label, (string) $input);
465 * BillingCounty getter.
469 public function getBillingCounty($label = 'default') {
470 return $this->get('billingCounty', $label);
474 * BillingCounty setter.
476 * Nb. we can't validate this unless we have the country ID too, so we don't.
478 * @param string $input
479 * @param string $label e.g. 'default'
481 public function setBillingCounty($input, $label = 'default') {
482 return $this->set('billingCounty', $label, (string) $input);
486 * BillingCountry getter.
490 public function getBillingCountry($label = 'default') {
491 return $this->get('billingCountry', $label);
495 * BillingCountry setter.
497 * Nb. We require and we store a 2 character country code.
499 * @param string $input
500 * @param string $label e.g. 'default'
502 public function setBillingCountry($input, $label = 'default') {
503 if (!is_string($input) ||
strlen($input) !== 2) {
504 throw new \
InvalidArgumentException("setBillingCountry expects ISO 3166-1 alpha-2 country code.");
506 if (!CRM_Core_PseudoConstant
::getKey('CRM_Core_BAO_Address', 'country_id', $input)) {
507 throw new \
InvalidArgumentException("setBillingCountry expects ISO 3166-1 alpha-2 country code.");
509 return $this->set('billingCountry', $label, (string) $input);
515 public function getContactID($label = 'default'): int {
516 return $this->get('contactID', $label);
520 * @param int $contactID
521 * @param string $label
523 public function setContactID($contactID, $label = 'default') {
524 // We don't use this because it counts zero as positive: CRM_Utils_Type::validate($contactID, 'Positive');
525 if (!($contactID > 0)) {
526 throw new InvalidArgumentException("ContactID must be a positive integer");
529 return $this->set('contactID', $label, (int) $contactID);
533 * Getter for contributionID.
536 * @param string $label
538 public function getContributionID($label = 'default') {
539 return $this->get('contributionID', $label);
543 * @param int $contributionID
544 * @param string $label e.g. 'default'
546 public function setContributionID($contributionID, $label = 'default') {
547 // We don't use this because it counts zero as positive: CRM_Utils_Type::validate($contactID, 'Positive');
548 if (!($contributionID > 0)) {
549 throw new InvalidArgumentException("ContributionID must be a positive integer");
552 return $this->set('contributionID', $label, (int) $contributionID);
556 * Getter for contributionRecurID.
559 * @param string $label
561 public function getContributionRecurID($label = 'default') {
562 return $this->get('contributionRecurID', $label);
566 * @param int $contributionRecurID
567 * @param string $label e.g. 'default'
569 public function setContributionRecurID($contributionRecurID, $label = 'default') {
570 // We don't use this because it counts zero as positive: CRM_Utils_Type::validate($contactID, 'Positive');
571 if (!($contributionRecurID > 0)) {
572 throw new InvalidArgumentException("ContributionRecurID must be a positive integer");
575 return $this->set('contributionRecurID', $label, (int) $contributionRecurID);
579 * Three character currency code.
581 * https://en.wikipedia.org/wiki/ISO_3166-1_alpha-3
583 * @param string $label e.g. 'default'
585 public function getCurrency($label = 'default') {
586 return $this->get('currency', $label);
590 * Three character currency code.
592 * @param string $value
593 * @param string $label e.g. 'default'
595 public function setCurrency($value, $label = 'default') {
596 if (!preg_match('/^[A-Z]{3}$/', $value)) {
597 throw new \
InvalidArgumentException("Attemted to setCurrency with a value that was not an ISO 3166-1 alpha 3 currency code");
599 return $this->set('currency', $label, $value);
604 * @param string $label
608 public function getDescription($label = 'default') {
609 return $this->get('description', $label);
613 * @param string $description
614 * @param string $label e.g. 'default'
616 public function setDescription($description, $label = 'default') {
617 // @todo this logic was copied from a commit that then got deleted. Is it good?
618 $uninformativeStrings = [
619 ts('Online Event Registration: '),
620 ts('Online Contribution: '),
622 $cleanedDescription = str_replace($uninformativeStrings, '', $description);
623 return $this->set('description', $label, $cleanedDescription);
631 public function getEmail($label = 'default') {
632 return $this->get('email', $label);
638 * @param string $email
639 * @param string $label e.g. 'default'
641 public function setEmail($email, $label = 'default') {
642 return $this->set('email', $label, (string) $email);
646 * Amount of money charged in fees by the payment processor.
648 * This is notified by (some) payment processers.
650 * @param string $label
654 public function getFeeAmount($label = 'default') {
655 return $this->get('feeAmount', $label);
659 * @param string $feeAmount
660 * @param string $label e.g. 'default'
662 public function setFeeAmount($feeAmount, $label = 'default') {
663 if (!is_numeric($feeAmount)) {
664 throw new \
InvalidArgumentException("feeAmount must be a number.");
666 return $this->set('feeAmount', $label, (float) $feeAmount);
674 public function getFirstName($label = 'default') {
675 return $this->get('firstName', $label);
681 * @param string $firstName
682 * @param string $label e.g. 'default'
684 public function setFirstName($firstName, $label = 'default') {
685 return $this->set('firstName', $label, (string) $firstName);
689 * Getter for invoiceID.
691 * @param string $label
693 * @return string|null
695 public function getInvoiceID($label = 'default') {
696 return $this->get('invoiceID', $label);
700 * @param string $invoiceID
701 * @param string $label e.g. 'default'
703 public function setInvoiceID($invoiceID, $label = 'default') {
704 return $this->set('invoiceID', $label, $invoiceID);
708 * Getter for isBackOffice.
710 * @param string $label
714 public function getIsBackOffice($label = 'default'):bool {
715 // @todo should this return FALSE instead of exception to keep current situation?
716 return $this->get('isBackOffice', $label);
720 * @param bool $isBackOffice
721 * @param string $label e.g. 'default'
723 public function setIsBackOffice($isBackOffice, $label = 'default') {
724 if (is_null($isBackOffice)) {
725 throw new \
InvalidArgumentException("isBackOffice must be a bool, received NULL.");
727 return $this->set('isBackOffice', $label, (bool) $isBackOffice);
731 * Getter for isRecur.
733 * @param string $label
737 public function getIsRecur($label = 'default'):bool {
738 return $this->get('isRecur', $label);
742 * @param bool $isRecur
743 * @param string $label e.g. 'default'
745 public function setIsRecur($isRecur, $label = 'default') {
746 if (is_null($isRecur)) {
747 throw new \
InvalidArgumentException("isRecur must be a bool, received NULL.");
749 return $this->set('isRecur', $label, (bool) $isRecur);
757 public function getLastName($label = 'default') {
758 return $this->get('lastName', $label);
764 * @param string $lastName
765 * @param string $label e.g. 'default'
767 public function setLastName($lastName, $label = 'default') {
768 return $this->set('lastName', $label, (string) $lastName);
772 * Getter for payment processor generated string for charging.
774 * A payment token could be a single use token (e.g generated by
775 * a client side script) or a token that permits recurring or on demand charging.
777 * The key thing is it is passed to the processor in lieu of card details to
778 * initiate a payment.
780 * Generally if a processor is going to pass in a payment token generated through
781 * javascript it would add 'payment_token' to the array it returns in it's
782 * implementation of getPaymentFormFields. This will add a hidden 'payment_token' field to
783 * the form. A good example is client side encryption where credit card details are replaced by
784 * an encrypted token using a gateway provided javascript script. In this case the javascript will
785 * remove the credit card details from the form before submitting and populate the payment_token field.
787 * A more complex example is used by paypal checkout where the payment token is generated
788 * via a pre-approval process. In that case the doPreApproval function is called on the processor
789 * class to get information to then interact with paypal via js, finally getting a payment token.
790 * (at this stage the pre-approve api is not in core but that is likely to change - we just need
791 * to think about the permissions since we don't want to expose to anonymous user without thinking
792 * through any risk of credit-card testing using it.
794 * If the token is not totally transient it would be saved to civicrm_payment_token.token.
796 * @param string $label
798 * @return string|null
800 public function getPaymentToken($label = 'default') {
801 return $this->get('paymentToken', $label);
805 * @param string $paymentToken
806 * @param string $label e.g. 'default'
808 public function setPaymentToken($paymentToken, $label = 'default') {
809 return $this->set('paymentToken', $label, $paymentToken);
817 public function getPhone($label = 'default') {
818 return $this->get('phone', $label);
824 * @param string $phone
825 * @param string $label e.g. 'default'
827 public function setPhone($phone, $label = 'default') {
828 return $this->set('phone', $label, (string) $phone);
832 * Combined with recurFrequencyUnit this gives how often billing will take place.
834 * e.g every if this is 1 and recurFrequencyUnit is 'month' then it is every 1 month.
837 public function getRecurFrequencyInterval($label = 'default') {
838 return $this->get('recurFrequencyInterval', $label);
842 * @param int $recurFrequencyInterval
843 * @param string $label e.g. 'default'
845 public function setRecurFrequencyInterval($recurFrequencyInterval, $label = 'default') {
846 if (!($recurFrequencyInterval > 0)) {
847 throw new InvalidArgumentException("recurFrequencyInterval must be a positive integer");
850 return $this->set('recurFrequencyInterval', $label, (int) $recurFrequencyInterval);
854 * Getter for recurFrequencyUnit.
855 * Combined with recurFrequencyInterval this gives how often billing will take place.
857 * e.g every if this is 'month' and recurFrequencyInterval is 1 then it is every 1 month.
860 * @param string $label
862 * @return string month|day|year
864 public function getRecurFrequencyUnit($label = 'default') {
865 return $this->get('recurFrequencyUnit', $label);
869 * @param string $recurFrequencyUnit month|day|week|year
870 * @param string $label e.g. 'default'
872 public function setRecurFrequencyUnit($recurFrequencyUnit, $label = 'default') {
873 if (!preg_match('/^day|week|month|year$/', $recurFrequencyUnit)) {
874 throw new \
InvalidArgumentException("recurFrequencyUnit must be day|week|month|year");
876 return $this->set('recurFrequencyUnit', $label, $recurFrequencyUnit);
880 * Set the unique payment processor service provided ID for a particular subscription.
882 * Nb. this is stored in civicrm_contribution_recur.processor_id and is NOT
883 * in any way related to the payment processor ID.
887 public function getRecurProcessorID($label = 'default') {
888 return $this->get('recurProcessorID', $label);
892 * Set the unique payment processor service provided ID for a particular
895 * @param string $input
896 * @param string $label e.g. 'default'
898 public function setRecurProcessorID($input, $label = 'default') {
899 if (empty($input) ||
strlen($input) > 255) {
900 throw new \
InvalidArgumentException("processorID field has max length of 255");
902 return $this->set('recurProcessorID', $label, $input);
906 * Getter for payment processor generated string for the transaction ID.
908 * Note some gateways generate a reference for the order and one for the
909 * payment. This is for the payment reference and is saved to
910 * civicrm_financial_trxn.trxn_id.
912 * @param string $label
914 * @return string|null
916 public function getTransactionID($label = 'default') {
917 return $this->get('transactionID', $label);
921 * @param string $transactionID
922 * @param string $label e.g. 'default'
924 public function setTransactionID($transactionID, $label = 'default') {
925 return $this->set('transactionID', $label, $transactionID);
929 * Getter for trxnResultCode.
931 * Additional information returned by the payment processor regarding the
934 * This would normally be saved in civicrm_financial_trxn.trxn_result_code.
937 * @param string $label
939 * @return string|null
941 public function getTrxnResultCode($label = 'default') {
942 return $this->get('trxnResultCode', $label);
946 * @param string $trxnResultCode
947 * @param string $label e.g. 'default'
949 public function setTrxnResultCode($trxnResultCode, $label = 'default') {
950 return $this->set('trxnResultCode', $label, $trxnResultCode);
953 // Custom Properties.
956 * Sometimes we may need to pass in things that are specific to the Payment
959 * @param string $prop
960 * @param string $label e.g. 'default' or 'old' or 'new'
963 * @throws InvalidArgumentException if trying to use this against a non-custom property.
965 public function getCustomProperty($prop, $label = 'default') {
966 if (isset(static::$propMap[$prop])) {
967 throw new \
InvalidArgumentException("Attempted to get '$prop' via getCustomProperty - must use using its getter.");
969 return $this->props
[$label][$prop] ??
NULL;
973 * We have to leave validation to the processor, but we can still give them a
974 * way to store their data on this PropertyBag
976 * @param string $prop
977 * @param mixed $value
978 * @param string $label e.g. 'default' or 'old' or 'new'
980 * @throws InvalidArgumentException if trying to use this against a non-custom property.
982 public function setCustomProperty($prop, $value, $label = 'default') {
983 if (isset(static::$propMap[$prop])) {
984 throw new \
InvalidArgumentException("Attempted to set '$prop' via setCustomProperty - must use using its setter.");
986 $this->props
[$label][$prop] = $value;