summaryrefslogtreecommitdiff
path: root/src/Controller/Building.php
blob: d8fe65677e4a6b606f1bb397276b0e87ac6ff4f1 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
<?php

namespace App\Controller;

use App\DB;
use App\Model\Building as Model;
use App\Model\Event;
use App\Model\Village;
use App\Router;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;

class Building
{
  #[Route(path: '/village/{x}/{y}/building/{type}/level-up', methods: ['POST'])]
  public function levelUp(Request $request): Response
  {
    $village = Village::getByCoordinates($request->get('x'), $request->get('y'));
    $building = Model::getByVillage($village->id, $request->get('type'));

    // resources
    foreach ($building->getResourceRequirements() as $resourceType => $resourceValue) {
      $village->{$resourceType} -= $resourceValue;
    }
    $village->updateResources();

    // event
    $event = new Event();
    $event->type = 'UpgradeBuilding';
    $event->time = (new \DateTime())->add(\DateInterval::createFromDateString($building->getBuildTime() . ' seconds'));
    $event->payload = json_encode([
      'id' => $building->id,
    ]);

    DB::query(
      'insert into events (type, time, payload, village_id) VALUES (:type, :time, :payload, :id)',
      ['type' => $event->type, 'time' => $event->time->format('c'), 'payload' => $event->payload, 'id' => $village->id]
    );

    return new RedirectResponse(
      Router::generate(
        'village.show',
        ['x' => $request->get('x'), 'y' => $request->get('y')]
      )
    );
  }
}