public function moveDir(string $cabin, string $root, string $subdirectory, array $post = []) : bool
{
$this->db->beginTransaction();
// Get the directory IDs...
$dir = empty($root) ? $subdirectory : $root . '/' . $subdirectory;
$nc = empty($root) ? $post['new_dir'] : $root . '/' . $post['new_dir'];
try {
if (empty($dir)) {
$dirId = null;
} else {
$dirId = $this->getDirectoryId(\Airship\chunk($dir), $cabin);
}
if (empty($nc)) {
$newDir = null;
} else {
$newDir = $this->getDirectoryId(\Airship\chunk($nc), $cabin);
}
} catch (FileNotFound $ex) {
$this->db->rollBack();
return false;
}
// Grab some facts about the existing directory
$oldParent = $this->db->cell('SELECT parent FROM airship_dirs WHERE directoryid = ?', $dirId);
$dirName = $this->db->cell('SELECT name FROM airship_dirs WHERE directoryid = ?', $dirId);
// Did we move directories?
if ($oldParent !== $newDir) {
// Detect collisions then update if there are none
if ($newDir) {
$exists = $this->db->exists('SELECT
count(*)
FROM
airship_dirs
WHERE
parent = ?
AND name = ?
AND directoryid != ?', $newDir, $post['new_name'], $dirId);
if ($exists) {
// There's already a directory here with the same name
$this->db->rollBack();
return false;
}
// Let's move it and, optionally, change the name too
$this->db->update('airship_dirs', ['parent' => $newDir, 'name' => $post['new_name']], ['directoryid' => $dirId]);
} else {
$exists = $this->db->exists('SELECT
count(*)
FROM
airship_dirs
WHERE
parent IS NULL
AND cabin = ?
AND name = ?
AND directoryid != ?', $cabin, $post['new_name'], $dirId);
if ($exists) {
// There's already a directory here with the same name
$this->db->rollBack();
return false;
}
// Let's move it and, optionally, change the name too
$this->db->update('airship_dirs', ['parent' => null, 'name' => $post['new_name']], ['directoryid' => $dirId]);
}
} elseif ($post['new_name'] !== $dirName) {
// Detect name collisions
if ($newDir) {
$exists = $this->db->exists('SELECT
count(*)
FROM
airship_dirs
WHERE
parent = ?
AND name = ?
AND directoryid != ?', $newDir, $post['new_name'], $dirId);
} else {
$exists = $this->db->exists('SELECT
count(*)
FROM
airship_dirs
WHERE
parent IS NULL
AND cabin = ?
AND name = ?
AND directoryid != ?', $cabin, $post['new_name'], $dirId);
}
if ($exists) {
// There's already a directory here with the same name
$this->db->rollBack();
return false;
}
// Change the name
$this->db->update('airship_dirs', ['name' => $post['new_name']], ['directoryid' => $dirId]);
} else {
// Nothing was changed!
$this->db->rollBack();
return false;
}
return $this->db->commit();
}