Skip to content

Instantly share code, notes, and snippets.

@husseinalhammad
Last active October 5, 2021 13:48
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save husseinalhammad/ca0a14d319017b6d77cbb7860f08af4f to your computer and use it in GitHub Desktop.
Save husseinalhammad/ca0a14d319017b6d77cbb7860f08af4f to your computer and use it in GitHub Desktop.
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