Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Perch Import API - find_or_create_collection_item()
<?php
/**
* Find a Collection Item by a field. If not exists, create new.
*
* @param string $collectionKey
* @param string $template
* @param array $field $field = ['id' => '', 'value' => '']
* @param array $data
* @param boolean $return_item set to true to return item instead of _id
*
*/
function find_or_create_collection_item($collectionKey, $template, $field, $data = [], $return_item = false) {
$ImporterAPI = new PerchAPI(1.0, 'my_importer');
$Importer = $ImporterAPI->get('CollectionImporter');
$Template = $ImporterAPI->get('Template');
$Importer->set_collection($collectionKey);
$Template->set($template, 'content');
$Importer->set_template($Template);
$items = $Importer->find_items([
'filter' => $field['id'],
'value' => $field['value'],
]);
if (count($items)) {
// found existing
foreach($items as $item) {
if($return_item) {
return $item;
} else {
return $item['_id'];
}
}
} elseif(is_array($data) && !empty($data)) {
// new item
try {
return $Importer->add_item($data);
} catch (Exception $e) {
die('Error: '.$e->getMessage());
}
}
return false;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.