Last active
July 16, 2019 20:11
-
-
Save colemanw/36733cd098cc7517e6b8f056bd5d3a75 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* Trait mixed into BAOs who support bulk-save operations | |
*/ | |
trait CRM_Core_BulkSaveTrait { | |
/** | |
* @param $params | |
* @return CRM_Core_DAO|NULL | |
*/ | |
public static function create($params) { | |
$baoName = static::class; | |
$method = empty($params['id']) ? '_bulkCreateObjects' : '_bulkUpdateObjects'; | |
$result = self::$method($baoName, [$params]); | |
$obj = NULL; | |
if (!empty($result[0])) { | |
$obj = new static(); | |
$obj->copyValues($result[0]); | |
} | |
return $obj; | |
} | |
/** | |
* @param $items | |
* @param array $defaults | |
* @param bool $reload | |
* @return array[] | |
*/ | |
public static function bulkSave($items, $defaults = [], $reload = FALSE) { | |
return self::_bulkSaveObjects(static::class, $items, $defaults); | |
} | |
/** | |
* @param CRM_Core_DAO|string $baoName | |
* @param array $items | |
* @param array $defaults | |
* @param bool $reload | |
* @return array[] | |
*/ | |
public static function _bulkSaveObjects($baoName, $items, $defaults = [], $reload = FALSE) { | |
$toCreate = $toUpdate = $result = []; | |
foreach ($items as $item) { | |
if (empty($item['id'])) { | |
$toCreate[] = $item + (array) $defaults; | |
} | |
else { | |
$toUpdate[$item['id']] = $item + (array) $defaults; | |
} | |
} | |
if ($toCreate) { | |
$result = self::_bulkCreateObjects($baoName, $toCreate); | |
} | |
if ($toUpdate) { | |
$result = array_merge($result, self::_bulkUpdateObjects($baoName, $toUpdate, $reload)); | |
} | |
return $result; | |
} | |
/** | |
* @param CRM_Core_DAO|string $baoName | |
* @param array $items | |
* @return array[] | |
*/ | |
public static function _bulkCreateObjects($baoName, $items) { | |
$fields = $baoName::fields(); | |
$result = []; | |
// TODO: | |
// - Call pre hooks for each item | |
// - Compose efficient INSERT query & execute | |
// - Save custom data | |
// - Call post hooks | |
return $result; | |
} | |
/** | |
* @param CRM_Core_DAO|string $baoName | |
* @param array $items | |
* @param bool $reload | |
* @return array[] | |
*/ | |
public static function _bulkUpdateObjects($baoName, $items, $reload) { | |
// TODO: I don't think there IS a way to do a mass-update in mySql so I guess we'll just | |
// - Loop through items, foreach: | |
// - Call pre-hook | |
// - Do a SQL UPDATE | |
// - Save custom data | |
// - Call post-hook | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
See https://lab.civicrm.org/dev/core/issues/1093