|
2 | 2 |
|
3 | 3 | namespace Drupal\hetzner_api\Controller; |
4 | 4 |
|
5 | | -class HetznerController { |
6 | | - // Controller logic here |
| 5 | +use Drupal\Core\Controller\ControllerBase; |
| 6 | +use Symfony\Component\DependencyInjection\ContainerInterface; |
| 7 | +use Symfony\Component\HttpFoundation\Request; |
| 8 | +use Drupal\hetzner_api\Service\HetznerApiService; |
| 9 | + |
| 10 | +class HetznerController extends ControllerBase { |
| 11 | + |
| 12 | + protected $hetznerService; |
| 13 | + |
| 14 | + public function __construct(HetznerApiService $hetznerService) { |
| 15 | + $this->hetznerService = $hetznerService; |
| 16 | + } |
| 17 | + |
| 18 | + public static function create(ContainerInterface $container) { |
| 19 | + return new static( |
| 20 | + $container->get('hetzner_api.api') |
| 21 | + ); |
| 22 | + } |
| 23 | + |
| 24 | + /** |
| 25 | + * Route: /hetzner/servers |
| 26 | + */ |
| 27 | + public function getServers(Request $request = NULL) { |
| 28 | + $force = $request && $request->query->get('refresh') === '1'; |
| 29 | + $servers = $this->hetznerService->getServers($force); |
| 30 | + |
| 31 | + $header = ['Name', 'Status', 'IPv4', 'Created']; |
| 32 | + $rows = []; |
| 33 | + |
| 34 | + foreach ($servers as $server) { |
| 35 | + $status = ucfirst($server['status']); |
| 36 | + $color = $server['status'] === 'running' ? 'green' : 'red'; |
| 37 | + |
| 38 | + $rows[] = [ |
| 39 | + $server['name'], |
| 40 | + ['data' => $status, 'style' => "color:$color;font-weight:bold"], |
| 41 | + $server['public_net']['ipv4']['ip'] ?? '—', |
| 42 | + date('Y-m-d H:i', strtotime($server['created'])), |
| 43 | + ]; |
| 44 | + } |
| 45 | + |
| 46 | + return [ |
| 47 | + '#type' => 'table', |
| 48 | + '#header' => $header, |
| 49 | + '#rows' => $rows, |
| 50 | + '#attributes' => ['id' => 'hetzner-server-table'], |
| 51 | + '#attached' => [ |
| 52 | + 'library' => ['hetzner_api/refresh'], |
| 53 | + ], |
| 54 | + ]; |
| 55 | + } |
| 56 | + |
| 57 | + /** |
| 58 | + * Admin sync route: /admin/config/services/hetzner-api/sync |
| 59 | + */ |
| 60 | + public function manualSync() { |
| 61 | + $count = $this->hetznerService->syncServersToNodes(TRUE); |
| 62 | + $this->messenger()->addStatus($this->t('Synkroniseret @count server(e) fra Hetzner.', ['@count' => $count])); |
| 63 | + return $this->redirect('system.admin_config_services'); |
| 64 | + } |
| 65 | + |
7 | 66 | } |
| 67 | + |
0 commit comments