Last active
October 5, 2021 13:48
-
-
Save husseinalhammad/ca0a14d319017b6d77cbb7860f08af4f to your computer and use it in GitHub Desktop.
Perch Import API - find_or_create_collection_item()
This file contains 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 | |
/** | |
* 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