goliath/src/Controllers/TicketController.php

103 lines
3.1 KiB
PHP

<?php
namespace BitGoblin\Goliath\Controllers;
use Psr\Http\Message\ResponseInterface as Response;
use Psr\Http\Message\ServerRequestInterface as Request;
use Slim\Routing\RouteContext;
use Slim\Views\Twig;
use BitGoblin\Goliath\Models\Ticket;
class TicketController extends Controller {
public function getView(Request $request, Response $response, array $args): Response {
$ticket = Ticket::where('id', $args['ticket_id'])->first();
$view = Twig::fromRequest($request);
return $view->render($response, 'ticket/view.twig', [
'ticket' => $ticket,
]);
}
public function getCreate(Request $request, Response $response): Response {
$view = Twig::fromRequest($request);
return $view->render($response, 'ticket/create.twig');
}
public function postCreate(Request $request, Response $response): Response {
$params = (array)$request->getParsedBody();
$ticket = new Ticket;
$ticket->title = $params['ticket_title'];
$ticket->body = $params['ticket_body'];
$ticket->severity = $params['ticket_severity'];
$ticket->due_at = $params['ticket_due'];
$ticket->save();
// redirect the user back to the home page
return $response
->withHeader('Location', '/')
->withStatus(302);
}
public function getEdit(Request $request, Response $response, array $args): Response {
$ticket = Ticket::where('id', $args['ticket_id'])->get();
$view = Twig::fromRequest($request);
return $view->render($response, 'ticket/edit.twig', [
'ticket' => $ticket[0],
]);
}
public function postEdit(Request $request, Response $response, array $args): Response {
$ticket = Ticket::where('id', $args['ticket_id'])->first();
$params = (array)$request->getParsedBody();
$ticket->title = $params['ticket_title'];
$ticket->body = $params['ticket_body'];
$ticket->severity = $params['ticket_severity'];
$ticket->due_at = $params['ticket_due'];
$ticket->save();
// redirect the user back to the home page
$routeContext = RouteContext::fromRequest($request);
$routeParser = $routeContext->getRouteParser();
return $response
->withHeader('Location', $routeParser->urlFor('ticket.view', ['ticket_id' => $ticket->id]))
->withStatus(302);
}
public function postEditAttr(Request $request, Response $response, array $args): Response {
// grab ticket from database
$ticket = Ticket::where('id', $args['ticket_id'])->first();
// edit the specified attribute
$params = (array)$request->getParsedBody();
$attr = $args['attr'];
$ticket->$attr = $params[$attr];
// save updated ticket
$ticket->save();
// return a response
$response->getBody()->write(json_encode([
'result' => 'success',
'updated_at' => $ticket->formatUpdatedAt(),
]));
return $response;
}
public function getDelete(Request $request, Response $response, array $args): Response {
$ticket = Ticket::where('id', $args['ticket_id'])->first();
$ticket->delete();
return $response
->withHeader('Location', '/')
->withStatus(302);
}
}