Skip to content

Instantly share code, notes, and snippets.

@sepiariver
Last active April 1, 2019 14:21
Show Gist options
  • Save sepiariver/684e1fcd5c47a99c40b4d6f6e8c81a4d to your computer and use it in GitHub Desktop.
Save sepiariver/684e1fcd5c47a99c40b4d6f6e8c81a4d to your computer and use it in GitHub Desktop.
Imports a JSON file as output from the sample_json_export.php script.
<?php
// Only run via SSH
if (PHP_SAPI !== 'cli') exit();
// Instantiate MODX
@include(dirname(__FILE__) . '/config.core.php');
if (!defined('MODX_CORE_PATH')) define('MODX_CORE_PATH', dirname(__FILE__) . '/core/');
include_once (MODX_CORE_PATH . "model/modx/modx.class.php");
$modx= new modX();
$modx->initialize('web');
// If we can't find a Resource matching the import criteria, do we create a new Resource?
$createOnFail = false;
// Import file
$importPath = dirname(__FILE__);
$importFilename = 'export.json';
$import = file_get_contents($importPath . '/' . $importFilename);
if (!$import) {
echo "Failed to get import file.";
exit();
}
$import = $modx->fromJSON($import);
if (!is_array($import)) {
echo "Bad import data";
exit();
}
// Allowed object classes
$allowed = array(
'modResource' => 1,
'modSnippet' => 1,
'modPlugin' => 1,
'modChunk' => 1,
'modTemplate' => 1,
);
// Iterate over classes
foreach ($import as $class => $items) {
// Check class
if (!isset($allowed[$class]) || !$allowed[$class] || !is_array($items)) continue;
// Start counting
$total = 0;
$success = 0;
$fail = 0;
$skipped = 0;
// Iterate over class members
foreach ($items as $item) {
$total++;
// required elements
if (!isset($item['where'], $item['object'])) {
$skipped++;
continue;
}
// special case for "create" action
if ($item['where'] === false) {
// create new object
$object = $modx->newObject($class);
if (!$object) {
$failed++;
continue;
}
// populate with values
$object->fromArray($item['object']);
// attempt to save
// ** BEWARE of collisions on unique fields **
if ($object->save()) {
$success++;
} else {
$fail++;
}
} elseif (is_array($item['where'])) {
// fetch existing object
// hopefully you double-checked your query criteria to ensure you found the correct object!
$object = $modx->getObject($class, $item['where']);
// if we didn't find it, we either create a new one or skip this one
if (!$object) {
if (!$createOnFail) {
$failed++;
continue;
} else {
$object = $modx->newObject($class);
if (!$object) {
$failed++;
continue;
}
}
}
// populate with values
$object->fromArray($item['object']);
// attempt to save
if ($object->save()) {
$success++;
} else {
$fail++;
}
} else {
$skipped++;
continue;
}
}
// primitive reporting
echo $success . ' succeeded, ' . $fail . ' failed, and ' . $skipped . ' skipped out of total ' . $total . ' ' . $class . '<br>' . PHP_EOL;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment