SnippetProvider.php 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. <?php
  2. namespace ModulesGarden\ProxmoxAddon\App\Providers;
  3. use ModulesGarden\ProxmoxAddon\App\Models\Snippet;
  4. use ModulesGarden\ProxmoxAddon\App\Repositories\ServerConfigurationRepository;
  5. use phpseclib3\Net\SSH2;
  6. class SnippetProvider
  7. {
  8. /**
  9. * @var SSH2
  10. */
  11. protected $ssh;
  12. protected $lastResponse;
  13. /**
  14. * SnippetProvider constructor.
  15. * @param SSH2 $ssh
  16. * @param ServerConfigurationRepository $cerverConfiguration
  17. */
  18. public function __construct(SSH2 $ssh)
  19. {
  20. $this->ssh = $ssh;
  21. }
  22. public function create(Snippet $snippet){
  23. if($this->exists($snippet)){
  24. throw new \Exception(sprintf("File already exist: %s",$snippet->getFileDirectory()));
  25. }
  26. $this->lastResponse = $this->ssh->exec(sprintf("echo '%s' > %s", $snippet->getContent(), $snippet->getFileDirectory()));
  27. }
  28. /**
  29. * @param Snippet $snippet
  30. * @return bool
  31. * @example ls /var/lib/vz/snippets/userconfig.yaml
  32. */
  33. public function exists(Snippet $snippet){
  34. $this->lastResponse = $this->ssh->exec(sprintf("ls %s", $snippet->getFileDirectory()) );
  35. $response = str_replace(["\r", "\n"],["",""],$this->lastResponse );
  36. return $response == $snippet->getFileDirectory() ;
  37. }
  38. public function delete(Snippet $snippet){
  39. $this->lastResponse = $this->ssh->exec(sprintf("rm %s", $snippet->getFileDirectory()) );
  40. if(preg_match("/cannot remove/",$this->lastResponse)){
  41. throw new \Exception($this->lastResponse);
  42. }
  43. }
  44. }