DolibarrSyncService.php 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637
  1. <?php
  2. declare(strict_types=1);
  3. namespace App\Service\Dolibarr;
  4. use App\Entity\Core\AddressPostal;
  5. use App\Entity\Core\ContactPoint;
  6. use App\Entity\Organization\Organization;
  7. use App\Entity\Person\Person;
  8. use App\Enum\Access\FunctionEnum;
  9. use App\Enum\Access\RoleEnum;
  10. use App\Enum\Core\ContactPointTypeEnum;
  11. use App\Enum\Organization\AddressPostalOrganizationTypeEnum;
  12. use App\Enum\Organization\OrganizationIdsEnum;
  13. use App\Enum\Organization\SettingsProductEnum;
  14. use App\Enum\Person\GenderEnum;
  15. use App\Repository\Access\AccessRepository;
  16. use App\Repository\Access\FunctionTypeRepository;
  17. use App\Repository\Organization\OrganizationRepository;
  18. use App\Service\Core\AddressPostalUtils;
  19. use App\Service\Rest\Operation\BaseRestOperation;
  20. use App\Service\Rest\Operation\CreateOperation;
  21. use App\Service\Rest\Operation\UpdateOperation;
  22. use Exception;
  23. use HttpException;
  24. use libphonenumber\PhoneNumber;
  25. use libphonenumber\PhoneNumberFormat;
  26. use libphonenumber\PhoneNumberUtil;
  27. use Psr\Log\LoggerInterface;
  28. use Symfony\Contracts\Translation\TranslatorInterface;
  29. /**
  30. * Push the data from the Opentalent DB into the Dolibarr DB, trough both applications
  31. * REST APIs.
  32. *
  33. * ** /!\ This sync is and must remain one-sided: Opentalent DB => Dolibarr DB **
  34. */
  35. class DolibarrSyncService
  36. {
  37. public function __construct(
  38. private OrganizationRepository $organizationRepository,
  39. private AccessRepository $accessRepository,
  40. private FunctionTypeRepository $functionTypeRepository,
  41. private DolibarrApiService $dolibarrApiService,
  42. private TranslatorInterface $translator,
  43. private LoggerInterface $logger
  44. ) {}
  45. /**
  46. * Performs a scan, comparing data from the Opentalent DB and the data returned
  47. * by the Dolibarr API
  48. *
  49. * Errors during the scan are recorded in the $this->scanErrors
  50. *
  51. * Returns an array of DolibarrSyncOperations
  52. *
  53. * @var callable | null $progressionCallback A callback method for indicating the current progression of the process;
  54. * Shall accept two integer arguments: current progression, and total.
  55. * @return array<BaseRestOperation>
  56. * @throws Exception
  57. */
  58. public function scan(?callable $progressionCallback = null): array {
  59. $this->logger->info("-- Scan started --");
  60. // Index the dolibarr clients by organization ids
  61. $dolibarrClientsIndex = $this->getDolibarrSocietiesIndex();
  62. $this->logger->info(count($dolibarrClientsIndex) . " clients fetched from dolibarr");
  63. // Get all active accesses
  64. $membersIndex = $this->getActiveMembersIndex();
  65. // Get all the missions with an admin default role
  66. $adminMissions = [];
  67. foreach ($this->functionTypeRepository->findBy(['roleByDefault' => RoleEnum::ROLE_ADMIN()->getValue()]) as $functionType) {
  68. $adminMissions[] = $functionType->getMission();
  69. }
  70. // Store networks ids id dolibarr
  71. $cmfDolibarrId = (int)($this->dolibarrApiService->getSociety(OrganizationIdsEnum::CMF()->getValue())['id']);
  72. $ffecDolibarrId = (int)($this->dolibarrApiService->getSociety(OrganizationIdsEnum::FFEC()->getValue())['id']);
  73. // Loop over the Opentalent organizations, and fill up the operations list
  74. $operations = [];
  75. $i = 0; $total = count($dolibarrClientsIndex);
  76. foreach ($dolibarrClientsIndex as $organizationId => $dolibarrSociety) {
  77. $dolibarrSociety = $this->sanitizeDolibarrData($dolibarrSociety);
  78. $organization = $this->organizationRepository->find($organizationId);
  79. if ($organization === null) {
  80. $this->logger->error("Organization " . $organizationId . " not found in the Opentalent DB");
  81. continue;
  82. }
  83. // Populate the expectedContacts array
  84. $organizationMembers = $membersIndex[$organization->getId()] ?? [];
  85. // ===== Update Society =====
  86. $newSocietyData = [];
  87. // Sync name
  88. $newSocietyData['name'] = trim($organization->getName());
  89. // Sync contact data of the client
  90. $mainAddress = $this->getOrganizationPostalAddress($organization);
  91. if ($mainAddress !== null) {
  92. $streetAddress = AddressPostalUtils::getFullStreetAddress($mainAddress);
  93. if (trim($mainAddress->getAddressOwner() ?? '') !== '') {
  94. $streetAddress = $mainAddress->getAddressOwner() . '\n' . $streetAddress;
  95. }
  96. $newSocietyData['address'] = $streetAddress;
  97. $newSocietyData['zip'] = $mainAddress->getPostalCode();
  98. $newSocietyData['town'] = $mainAddress->getAddressCity();
  99. } else {
  100. $newSocietyData['address'] = null;
  101. $newSocietyData['zip'] = null;
  102. $newSocietyData['town'] = null;
  103. }
  104. // Sync contact
  105. $newSocietyData['email'] = $this->getOrganizationEmail($organization);
  106. $newSocietyData['phone'] = $this->getOrganizationPhone($organization);
  107. // Sync Network
  108. $newSocietyData['parent'] = match (
  109. $organization->getNetworkOrganizations()?->first()?->getNetwork()?->getId()
  110. ) {
  111. OrganizationIdsEnum::CMF()->getValue() => $cmfDolibarrId,
  112. OrganizationIdsEnum::FFEC()->getValue() => $ffecDolibarrId,
  113. default => null
  114. };
  115. // More infos
  116. $infos = [];
  117. $product = $organization->getSettings()->getProduct();
  118. if (SettingsProductEnum::isSchool($product)) {
  119. $infos[] = $this->translator->trans('STUDENTS_COUNT') . " : " .
  120. $this->countWithMission([FunctionEnum::STUDENT()->getValue()], $organizationMembers);
  121. }
  122. if (SettingsProductEnum::isSchool($product) || SettingsProductEnum::isArtist($product)) {
  123. $infos[] = $this->translator->trans('ADHERENTS_COUNT') . " : " .
  124. $this->countWithMission([FunctionEnum::ADHERENT()->getValue()], $organizationMembers);
  125. }
  126. $infos[] = $this->translator->trans('ADMIN_ACCESS_COUNT') . " : " .
  127. $this->countWithMission($adminMissions, $organizationMembers);
  128. // /!\ On est forcé de passer la sub-array entière pour mettre à jour le champ modifié, sinon
  129. // tous les autres champs seront passés à null...
  130. $newSocietyData['array_options'] = $dolibarrSociety["array_options"];
  131. $newSocietyData['array_options']['options_2iopeninfoopentalent'] = implode("\n", $infos);
  132. // Only update the fields that are different
  133. $newSocietyData = $this->filterDiff($dolibarrSociety, $newSocietyData);
  134. // Add an update operation if some data has to be updated
  135. if (!empty($newSocietyData)) {
  136. $operations[] = new UpdateOperation(
  137. 'Update society : ' . $organization->getName() . ' (' . $organization->getId() . ')',
  138. 'thirdparties',
  139. $dolibarrSociety,
  140. $newSocietyData
  141. );
  142. }
  143. // ===== Update Contacts =====
  144. $dolibarrContactsIndex = $this->getDolibarrContactsIndex((int)$dolibarrSociety['id']);
  145. $contactsProcessed = [];
  146. foreach ($organizationMembers as $accessId => $missions) {
  147. foreach ($missions as $mission) {
  148. if (in_array($mission, FunctionEnum::getOfficeMissions())) {
  149. $access = $this->accessRepository->find($accessId);
  150. $person = $access->getPerson();
  151. // Keep track of the contacts seen
  152. if (in_array($person->getId(), $contactsProcessed)) {
  153. // already updated from another mission
  154. continue;
  155. }
  156. $contactsProcessed[] = $person->getId();
  157. // special: if the contact has no name, ignore it
  158. if (!$person->getName()) {
  159. continue;
  160. }
  161. // Build parameters for the query (if a query is needed
  162. $dolibarrContact = $dolibarrContactsIndex[$person->getId()] ?? null;
  163. $dolibarrContact = $this->sanitizeDolibarrData($dolibarrContact);
  164. $contact = $this->getPersonContact($person);
  165. $newContactData = [
  166. 'civility_code' => $person->getGender() ? $this->translator->trans($person->getGender()) : null,
  167. 'lastname' => trim($person->getName()),
  168. 'firstname' => trim($person->getGivenName()),
  169. 'email' => $contact?->getEmail(),
  170. 'phone_pro' => $contact?->getTelphone() ? $this->formatPhoneNumber($contact?->getTelphone()) : null,
  171. 'phone_mobile' => $contact?->getMobilPhone() ? $this->formatPhoneNumber($contact?->getMobilPhone()): null,
  172. 'poste' => $this->formatContactPosition($missions, $person->getGender())
  173. ];
  174. if ($dolibarrContact === null) {
  175. // New contact
  176. $newContactData['socid'] = (int)$dolibarrSociety['id'];
  177. $newContactData['array_options'] = [
  178. 'options_2iopen_person_id' => $person->getId()
  179. ];
  180. $operations[] = new CreateOperation(
  181. 'New contact: ' . $person->getName() . ' ' . $person->getGivenName() . ' (' . $person->getId() . ')',
  182. 'contacts',
  183. $newContactData
  184. );
  185. } else {
  186. // Only update the fields that are different
  187. $newContactData = $this->filterDiff($dolibarrContact, $newContactData);
  188. // add an update operation if some data has to be updated
  189. if (!empty($newContactData)) {
  190. $operations[] = new UpdateOperation(
  191. 'Update contact: ' . $person->getName() . ' ' . $person->getGivenName() . ' (' . $person->getId() . ')' .
  192. ' in ' . $organization->getName() . ' (' . $organization->getId() . ')',
  193. 'contacts',
  194. $dolibarrContact,
  195. $newContactData,
  196. );
  197. }
  198. }
  199. // No need to test the other missions of this access
  200. break;
  201. }
  202. }
  203. }
  204. foreach ($dolibarrContactsIndex as $personId => $contactData) {
  205. if ((int)$contactData['statut'] === 0) {
  206. // contact is already disabled
  207. continue;
  208. }
  209. if (!in_array($personId, $contactsProcessed)) {
  210. // Ce personId n'existe plus dans les membres Opentalent de cette société, on delete
  211. $operations[] = new UpdateOperation(
  212. 'Disable contact: ' . $contactData['lastname'] . ' ' . $contactData['firstname'] . ' (' . $personId . ')' .
  213. ' from ' . $organization->getName() . ' (' . $organization->getId() . ')',
  214. 'contacts',
  215. $contactData,
  216. ['statut' => 0]
  217. );
  218. }
  219. }
  220. // Next society
  221. $i++;
  222. if ($progressionCallback !== null) {
  223. $progressionCallback($i, $total);
  224. }
  225. }
  226. $this->logger->info('Scan done, ' . count($operations) . ' required operations listed');
  227. foreach ($operations as $operation) {
  228. $this->logger->debug($operation->getLabel());
  229. foreach ($operation->getChangeLog() as $message) {
  230. $this->logger->debug(' ' . $message);
  231. }
  232. }
  233. $this->logger->info('Scan ended');
  234. return $operations;
  235. }
  236. /**
  237. * Execute the operations listed with the DolibarrSyncService::scan method
  238. *
  239. * Returns an array of DolibarrSyncOperations
  240. *
  241. * @param array<BaseRestOperation> $operations
  242. * @return array<BaseRestOperation>
  243. * @throws Exception
  244. *@var callable | null $progressionCallback A callback method for indicating the current progression of the process;
  245. * Shall accept two integer arguments: current progression, and total.
  246. */
  247. public function execute(array $operations, ?callable $progressionCallback = null): array
  248. {
  249. $this->logger->info('-- Execution started --');
  250. $this->logger->info(count($operations) . ' operations pending...');
  251. $done = 0; $errors = 0; $unknown = 0;
  252. $i = 0; $total = count($operations);
  253. foreach ($operations as $operation) {
  254. if ($operation->getStatus() !== BaseRestOperation::STATUS_READY) {
  255. // operation has already been treated
  256. $this->logger->warning('Tried to execute an operation that was not marked as ready : ' . $operation);
  257. continue;
  258. }
  259. $operation->execute($this->dolibarrApiService);
  260. if ($operation->getStatus() === BaseRestOperation::STATUS_ERROR) {
  261. $this->logger->error('Error while executing operation : ' . $operation);
  262. $this->logger->error(implode("\n", $operation->getChangeLog()));
  263. $this->logger->error($operation->getErrorMessage());
  264. $errors++;
  265. } elseif ($operation->getStatus() === BaseRestOperation::STATUS_DONE) {
  266. $done++;
  267. } else {
  268. $unknown++;
  269. }
  270. $i++;
  271. if ($progressionCallback !== null) {
  272. $progressionCallback($i, $total);
  273. }
  274. }
  275. $this->logger->info('Execution ended');
  276. $this->logger->info('Done : ' . $done);
  277. $this->logger->info('Errors : ' . $errors);
  278. if ($unknown > 0)
  279. $this->logger->warning('Unknown : ' . $unknown);
  280. return $operations;
  281. }
  282. /**
  283. * Scan and execute the sync process
  284. *
  285. * @return array<BaseRestOperation>
  286. * @throws HttpException
  287. * @throws Exception
  288. */
  289. public function run(): array
  290. {
  291. $operations = $this->scan();
  292. $this->execute($operations);
  293. return $operations;
  294. }
  295. /**
  296. * Get the client societies dolibarr and index them by organization id
  297. *
  298. * @return array An index of the form [$organizationId => $dolibarrData]
  299. */
  300. protected function getDolibarrSocietiesIndex(): array
  301. {
  302. $index = [];
  303. foreach ($this->dolibarrApiService->getAllClients() as $clientData) {
  304. $organizationId = $clientData["array_options"]["options_2iopen_organization_id"] ?? null;
  305. if (!$organizationId > 0) {
  306. $this->logger->warning(
  307. 'Dolibarr client has no organization id: ' .
  308. $clientData['name'] . ' (' . $clientData['id'] . ')'
  309. );
  310. continue;
  311. }
  312. $index[$organizationId] = $clientData;
  313. }
  314. return $index;
  315. }
  316. /**
  317. * Get the dolibarr contacts of the society and index them by person_id
  318. *
  319. * @return array An index of the form [$personId => $dolibarrData]
  320. */
  321. protected function getDolibarrContactsIndex(int $socId): array {
  322. $index = [];
  323. $contacts = $this->dolibarrApiService->getOpentalentContacts($socId);
  324. foreach ($contacts as $contactData) {
  325. $personId = intval($contactData["array_options"]["options_2iopen_person_id"]);
  326. $index[$personId] = $contactData;
  327. }
  328. return $index;
  329. }
  330. /**
  331. * Returns an index of all the active members with their current mission(s)
  332. *
  333. * Index is the form: [$organizationId => [$accessId => [$mission, $mission...], $accessId...], $organizationId2...]
  334. *
  335. * @return array
  336. */
  337. protected function getActiveMembersIndex(): array {
  338. $index = [];
  339. $results = $this->accessRepository->getAllActiveMembersAndMissions();
  340. foreach ($results as $row) {
  341. $accessId = $row['id'];
  342. $organizationId = $row['organization_id'];
  343. $mission = $row['mission'];
  344. if (!array_key_exists($organizationId, $index)) {
  345. $index[$organizationId] = [];
  346. }
  347. if (!array_key_exists($accessId, $index[$organizationId])) {
  348. $index[$organizationId][$accessId] = [];
  349. }
  350. $index[$organizationId][$accessId][] = $mission;
  351. }
  352. return $index;
  353. }
  354. /**
  355. * Because for some fields the dolibarr api returns empty strings even when field is null in DB,
  356. * we have to post-process it to avoid unnecessary and endless update operations
  357. *
  358. * As far as we know, there is no harm here to replace every empty string value by a null value
  359. * (no loss of information)
  360. *
  361. * @param array|null $data
  362. * @return array|null
  363. */
  364. protected static function sanitizeDolibarrData(?array $data): ?array {
  365. if ($data === null)
  366. return null;
  367. foreach ($data as $field => $value) {
  368. if (is_array($value)) {
  369. $data[$field] = self::sanitizeDolibarrData($value);
  370. } else {
  371. if ($value === '') {
  372. $data[$field] = null;
  373. }
  374. }
  375. }
  376. return $data;
  377. }
  378. /**
  379. * Retrieve the postal address of the organization
  380. *
  381. * @param Organization $organization
  382. * @return AddressPostal|null
  383. */
  384. protected function getOrganizationPostalAddress(Organization $organization): ?AddressPostal {
  385. $addressPriorities = [
  386. AddressPostalOrganizationTypeEnum::ADDRESS_BILL()->getValue(),
  387. AddressPostalOrganizationTypeEnum::ADDRESS_CONTACT()->getValue(),
  388. AddressPostalOrganizationTypeEnum::ADDRESS_HEAD_OFFICE()->getValue(),
  389. AddressPostalOrganizationTypeEnum::ADDRESS_PRACTICE()->getValue(),
  390. AddressPostalOrganizationTypeEnum::ADDRESS_OTHER()->getValue()
  391. ];
  392. $organizationAddressPostal = $organization->getOrganizationAddressPostals();
  393. foreach ($addressPriorities as $addressType) {
  394. foreach ($organizationAddressPostal as $postalAddress) {
  395. if ($postalAddress->getType() == $addressType) {
  396. return $postalAddress->getAddressPostal();
  397. }
  398. }
  399. }
  400. return null;
  401. }
  402. /**
  403. * Retrieve the phone for the organization
  404. *
  405. * @param Organization $organization
  406. * @return string|null
  407. */
  408. protected function getOrganizationPhone(Organization $organization): ?string
  409. {
  410. $contactPriorities = [
  411. ContactPointTypeEnum::BILL()->getValue(),
  412. ContactPointTypeEnum::CONTACT()->getValue(),
  413. ContactPointTypeEnum::PRINCIPAL()->getValue(),
  414. ContactPointTypeEnum::OTHER()->getValue()
  415. ];
  416. $contactPoints = $organization->getContactPoints();
  417. foreach ($contactPriorities as $contactType) {
  418. foreach ($contactPoints as $contactPoint) {
  419. if ($contactPoint->getContactType() === $contactType) {
  420. if ($contactPoint->getTelphone() !== null) {
  421. return $this->formatPhoneNumber($contactPoint->getTelphone());
  422. }
  423. if ($contactPoint->getMobilPhone() !== null) {
  424. return $this->formatPhoneNumber($contactPoint->getMobilPhone());
  425. }
  426. }
  427. }
  428. }
  429. return null;
  430. }
  431. /**
  432. * Retrieve the email for the organization
  433. *
  434. * @param Organization $organization
  435. * @return string|null
  436. */
  437. protected function getOrganizationEmail(Organization $organization): ?string {
  438. $contactPriorities = [
  439. ContactPointTypeEnum::BILL()->getValue(),
  440. ContactPointTypeEnum::CONTACT()->getValue(),
  441. ContactPointTypeEnum::PRINCIPAL()->getValue(),
  442. ContactPointTypeEnum::OTHER()->getValue()
  443. ];
  444. $contactPoints = $organization->getContactPoints();
  445. foreach ($contactPriorities as $contactType) {
  446. foreach ($contactPoints as $contactPoint) {
  447. if ($contactPoint->getContactType() == $contactType && $contactPoint->getEmail() !== null) {
  448. return $contactPoint->getEmail();
  449. }
  450. }
  451. }
  452. return null;
  453. }
  454. /**
  455. * Returns the number of accesses possessing at least one of the missions
  456. *
  457. * @param array $missions A list of missions
  458. * @param array $members An organization members as returned by getActiveMembersIndex: [$accessID => [$missions...]]
  459. * @return int
  460. */
  461. protected static function countWithMission(array $missions, array $members): int {
  462. return count(array_filter(
  463. $members,
  464. function ($actualMissions) use ($missions) { return !empty(array_intersect($actualMissions, $missions)); }
  465. ));
  466. }
  467. /**
  468. * Return the best contact point for the given Person, or null if none
  469. *
  470. * @param Person $person
  471. * @return ContactPoint|null
  472. */
  473. protected function getPersonContact(Person $person): ?ContactPoint {
  474. $contactPriorities = [
  475. ContactPointTypeEnum::PRINCIPAL()->getValue(),
  476. ContactPointTypeEnum::OTHER()->getValue()
  477. ];
  478. $contactPoints = $person->getContactPoints();
  479. foreach ($contactPriorities as $contactType) {
  480. foreach ($contactPoints as $contactPoint) {
  481. if ($contactPoint->getContactType() === $contactType) {
  482. return $contactPoint;
  483. }
  484. }
  485. }
  486. return null;
  487. }
  488. /**
  489. * Format the contact position from its gender and missions
  490. *
  491. * @param array $missions
  492. * @param string|null $gender
  493. * @return string
  494. */
  495. protected function formatContactPosition(array $missions, ?string $gender = 'X'): string {
  496. $to_exclude = [
  497. FunctionEnum::ADHERENT()->getValue(),
  498. FunctionEnum::STUDENT()->getValue(),
  499. FunctionEnum::OTHER()->getValue()
  500. ];
  501. $poste = implode(
  502. ', ',
  503. array_map(
  504. function($m) use ($gender) {
  505. return $this->translator->trans(
  506. $m,
  507. ['gender' => [
  508. GenderEnum::MISS()->getValue() => 'F',
  509. GenderEnum::MISTER()->getValue() => 'M'
  510. ][$gender] ?? 'X']
  511. );
  512. },
  513. array_filter(
  514. $missions,
  515. function ($m) use ($to_exclude) {
  516. return !in_array($m, $to_exclude);
  517. }
  518. )
  519. )
  520. );
  521. if (strlen($poste) > 80) {
  522. $poste = mb_substr($poste, 0, 77, "utf-8") . '...';
  523. }
  524. return $poste;
  525. }
  526. /**
  527. * Format a phone number into international format
  528. *
  529. * @param PhoneNumber $phoneNumber
  530. * @return mixed
  531. */
  532. protected static function formatPhoneNumber(PhoneNumber $phoneNumber): string {
  533. $phoneUtil = PhoneNumberUtil::getInstance();
  534. return str_replace(
  535. ' ',
  536. '',
  537. $phoneUtil->format($phoneNumber, PhoneNumberFormat::INTERNATIONAL)
  538. );
  539. }
  540. /**
  541. * Returns an array containing the keys/values from the newData array
  542. * which are absent or different from $initialData
  543. *
  544. * /!\ Sub-arrays shall stay complete and must not be filtered
  545. *
  546. * Because for some fields the dolibarr api returns empty strings even when field is null in DB,
  547. * we have to consider null and empty-string as equals. As far as we know, this causes no loss of information.
  548. *
  549. * @param array $initialData
  550. * @param array $newData
  551. * @return array
  552. */
  553. protected static function filterDiff(array $initialData, array $newData): array
  554. {
  555. $result = [];
  556. foreach ($newData as $field => $value) {
  557. if (
  558. ($value ?? '') !== ($initialData[$field] ?? '') ||
  559. !array_key_exists($field, $initialData)
  560. ) {
  561. $result[$field] = $value;
  562. }
  563. }
  564. return $result;
  565. }
  566. }