Backup.php 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. <?php
  2. /**
  3. * Copyright © 2013-2017 Magento, Inc. All rights reserved.
  4. * See COPYING.txt for license details.
  5. */
  6. namespace Magento\Update;
  7. use Magento\Update\Backup\BackupInfo;
  8. use Magento\Update\Status;
  9. /**
  10. * Class for creating Magento codebase backups.
  11. */
  12. class Backup
  13. {
  14. /**
  15. * @var BackupInfo
  16. */
  17. protected $backupInfo;
  18. /**
  19. * @var Status
  20. */
  21. protected $status;
  22. /**
  23. * Initialize dependencies.
  24. *
  25. * @param BackupInfo|null $backupInfo
  26. * @param Status|null $status
  27. */
  28. public function __construct(BackupInfo $backupInfo = null, Status $status = null)
  29. {
  30. $this->backupInfo = $backupInfo ? $backupInfo : new BackupInfo();
  31. $this->status = $status ? $status : new Status();
  32. }
  33. /**
  34. * Create backup archive using unix zip tool.
  35. *
  36. * @return $this
  37. * @throws \RuntimeException
  38. */
  39. public function execute()
  40. {
  41. $backupFilePath = $this->backupInfo->getBackupPath() . $this->backupInfo->generateBackupFilename();
  42. $command = $this->buildShellCommand($backupFilePath);
  43. $this->status->add(sprintf('Creating backup archive "%s" ...', $backupFilePath), \Psr\Log\LogLevel::INFO);
  44. exec($command, $output, $return);
  45. if ($return) {
  46. throw new \RuntimeException(
  47. sprintf('Cannot create backup with command "%s": %s', $command, implode("\n", $output),
  48. \Psr\Log\LogLevel::ERROR
  49. )
  50. );
  51. }
  52. $this->status->add(sprintf('Backup archive "%s" has been created.', $backupFilePath), \Psr\Log\LogLevel::INFO);
  53. return $this;
  54. }
  55. /**
  56. * Construct shell command for creating backup archive.
  57. *
  58. * @param string $backupFilePath
  59. * @return string
  60. */
  61. protected function buildShellCommand($backupFilePath)
  62. {
  63. $excludedElements = '';
  64. foreach ($this->backupInfo->getBlacklist() as $excludedElement) {
  65. $elementPath = $excludedElement;
  66. $fullPath = $this->backupInfo->getArchivedDirectory() . '/' . $elementPath;
  67. $excludedElements .= is_dir($fullPath) ? $elementPath . '\* ' : $elementPath . ' ';
  68. }
  69. $changeDirectoryCommand = sprintf("cd %s", $this->backupInfo->getArchivedDirectory());
  70. $zipCommand = sprintf("zip -r %s . -x %s", $backupFilePath, $excludedElements);
  71. return $changeDirectoryCommand . ' && ' . $zipCommand;
  72. }
  73. }