diff --git a/filesystem/Folder.php b/filesystem/Folder.php index 1d987511d..99596e44f 100755 --- a/filesystem/Folder.php +++ b/filesystem/Folder.php @@ -10,6 +10,38 @@ class Folder extends File { static $plural_name = "Folders"; + function populateDefaults() { + parent::populateDefaults(); + + if(!$this->Name) $this->Name = _t('AssetAdmin.NEWFOLDER',"NewFolder"); + } + + function onBeforeWrite() { + // Ensure folders can't contain path information, just a name + $this->Name = basename($this->Name); + + // Get the folder to be created + if($this->ParentID) { + if(!is_numeric($this->ParentID)) $this->ParentID = 0; + $parentObj = DataObject::get_by_id($this->class, $this->ParentID); + } + // TODO Check that the $parentObj matches the ASSETS_PATH + if(isset($parentObj->ID)) $path = $parentObj->FullPath . $this->Name; + else $path = ASSETS_PATH . '/' . $this->Name; + + // Ensure uniqueness + $i = 2; + $basePath = $path . '-'; + while(file_exists($path)) { + $path = $basePath . $i; + $i++; + } + + Filesystem::makeFolder($path); + + parent::onBeforeWrite(); + } + /* * Find the given folder or create it, recursively. * @@ -31,7 +63,7 @@ class Folder extends File { $item->Name = $part; $item->Title = $part; $item->write(); - if(!file_exists($item->getFullPath())) mkdir($item->getFullPath(),Filesystem::$folder_create_mask); + if(!file_exists($item->getFullPath())) Filesystem::makeFolder($item->getFullPath()); } $parentID = $item->ID; } diff --git a/tests/model/FolderTest.php b/tests/model/FolderTest.php new file mode 100644 index 000000000..31711053a --- /dev/null +++ b/tests/model/FolderTest.php @@ -0,0 +1,50 @@ +Name = '__FolderTest'; + $parentFolder->write(); + $this->assertEquals( + $parentFolder->getFullPath(), + ASSETS_PATH . '/' . $parentFolder->Name . '/', + 'Folder record creates matching path on filesystem on first write' + ); + $this->assertFileExists( + $parentFolder->getFullPath(), + 'Folder record without ParentID creates a folder in the $base_dir on filesystem on first write' + ); + + $childFolder = new Folder(); + $childFolder->ParentID = $parentFolder->ID; + $childFolder->Name = 'child'; + $childFolder->write(); + $this->assertEquals( + $childFolder->getFullPath(), + ASSETS_PATH . '/' . $parentFolder->Name . '/' . $childFolder->Name . '/', + 'Folder record creates matching path on filesystem on first write' + ); + $this->assertFileExists( + $childFolder->getFullPath(), + 'Folder record without ParentID creates a folder on filesystem on first write' + ); + } + + function testFolderNameCantDuplicate() { + $folder = new Folder(); + $folder->Name = 'myfolder'; + $folder->write(); + + $folder2 = new Folder(); + $folder2->Name = 'myfolder'; + $folder2->write(); + $this->assertNotEquals( + $folder->Name, + $folder2->Name, + 'Folder write renames to avoid duplicates on filesystem' + ); + } +} +?> \ No newline at end of file