AbstractAddress.php 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669
  1. <?php
  2. /**
  3. * Copyright © Magento, Inc. All rights reserved.
  4. * See COPYING.txt for license details.
  5. */
  6. namespace Magento\Customer\Model\Address;
  7. use Magento\Customer\Api\AddressMetadataInterface;
  8. use Magento\Customer\Api\Data\AddressInterface;
  9. use Magento\Customer\Api\Data\AddressInterfaceFactory;
  10. use Magento\Customer\Api\Data\RegionInterface;
  11. use Magento\Customer\Api\Data\RegionInterfaceFactory;
  12. use Magento\Customer\Model\Data\Address as AddressData;
  13. use Magento\Framework\App\ObjectManager;
  14. use Magento\Framework\Model\AbstractExtensibleModel;
  15. /**
  16. * Address abstract model
  17. *
  18. * @method string getPrefix()
  19. * @method string getSuffix()
  20. * @method string getFirstname()
  21. * @method string getMiddlename()
  22. * @method string getLastname()
  23. * @method string getCountryId()
  24. * @method string getCity()
  25. * @method string getTelephone()
  26. * @method string getCompany()
  27. * @method string getFax()
  28. * @method string getPostcode()
  29. * @method bool getShouldIgnoreValidation()
  30. * @SuppressWarnings(PHPMD.CouplingBetweenObjects)
  31. *
  32. * @api
  33. * @since 100.0.2
  34. */
  35. class AbstractAddress extends AbstractExtensibleModel implements AddressModelInterface
  36. {
  37. /**
  38. * Possible customer address types
  39. */
  40. const TYPE_BILLING = 'billing';
  41. const TYPE_SHIPPING = 'shipping';
  42. /**
  43. * Prefix of model events
  44. *
  45. * @var string
  46. */
  47. protected $_eventPrefix = 'customer_address';
  48. /**
  49. * Name of event object
  50. *
  51. * @var string
  52. */
  53. protected $_eventObject = 'customer_address';
  54. /**
  55. * Directory country models
  56. *
  57. * @var \Magento\Directory\Model\Country[]
  58. */
  59. protected static $_countryModels = [];
  60. /**
  61. * Directory region models
  62. *
  63. * @var \Magento\Directory\Model\Region[]
  64. */
  65. protected static $_regionModels = [];
  66. /**
  67. * Directory data
  68. *
  69. * @var \Magento\Directory\Helper\Data
  70. */
  71. protected $_directoryData = null;
  72. /**
  73. * @var \Magento\Eav\Model\Config
  74. */
  75. protected $_eavConfig;
  76. /**
  77. * @var Config
  78. */
  79. protected $_addressConfig;
  80. /**
  81. * @var \Magento\Directory\Model\RegionFactory
  82. */
  83. protected $_regionFactory;
  84. /**
  85. * @var \Magento\Directory\Model\CountryFactory
  86. */
  87. protected $_countryFactory;
  88. /**
  89. * @var AddressMetadataInterface
  90. */
  91. protected $metadataService;
  92. /**
  93. * @var AddressInterfaceFactory
  94. */
  95. protected $addressDataFactory;
  96. /**
  97. * @var RegionInterfaceFactory
  98. */
  99. protected $regionDataFactory;
  100. /**
  101. * @var \Magento\Framework\Api\DataObjectHelper
  102. */
  103. protected $dataObjectHelper;
  104. /** @var CompositeValidator */
  105. private $compositeValidator;
  106. /**
  107. * @param \Magento\Framework\Model\Context $context
  108. * @param \Magento\Framework\Registry $registry
  109. * @param \Magento\Framework\Api\ExtensionAttributesFactory $extensionFactory
  110. * @param \Magento\Framework\Api\AttributeValueFactory $customAttributeFactory
  111. * @param \Magento\Directory\Helper\Data $directoryData
  112. * @param \Magento\Eav\Model\Config $eavConfig
  113. * @param Config $addressConfig
  114. * @param \Magento\Directory\Model\RegionFactory $regionFactory
  115. * @param \Magento\Directory\Model\CountryFactory $countryFactory
  116. * @param AddressMetadataInterface $metadataService
  117. * @param AddressInterfaceFactory $addressDataFactory
  118. * @param RegionInterfaceFactory $regionDataFactory
  119. * @param \Magento\Framework\Api\DataObjectHelper $dataObjectHelper
  120. * @param \Magento\Framework\Model\ResourceModel\AbstractResource $resource
  121. * @param \Magento\Framework\Data\Collection\AbstractDb $resourceCollection
  122. * @param array $data
  123. * @param CompositeValidator $compositeValidator
  124. *
  125. * @SuppressWarnings(PHPMD.ExcessiveParameterList)
  126. */
  127. public function __construct(
  128. \Magento\Framework\Model\Context $context,
  129. \Magento\Framework\Registry $registry,
  130. \Magento\Framework\Api\ExtensionAttributesFactory $extensionFactory,
  131. \Magento\Framework\Api\AttributeValueFactory $customAttributeFactory,
  132. \Magento\Directory\Helper\Data $directoryData,
  133. \Magento\Eav\Model\Config $eavConfig,
  134. Config $addressConfig,
  135. \Magento\Directory\Model\RegionFactory $regionFactory,
  136. \Magento\Directory\Model\CountryFactory $countryFactory,
  137. AddressMetadataInterface $metadataService,
  138. AddressInterfaceFactory $addressDataFactory,
  139. RegionInterfaceFactory $regionDataFactory,
  140. \Magento\Framework\Api\DataObjectHelper $dataObjectHelper,
  141. \Magento\Framework\Model\ResourceModel\AbstractResource $resource = null,
  142. \Magento\Framework\Data\Collection\AbstractDb $resourceCollection = null,
  143. array $data = [],
  144. CompositeValidator $compositeValidator = null
  145. ) {
  146. $this->_directoryData = $directoryData;
  147. $data = $this->_implodeArrayField($data);
  148. $this->_eavConfig = $eavConfig;
  149. $this->_addressConfig = $addressConfig;
  150. $this->_regionFactory = $regionFactory;
  151. $this->_countryFactory = $countryFactory;
  152. $this->metadataService = $metadataService;
  153. $this->addressDataFactory = $addressDataFactory;
  154. $this->regionDataFactory = $regionDataFactory;
  155. $this->dataObjectHelper = $dataObjectHelper;
  156. $this->compositeValidator = $compositeValidator ?: ObjectManager::getInstance()
  157. ->get(CompositeValidator::class);
  158. parent::__construct(
  159. $context,
  160. $registry,
  161. $extensionFactory,
  162. $customAttributeFactory,
  163. $resource,
  164. $resourceCollection,
  165. $data
  166. );
  167. }
  168. /**
  169. * Get full customer name
  170. *
  171. * @return string
  172. */
  173. public function getName()
  174. {
  175. $name = '';
  176. if ($this->_eavConfig->getAttribute('customer_address', 'prefix')->getIsVisible() && $this->getPrefix()) {
  177. $name .= $this->getPrefix() . ' ';
  178. }
  179. $name .= $this->getFirstname();
  180. $middleName = $this->_eavConfig->getAttribute('customer_address', 'middlename');
  181. if ($middleName->getIsVisible() && $this->getMiddlename()) {
  182. $name .= ' ' . $this->getMiddlename();
  183. }
  184. $name .= ' ' . $this->getLastname();
  185. if ($this->_eavConfig->getAttribute('customer_address', 'suffix')->getIsVisible() && $this->getSuffix()) {
  186. $name .= ' ' . $this->getSuffix();
  187. }
  188. return $name;
  189. }
  190. /**
  191. * Retrieve street field of an address
  192. *
  193. * @return string[]
  194. */
  195. public function getStreet()
  196. {
  197. if (is_array($this->getStreetFull())) {
  198. return $this->getStreetFull();
  199. }
  200. return explode("\n", $this->getStreetFull());
  201. }
  202. /**
  203. * Get street line by number
  204. *
  205. * @param int $number
  206. * @return string
  207. */
  208. public function getStreetLine($number)
  209. {
  210. $lines = $this->getStreet();
  211. return $lines[$number - 1] ?? '';
  212. }
  213. /**
  214. * Retrieve text of street lines, concatenated using LF symbol
  215. *
  216. * @return string
  217. */
  218. public function getStreetFull()
  219. {
  220. $street = $this->getData('street');
  221. return is_array($street) ? implode("\n", $street) : $street;
  222. }
  223. /**
  224. * Alias for a street setter. To be used though setDataUsingMethod('street_full', $value).
  225. *
  226. * @param string|string[] $street
  227. * @return $this
  228. */
  229. public function setStreetFull($street)
  230. {
  231. return $this->setStreet($street);
  232. }
  233. /**
  234. * Non-magic setter for a street field
  235. *
  236. * @param string|string[] $street
  237. * @return $this
  238. */
  239. public function setStreet($street)
  240. {
  241. $this->setData('street', $street);
  242. return $this;
  243. }
  244. /**
  245. * Enforce format of the street field or other multiline custom attributes
  246. *
  247. * @param array|string $key
  248. * @param array|string|null $value
  249. *
  250. * @return \Magento\Framework\DataObject
  251. */
  252. public function setData($key, $value = null)
  253. {
  254. if (is_array($key)) {
  255. $key = $this->_implodeArrayField($key);
  256. } elseif (is_array($value) && $this->isAddressMultilineAttribute($key)) {
  257. $value = $this->_implodeArrayValues($value);
  258. }
  259. return parent::setData($key, $value);
  260. }
  261. /**
  262. * Check that address can have multiline attribute by this code (as street or some custom attribute)
  263. *
  264. * @param string $code
  265. * @return bool
  266. */
  267. protected function isAddressMultilineAttribute($code)
  268. {
  269. return $code == 'street' || in_array($code, $this->getCustomAttributesCodes());
  270. }
  271. /**
  272. * Implode value of the array field, if it is present among other fields
  273. *
  274. * @param array $data
  275. * @return array
  276. */
  277. protected function _implodeArrayField(array $data)
  278. {
  279. foreach ($data as $key => $value) {
  280. if (is_array($value) && $this->isAddressMultilineAttribute($key)) {
  281. $data[$key] = $this->_implodeArrayValues($data[$key]);
  282. }
  283. }
  284. return $data;
  285. }
  286. /**
  287. * Combine values of field lines into a single string
  288. *
  289. * @param string[]|string $value
  290. * @return string
  291. */
  292. protected function _implodeArrayValues($value)
  293. {
  294. if (is_array($value)) {
  295. if (!count($value)) {
  296. return '';
  297. }
  298. $isScalar = false;
  299. foreach ($value as $val) {
  300. if (is_scalar($val)) {
  301. $isScalar = true;
  302. }
  303. }
  304. if ($isScalar) {
  305. $value = trim(implode("\n", $value));
  306. }
  307. }
  308. return $value;
  309. }
  310. /**
  311. * Create fields street1, street2, etc.
  312. *
  313. * To be used in controllers for views data
  314. *
  315. * @return $this
  316. */
  317. public function explodeStreetAddress()
  318. {
  319. $streetLines = $this->getStreet();
  320. foreach ($streetLines as $i => $line) {
  321. $this->setData('street' . ($i + 1), $line);
  322. }
  323. return $this;
  324. }
  325. /**
  326. * Retrieve region name
  327. *
  328. * @return string
  329. */
  330. public function getRegion()
  331. {
  332. $regionId = $this->getData('region_id');
  333. $region = $this->getData('region');
  334. if (!$regionId && is_numeric($region)) {
  335. if ($this->getRegionModel($region)->getCountryId() == $this->getCountryId()) {
  336. $this->setData('region', $this->getRegionModel($region)->getName());
  337. $this->setData('region_id', $region);
  338. }
  339. } elseif ($regionId) {
  340. if ($this->getRegionModel($regionId)->getCountryId() == $this->getCountryId()) {
  341. $this->setData('region', $this->getRegionModel($regionId)->getName());
  342. }
  343. } elseif (is_string($region)) {
  344. $this->setData('region', $region);
  345. }
  346. return $this->getData('region');
  347. }
  348. /**
  349. * Return 2 letter state code if available, otherwise full region name
  350. *
  351. * @return string
  352. */
  353. public function getRegionCode()
  354. {
  355. $regionId = $this->getData('region_id');
  356. $region = $this->getData('region');
  357. if (!$regionId && is_numeric($region)) {
  358. if ($this->getRegionModel($region)->getCountryId() == $this->getCountryId()) {
  359. $this->setData('region_code', $this->getRegionModel($region)->getCode());
  360. }
  361. } elseif ($regionId) {
  362. if ($this->getRegionModel($regionId)->getCountryId() == $this->getCountryId()) {
  363. $this->setData('region_code', $this->getRegionModel($regionId)->getCode());
  364. }
  365. } elseif (is_string($region)) {
  366. $this->setData('region_code', $region);
  367. }
  368. return $this->getData('region_code');
  369. }
  370. /**
  371. * Return Region ID
  372. *
  373. * @return int
  374. */
  375. public function getRegionId()
  376. {
  377. $regionId = $this->getData('region_id');
  378. $region = $this->getData('region');
  379. if (!$regionId) {
  380. if (is_numeric($region)) {
  381. $this->setData('region_id', $region);
  382. $this->unsRegion();
  383. } else {
  384. $regionModel = $this->_createRegionInstance()->loadByCode(
  385. $this->getRegionCode(),
  386. $this->getCountryId()
  387. );
  388. $this->setData('region_id', $regionModel->getId());
  389. }
  390. }
  391. return $this->getData('region_id');
  392. }
  393. /**
  394. * Get country
  395. *
  396. * @return string
  397. */
  398. public function getCountry()
  399. {
  400. $country = $this->getCountryId();
  401. return $country ? $country : $this->getData('country');
  402. }
  403. /**
  404. * Retrieve country model
  405. *
  406. * @return \Magento\Directory\Model\Country
  407. */
  408. public function getCountryModel()
  409. {
  410. if (!isset(self::$_countryModels[$this->getCountryId()])) {
  411. $country = $this->_createCountryInstance();
  412. $country->load($this->getCountryId());
  413. self::$_countryModels[$this->getCountryId()] = $country;
  414. }
  415. return self::$_countryModels[$this->getCountryId()];
  416. }
  417. /**
  418. * Retrieve country model
  419. *
  420. * @param int|null $regionId
  421. * @return \Magento\Directory\Model\Region
  422. */
  423. public function getRegionModel($regionId = null)
  424. {
  425. if ($regionId === null) {
  426. $regionId = $this->getRegionId();
  427. }
  428. if (!isset(self::$_regionModels[$regionId])) {
  429. $region = $this->_createRegionInstance();
  430. $region->load($regionId);
  431. self::$_regionModels[$regionId] = $region;
  432. }
  433. return self::$_regionModels[$regionId];
  434. }
  435. /**
  436. * Format address in a specific way
  437. *
  438. * Deprecated, use this code instead:
  439. * $renderer = $this->_addressConfig->getFormatByCode('html')->getRenderer();
  440. * $addressMapper = \Magento\Customer\Model\Address\Mapper type
  441. * $addressData = $addressMapper->toFlatArray($address);
  442. * $formattedAddress = $renderer->renderArray($addressData);
  443. *
  444. * @param string $type
  445. * @return string|null
  446. */
  447. public function format($type)
  448. {
  449. if (!($formatType = $this->getConfig()->getFormatByCode($type)) || !$formatType->getRenderer()) {
  450. return null;
  451. }
  452. $this->_eventManager->dispatch('customer_address_format', ['type' => $formatType, 'address' => $this]);
  453. return $formatType->getRenderer()->render($this);
  454. }
  455. /**
  456. * Retrieve address config object
  457. *
  458. * @return Config
  459. */
  460. public function getConfig()
  461. {
  462. return $this->_addressConfig;
  463. }
  464. /**
  465. * Processing object before save data
  466. *
  467. * @return $this
  468. */
  469. public function beforeSave()
  470. {
  471. parent::beforeSave();
  472. $this->getRegion();
  473. return $this;
  474. }
  475. /**
  476. * Create address data object based on current address model.
  477. *
  478. * @param int|null $defaultBillingAddressId
  479. * @param int|null $defaultShippingAddressId
  480. *
  481. * @return AddressInterface
  482. * Use Api/Data/AddressInterface as a result of service operations. Don't rely on the model to provide
  483. * the instance of Api/Data/AddressInterface
  484. * @SuppressWarnings(PHPMD.CyclomaticComplexity)
  485. * @throws \Magento\Framework\Exception\LocalizedException
  486. */
  487. public function getDataModel($defaultBillingAddressId = null, $defaultShippingAddressId = null)
  488. {
  489. $addressId = $this->getId();
  490. $attributes = $this->metadataService->getAllAttributesMetadata();
  491. $addressData = [];
  492. foreach ($attributes as $attribute) {
  493. $code = $attribute->getAttributeCode();
  494. if ($this->getData($code) !== null) {
  495. if ($code === AddressInterface::STREET) {
  496. $addressData[$code] = $this->getDataUsingMethod($code);
  497. } else {
  498. $addressData[$code] = $this->getData($code);
  499. }
  500. }
  501. }
  502. /** @var RegionInterface $region */
  503. $region = $this->regionDataFactory->create();
  504. $region->setRegion($this->getRegion())
  505. ->setRegionCode($this->getRegionCode())
  506. ->setRegionId($this->getRegionId());
  507. $addressData[AddressData::REGION] = $region;
  508. $addressDataObject = $this->addressDataFactory->create();
  509. $this->dataObjectHelper->populateWithArray(
  510. $addressDataObject,
  511. $addressData,
  512. \Magento\Customer\Api\Data\AddressInterface::class
  513. );
  514. if ($addressId) {
  515. $addressDataObject->setId($addressId);
  516. }
  517. if ($this->getCustomerId() || $this->getParentId()) {
  518. $customerId = $this->getCustomerId() ?: $this->getParentId();
  519. $addressDataObject->setCustomerId($customerId);
  520. if ($defaultBillingAddressId == $addressId) {
  521. $addressDataObject->setIsDefaultBilling(true);
  522. }
  523. if ($defaultShippingAddressId == $addressId) {
  524. $addressDataObject->setIsDefaultShipping(true);
  525. }
  526. }
  527. return $addressDataObject;
  528. }
  529. /**
  530. * Validate address attribute values.
  531. *
  532. * @return array|bool
  533. */
  534. public function validate()
  535. {
  536. if ($this->getShouldIgnoreValidation()) {
  537. return true;
  538. }
  539. $errors = $this->compositeValidator->validate($this);
  540. if (empty($errors)) {
  541. return true;
  542. }
  543. return $errors;
  544. }
  545. /**
  546. * Create region instance
  547. *
  548. * @return \Magento\Directory\Model\Region
  549. */
  550. protected function _createRegionInstance()
  551. {
  552. return $this->_regionFactory->create();
  553. }
  554. /**
  555. * Create country instance
  556. *
  557. * @return \Magento\Directory\Model\Country
  558. */
  559. protected function _createCountryInstance()
  560. {
  561. return $this->_countryFactory->create();
  562. }
  563. /**
  564. * Unset Region from address
  565. *
  566. * @return $this
  567. * @since 101.0.0
  568. */
  569. public function unsRegion()
  570. {
  571. return $this->unsetData("region");
  572. }
  573. /**
  574. * Is company required
  575. *
  576. * @return bool
  577. * @since 101.0.0
  578. * @throws \Magento\Framework\Exception\LocalizedException
  579. */
  580. protected function isCompanyRequired()
  581. {
  582. return ($this->_eavConfig->getAttribute('customer_address', 'company')->getIsRequired());
  583. }
  584. /**
  585. * Is telephone required
  586. *
  587. * @return bool
  588. * @since 101.0.0
  589. * @throws \Magento\Framework\Exception\LocalizedException
  590. */
  591. protected function isTelephoneRequired()
  592. {
  593. return ($this->_eavConfig->getAttribute('customer_address', 'telephone')->getIsRequired());
  594. }
  595. /**
  596. * Is fax required
  597. *
  598. * @return bool
  599. * @since 101.0.0
  600. * @throws \Magento\Framework\Exception\LocalizedException
  601. */
  602. protected function isFaxRequired()
  603. {
  604. return ($this->_eavConfig->getAttribute('customer_address', 'fax')->getIsRequired());
  605. }
  606. }