|
| 1 | +<?php |
| 2 | + |
| 3 | +namespace Kanboard\Plugin\DatabaseStorage\Command; |
| 4 | + |
| 5 | +use Kanboard\Console\BaseCommand; |
| 6 | +use Kanboard\Core\ObjectStorage\ObjectStorageException; |
| 7 | +use Kanboard\Plugin\DatabaseStorage\DatabaseObjectStorage; |
| 8 | +use RecursiveDirectoryIterator; |
| 9 | +use RecursiveIteratorIterator; |
| 10 | +use Symfony\Component\Console\Helper\Table; |
| 11 | +use Symfony\Component\Console\Input\InputInterface; |
| 12 | +use Symfony\Component\Console\Output\OutputInterface; |
| 13 | + |
| 14 | +class MigrateCommand extends BaseCommand |
| 15 | +{ |
| 16 | + protected function configure() |
| 17 | + { |
| 18 | + $this |
| 19 | + ->setName('db-storage:migrate') |
| 20 | + ->setDescription('Migrate local files to the database'); |
| 21 | + } |
| 22 | + |
| 23 | + protected function execute(InputInterface $input, OutputInterface $output) |
| 24 | + { |
| 25 | + if (! file_exists(FILES_DIR)) { |
| 26 | + $output->writeln('<error>Directory not found: '.FILES_DIR.'</error>'); |
| 27 | + } else { |
| 28 | + $files = new RecursiveIteratorIterator(new RecursiveDirectoryIterator(FILES_DIR), RecursiveIteratorIterator::SELF_FIRST); |
| 29 | + $storage = new DatabaseObjectStorage($this->container['db']);; |
| 30 | + |
| 31 | + foreach($files as $file) { |
| 32 | + if ($file->getFilename(){0} !== '.' && ! $file->isDir()) { |
| 33 | + $key = substr($file->getRealPath(), strlen(FILES_DIR) + 1); |
| 34 | + |
| 35 | + if (! $this->fileExists($storage, $key)) { |
| 36 | + $output->writeln('<info>Migrating '.$file->getFilename().'</info>'); |
| 37 | + $blob = $this->readFile($file->getRealPath()); |
| 38 | + $storage->put($key, $blob); |
| 39 | + } |
| 40 | + } |
| 41 | + } |
| 42 | + } |
| 43 | + } |
| 44 | + |
| 45 | + protected function fileExists(DatabaseObjectStorage $storage, $key) |
| 46 | + { |
| 47 | + try { |
| 48 | + $storage->get($key); |
| 49 | + return true; |
| 50 | + } catch (ObjectStorageException $e) {} |
| 51 | + |
| 52 | + return false; |
| 53 | + } |
| 54 | + |
| 55 | + protected function readFile($filename) |
| 56 | + { |
| 57 | + $handle = fopen($filename, 'rb'); |
| 58 | + $contents = fread($handle, filesize($filename)); |
| 59 | + fclose($handle); |
| 60 | + return $contents; |
| 61 | + } |
| 62 | +} |
0 commit comments