pimcore

Delete all empty folders in Pimcore 10.5 Data Object via PHP


I've a PHP command which reads data from an external source and inserts data in Pimcore 10.5 as Data Objects.

This procedure leaves behind a few empty Pimcore Data Object folder.

Is there a built-in Pimcore procedure to remove all empty folders programmatically or should I just traverse the tree and remove them on my own?


Solution

  • I wrote my own code:

        protected function removeEmptyFolders() : static
        {
            $this->fxTitle("Removing empty folder(s)...");
    
            $oFolders = Folder::getList([
                'condition' => "o_type = 'folder' AND o_parentId > 0"
            ])->load();
    
            $folderNum = count($oFolders);
    
            if( $folderNum == 0 ) {
    
                $this->fxWarning("No folders detected!");
                return $this;
            }
    
            $this->fxInfo("##$folderNum## folder(s) loaded");
    
            $arrFolderByPath = [];
            foreach($oFolders as $folder) {
    
                $path = $folder->getPath() . $folder->getKey() . "/";
                $arrFolderByPath[$path] = $folder;
            }
    
            //
            $oDataObjects = Folder::getList([
                'condition' => "o_parentId > 0"
            ])->load();
    
            foreach($oDataObjects as $folder) {
    
                $path = $folder->getPath();
                if( array_key_exists($path, $arrFolderByPath) && $folder->getId() != $arrFolderByPath[$path]->getId() ) {
                    unset($arrFolderByPath[$path]);
                }
            }
    
            $folderNum = count($arrFolderByPath);
            if( $folderNum == 0 ) {
    
                $this->fxInfo("No empty folders detected");
                return $this;
            }
    
            $this->fxInfo("Deleting ##$folderNum## folder(s)...");
    
            foreach($arrFolderByPath as $folder) {
    
                $deletedFolderTitle = implode(' | ', [$folder->getId(), $folder->getPath(), $folder->getKey()]) . PHP_EOL;
    
                if( $this->isNotDryRun() ) {
                    $folder->delete();
                }
    
                $this->fxOK($deletedFolderTitle);
            }
    
            if( $this->isDryRun() ) {
                // prevent infinite recursion
                return $this;
            }
    
            return $this->removeEmptyFolders();
        }