summaryrefslogtreecommitdiff
path: root/src/Model/Unit.php
blob: a0d1a357091e3e974653e520181ffb284d83b715 (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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
<?php

namespace App\Model;

use App\DB;
use App\Model;

class Unit
{
  public int $id;

  public int $amount;
  public string $type;
  public bool $isTraveling;

  public int $homeVillageId;
  public int $residenceVillageId;

  public string $createdAt;
  public string $updatedAt;

  public string $buildingType;
  public int $travelTime;
  public int $populationDemandFactor;
  public array $resourceRequirements = [];


  public function getBuildTime(int $amount): int
  {
    return intval(($_ENV['BASE_UNIT_BUILD_TIME_FACTOR'] / ($this->getBuilding()->level ?: 1)) * $amount);
  }

  public function getPopulationDemand(): int
  {
    return $this->getPopulationDemandForAmount($this->amount);
  }

  public function getPopulationDemandForAmount(int $amount): int
  {
    return $amount * $this->populationDemandFactor;
  }


  /* Relations */

  public function getBuilding(): ?Building
  {
    return Village::getBuilding($this->homeVillageId, $this->buildingType);
  }

  public function cast(): Unit
  {
    $class = Unit::resolveType($this->type);

    return Model::castToType($this, Unit::resolveType($this->type));
  }

  public static function resolveType(string $type): string
  {
    return __NAMESPACE__ . '\\Unit\\' . $type;
  }


  /* Static */

  public static function getAmountResiding(string $unitType, int $villageId): int
  {
    $statement = DB::query(
      'select SUM(amount) from village_units where type=:type and residence_village_id=:id',
      ['type' => $unitType, 'id' => $villageId]
    );
    $result = $statement->fetch()['sum'];

    return intval($result);
  }

}