diff --git a/composer.json b/composer.json
index 875d4bd8..b73c725d 100644
--- a/composer.json
+++ b/composer.json
@@ -29,7 +29,8 @@
"erusev/parsedown-extra": "^0.8.1",
"nette/caching": "^3.0",
"illuminate/database": "^8.61",
- "illuminate/events": "^8.61"
+ "illuminate/events": "^8.61",
+ "spatie/data-transfer-object": "^3.7"
},
"autoload": {
"psr-4": {
diff --git a/composer.lock b/composer.lock
index 1679a960..251400a7 100644
--- a/composer.lock
+++ b/composer.lock
@@ -4,7 +4,7 @@
"Read more about it at https://getcomposer.org/doc/01-basic-usage.md#installing-dependencies",
"This file is @generated automatically"
],
- "content-hash": "94cfbcb22b9f475e421ad5009391006f",
+ "content-hash": "1983b89436fd8017db508592ddf542e4",
"packages": [
{
"name": "brandonwamboldt/utilphp",
@@ -2636,6 +2636,69 @@
},
"time": "2021-06-29T04:31:23+00:00"
},
+ {
+ "name": "spatie/data-transfer-object",
+ "version": "3.7.3",
+ "source": {
+ "type": "git",
+ "url": "https://github.com/spatie/data-transfer-object.git",
+ "reference": "341f72c77e0fce40ea2e0dcb212cb54dc27bbe72"
+ },
+ "dist": {
+ "type": "zip",
+ "url": "https://api.github.com/repos/spatie/data-transfer-object/zipball/341f72c77e0fce40ea2e0dcb212cb54dc27bbe72",
+ "reference": "341f72c77e0fce40ea2e0dcb212cb54dc27bbe72",
+ "shasum": ""
+ },
+ "require": {
+ "php": "^8.0"
+ },
+ "require-dev": {
+ "illuminate/collections": "^8.36",
+ "jetbrains/phpstorm-attributes": "^1.0",
+ "larapack/dd": "^1.1",
+ "phpunit/phpunit": "^9.0"
+ },
+ "type": "library",
+ "autoload": {
+ "psr-4": {
+ "Spatie\\DataTransferObject\\": "src"
+ }
+ },
+ "notification-url": "https://packagist.org/downloads/",
+ "license": [
+ "MIT"
+ ],
+ "authors": [
+ {
+ "name": "Brent Roose",
+ "email": "brent@spatie.be",
+ "homepage": "https://spatie.be",
+ "role": "Developer"
+ }
+ ],
+ "description": "Data transfer objects with batteries included",
+ "homepage": "https://github.com/spatie/data-transfer-object",
+ "keywords": [
+ "data-transfer-object",
+ "spatie"
+ ],
+ "support": {
+ "issues": "https://github.com/spatie/data-transfer-object/issues",
+ "source": "https://github.com/spatie/data-transfer-object/tree/3.7.3"
+ },
+ "funding": [
+ {
+ "url": "https://spatie.be/open-source/support-us",
+ "type": "custom"
+ },
+ {
+ "url": "https://github.com/spatie",
+ "type": "github"
+ }
+ ],
+ "time": "2021-12-30T20:31:10+00:00"
+ },
{
"name": "symfony/console",
"version": "v5.3.10",
diff --git a/hwe/_admin2.php b/hwe/_admin2.php
index 87b2bb2b..2ccb1358 100644
--- a/hwe/_admin2.php
+++ b/hwe/_admin2.php
@@ -59,10 +59,10 @@ $db = DB::db();
if ($general['block'] > 0) {
$style .= "background-color:red;";
}
- if ($general['npc'] >= 2) {
- $style .= "color:cyan;";
- } elseif ($general['npc'] == 1) {
- $style .= "color:skyblue;";
+
+ $npcColor = getNPCColor($general['npc']);
+ if($npcColor !== null){
+ $style .= "color:{$npcColor};";
}
echo "
diff --git a/hwe/_admin4.php b/hwe/_admin4.php
index 2ef4c18f..39795c54 100644
--- a/hwe/_admin4.php
+++ b/hwe/_admin4.php
@@ -70,13 +70,10 @@ function colorBlockedName($general)
if ($general['block'] > 0) {
$style .= "background-color:red;";
}
- if ($general['npc'] >= 2) {
- $style .= "color:cyan;";
- } elseif ($general['npc'] == 1) {
- $style .= "color:skyblue;";
- }
- if ($general['con'] > $conlimit) {
- $style .= "color:red;";
+
+ $npcColor = getNPCColor($general['npc']);
+ if($npcColor !== null){
+ $style .= "color:{$npcColor};";
}
echo "
diff --git a/hwe/a_genList.php b/hwe/a_genList.php
index b83e4e3b..750c1da5 100644
--- a/hwe/a_genList.php
+++ b/hwe/a_genList.php
@@ -155,13 +155,7 @@ if ($gameStor->isunited) {
- if ($general['npc'] >= 2) {
- $name = "{$general['name']} ";
- } elseif ($general['npc'] == 1) {
- $name = "{$general['name']} ";
- } else {
- $name = "{$general['name']}";
- }
+ $name = formatName($general['name'], $general['npc']);
if (key_exists($general['owner'], $ownerNameList)) {
$name = $name . '(' . $ownerNameList[$general['owner']] . ') ';
diff --git a/hwe/a_kingdomList.php b/hwe/a_kingdomList.php
index 38a38a89..3c3f2e43 100644
--- a/hwe/a_kingdomList.php
+++ b/hwe/a_kingdomList.php
@@ -10,7 +10,7 @@ $userID = Session::getUserID();
$db = DB::db();
$gameStor = KVStorage::getStorage($db, 'game_env');
-
+$gameStor->cacheValues(['killturn', 'autorun_user', 'turnterm']);
increaseRefresh("세력일람", 2);
$me = $db->queryFirstRow('SELECT con, turntime FROM general WHERE owner=%i', $userID);
@@ -33,6 +33,7 @@ if ($con >= 2) {
= WebUtil::printCSS('../d_shared/common.css') ?>
= WebUtil::printDist('ts', ['common', 'extKingdoms']) ?>
+ = WebUtil::printStaticValues($gameStor->getValues(['killturn', 'autorun_user', 'turnterm'])) ?>
@@ -144,13 +145,7 @@ if ($con >= 2) {
장수 일람 : ";
foreach ($generals as $general) {
- if ($general['npc'] >= 2) {
- echo "{$general['name']} , ";
- } elseif ($general['npc'] == 1) {
- echo "{$general['name']} , ";
- } else {
- echo "{$general['name']}, ";
- }
+ echo formatName($general['name'], $general['npc']).', ';
}
echo "
diff --git a/hwe/b_betting.php b/hwe/b_betting.php
index 70285953..bbf065df 100644
--- a/hwe/b_betting.php
+++ b/hwe/b_betting.php
@@ -69,7 +69,7 @@ $str2 = getTournamentTime();
if ($str2) {
$str2 = ', ' . $str2;
}
-$str3 = getTournamentTerm();
+$str3 = getTournamentTermText();
if ($str3) {
$str3 = ', ' . $str3;
}
@@ -132,11 +132,8 @@ if ($str3) {
if ($general['name'] == "") {
$general['name'] = "-";
}
- if ($general['npc'] >= 2) {
- $general['name'] = "" . $general['name'] . " ";
- } elseif ($general['npc'] == 1) {
- $general['name'] = "" . $general['name'] . " ";
- }
+
+ $general['name'] = formatName($general['name'], $general['npc']);
echo "{$general['name']} ";
}
@@ -162,11 +159,7 @@ if ($str3) {
if ($general['name'] == "") {
$general['name'] = "-";
}
- if ($general['npc'] >= 2) {
- $general['name'] = "" . $general['name'] . " ";
- } elseif ($general['npc'] == 1) {
- $general['name'] = "" . $general['name'] . " ";
- }
+ $general['name'] = formatName($general['name'], $general['npc']);
if ($general['win'] > 0) {
$line[$i] = "";
$cent[intdiv($i, 2)] = "";
@@ -208,11 +201,7 @@ if ($str3) {
if ($general['name'] == "") {
$general['name'] = "-";
}
- if ($general['npc'] >= 2) {
- $general['name'] = "" . $general['name'] . " ";
- } elseif ($general['npc'] == 1) {
- $general['name'] = "" . $general['name'] . " ";
- }
+ $general['name'] = formatName($general['name'], $general['npc']);
if ($general['win'] > 0) {
$line[$i] = "";
$cent[intdiv($i, 2)] = "";
@@ -254,11 +243,7 @@ if ($str3) {
if ($general['name'] == "") {
$general['name'] = "-";
}
- if ($general['npc'] >= 2) {
- $general['name'] = "" . $general['name'] . " ";
- } elseif ($general['npc'] == 1) {
- $general['name'] = "" . $general['name'] . " ";
- }
+ $general['name'] = formatName($general['name'], $general['npc']);
if ($general['win'] > 0) {
$line[$i] = "";
$cent[intdiv($i, 2)] = "";
@@ -300,11 +285,7 @@ if ($str3) {
if ($general['name'] == "") {
$general['name'] = "-";
}
- if ($general['npc'] >= 2) {
- $general['name'] = "" . $general['name'] . " ";
- } elseif ($general['npc'] == 1) {
- $general['name'] = "" . $general['name'] . " ";
- }
+ $general['name'] = formatName($general['name'], $general['npc']);
if ($general['win'] > 0) {
$line[$i] = "";
$cent[intdiv($i, 2)] = "";
diff --git a/hwe/b_myGenInfo.php b/hwe/b_myGenInfo.php
index 015559e7..8d2a6c7d 100644
--- a/hwe/b_myGenInfo.php
+++ b/hwe/b_myGenInfo.php
@@ -146,13 +146,7 @@ if ($gameStor->isunited) {
$intel = "{$general['intel']}";
}
- if ($general['npc'] >= 2) {
- $name = "{$general['name']} ";
- } elseif ($general['npc'] == 1) {
- $name = "{$general['name']} ";
- } else {
- $name = "{$general['name']}";
- }
+ $name = formatName($general['name'], $general['npc']);
if (key_exists($general['owner'], $ownerNameList)) {
$name = $name . '(' . $ownerNameList[$general['owner']] . ') ';
diff --git a/hwe/b_tournament.php b/hwe/b_tournament.php
index cb4bc0d6..a174cbfc 100644
--- a/hwe/b_tournament.php
+++ b/hwe/b_tournament.php
@@ -198,7 +198,7 @@ switch ($admin['tnmt_type']) {
if ($str2) {
$str2 = ', ' . $str2;
}
- $str3 = getTournamentTerm();
+ $str3 = getTournamentTermText();
if ($str3) {
$str3 = ', ' . $str3;
}
@@ -240,11 +240,7 @@ switch ($admin['tnmt_type']) {
if ($general['name'] == "") {
$general['name'] = "-";
}
- if ($general['npc'] >= 2) {
- $general['name'] = "" . $general['name'] . " ";
- } elseif ($general['npc'] == 1) {
- $general['name'] = "" . $general['name'] . " ";
- }
+ $general['name'] = formatName($general['name'], $general['npc']);
echo " {$general['name']} ";
}
@@ -270,11 +266,7 @@ switch ($admin['tnmt_type']) {
if ($general['name'] == "") {
$general['name'] = "-";
}
- if ($general['npc'] >= 2) {
- $general['name'] = "" . $general['name'] . " ";
- } elseif ($general['npc'] == 1) {
- $general['name'] = "" . $general['name'] . " ";
- }
+ $general['name'] = formatName($general['name'], $general['npc']);
if ($general['win'] > 0) {
$line[$i] = "";
$cent[intdiv($i, 2)] = "";
@@ -316,11 +308,7 @@ switch ($admin['tnmt_type']) {
if ($general['name'] == "") {
$general['name'] = "-";
}
- if ($general['npc'] >= 2) {
- $general['name'] = "" . $general['name'] . " ";
- } elseif ($general['npc'] == 1) {
- $general['name'] = "" . $general['name'] . " ";
- }
+ $general['name'] = formatName($general['name'], $general['npc']);
if ($general['win'] > 0) {
$line[$i] = "";
$cent[intdiv($i, 2)] = "";
@@ -363,11 +351,7 @@ switch ($admin['tnmt_type']) {
if ($general['name'] == "") {
$general['name'] = "-";
}
- if ($general['npc'] >= 2) {
- $general['name'] = "" . $general['name'] . " ";
- } elseif ($general['npc'] == 1) {
- $general['name'] = "" . $general['name'] . " ";
- }
+ $general['name'] = formatName($general['name'], $general['npc']);
if ($general['win'] > 0) {
$line[$i] = "";
$cent[intdiv($i, 2)] = "";
@@ -409,11 +393,7 @@ switch ($admin['tnmt_type']) {
if ($general['name'] == "") {
$general['name'] = "-";
}
- if ($general['npc'] >= 2) {
- $general['name'] = "" . $general['name'] . " ";
- } elseif ($general['npc'] == 1) {
- $general['name'] = "" . $general['name'] . " ";
- }
+ $general['name'] = formatName($general['name'], $general['npc']);
if ($general['win'] > 0) {
$line[$i] = "";
$cent[intdiv($i, 2)] = "";
diff --git a/hwe/d_setting/templates/allButton.php.orig b/hwe/d_setting/templates/allButton.php.orig
index e21f008b..f1bfd702 100644
--- a/hwe/d_setting/templates/allButton.php.orig
+++ b/hwe/d_setting/templates/allButton.php.orig
@@ -1,18 +1,16 @@
-
+=$btnBegin??''?>">세력도 =$btnEnd??''?>
+=$btnBegin??''?>">세력일람 =$btnEnd??''?>
+=$btnBegin??''?>">장수일람 =$btnEnd??''?>
+=$btnBegin??''?>">명장일람 =$btnEnd??''?>
+=$btnBegin??''?>">연감 =$btnEnd??''?>
+=$btnBegin??''?>">명예의전당 =$btnEnd??''?>
+=$btnBegin??''?>">왕조일람 =$btnEnd??''?>
+=$btnBegin??''?>">천통국 베팅 =$btnEnd??''?>
+=$btnBegin??''?>">삼모게시판 =$btnEnd??''?>
+=$btnBegin??''?>">팁/강좌 =$btnEnd??''?>
+=$btnBegin??''?>">삼국 일보 =$btnEnd??''?>
+=$btnBegin??''?>">개인 열전 =$btnEnd??''?>
+=$btnBegin??''?>">국가 열전 =$btnEnd??''?>
+=$btnBegin??''?>">패치 내역 =$btnEnd??''?>
+=$btnBegin??''?>">전투 시뮬레이터 =$btnEnd??''?>
+=$btnBegin??''?>">= $call ?> =$btnEnd??''?>
\ No newline at end of file
diff --git a/hwe/func_template.php b/hwe/func_template.php
index 6f264148..5ef56848 100644
--- a/hwe/func_template.php
+++ b/hwe/func_template.php
@@ -215,14 +215,35 @@ function formatLeadershipBonus(int $value): string
return "+{$value} ";
}
+function getNPCColor(int $npc): ?string{
+ if ($npc == 1) {
+ return 'skyblue';
+ }
+ if ($npc == 4){
+ return 'deepskyblue';
+ }
+ if ($npc == 5){
+ return 'darkcyan';
+ }
+ if ($npc == 6){
+ return 'mediumaquamarine';
+ }
+
+ if ($npc > 1) {
+ return 'cyan';
+ }
+
+ return null;
+}
+
function formatName(string $name, int $npc): string
{
- if ($npc == 1) {
- $name = "$name ";
- } else if ($npc > 1) {
- $name = "$name ";
+ $color = getNPCColor($npc);
+ if($color === null){
+ return $name;
}
- return $name;
+
+ return "$name ";
}
function getMapTheme(): string
diff --git a/hwe/func_tournament.php b/hwe/func_tournament.php
index d3d8c3cc..80fd8744 100644
--- a/hwe/func_tournament.php
+++ b/hwe/func_tournament.php
@@ -164,40 +164,44 @@ function processTournament()
$gameStor->tnmt_time = (new \DateTimeImmutable($admin['tnmt_time']))->add(new \DateInterval("PT{$second}S"))->format('Y-m-d H:i:s');
}
-function getTournamentTerm()
-{
+function getTournamentTerm(): ?int{
$db = DB::db();
$gameStor = KVStorage::getStorage($db, 'game_env');
$tnmt_auto = $gameStor->tnmt_auto;
-
- switch ($tnmt_auto) {
- case 0:
- $str = '';
- break;
- case 1:
- $str = "경기당 12분";
- break;
- case 2:
- $str = "경기당 7분";
- break;
- case 3:
- $str = "경기당 3분";
- break;
- case 4:
- $str = "경기당 1분";
- break;
- case 5:
- $str = "경기당 30초";
- break;
- case 6:
- $str = "경기당 15초";
- break;
- case 7:
- $str = "경기당 5초";
- break;
+ switch($tnmt_auto){
+ case 0: return null;
+ case 1: return 12 * 60;
+ case 2: return 7 * 60;
+ case 3: return 3 * 60;
+ case 4: return 1 * 60;
+ case 5: return 30;
+ case 6: return 15;
+ case 7: return 5;
}
- return $str;
+ return null;
+}
+
+function getTournamentTermText()
+{
+ $term = getTournamentTerm();
+
+ if($term === null){
+ return '수동';
+ }
+
+ if($term % 60 === 0){
+ $termMin = intdiv($term, 60);
+ return "경기당 {$termMin}분";
+ }
+
+ if($term > 60){
+ $termSec = $term % 60;
+ $termMin = intdiv($term, 60);
+ return "경기당 {$termMin}분 {$termSec}초";
+ }
+
+ return "경기당 {$term}초";
}
function getTournamentTime()
@@ -261,10 +265,8 @@ function printRow($k, $npc, $name, $abil, $tgame, $win, $draw, $lose, $gd, $gl,
$k += 1;
if ($prmt > 0) {
$name = "" . $name . " ";
- } elseif ($npc >= 2) {
- $name = "" . $name . " ";
- } elseif ($npc == 1) {
- $name = "" . $name . " ";
+ } else if($npc > 0){
+ $name = formatName($name, $npc);
}
echo "$k $name $abil $tgame $win $draw $lose $gd $gl ";
}
diff --git a/hwe/index.php b/hwe/index.php
index 67d4cb93..c7ece75b 100644
--- a/hwe/index.php
+++ b/hwe/index.php
@@ -149,14 +149,14 @@ if (!$otherTextInfo) {
= $scenario ?>
- NPC수 : = $extend ?>
-
-
- NPC상성 : = $fiction ?>
+ NPC 수, 상성 : = $extend ?>,= $fiction ?>
NPC선택 : = $npcmode ?>
+
+ 토너먼트 : = getTournamentTermText() ?>
+
기타 설정: = $otherTextInfo ?>
diff --git a/hwe/process_war.php b/hwe/process_war.php
index e8cae199..fd82b726 100644
--- a/hwe/process_war.php
+++ b/hwe/process_war.php
@@ -1,28 +1,29 @@
getNationID();
$defenderNationID = $rawDefenderCity['nation'];
- if($defenderNationID == 0){
+ if ($defenderNationID == 0) {
$rawDefenderNation = [
- 'nation'=>0,
- 'name'=>'재야',
- 'capital'=>0,
- 'level'=>0,
- 'gold'=>0,
- 'rice'=>10000,
- 'type'=>GameConst::$neutralNationType,
- 'tech'=>0,
- 'gennum'=>1
+ 'nation' => 0,
+ 'name' => '재야',
+ 'capital' => 0,
+ 'level' => 0,
+ 'gold' => 0,
+ 'rice' => 10000,
+ 'type' => GameConst::$neutralNationType,
+ 'tech' => 0,
+ 'gennum' => 1
];
- }
- else{
+ } else {
$rawDefenderNation = $db->queryFirstRow('SELECT nation,`level`,`name`,capital,gennum,tech,`type`,gold,rice FROM nation WHERE nation = %i', $defenderNationID);
}
@@ -36,29 +37,29 @@ function processWar(General $attackerGeneral, array $rawAttackerNation, array $r
$defenderIDList = $db->queryFirstColumn('SELECT no FROM general WHERE nation=%i AND city=%i AND nation!=0 and crew > 0 and rice>(crew/100) and train>=defence_train and atmos>=defence_train', $city->getVar('nation'), $city->getVar('city'));
$defenderList = General::createGeneralObjListFromDB($defenderIDList, null, 2);
- usort($defenderList, function(General $lhs, General $rhs){
- return -(extractBattleOrder($lhs) <=> extractBattleOrder($rhs));
+ usort($defenderList, function (General $lhs, General $rhs) {
+ return - (extractBattleOrder($lhs) <=> extractBattleOrder($rhs));
});
$iterDefender = new \ArrayIterator($defenderList);
$iterDefender->rewind();
- $getNextDefender = function(?WarUnit $prevDefender, bool $reqNext) use ($iterDefender, $rawDefenderNation, $rawDefenderCity, $db) {
- if($prevDefender !== null){
+ $getNextDefender = function (?WarUnit $prevDefender, bool $reqNext) use ($iterDefender, $rawDefenderNation, $rawDefenderCity, $db) {
+ if ($prevDefender !== null) {
$prevDefender->applyDB($db);
}
- if(!$reqNext){
+ if (!$reqNext) {
return null;
}
- if(!$iterDefender->valid()){
+ if (!$iterDefender->valid()) {
return null;
}
$nextDefender = $iterDefender->current();
$nextDefender->setRawCity($rawDefenderCity);
- if(extractBattleOrder($nextDefender) <= 0){
+ if (extractBattleOrder($nextDefender) <= 0) {
return null;
}
@@ -82,8 +83,8 @@ function processWar(General $attackerGeneral, array $rawAttackerNation, array $r
$updateAttackerNation = [];
$updateDefenderNation = [];
- if($city->getVar('supply')){
- if($city->getPhase() > 0){
+ if ($city->getVar('supply')) {
+ if ($city->getPhase() > 0) {
$rice = $city->getKilled() / 100 * 0.8;
$rice *= $city->getCrewType()->rice;
$rice *= getTechCost($rawDefenderNation['tech']);
@@ -91,12 +92,10 @@ function processWar(General $attackerGeneral, array $rawAttackerNation, array $r
Util::setRound($rice);
$updateDefenderNation['rice'] = max(0, $rawDefenderNation['rice'] - $rice);
- }
- else if($conquerCity){
- if($rawDefenderNation['capital'] == $rawDefenderCity['city']){
+ } else if ($conquerCity) {
+ if ($rawDefenderNation['capital'] == $rawDefenderCity['city']) {
$updateDefenderNation['rice'] = $rawDefenderNation['rice'] + 1000;
- }
- else{
+ } else {
$updateDefenderNation['rice'] = $rawDefenderNation['rice'] + 500;
}
}
@@ -120,29 +119,29 @@ function processWar(General $attackerGeneral, array $rawAttackerNation, array $r
$attackerGenCnt_eff = $db->queryFirstField('SELECT count(no) FROM general WHERE nation=%i AND npc != 5', $rawAttackerNation['nation']);
$defenderGenCnt_eff = $db->queryFirstField('SELECT count(no) FROM general WHERE nation=%i AND npc != 5', $rawDefenderNation['nation']);
- if($attackerGenCnt_eff < GameConst::$initialNationGenLimit){
+ if ($attackerGenCnt_eff < GameConst::$initialNationGenLimit) {
$attackerGenCnt = GameConst::$initialNationGenLimit;
$attackerGenCnt_eff = GameConst::$initialNationGenLimit;
}
- if($defenderGenCnt_eff < GameConst::$initialNationGenLimit){
+ if ($defenderGenCnt_eff < GameConst::$initialNationGenLimit) {
$defenderGenCnt = GameConst::$initialNationGenLimit;
$defenderGenCnt_eff = GameConst::$initialNationGenLimit;
}
- if($attackerGenCnt != $attackerGenCnt_eff){
+ if ($attackerGenCnt != $attackerGenCnt_eff) {
$attackerIncTech *= $attackerGenCnt / $attackerGenCnt_eff;
}
- if($defenderGenCnt != $defenderGenCnt_eff){
+ if ($defenderGenCnt != $defenderGenCnt_eff) {
$defenderIncTech *= $defenderGenCnt / $defenderGenCnt_eff;
}
- if(TechLimit($startYear, $year, $rawAttackerNation['tech'])){
+ if (TechLimit($startYear, $year, $rawAttackerNation['tech'])) {
$attackerIncTech /= 4;
}
- if(TechLimit($startYear, $year, $rawDefenderNation['tech'])){
+ if (TechLimit($startYear, $year, $rawDefenderNation['tech'])) {
$defenderIncTech /= 4;
}
@@ -159,41 +158,42 @@ function processWar(General $attackerGeneral, array $rawAttackerNation, array $r
$db->update('nation', $updateDefenderNation, 'nation=%i', $defenderNationID);
$db->update('diplomacy', [
- 'dead'=>$db->sqleval('dead + %i', $attacker->getDead())
+ 'dead' => $db->sqleval('dead + %i', $attacker->getDead())
], 'me = %i and you = %i', $attackerNationID, $defenderNationID);
$db->update('diplomacy', [
- 'dead'=>$db->sqleval('dead + %i', $attacker->getKilled())
+ 'dead' => $db->sqleval('dead + %i', $attacker->getKilled())
], 'me = %i and you = %i', $defenderNationID, $attackerNationID);
- if(!$conquerCity){
+ if (!$conquerCity) {
return;
}
ConquerCity([
- 'startyear'=>$startYear,
- 'year'=>$year,
- 'month'=>$month,
- 'city_rate'=>$cityRate,
- 'join_mode'=>$joinMode,
+ 'startyear' => $startYear,
+ 'year' => $year,
+ 'month' => $month,
+ 'city_rate' => $cityRate,
+ 'join_mode' => $joinMode,
], $attacker->getGeneral(), $city->getRaw());
}
-function extractBattleOrder(General $general){
- if($general->getVar('crew') == 0){
+function extractBattleOrder(General $general)
+{
+ if ($general->getVar('crew') == 0) {
return 0;
}
- if($general->getVar('rice') <= $general->getVar('crew') / 100){
+ if ($general->getVar('rice') <= $general->getVar('crew') / 100) {
return 0;
}
$defence_train = $general->getVar('defence_train');
- if($general->getVar('train') < $defence_train){
+ if ($general->getVar('train') < $defence_train) {
return 0;
}
- if($general->getVar('atmos') < $defence_train){
+ if ($general->getVar('atmos') < $defence_train) {
return 0;
}
@@ -210,8 +210,8 @@ function processWar_NG(
callable $getNextDefender,
WarUnitCity $city,
int $relYear
-):bool{
- $templates = new \League\Plates\Engine(__DIR__.'/templates');
+): bool {
+ $templates = new \League\Plates\Engine(__DIR__ . '/templates');
$logger = $attacker->getLogger();
@@ -231,11 +231,11 @@ function processWar_NG(
$logger->pushGlobalActionLog("{$attacker->getNationVar('name')} >의 {$attacker->getName()}>{$josaYi} {$city->getName()} >{$josaRo} 진격합니다.");
$logger->pushGeneralActionLog("{$city->getName()} >{$josaRo} 진격>합니다. <1>$date>");
- for($currPhase = 0; $currPhase < $attacker->getMaxPhase(); $currPhase+=1){
- if($defender === null){
+ for ($currPhase = 0; $currPhase < $attacker->getMaxPhase(); $currPhase += 1) {
+ if ($defender === null) {
$defender = $city;
- if($city->getNationVar('rice') <= 0 && $city->getVar('supply')){
+ if ($city->getNationVar('rice') <= 0 && $city->getVar('supply')) {
//병량 패퇴
$attacker->setOppose($defender);
$defender->setOppose($attacker);
@@ -256,7 +256,7 @@ function processWar_NG(
}
}
- if($defender->getPhase() == 0){
+ if ($defender->getPhase() == 0) {
$defender->setPrePhase($currPhase);
$attacker->addTrain(1);
@@ -276,7 +276,7 @@ function processWar_NG(
$attackerName = $attacker->getName();
$attackerCrewTypeName = $attacker->getCrewTypeName();
- if($defender instanceof WarUnitGeneral){
+ if ($defender instanceof WarUnitGeneral) {
$defenderName = $defender->getName();
$defenderCrewTypeName = $defender->getCrewTypeName();
@@ -291,8 +291,7 @@ function processWar_NG(
$josaRo = JosaUtil::pick($defenderCrewTypeName, '로');
$josaUl = JosaUtil::pick($attackerCrewTypeName, '을');
$defender->getLogger()->pushGeneralActionLog("{$defenderCrewTypeName}{$josaRo} {$attackerName}>의 {$attackerCrewTypeName}{$josaUl} 수비>합니다.");
- }
- else{
+ } else {
$josaYi = JosaUtil::pick($attackerName, '이');
$josaRo = JosaUtil::pick($attackerCrewTypeName, '로');
$logger->pushGlobalActionLog("{$attackerName}>{$josaYi} {$attackerCrewTypeName}{$josaRo} 성벽을 공격합니다.");
@@ -324,16 +323,15 @@ function processWar_NG(
$attackerHP = $attacker->getHP();
$defenderHP = $defender->getHP();
- if($deadAttacker > $attackerHP || $deadDefender > $defenderHP){
+ if ($deadAttacker > $attackerHP || $deadDefender > $defenderHP) {
$deadAttackerRatio = $deadAttacker / max(1, $attackerHP);
$deadDefenderRatio = $deadDefender / max(1, $defenderHP);
- if($deadDefenderRatio > $deadAttackerRatio){
+ if ($deadDefenderRatio > $deadAttackerRatio) {
//수비자가 더 병력 부족
$deadAttacker /= $deadDefenderRatio;
$deadDefender = $defenderHP;
- }
- else{
+ } else {
//공격자가 더 병력 부족
$deadDefender /= $deadAttackerRatio;
$deadAttacker = $attackerHP;
@@ -351,7 +349,7 @@ function processWar_NG(
$phaseNickname = $currPhase + 1;
- if($deadAttacker > 0 || $deadDefender > 0){
+ if ($deadAttacker > 0 || $deadDefender > 0) {
$attacker->getLogger()->pushGeneralBattleDetailLog(
"$phaseNickname : 【{$attacker->getName()}】> {$attacker->getHP()} (-$deadAttacker)> VS {$defender->getHP()} (-$deadDefender)> 【{$defender->getName()}】>"
);
@@ -365,7 +363,7 @@ function processWar_NG(
$attacker->addPhase();
$defender->addPhase();
- if(!$attacker->continueWar($noRice)){
+ if (!$attacker->continueWar($noRice)) {
$attacker->logBattleResult();
$defender->logBattleResult();
@@ -377,10 +375,9 @@ function processWar_NG(
$josaYi = JosaUtil::pick($attacker->getCrewTypeName(), '이');
$logger->pushGlobalActionLog("{$attacker->getName()}>의 {$attacker->getCrewTypeName()}{$josaYi} 퇴각했습니다.");
- if($noRice){
+ if ($noRice) {
$attacker->getLogger()->pushGeneralActionLog("군량 부족으로 퇴각합니다.", ActionLogger::PLAIN);
- }
- else{
+ } else {
$attacker->getLogger()->pushGeneralActionLog("퇴각했습니다.", ActionLogger::PLAIN);
}
$defender->getLogger()->pushGeneralActionLog("{$attacker->getName()}>의 {$attacker->getCrewTypeName()}{$josaYi} 퇴각했습니다.", ActionLogger::PLAIN);
@@ -388,7 +385,7 @@ function processWar_NG(
break;
}
- if(!$defender->continueWar($noRice)){
+ if (!$defender->continueWar($noRice)) {
$attacker->logBattleResult();
$defender->logBattleResult();
@@ -399,7 +396,7 @@ function processWar_NG(
$attacker->tryWound();
$defender->tryWound();
- if($defender === $city){
+ if ($defender === $city) {
$attacker->addLevelExp(1000);
$conquerCity = true;
break;
@@ -407,33 +404,30 @@ function processWar_NG(
$josaYi = JosaUtil::pick($defender->getCrewTypeName(), '이');
- if($noRice){
+ if ($noRice) {
$logger->pushGlobalActionLog("{$defender->getName()}>의 {$defender->getCrewTypeName()}{$josaYi} 패퇴했습니다.");
- $attacker->getLogger()->pushGeneralActionLog("{$defender->getName()}>의 {$defender->getCrewTypeName()}{$josaYi} 패퇴했습니다.", ActionLogger::PLAIN);
+ $attacker->getLogger()->pushGeneralActionLog("{$defender->getName()}>의 {$defender->getCrewTypeName()}{$josaYi} 패퇴했습니다.", ActionLogger::PLAIN);
$defender->getLogger()->pushGeneralActionLog("군량 부족으로 패퇴합니다.", ActionLogger::PLAIN);
- }
- else{
+ } else {
$logger->pushGlobalActionLog("{$defender->getName()}>의 {$defender->getCrewTypeName()}{$josaYi} 전멸했습니다.");
- $attacker->getLogger()->pushGeneralActionLog("{$defender->getName()}>의 {$defender->getCrewTypeName()}{$josaYi} 전멸했습니다.", ActionLogger::PLAIN);
+ $attacker->getLogger()->pushGeneralActionLog("{$defender->getName()}>의 {$defender->getCrewTypeName()}{$josaYi} 전멸했습니다.", ActionLogger::PLAIN);
$defender->getLogger()->pushGeneralActionLog("전멸했습니다.", ActionLogger::PLAIN);
}
- if($currPhase + 1 == $attacker->getMaxPhase()){
+ if ($currPhase + 1 == $attacker->getMaxPhase()) {
break;
}
$defender->finishBattle();
$defender = ($getNextDefender)($defender, true);
- if($defender !== null && !($defender instanceof WarUnitGeneral)){
+ if ($defender !== null && !($defender instanceof WarUnitGeneral)) {
throw new \RuntimeException('다음 수비자를 받아오는데 실패');
}
-
}
-
}
- if($currPhase == $attacker->getMaxPhase()){
+ if ($currPhase == $attacker->getMaxPhase()) {
//마지막 페이즈의 전투 마무리
$attacker->logBattleResult();
$defender->logBattleResult();
@@ -445,9 +439,9 @@ function processWar_NG(
$attacker->finishBattle();
$defender->finishBattle();
- if($defender instanceof WarUnitCity){
+ if ($defender instanceof WarUnitCity) {
$newConflict = $defender->addConflict();
- if($newConflict){
+ if ($newConflict) {
$nationName = $attacker->getNationVar('name');
$josaYi = JosaUtil::pick($nationName, '이');
$logger->pushGlobalHistoryLog("【분쟁】 >{$nationName} >{$josaYi} {$defender->getName()} > 공략에 가담하여 분쟁이 발생하고 있습니다.");
@@ -459,33 +453,36 @@ function processWar_NG(
return $conquerCity;
}
-function DeleteConflict($nation) {
+function DeleteConflict($nation)
+{
$db = DB::db();
- foreach($db->queryAllLists('SELECT city, conflict FROM city WHERE conflict!=%s', '{}') as list($cityID, $rawConflict)){
+ foreach ($db->queryAllLists('SELECT city, conflict FROM city WHERE conflict!=%s', '{}') as list($cityID, $rawConflict)) {
$conflict = Json::decode($rawConflict);
- if(!$conflict || !is_array($conflict)){
+ if (!$conflict || !is_array($conflict)) {
continue;
}
- if(!key_exists($nation, $conflict)){
+ if (!key_exists($nation, $conflict)) {
continue;
}
unset($conflict[$nation]);
$db->update('city', [
- 'conflict'=>Json::encode($conflict)
+ 'conflict' => Json::encode($conflict)
], 'city=%i', $cityID);
}
}
-function getConquerNation($city) : int {
+function getConquerNation($city): int
+{
$conflict = Json::decode($city['conflict']);
return Util::array_first_key($conflict);
}
-function ConquerCity(array $admin, General $general, array $city) {
+function ConquerCity(array $admin, General $general, array $city)
+{
$db = DB::db();
$year = $admin['year'];
@@ -506,7 +503,7 @@ function ConquerCity(array $admin, General $general, array $city) {
$defenderNationLogger = new ActionLogger(0, $defenderNationID, $year, $month);
- if($defenderNationID) {
+ if ($defenderNationID) {
$defenderNationDecoration = "{$defenderNationName} >의";
} else {
$defenderNationDecoration = "공백지인";
@@ -524,8 +521,29 @@ function ConquerCity(array $admin, General $general, array $city) {
$defenderNationLogger->pushNationalHistoryLog("{$attackerNationName} >의 {$attackerGeneralName}>에 의해 {$cityName} >{$josaYiCity} 함락>");
+ $gameStor = KVStorage::getStorage($db, 'game_env');
+
+ // 이벤트 핸들러 동작
+ $e_env = null;
+ foreach (DB::db()->query('SELECT * FROM event WHERE target = "OCCUPY_CITY" ORDER BY `priority` DESC, `id` ASC') as $rawEvent) {
+ if ($e_env === null) {
+ $e_env = $gameStor->getAll(false);
+ }
+ $eventID = $rawEvent['id'];
+ $cond = Json::decode($rawEvent['condition']);
+ $action = Json::decode($rawEvent['action']);
+ $event = new Event\EventHandler($cond, $action);
+ $e_env['currentEventID'] = $eventID;
+
+ $event->tryRunEvent($e_env);
+ }
+
+ if ($e_env !== null) {
+ $gameStor->resetCache();
+ }
+
// 국가 멸망시
- if($defenderNationID && $db->queryFirstField('SELECT count(city) FROM city WHERE nation = %i', $defenderNationID) === 1) {
+ if ($defenderNationID && $db->queryFirstField('SELECT count(city) FROM city WHERE nation = %i', $defenderNationID) === 1) {
$defenderNationLogger->flush();
unset($defenderNationLogger);
@@ -545,17 +563,17 @@ function ConquerCity(array $admin, General $general, array $city) {
$loseGeneralGold = 0;
$loseGeneralRice = 0;
- foreach($oldNationGenerals as $oldGeneral){
- $loseGold = intdiv($oldGeneral->getVar('gold') * (rand()%30+20), 100);
- $loseRice = intdiv($oldGeneral->getVar('rice') * (rand()%30+20), 100);
+ foreach ($oldNationGenerals as $oldGeneral) {
+ $loseGold = intdiv($oldGeneral->getVar('gold') * (rand() % 30 + 20), 100);
+ $loseRice = intdiv($oldGeneral->getVar('rice') * (rand() % 30 + 20), 100);
$oldGeneral->getLogger()->pushGeneralActionLog(
"도주하며 금$loseGold> 쌀$loseRice>을 분실했습니다.",
ActionLogger::PLAIN
);
$oldGeneral->increaseVar('gold', -$loseGold);
$oldGeneral->increaseVar('rice', -$loseRice);
- $oldGeneral->addExperience(-$oldGeneral->getVar('experience')*0.1, false);
- $oldGeneral->addDedication(-$oldGeneral->getVar('dedication')*0.5, false);
+ $oldGeneral->addExperience(-$oldGeneral->getVar('experience') * 0.1, false);
+ $oldGeneral->addDedication(-$oldGeneral->getVar('dedication') * 0.5, false);
$loseGeneralGold += $loseGold;
$loseGeneralRice += $loseRice;
@@ -563,21 +581,21 @@ function ConquerCity(array $admin, General $general, array $city) {
$oldGeneral->applyDB($db);
//모두 등용장 발부
- if($admin['join_mode'] != 'onlyRandom' && Util::randBool(0.5)) {
+ if ($admin['join_mode'] != 'onlyRandom' && Util::randBool(0.5)) {
$msg = ScoutMessage::buildScoutMessage($attackerID, $oldGeneral->getID());
- if($msg){
+ if ($msg) {
$msg->send(true);
}
}
//NPC인 경우 일정 확률로 임관(엔장, 인재, 의병)
$npcType = $oldGeneral->getNPCType();
- if($admin['join_mode'] != 'onlyRandom' && 2 <= $npcType && $npcType <= 8 && $npcType != 5 && Util::randBool(GameConst::$joinRuinedNPCProp)) {
+ if ($admin['join_mode'] != 'onlyRandom' && 2 <= $npcType && $npcType <= 8 && $npcType != 5 && Util::randBool(GameConst::$joinRuinedNPCProp)) {
$cmd = buildGeneralCommandClass('che_임관', $oldGeneral, $admin, [
- 'destNationID'=>$attackerNationID
+ 'destNationID' => $attackerNationID
]);
$joinTurn = Util::randRangeInt(0, 12);
- if($joinTurn){
+ if ($joinTurn) {
_setGeneralCommand(buildGeneralCommandClass('che_견문', $oldGeneral, $admin), iterator_to_array(Util::range($joinTurn)));
}
_setGeneralCommand($cmd, [$joinTurn]);
@@ -596,37 +614,56 @@ function ConquerCity(array $admin, General $general, array $city) {
// 기본량 제외 금쌀50% + 장수들 분실 금쌀50% 흡수
$db->update('nation', [
- 'gold'=>$db->sqleval('gold + %i', $loseNationGold),
- 'rice'=>$db->sqleval('rice + %i', $loseNationRice),
+ 'gold' => $db->sqleval('gold + %i', $loseNationGold),
+ 'rice' => $db->sqleval('rice + %i', $loseNationRice),
], 'nation=%i', $attackerNationID);
//아국 수뇌부에게 로그 전달
$loseNationGoldText = number_format($loseNationGold);
$loseNationRiceText = number_format($loseNationRice);
$resourceLog = "{$defenderNationName} > 정복으로 금{$loseNationGoldText}> 쌀{$loseNationRiceText}>을 획득했습니다.";
- foreach($db->queryFirstColumn(
- 'SELECT no FROM general WHERE nation=%i AND officer_level>=5', $attackerNationID
- ) as $attackerChiefID
- ){
- if($attackerChiefID == $attackerID){
+ foreach ($db->queryFirstColumn(
+ 'SELECT no FROM general WHERE nation=%i AND officer_level>=5',
+ $attackerNationID
+ ) as $attackerChiefID) {
+ if ($attackerChiefID == $attackerID) {
$attackerLogger->pushGeneralActionLog($resourceLog, ActionLogger::PLAIN);
- }
- else{
+ } else {
$chiefLogger = new ActionLogger($attackerChiefID, $attackerNationID, $year, $month);
$chiefLogger->pushGeneralActionLog($resourceLog, ActionLogger::PLAIN);
$chiefLogger->flush();
}
}
- // 멸망이 아니면
+
+ // 이벤트 핸들러 동작
+ $e_env = null;
+ foreach (DB::db()->query('SELECT * FROM event WHERE target = "DESTROY_NATION" ORDER BY `priority` DESC, `id` ASC') as $rawEvent) {
+ if ($e_env === null) {
+ $e_env = $gameStor->getAll(false);
+ }
+ $eventID = $rawEvent['id'];
+ $cond = Json::decode($rawEvent['condition']);
+ $action = Json::decode($rawEvent['action']);
+ $event = new Event\EventHandler($cond, $action);
+ $e_env['currentEventID'] = $eventID;
+
+ $event->tryRunEvent($e_env);
+ }
+
+ if ($e_env !== null) {
+ $gameStor->resetCache();
+ }
+
+ // 멸망이 아니면
} else {
// 태수,군사,종사은 일반으로...
- $db->update('general',[
- 'officer_level'=>1,
- 'officer_city'=>0,
- ], 'officer_city = %i',$cityID);
+ $db->update('general', [
+ 'officer_level' => 1,
+ 'officer_city' => 0,
+ ], 'officer_city = %i', $cityID);
//수도였으면 긴급 천도
- if($defenderNationID && $defenderStaticNation['capital'] == $cityID) {
+ if ($defenderNationID && $defenderStaticNation['capital'] == $cityID) {
$minCity = findNextCapital($cityID, $defenderNationID);
$minCityName = CityConst::byID($minCity)->name;
@@ -636,10 +673,10 @@ function ConquerCity(array $admin, General $general, array $city) {
$moveLog = "수도가 함락되어 $minCityName >으로 긴급천도>합니다.";
//아국 수뇌부에게 로그 전달
- foreach($db->queryFirstColumn(
- 'SELECT no FROM general WHERE nation=%i AND officer_level>=5', $defenderNationID
- ) as $defenderChiefID
- ){
+ foreach ($db->queryFirstColumn(
+ 'SELECT no FROM general WHERE nation=%i AND officer_level>=5',
+ $defenderNationID
+ ) as $defenderChiefID) {
$chiefLogger = new ActionLogger($defenderChiefID, $defenderNationID, $year, $month);
$chiefLogger->pushGeneralActionLog($moveLog, ActionLogger::PLAIN);
$chiefLogger->flush();
@@ -647,22 +684,22 @@ function ConquerCity(array $admin, General $general, array $city) {
//천도
$db->update('nation', [
- 'capital'=>$minCity,
- 'gold'=>$db->sqleval('gold * 0.5'),
- 'rice'=>$db->sqleval('rice * 0.5'),
+ 'capital' => $minCity,
+ 'gold' => $db->sqleval('gold * 0.5'),
+ 'rice' => $db->sqleval('rice * 0.5'),
], 'nation=%i', $defenderNationID);
//보급도시로 만듬
$db->update('city', [
- 'supply'=>1
+ 'supply' => 1
], 'city=%i', $minCity);
//수뇌부 이동
$db->update('general', [
- 'city'=>$minCity
- ], 'nation=%i AND officer_level>=5',$defenderNationID);
+ 'city' => $minCity
+ ], 'nation=%i AND officer_level>=5', $defenderNationID);
//장수 사기 감소
$db->update('general', [
- 'atmos'=>$db->sqleval('atmos*0.8')
- ], 'nation=%i',$defenderNationID);
+ 'atmos' => $db->sqleval('atmos*0.8')
+ ], 'nation=%i', $defenderNationID);
refreshNationStaticInfo();
}
@@ -673,10 +710,9 @@ function ConquerCity(array $admin, General $general, array $city) {
if ($conquerNation == $attackerNationID) {
// 이동
$db->update('general', [
- 'city'=>$cityID
+ 'city' => $cityID
], 'no=%i', $attackerID);
- }
- else{
+ } else {
$conquerNationName = getNationStaticInfo($conquerNation)['name'];
$conquerNationLogger = new ActionLogger(0, $conquerNation, $year, $month);
@@ -690,16 +726,16 @@ function ConquerCity(array $admin, General $general, array $city) {
}
$query = [
- 'supply'=>1,
- 'term'=>0,
- 'conflict'=>'{}',
- 'agri'=>$db->sqleval('agri*0.7'),
- 'comm'=>$db->sqleval('comm*0.7'),
- 'secu'=>$db->sqleval('secu*0.7'),
- 'nation'=>$conquerNation,
- 'officer_set'=>0,
+ 'supply' => 1,
+ 'term' => 0,
+ 'conflict' => '{}',
+ 'agri' => $db->sqleval('agri*0.7'),
+ 'comm' => $db->sqleval('comm*0.7'),
+ 'secu' => $db->sqleval('secu*0.7'),
+ 'nation' => $conquerNation,
+ 'officer_set' => 0,
];
- if($city['level'] > 3) {
+ if ($city['level'] > 3) {
$query['def'] = 1000;
$query['wall'] = 1000;
} else {
@@ -717,45 +753,44 @@ function ConquerCity(array $admin, General $general, array $city) {
$nearNationsID[] = $conquerNation;
$nearNationsID = array_unique($nearNationsID);
- foreach($nearNationsID as $nationNationID){
+ foreach ($nearNationsID as $nationNationID) {
SetNationFront($nationNationID);
}
}
-function findNextCapital(int $capitalID, int $nationID):int{
+function findNextCapital(int $capitalID, int $nationID): int
+{
$distList = searchDistance($capitalID, 99, true);
$cities = [];
- foreach(
- DB::db()->query(
+ foreach (DB::db()->query(
'SELECT city, pop FROM city WHERE nation=%i and city!=%i',
$nationID,
$capitalID
- ) as $row
- ){
+ ) as $row) {
$cities[$row['city']] = $row['pop'];
};
- foreach($distList as $dist=>$distSubList){
+ foreach ($distList as $dist => $distSubList) {
$maxCityPop = 0;
$minCity = 0;
- foreach($distSubList as $cityID){
- if(!key_exists($cityID, $cities)){
+ foreach ($distSubList as $cityID) {
+ if (!key_exists($cityID, $cities)) {
continue;
}
$cityPop = $cities[$cityID];
- if($cityPop < $maxCityPop){
+ if ($cityPop < $maxCityPop) {
continue;
}
$minCity = $cityID;
$maxCityPop = $cityPop;
}
- if($minCity){
+ if ($minCity) {
return $minCity;
}
}
throw new \RuntimeException('도시가 남지 않았는데 긴천을 시도하고 있습니다');
-}
\ No newline at end of file
+}
diff --git a/hwe/sammo/API/Betting/Bet.php b/hwe/sammo/API/Betting/Bet.php
new file mode 100644
index 00000000..492f34a3
--- /dev/null
+++ b/hwe/sammo/API/Betting/Bet.php
@@ -0,0 +1,63 @@
+args);
+ $v->rule('required', [
+ 'bettingID',
+ 'bettingType',
+ 'amount'
+ ])
+ ->rule('integer', 'bettingID')
+ ->rule('integerArray', 'bettingType')
+ ->rule('integer', 'amount')
+ ->rule('min', 'amount', 1);
+
+ if (!$v->validate()) {
+ return $v->errorStr();
+ }
+ return null;
+ }
+
+ public function getRequiredSessionMode(): int
+ {
+ return static::REQ_GAME_LOGIN;
+ }
+
+ public function launch(Session $session, ?DateTimeInterface $modifiedSince, ?string $reqEtag)
+ {
+ /** @var int */
+ $bettingID = $this->args['bettingID'];
+ /** @var int[] */
+ $bettingType = $this->args['bettingType'];
+ /** @var int */
+ $amount = $this->args['amount'];
+
+ $bettingHelper = new Betting($bettingID);
+ try{
+ $bettingHelper->bet($session->generalID, $session->userID, $bettingType, $amount);
+ }
+ catch(\Throwable $e){
+ return $e->getMessage();
+ }
+
+ return [
+ 'result' => true
+ ];
+ }
+}
diff --git a/hwe/sammo/API/Betting/GetBettingDetail.php b/hwe/sammo/API/Betting/GetBettingDetail.php
new file mode 100644
index 00000000..99548309
--- /dev/null
+++ b/hwe/sammo/API/Betting/GetBettingDetail.php
@@ -0,0 +1,97 @@
+args);
+ $v->rule('required', [
+ 'betting_id',
+ ])
+ ->rule('integer', 'betting_id');
+
+ if (!$v->validate()) {
+ return $v->errorStr();
+ }
+ return null;
+ }
+
+ public function getRequiredSessionMode(): int
+ {
+ return static::REQ_GAME_LOGIN | static::REQ_READ_ONLY;
+ }
+
+ public function launch(Session $session, ?DateTimeInterface $modifiedSince, ?string $reqEtag)
+ {
+ $db = DB::db();
+
+ /** @var int */
+ $bettingID = $this->args['betting_id'];
+
+ $gameStor = KVStorage::getStorage($db, 'game_env');
+ $bettingStor = KVStorage::getStorage($db, 'betting');
+ $rawBettingInfo = $bettingStor->getValue("id_{$bettingID}");
+ if($rawBettingInfo === null){
+ return '해당 베팅이 없습니다';
+ }
+
+ try{
+ $bettingInfo = new BettingInfo($rawBettingInfo);
+ }
+ catch(\Error $e){
+ return $e->getMessage();
+ }
+
+ [$year, $month] = $gameStor->getValuesAsArray(['year', 'month']);
+
+ $bettingDetail = [];
+
+ foreach ($db->queryAllLists(
+ 'SELECT betting_type, sum(amount) as sum_amount FROM ng_betting WHERE betting_id = %i GROUP BY betting_type',
+ $bettingID
+ ) as [$bettingType, $amount]) {
+ $bettingDetail[] = [$bettingType, Util::toInt($amount)];
+ }
+
+ [$year, $month] = $gameStor->getValuesAsArray(['year', 'month']);
+
+ $myBetting = [];
+ foreach($db->queryAllLists(
+ 'SELECT betting_type, sum(amount) as sum_amount FROM ng_betting WHERE betting_id = %i AND user_id = %i GROUP BY betting_type',
+ $bettingID, $session->userID
+ ) as [$bettingType, $amount]){
+ $myBetting[] = [$bettingType, Util::toInt($amount)];
+ }
+
+ if($bettingInfo->reqInheritancePoint){
+ $inheritStor = KVStorage::getStorage($db, "inheritance_{$session->userID}");
+ $remainPoint = ($inheritStor->getValue('previous') ?? [0,0])[0];
+ }
+ else{
+ $remainPoint = $db->queryFirstField('SELECT gold FROM general WHERE no = %i', $session->generalID)??0;
+ }
+
+ return [
+ 'result' => true,
+ 'bettingInfo' => $rawBettingInfo,
+ 'bettingDetail' => $bettingDetail,
+ 'myBetting' => $myBetting,
+ 'remainPoint' => $remainPoint,
+ 'year' => $year,
+ 'month' => $month,
+ ];
+ }
+}
diff --git a/hwe/sammo/API/Betting/GetBettingList.php b/hwe/sammo/API/Betting/GetBettingList.php
new file mode 100644
index 00000000..57a25fbf
--- /dev/null
+++ b/hwe/sammo/API/Betting/GetBettingList.php
@@ -0,0 +1,81 @@
+userID;
+
+ $me = $db->queryFirstRow('SELECT no,nation,officer_level,con,turntime,belong,penalty,permission FROM general WHERE owner=%i', $userID);
+ $con = checkLimit($me['con']);
+ if ($con >= 2) {
+ return "접속 제한중입니다.";
+ }
+
+ $bettingList = [];
+ foreach ($bettingStor->getAll() as $_key => $rawItem) {
+ $item = new BettingInfo($rawItem);
+ unset($rawItem['candidates']);
+ $bettingList[$item->id] = $rawItem;
+ $bettingList[$item->id]['totalAmount'] = 0;
+ }
+
+ [$year, $month] = $gameStor->getValuesAsArray(['year', 'month']);
+
+ if(!$bettingList){
+ return [
+ 'result' => true,
+ 'bettingList' => $bettingList,
+ 'year' => $year,
+ 'month' => $month,
+ ];
+ }
+
+ $bettingIDList = array_keys($bettingList);
+ // XXX: query cache만 믿고 sum을 하는 짓을 벌여도 되는가?
+ foreach ($db->queryAllLists(
+ 'SELECT betting_id, sum(amount) as total_amount FROM ng_betting WHERE betting_id IN %li GROUP BY betting_id',
+ $bettingIDList
+ ) as [$bettingID, $totalAmount]) {
+ if (!key_exists($bettingID, $bettingList)) {
+ continue;
+ }
+ $bettingList[$bettingID]['totalAmount'] = $totalAmount;
+ }
+
+
+ return [
+ 'result' => true,
+ 'bettingList' => $bettingList,
+ 'year' => $year,
+ 'month' => $month,
+ ];
+ }
+}
diff --git a/hwe/sammo/API/Global/GetNationList.php b/hwe/sammo/API/Global/GetNationList.php
new file mode 100644
index 00000000..f3bd80aa
--- /dev/null
+++ b/hwe/sammo/API/Global/GetNationList.php
@@ -0,0 +1,65 @@
+ $lhs['power'];
+ });
+
+ $nations[0] = getNationStaticInfo(0);
+
+ foreach ($db->query('SELECT npc,name,nation,officer_level,permission FROM `general` ORDER BY dedication DESC') as $general) {
+ $nationID = $general['nation'];
+
+ $permission = $general['permission'];
+ if($permission != 'auditor' && $permission != 'ambassador'){
+ unset($general['permission']);
+ }
+
+ if($general['officer_level'] < 5){
+ $general['officer_level'] = 1;
+ }
+
+ if (!key_exists('generals', $nations[$nationID])) {
+ $nations[$nationID]['generals'] = [];
+ }
+ $nations[$nationID]['generals'][] = $general;
+ }
+
+ foreach ($db->queryAllLists('SELECT city, name, nation FROM city') as [$cityID, $cityName, $nationID]) {
+ if (!key_exists('cities', $nations[$nationID])) {
+ $nations[$nationID]['cities'] = [];
+ }
+ $nations[$nationID]['cities'][$cityID] = $cityName;
+ }
+
+ return [
+ 'result' => true,
+ 'nations' => $nations,
+ ];
+ }
+}
diff --git a/hwe/sammo/Betting.php b/hwe/sammo/Betting.php
new file mode 100644
index 00000000..191fa9b0
--- /dev/null
+++ b/hwe/sammo/Betting.php
@@ -0,0 +1,361 @@
+getValue("id_{$bettingID}");
+ if ($rawBettingInfo === null) {
+ throw new \RuntimeException("해당 베팅이 없습니다: {$bettingID}");
+ }
+ $this->info = new BettingInfo($rawBettingInfo);
+ }
+
+ private function _convertBettingKey(array $bettingType): string
+ {
+ return Json::encode($bettingType);
+ }
+
+ public function purifyBettingKey(array $bettingType): array
+ {
+ $selectCnt = $this->info->selectCnt;
+ sort($bettingType, SORT_NUMERIC);
+ $bettingType = array_unique($bettingType, SORT_NUMERIC); //NOTE: key로 바로 사용하므로 중요함
+ if (count($bettingType) != $selectCnt) {
+ throw new \InvalidArgumentException('중복된 값이 있습니다.');
+ }
+
+ if ($bettingType[0] < 0) {
+ throw new \InvalidArgumentException('올바르지 않은 값이 있습니다.(0 미만)' . print_r($bettingType, true));
+ }
+
+ if (Util::array_last($bettingType) >= count($this->info->candidates)) {
+ throw new \InvalidArgumentException('올바르지 않은 값이 있습니다.(초과)' . print_r($bettingType, true));
+ }
+
+ return $bettingType;
+ }
+
+ public function convertBettingKey(array $bettingType): string
+ {
+ $bettingType = $this->purifyBettingKey($bettingType);
+ return $this->_convertBettingKey($bettingType);
+ }
+
+ public function getInfo(): BettingInfo
+ {
+ return $this->info;
+ }
+
+ public function bet(int $generalID, ?int $userID, array $bettingType, int $amount): void{
+ $bettingInfo = $this->info;
+
+ if ($bettingInfo->finished) {
+ throw new \RuntimeException('이미 종료된 베팅입니다');
+ }
+
+ if ($bettingInfo->finished) {
+ throw new \RuntimeException('이미 종료된 베팅입니다');
+ }
+ $db = DB::db();
+ $gameStor = KVStorage::getStorage($db, 'game_env');
+
+ [$year, $month] = $gameStor->getValuesAsArray(['year', 'month']);
+ $yearMonth = Util::joinYearMonth($year, $month);
+
+
+ if ($bettingInfo->closeYearMonth <= $yearMonth) {
+ throw new \RuntimeException('이미 마감된 베팅입니다');
+ }
+
+ if ($bettingInfo->openYearMonth > $yearMonth) {
+ throw new \RuntimeException('아직 시작되지 않은 베팅입니다');
+ }
+
+ if (count($bettingType) != $bettingInfo->selectCnt) {
+ throw new \RuntimeException('필요한 선택 수를 채우지 못했습니다.');
+ }
+
+ $bettingTypeKey = $this->convertBettingKey($bettingType);
+
+ $inheritStor = KVStorage::getStorage($db, "inheritance_{$userID}");
+
+ $prevBetAmount = $db->queryFirstField('SELECT sum(amount) FROM ng_betting WHERE betting_id = %i AND user_id = %i', $this->bettingID, $userID) ?? 0;
+
+ if ($prevBetAmount + $amount > 1000) {
+ throw new \RuntimeException((1000 - $prevBetAmount) . ' 포인트까지만 베팅 가능합니다.');
+ }
+
+ if ($bettingInfo->reqInheritancePoint) {
+ $remainPoint = ($inheritStor->getValue('previous') ?? [0, 0])[0];
+ if ($remainPoint < $amount) {
+ throw new \RuntimeException('유산포인트가 충분하지 않습니다.');
+ }
+ } else {
+ $remainPoint = $db->queryFirstField('SELECT gold FROM general WHERE no = %i', $generalID) ?? 0;
+ if ($remainPoint < GameConst::$generalMinimumGold + $amount) {
+ throw new \RuntimeException('금이 부족합니다.');
+ }
+ }
+
+ $bettingItem = new BettingItem([
+ 'betting_id' => $this->bettingID,
+ 'general_id' => $generalID,
+ 'user_id' => $userID,
+ 'betting_type' => $bettingTypeKey,
+ 'amount' => $amount
+ ]);
+
+ $db->insertUpdate(
+ 'ng_betting',
+ $bettingItem->toArray(),
+ ['amount' => $db->sqleval('amount + %i', $amount)]
+ );
+ if ($bettingInfo->reqInheritancePoint) {
+ $inheritStor->setValue('previous', [$remainPoint - $amount, null]);
+ $userLogger = new UserLogger($userID);
+ $userLogger->push("{$amount} 포인트를 베팅에 사용", "inheritPoint");
+ $userLogger->flush();
+ } else {
+ $db->update('general', [
+ 'gold' => $db->sqleval('gold - %i', $amount)
+ ], 'no = %i', $generalID);
+ }
+ }
+
+ /** @param int[] $result */
+ private function _calcRewardExclusive(array $bettingType): array
+ {
+ $db = DB::db();
+ $totalAmount = $db->queryFirstField('SELECT sum(amount) FROM ng_betting WHERE betting_id = %i');
+
+ if ($totalAmount == 0) {
+ return [];
+ }
+
+ $winnerList = $db->queryAllLists(
+ 'SELECT general_id, user_id, amount FROM ng_betting WHERE betting_id = %i AND betting_type = %s AND general_id > 0',
+ $this->bettingID,
+ $this->_convertBettingKey($bettingType)
+ );
+
+ $subAmount = 0;
+ foreach ($winnerList as [,, $amount]) {
+ $subAmount += $amount;
+ }
+
+ if ($subAmount == 0) {
+ return [];
+ }
+
+ $multiplier = $totalAmount / $subAmount;
+ $selectCnt = $this->info->selectCnt;
+
+ $result = [];
+ foreach ($winnerList as [$generalID, $userID, $amount]) {
+ $result[] = [
+ 'generalID' => $generalID,
+ 'userID' => $userID,
+ 'amount' => $amount * $multiplier,
+ 'matchPoint' => $selectCnt,
+ ];
+ }
+ return $result;
+ }
+
+
+
+ /** @param int[] $winnerType */
+ public function calcReward(array $winnerType): array
+ {
+ $selectCnt = $this->info->selectCnt;
+ if ($selectCnt == 1) {
+ return $this->_calcRewardExclusive($winnerType);
+ }
+
+ if ($this->info->isExlusive) {
+ return $this->_calcRewardExclusive($winnerType);
+ }
+ //아래는 2개 이상, 복합 보상 옵션
+
+ $winnerTypeMap = [];
+ foreach ($winnerType as $typeVal) {
+ $winnerTypeMap[$typeVal] = $typeVal;
+ }
+
+ $calcMatchPoint = function ($bettingType) use ($winnerTypeMap): int {
+ $result = 0;
+ foreach ($bettingType as $typeVal) {
+ if (key_exists($typeVal, $winnerTypeMap)) {
+ $result += 1;
+ }
+ }
+ return $result;
+ };
+
+ $totalAmount = 0;
+ $subAmount = [];
+ $subWinners = [];
+
+ foreach (Util::range($selectCnt + 1) as $matchPoint) {
+ $subAmount[$matchPoint] = 0;
+ $subWinners[$matchPoint] = [];
+ }
+
+ $db = DB::db();
+ foreach ($db->queryAllLists(
+ 'SELECT general_id, user_id, amount, betting_type FROM ng_betting WHERE betting_id = %i',
+ $this->bettingID
+ ) as [$generalID, $userID, $amount, $bettingTypeKey]) {
+ $bettingType = Json::decode($bettingTypeKey);
+ $matchPoint = $calcMatchPoint($bettingType);
+ $totalAmount += $amount;
+ if ($generalID == 0) {
+ continue;
+ }
+ $subAmount[$matchPoint] += $amount;
+ $subWinners[$matchPoint][] = [
+ 'generalID' => $generalID,
+ 'userID' => $userID,
+ 'amount' => $amount,
+ 'matchPoint' => $matchPoint,
+ ];
+ }
+
+ $remainRewardAmount = $totalAmount;
+ $rewardAmount = [];
+ foreach (Util::range($selectCnt, 0, -1) as $matchPoint) {
+ if (count($subWinners[$matchPoint]) == 0) {
+ continue;
+ }
+ if ($subAmount[$matchPoint] == 0) {
+ continue;
+ }
+
+ $givenRewardAmount = $remainRewardAmount / 2;
+ $rewardAmount[$matchPoint] = $givenRewardAmount;
+ $remainRewardAmount -= $givenRewardAmount; // /2가 아니라 다른 값이 될 경우를 대비..
+ }
+
+ foreach (Util::range(1, $selectCnt + 1) as $matchPoint) {
+ if (!key_exists($matchPoint, $rewardAmount)) {
+ continue;
+ }
+ $rewardAmount[$matchPoint] += $remainRewardAmount;
+ break;
+ }
+
+ $result = [];
+
+ foreach (Util::range($selectCnt + 1, 0, -1) as $matchPoint) {
+ if (!key_exists($matchPoint, $rewardAmount)) {
+ continue;
+ }
+ $subReward = $rewardAmount[$matchPoint];
+ if ($subReward == 0) {
+ continue;
+ }
+ $multiplier = $subReward / $subAmount[$matchPoint];
+ foreach ($subWinners[$matchPoint] as $subWinner) {
+ $subWinner['amount'] *= $multiplier;
+ $result[] = $subWinner;
+ }
+ }
+
+ return $result;
+ }
+
+ public function giveReward(array $winnerType)
+ {
+ $rewardList = $this->calcReward($winnerType);
+ $selectCnt = $this->info->selectCnt;
+
+ $db = DB::db();
+
+ if ($this->info->reqInheritancePoint) {
+ /** @var UserLogger[] */
+ $loggers = [];
+ foreach ($rewardList as $rewardItem) {
+ if ($rewardItem['userID'] === null) {
+ continue;
+ }
+ $userID = $rewardItem['userID'];
+ $amount = $rewardItem['amount'];
+
+ $inheritStor = KVStorage::getStorage($db, "inheritance_{$userID}");
+ $previousPoint = ($inheritStor->getValue('previous') ?? [0, 0])[0];
+ $nextPoint = $previousPoint + $amount;
+ $inheritStor->setValue('previous', [$nextPoint, 0]);
+ $inheritStor->invalidateCacheValue('previous');//XXX: 실제로는 previous 값을 사용할 수 없도록 락을 걸어야 한다.
+
+ $amountText = number_format($amount);
+ $previousPointText = number_format($previousPoint);
+ $nextPointText = number_format($nextPoint);
+
+ $matchPoint = $rewardItem['matchPoint'];
+
+ if ($matchPoint == $selectCnt) {
+ $partialText = '베팅 당첨';
+ } else {
+ $partialText = "베팅 부분 당첨({$matchPoint}/{$selectCnt})";
+ }
+
+ if (key_exists($userID, $loggers)) {
+ $userLogger = $loggers[$userID];
+ } else {
+ $userLogger = new UserLogger($userID);
+ $loggers[$userID] = $userLogger;
+ }
+
+ [$year, $month] = Util::parseYearMonth($this->info->openYearMonth);
+
+ $userLogger->push("{$this->info->name} {$partialText} 보상으로 {$amountText} 포인트 획득.", "inheritPoint");
+ $userLogger->push("포인트 {$previousPointText} => {$nextPointText}", "inheritPoint");
+ }
+
+ foreach ($loggers as $userLogger) {
+ $userLogger->flush();
+ }
+
+ } else {
+ $generalList = General::createGeneralObjListFromDB(array_unique(Util::squeezeFromArray($rewardList, 'generalID')), ['gold', 'npc'], 1);
+ foreach ($rewardList as $rewardItem) {
+ $gambler = $generalList[$rewardItem['generalID']];
+ $reward = Util::round($rewardItem['amount']);
+ $matchPoint = $rewardItem['matchPoint'];
+ $gambler->increaseVar('gold', $reward);
+ if (($gambler->getNPCType() == 0) || ($gambler->getNPCType() == 1 && $gambler->getRankVar('betgold', 0) > 0)) {
+ $gambler->increaseRankVar('betwingold', $reward);
+ $gambler->increaseRankVar('betwin', 1);
+ }
+
+ if ($matchPoint == $selectCnt) {
+ $partialText = '베팅 당첨';
+ } else {
+ $partialText = "베팅 부분 당첨({$matchPoint}/{$selectCnt})";
+ }
+ $rewardText = number_format($reward);
+ $gambler->getLogger()->pushGeneralActionLog("{$this->info->name}>의 {$partialText} 보상으로 {$rewardText}>의 금> 획득!", ActionLogger::EVENT_PLAIN);
+ }
+
+ foreach ($generalList as $general) {
+ $general->applyDB($db);
+ }
+ }
+
+ $this->info->finished = true;
+ $this->info->winner = $winnerType;
+ $bettingStor = KVStorage::getStorage($db, 'betting');
+ $bettingStor->setValue("id_{$this->bettingID}", $this->info->toArray());
+ }
+}
diff --git a/hwe/sammo/Command/General/che_해산.php b/hwe/sammo/Command/General/che_해산.php
index a4849548..a848e160 100644
--- a/hwe/sammo/Command/General/che_해산.php
+++ b/hwe/sammo/Command/General/che_해산.php
@@ -7,13 +7,17 @@ use \sammo\{
ActionLogger,
GameConst, GameUnitConst,
LastTurn,
- Command
+ Command,
+ Json,
+ KVStorage
};
use \sammo\Constraint\Constraint;
use \sammo\Constraint\ConstraintHelper;
use sammo\CityConst;
+use sammo\Event\EventHandler;
+
use function sammo\refreshNationStaticInfo;
use function sammo\deleteNation;
use function sammo\tryRollbackInheritUniqueItem;
@@ -98,6 +102,26 @@ class che_해산 extends Command\GeneralCommand{
tryRollbackInheritUniqueItem($general);
$general->applyDB($db);
+ // 이벤트 핸들러 동작
+ $gameStor = KVStorage::getStorage($db, 'game_env');
+ $e_env = null;
+ foreach (DB::db()->query('SELECT * FROM event WHERE target = "DESTROY_NATION" ORDER BY `priority` DESC, `id` ASC') as $rawEvent) {
+ if ($e_env === null) {
+ $e_env = $gameStor->getAll(false);
+ }
+ $eventID = $rawEvent['id'];
+ $cond = Json::decode($rawEvent['condition']);
+ $action = Json::decode($rawEvent['action']);
+ $event = new EventHandler($cond, $action);
+ $e_env['currentEventID'] = $eventID;
+
+ $event->tryRunEvent($e_env);
+ }
+
+ if ($e_env !== null) {
+ $gameStor->resetCache();
+ }
+
return true;
}
diff --git a/hwe/sammo/Command/Nation/che_피장파장.php b/hwe/sammo/Command/Nation/che_피장파장.php
index 5a050e31..06095d0b 100644
--- a/hwe/sammo/Command/Nation/che_피장파장.php
+++ b/hwe/sammo/Command/Nation/che_피장파장.php
@@ -230,7 +230,9 @@ class che_피장파장 extends Command\NationCommand
$yearMonth = Util::joinYearMonth($env['year'], $env['month']);
$nationStor->setValue($cmd->getNextExecuteKey(), $yearMonth + $this->getTargetPostReqTurn());
- $destNationStor->setValue($cmd->getNextExecuteKey(), $yearMonth + static::$delayCnt);
+
+ $destDelay = max($destNationStor->getValue($cmd->getNextExecuteKey()) ?? 0, $yearMonth);
+ $destNationStor->setValue($cmd->getNextExecuteKey(), $destDelay + static::$delayCnt);
$general->applyDB($db);
diff --git a/hwe/sammo/DTO/BettingInfo.php b/hwe/sammo/DTO/BettingInfo.php
new file mode 100644
index 00000000..81970429
--- /dev/null
+++ b/hwe/sammo/DTO/BettingInfo.php
@@ -0,0 +1,46 @@
+fillCnt){
$db = DB::db();
- $nations = $db->queryFirstColumn('SELECT nation FROM general WHERE npc < 2 AND officer_level = 12');
+ $nations = $db->queryFirstColumn('SELECT nation FROM general WHERE npc < 3 AND officer_level = 12');
$regGens = $db->queryFirstField('SELECT count(*) FROM general WHERE nation IN %li AND npc < 4', $nations);
$moreGenCnt = count($nations) * $this->fillCnt - $regGens;
}
diff --git a/hwe/sammo/Event/Action/FinishNationBetting.php b/hwe/sammo/Event/Action/FinishNationBetting.php
new file mode 100644
index 00000000..6cecba38
--- /dev/null
+++ b/hwe/sammo/Event/Action/FinishNationBetting.php
@@ -0,0 +1,64 @@
+bettingID);
+ } catch (\Exception $e) {
+ return [__CLASS__, false, $e->getMessage()];
+ }
+
+ $bettingInfo = $bettingHelper->getInfo();
+ if ($bettingInfo->type != 'bettingNation') {
+ return [__CLASS__, false, 'invalid type', $bettingInfo->type];
+ }
+
+ $winnerNations = $db->queryFirstColumn('SELECT nation FROM nation WHERE level > 0');
+ if (count($winnerNations) != $bettingInfo->selectCnt) {
+ return [__CLASS__, false, 'invalid winner cnt', $bettingInfo->selectCnt];
+ }
+
+ //nation_id와 betting_type이 일치하지 않으므로 정렬
+ $nationIDMap = [];
+ foreach ($bettingInfo->candidates as $idx => $candidate) {
+ $aux = $candidate->aux;
+ if (!$aux) {
+ return [__CLASS__, false, "invalid aux {$idx}:{$candidate->title}"];
+ }
+ $nationID = $aux['nation'];
+ $nationIDMap[$nationID] = $idx;
+ }
+
+ $winnerTypes = [];
+ foreach ($winnerNations as $winnerNationID) {
+ $winnerTypes[] = $nationIDMap[$winnerNationID];
+ }
+ $winnerTypes = $bettingHelper->purifyBettingKey($winnerTypes);
+
+ $bettingHelper->giveReward($winnerTypes);
+ $logger = new ActionLogger(0, 0, $env['year'], $env['month']);
+ [$year, $month] = Util::parseYearMonth($bettingInfo->openYearMonth);
+ $logger->pushGlobalHistoryLog("【내기】 > {$year}년 {$month}월에 열렸던 {$bettingInfo->name} 내기의 결과가 나왔습니다!");
+
+ return [__CLASS__, true];
+ }
+}
diff --git a/hwe/sammo/Event/Action/OpenNationBetting.php b/hwe/sammo/Event/Action/OpenNationBetting.php
new file mode 100644
index 00000000..8384d25c
--- /dev/null
+++ b/hwe/sammo/Event/Action/OpenNationBetting.php
@@ -0,0 +1,126 @@
+invalidateCacheValue('last_betting_id');
+ $bettingID = ($gameStor->getValue('last_betting_id') ?? 0) + 1;
+ $gameStor->setValue('last_betting_id', $bettingID);
+
+ $bettingStor = KVStorage::getStorage($db, 'betting');
+ [$year, $month] = [$env['year'], $env['month']];
+
+ if ($this->nationCnt == 1) {
+ $name = "천통국";
+ } else {
+ $name = "최후 {$this->nationCnt}국";
+ }
+
+
+ $openYearMonth = Util::joinYearMonth($year, $month);
+ $closeYearMonth = $openYearMonth + 24;
+
+ $citiesCnt = [];
+ foreach ($db->queryAllLists('SELECT nation, COUNT(*) AS cnt FROM city WHERE nation > 0 GROUP BY nation') as [$nationID, $cnt]) {
+ $citiesCnt[$nationID] = $cnt;
+ }
+
+ /** @var \sammo\DTO\SelectItem[] */
+ $candidates = [];
+
+ $nations = getAllNationStaticInfo();
+ uasort($nations, function($lhs, $rhs){
+ return -($lhs['power'] <=> $rhs['power']);
+ });
+
+ foreach ($nations as $nationRaw) {
+ $nationID = $nationRaw['nation'];
+ $cityCnt = $citiesCnt[$nationID] ?? 0;
+ $nationRaw['city_cnt'] = $cityCnt;
+ $info = [
+ "국력: {$nationRaw['power']}",
+ "장수 수: {$nationRaw['gennum']}",
+ "도시 수: {$cityCnt}",
+ ];
+
+ //NOTE: 도시 정보도 추가?
+ $candidates[] = new SelectItem(
+ title: $nationRaw['name'],
+ info: join(" ", $info),
+ isHtml: true,
+ aux: $nationRaw,
+ );
+ }
+
+ $bettingInfo = new BettingInfo(
+ id: $bettingID,
+ type: 'bettingNation',
+ name: "{$name} 예상",
+ finished: false,
+ selectCnt: $this->nationCnt,
+ reqInheritancePoint: true,
+ openYearMonth: $openYearMonth,
+ closeYearMonth: $closeYearMonth,
+ candidates: $candidates,
+ );
+ $bettingStor->setValue("id_{$bettingID}", $bettingInfo->toArray());
+
+ $db->insert('event', [
+ 'target' => 'DESTROY_NATION',
+ 'priority' => 1000,
+ 'condition' => Json::encode(
+ ["RemainNation", "<=", $this->nationCnt],
+ ),
+ 'action' => Json::encode([
+ ["FinishNationBetting", $bettingID],
+ ["DeleteEvent"],
+ ]),
+ ]);
+
+ if ($this->bonusPoint > 0) {
+ $db->insert('ng_betting', [
+ 'betting_id' => $bettingID,
+ 'general_id' => 0,
+ 'betting_type' => '[-1]',
+ 'amount' => $this->bonusPoint
+ ]);
+ }
+
+ $logger = new \sammo\ActionLogger(0, 0, $year, $month);
+ if ($this->nationCnt > 1) {
+ $logger->pushGlobalHistoryLog("【내기】 >중원의 강자를 점치는 내기>가 진행중입니다! 호사가의 참여를 기다립니다!");
+ } else {
+ $logger->pushGlobalHistoryLog("【내기】 >천하통일 후보를 점치는 내기>가 진행중입니다! 호사가의 참여를 기다립니다!");
+ }
+
+ $logger->flush();
+
+ return [__CLASS__, true];
+ }
+}
diff --git a/hwe/sammo/Event/Action/RaiseInvader.php b/hwe/sammo/Event/Action/RaiseInvader.php
index 186c6174..6e48412b 100644
--- a/hwe/sammo/Event/Action/RaiseInvader.php
+++ b/hwe/sammo/Event/Action/RaiseInvader.php
@@ -204,12 +204,16 @@ class RaiseInvader extends \sammo\Event\Action
$nationObj->postBuild($env);
refreshNationStaticInfo();
$db->insert('event', [
+ 'target' => 'month',
+ 'priority' => 1000,
'condition' => Json::encode(true),
'action' => Json::encode([["AutoDeleteInvader", $invaderNationID]]),
]);
}
$db->insert('event', [
+ 'target' => 'month',
+ 'priority' => 1000,
'condition' => Json::encode(true),
'action' => Json::encode([["InvaderEnding"]]),
]);
diff --git a/hwe/sammo/Event/Condition/RemainNation.php b/hwe/sammo/Event/Condition/RemainNation.php
new file mode 100644
index 00000000..5488aa85
--- /dev/null
+++ b/hwe/sammo/Event/Condition/RemainNation.php
@@ -0,0 +1,50 @@
+true,
+ '!='=>true,
+ '<'=>true,
+ '>'=>true,
+ '<='=>true,
+ '>='=>true,
+ ];
+
+ private $cmp;
+ private $cnt;
+
+ public function __construct(string $cmp, int $cnt){
+ //Cmp('==', '!=', '<=', '>=', '<', '>'), Cnt
+ if(!array_key_exists($cmp, self::AVAILABLE_CMP)){
+ throw new \InvalidArgumentException('올바르지 않은 비교연산자입니다');
+ }
+
+ $this->cmp = $cmp;
+ $this->cnt = $cnt;
+ }
+
+ public function eval($env=null){
+ $lhs = count(getAllNationStaticInfo());
+ $rhs = $this->cnt;
+
+ $value = false;
+ switch($this->cmp){
+ case '==': $value = ($lhs == $rhs); break;
+ case '!=': $value = ($lhs != $rhs); break;
+ case '<=': $value = ($lhs <= $rhs); break;
+ case '>=': $value = ($lhs >= $rhs); break;
+ case '<': $value = ($lhs < $rhs); break;
+ case '>': $value = ($lhs > $rhs); break;
+ }
+
+ return [
+ 'value'=>$value,
+ 'chain'=>[__CLASS__]
+ ];
+
+ }
+}
\ No newline at end of file
diff --git a/hwe/sammo/GeneralAI.php b/hwe/sammo/GeneralAI.php
index fd14f1b7..08189fb8 100644
--- a/hwe/sammo/GeneralAI.php
+++ b/hwe/sammo/GeneralAI.php
@@ -4137,7 +4137,7 @@ class GeneralAI
$dedicationList = array_map(function (General $general) {
return $general->getRaw();
}, array_filter($this->nationGenerals, function (General $rawGeneral) {
- return $rawGeneral->getVar('officer_level') != 5;
+ return $rawGeneral->getVar('npc') != 5;
}));
$riceIncome = getRiceIncome($nation['nation'], $nation['level'], $nation['rate'], $nation['capital'], $nation['type'], $cityList);
diff --git a/hwe/sammo/ResetHelper.php b/hwe/sammo/ResetHelper.php
index 5c188c0c..d2638a54 100644
--- a/hwe/sammo/ResetHelper.php
+++ b/hwe/sammo/ResetHelper.php
@@ -133,6 +133,8 @@ class ResetHelper{
$gameStor = KVStorage::getStorage($db, 'game_env');
$gameStor->resetValues();
$gameStor->next_season_idx = $seasonIdx;
+ $bettingStor = KVStorage::getStorage($db, 'betting');
+ $bettingStor->resetValues();
$lastExecuteStor = KVStorage::getStorage($db, 'next_execute');
$lastExecuteStor->resetValues();
diff --git a/hwe/sammo/Scenario.php b/hwe/sammo/Scenario.php
index 18872702..00578c40 100644
--- a/hwe/sammo/Scenario.php
+++ b/hwe/sammo/Scenario.php
@@ -19,7 +19,7 @@ class Scenario{
private $title;
private $history;
-
+
/** @var \sammo\Scenario\Nation[] */
private $nations;
/** @var \sammo\Scenario\Nation[] */
@@ -52,7 +52,7 @@ class Scenario{
}
list(
- $affinity, $name, $picturePath, $nationName, $locatedCity,
+ $affinity, $name, $picturePath, $nationName, $locatedCity,
$leadership, $strength, $intel, $officerLevel, $birth, $death, $ego,
$char, $text
) = $rawGeneral;
@@ -70,9 +70,9 @@ class Scenario{
$this->tmpGeneralQueue[$name] = $rawGeneral;
$obj = (new Scenario\GeneralBuilder(
- $name,
+ $name,
false,
- $picturePath,
+ $picturePath,
$nationID
));
if(!$initFull){
@@ -110,22 +110,22 @@ class Scenario{
$this->nations = [];
$this->nations[0] = $neutralNation;
$this->nationsInv = [$neutralNation->getName() => $neutralNation];
-
+
foreach (Util::array_get($data['nation'],[]) as $idx=>$rawNation) {
list($name, $color, $gold, $rice, $infoText, $tech, $type, $nationLevel, $cities) = $rawNation;
$nationID = $idx+1;
-
+
$nation = new Scenario\Nation(
- $nationID,
- $name,
- $color,
- $gold,
- $rice,
- $infoText,
- $tech,
- $type,
- $nationLevel,
+ $nationID,
+ $name,
+ $color,
+ $gold,
+ $rice,
+ $infoText,
+ $tech,
+ $type,
+ $nationLevel,
$cities
);
$this->nations[$nationID] = $nation;
@@ -134,7 +134,7 @@ class Scenario{
$this->diplomacy = Util::array_get($data['diplomacy'], []);
-
+
$this->generals = array_map(function($rawGeneral){
return $this->generateGeneral($rawGeneral, false, 2);
}, Util::array_get($data['general'], []));
@@ -166,22 +166,22 @@ class Scenario{
$this->nations = [];
$this->nations[0] = $neutralNation;
$this->nationsInv = [$neutralNation->getName() => $neutralNation];
-
+
foreach (Util::array_get($data['nation'],[]) as $idx=>$rawNation) {
list($name, $color, $gold, $rice, $infoText, $tech, $type, $nationLevel, $cities) = $rawNation;
$nationID = $idx+1;
-
+
$nation = new Scenario\Nation(
- $nationID,
- $name,
- $color,
- $gold,
- $rice,
- $infoText,
- $tech,
- $type,
- $nationLevel,
+ $nationID,
+ $name,
+ $color,
+ $gold,
+ $rice,
+ $infoText,
+ $tech,
+ $type,
+ $nationLevel,
$cities
);
$this->nations[$nationID] = $nation;
@@ -190,7 +190,7 @@ class Scenario{
$this->diplomacy = Util::array_get($data['diplomacy'], []);
-
+
$this->generals = array_map(function($rawGeneral){
return $this->generateGeneral($rawGeneral, true, 2);
}, Util::array_get($data['general'], []));
@@ -211,12 +211,22 @@ class Scenario{
$this->events = array_map(function($rawEvent){
//event는 여기서 풀지 않는다. 평가만 한다.
- $cond = $rawEvent[0];
- $action = array_slice($rawEvent, 1);
-
+ $target = $rawEvent[0];
+ if(!is_string($target)){
+ throw new \RuntimeException("{$target}이 문자열이 아님");
+ }
+ $priority = $rawEvent[1];
+ if(!is_int($priority)){
+ throw new \RuntimeException("{$priority}가 정수가 아님");
+ }
+ $cond = $rawEvent[2];
+ $action = array_slice($rawEvent, 3);
+
new \sammo\Event\EventHandler($cond, $action);
-
+
return [
+ 'target' => $target,
+ 'priority' => $priority,
'cond' => $cond,
'action' => $action
];
@@ -310,7 +320,7 @@ class Scenario{
$this->initLite();
return $this->nations;
}
-
+
public function getMapTheme(){
return $this->gameConf['mapName'];
}
@@ -377,7 +387,7 @@ class Scenario{
private function buildGenerals($env){
$this->initFull();
-
+
try{
$text = \file_get_contents(ServConfig::getSharedIconPath('../hook/list.json?1'));
$storedIcons = Json::decode($text);
@@ -398,7 +408,7 @@ class Scenario{
}
$rawGeneral = $this->tmpGeneralQueue[$general->getGeneralRawName()];
- $birth = $general->getBirthYear();
+ $birth = $general->getBirthYear();
if(!key_exists($birth, $remainGenerals)){
$remainGenerals[$birth] = [];
}
@@ -432,13 +442,13 @@ class Scenario{
}
$rawGeneral = $this->tmpGeneralQueue[$general->getGeneralRawName()];
- $birth = $general->getBirthYear();
+ $birth = $general->getBirthYear();
if(!key_exists($birth, $remainGenerals)){
$remainGenerals[$birth] = [];
}
$remainGenerals[$birth][] = array_merge(['RegNeutralNPC'], $rawGeneral);
}
-
+
return $remainGenerals;
}
@@ -508,7 +518,7 @@ class Scenario{
$nation->build($env);
}
-
+
refreshNationStaticInfo();
CityHelper::flushCache();
@@ -519,6 +529,8 @@ class Scenario{
$actions[] = ['DeleteEvent'];
$this->events[] = [
+ 'target'=>'Month',
+ 'priority'=>1000,
'cond'=>['Date', '>=', $targetYear, '1'],
'action'=>$actions
];
@@ -540,6 +552,8 @@ class Scenario{
$events = array_map(function($rawEvent){
return [
+ 'target'=>$rawEvent['target'],
+ 'priority'=>$rawEvent['priority'],
'condition'=>Json::encode($rawEvent['cond']),
'action'=>Json::encode($rawEvent['action'])
];
@@ -549,7 +563,7 @@ class Scenario{
$db->insert('event', $events);
}
-
+
pushGlobalHistoryLog($this->history, $env['year'], $env['month']);
@@ -568,7 +582,7 @@ class Scenario{
foreach(glob(self::SCENARIO_PATH.'/scenario_*.json') as $scenarioPath){
$scenarioName = pathinfo(basename($scenarioPath), PATHINFO_FILENAME);
$scenarioIdx = Util::array_last(explode('_', $scenarioName));
-
+
if(!is_numeric($scenarioIdx)){
continue;
}
diff --git a/hwe/sammo/Scenario/GeneralBuilder.php b/hwe/sammo/Scenario/GeneralBuilder.php
index 4fee435c..e6f52412 100644
--- a/hwe/sammo/Scenario/GeneralBuilder.php
+++ b/hwe/sammo/Scenario/GeneralBuilder.php
@@ -671,6 +671,7 @@ class GeneralBuilder{
'intel'=>$this->intel,
'experience'=>$experience,
'dedication'=>$dedication,
+ 'dedlevel'=>1,
'officer_level'=>$officerLevel,
'gold'=>$this->gold,
'rice'=>$this->rice,
diff --git a/hwe/sammo/TurnExecutionHelper.php b/hwe/sammo/TurnExecutionHelper.php
index b13058bb..afe536d3 100644
--- a/hwe/sammo/TurnExecutionHelper.php
+++ b/hwe/sammo/TurnExecutionHelper.php
@@ -398,7 +398,7 @@ class TurnExecutionHelper
// 1달마다 처리하는 것들, 벌점 감소 및 건국,전턴,합병 -1, 군량 소모
if (!preUpdateMonthly()) {
- $gameStor->resetCache(true);
+ $gameStor->resetCache();
unlock();
throw new \RuntimeException('preUpdateMonthly() 처리 에러');
}
@@ -435,7 +435,7 @@ class TurnExecutionHelper
// 이벤트 핸들러 동작
$e_env = null;
- foreach (DB::db()->query('SELECT * from event') as $rawEvent) {
+ foreach (DB::db()->query('SELECT * FROM event WHERE target = "MONTH" ORDER BY `priority` DESC, `id` ASC') as $rawEvent) {
if ($e_env === null) {
$e_env = $gameStor->getAll(false);
}
@@ -449,7 +449,7 @@ class TurnExecutionHelper
}
if ($e_env !== null) {
- $gameStor->resetCache(true);
+ $gameStor->resetCache();
}
postUpdateMonthly();
@@ -480,7 +480,7 @@ class TurnExecutionHelper
//거래 처리
processAuction();
// 잡금 해제
- $gameStor->resetCache(true);
+ $gameStor->resetCache();
unlock();
}
}
diff --git a/hwe/scenario/scenario_0.json b/hwe/scenario/scenario_0.json
index b47e808a..b32f4dc2 100644
--- a/hwe/scenario/scenario_0.json
+++ b/hwe/scenario/scenario_0.json
@@ -8,11 +8,13 @@
},
"events":[
[
+ "month", 1000,
["or", ["Date", "==", null, 12], ["Date", "==", null, 6]],
["CreateManyNPC", 10, 10],
["DeleteEvent"]
],
[
+ "month", 1000,
["Date", "==", 181, 1],
["RaiseNPCNation"],
["DeleteEvent"]
diff --git a/hwe/scenario/scenario_1.json b/hwe/scenario/scenario_1.json
index b609f4c6..b54183d7 100644
--- a/hwe/scenario/scenario_1.json
+++ b/hwe/scenario/scenario_1.json
@@ -11,11 +11,13 @@
},
"events":[
[
+ "month", 1000,
["or", ["Date", "==", null, 12], ["Date", "==", null, 6]],
["CreateManyNPC", 10, 10],
["DeleteEvent"]
],
[
+ "month", 1000,
["Date", "==", 181, 1],
["RaiseNPCNation"],
["DeleteEvent"]
diff --git a/hwe/scenario/scenario_1010.json b/hwe/scenario/scenario_1010.json
index 1a39d070..7162d196 100644
--- a/hwe/scenario/scenario_1010.json
+++ b/hwe/scenario/scenario_1010.json
@@ -12,7 +12,7 @@
]],
["황건적", "#FFD700", 10000, 10000, "황건적", 500, "태평도", 2, [
"업","계교","진류","관도","정도","평원","복양","패","허창","초"
- ]]
+ ]]
],
"diplomacy":[
],
@@ -703,7 +703,7 @@
],
"history":[
"●>184년 1월:【역사모드1】 >황건적의 난",
- "●>184년 1월:【황건적】 >전국 각지에서 황건적이 들고 일어서고 있습니다."
+ "●>184년 1월:【황건적】 >전국 각지에서 황건적이 들고 일어서고 있습니다."
],
"initialEvents":[
[
diff --git a/hwe/scenario/scenario_1020.json b/hwe/scenario/scenario_1020.json
index d6ce37d6..5cdab1e2 100644
--- a/hwe/scenario/scenario_1020.json
+++ b/hwe/scenario/scenario_1020.json
@@ -20,7 +20,7 @@
"진류"
]],
["유언", "#483D8B", 10000, 10000, "익주 주자사 유언", 1000, "유가", 3, [
- "성도", "면죽", "자동", "강주"
+ "성도", "면죽", "자동", "강주"
]],
["원술", "#FFC0CB", 10000, 10000, "4세 5공 명문 혈통 원소의 사촌 원술", 1000, "병가", 2, [
"완"
@@ -67,7 +67,7 @@
["공주", "#800080", 10000, 10000, "공주", 1000, "도가", 3, [
"초"
]]
-
+
],
"diplomacy":[
[1, 2, 1, 36],
diff --git a/hwe/scenario/scenario_1070.json b/hwe/scenario/scenario_1070.json
index d4aff9e3..5b84996f 100644
--- a/hwe/scenario/scenario_1070.json
+++ b/hwe/scenario/scenario_1070.json
@@ -8,8 +8,8 @@
},
"nation":[
["조조", "#000080", 10000, 10000, "하북을 제패하고 대군을 이끌고 남하하는 조조", 1000, "병가", 6, [
- "허창", "역경", "계교", "관도", "호관", "정도", "호로", "사곡", "함곡", "사수", "서주", "계",
- "북평", "진양", "남피", "평원", "하내", "업", "북해", "복양", "장안", "홍농", "낙양", "진류",
+ "허창", "역경", "계교", "관도", "호관", "정도", "호로", "사곡", "함곡", "사수", "서주", "계",
+ "북평", "진양", "남피", "평원", "하내", "업", "북해", "복양", "장안", "홍농", "낙양", "진류",
"패", "초", "하비", "완", "여남", "수춘", "신야", "양양", "강릉", "장판"
]],
["손권", "#FF0000", 10000, 10000, "조조의 남하에 유비와 불가침으로 맞서는 손권", 1000, "덕가", 4, [
diff --git a/hwe/scenario/scenario_2.json b/hwe/scenario/scenario_2.json
index 12f63c82..0b577eb9 100644
--- a/hwe/scenario/scenario_2.json
+++ b/hwe/scenario/scenario_2.json
@@ -15,11 +15,13 @@
},
"events":[
[
+ "month", 1000,
["or", ["Date", "==", null, 12], ["Date", "==", null, 6]],
["CreateManyNPC", 10, 10],
["DeleteEvent"]
],
[
+ "month", 1000,
["Date", "==", 181, 1],
["RaiseNPCNation"],
["DeleteEvent"]
diff --git a/hwe/scenario/scenario_2300.json b/hwe/scenario/scenario_2300.json
index 0aac9133..05f52f65 100644
--- a/hwe/scenario/scenario_2300.json
+++ b/hwe/scenario/scenario_2300.json
@@ -99,11 +99,13 @@
],
"events":[
[
+ "month", 1000,
["or", ["Date", "==", null, 12], ["Date", "==", null, 6]],
["CreateManyNPC", 10, 10],
["DeleteEvent"]
],
[
+ "month", 1000,
["Date", "==", 181, 1],
["RaiseNPCNation"],
["DeleteEvent"]
diff --git a/hwe/scenario/scenario_902.json b/hwe/scenario/scenario_902.json
index 987283e5..0ca1b5e0 100644
--- a/hwe/scenario/scenario_902.json
+++ b/hwe/scenario/scenario_902.json
@@ -59,11 +59,13 @@
},
"events":[
[
+ "month", 1000,
["Date", "==", null, 12],
["CreateManyNPC", 10, 10],
["DeleteEvent"]
],
[
+ "month", 1000,
["Date", "==", 182, 1],
["ChangeCity", "occupied", {
"trade":100
@@ -71,6 +73,7 @@
["DeleteEvent"]
],
[
+ "month", 1000,
["Date", "==", 182, 7],
["ChangeCity", "occupied", {
"trade":100
diff --git a/hwe/scenario/scenario_903.json b/hwe/scenario/scenario_903.json
index f99a15af..ab39c555 100644
--- a/hwe/scenario/scenario_903.json
+++ b/hwe/scenario/scenario_903.json
@@ -11,11 +11,13 @@
],
"events": [
[
+ "month", 1000,
["Date", "==", null, 12],
["CreateManyNPC", 100, 0],
["DeleteEvent"]
],
[
+ "month", 1000,
["Date", "==", 181, 12],
["ChangeCity", "occupied", {
"pop": "+60000",
diff --git a/hwe/scenario/scenario_904.json b/hwe/scenario/scenario_904.json
new file mode 100644
index 00000000..05452c20
--- /dev/null
+++ b/hwe/scenario/scenario_904.json
@@ -0,0 +1,184 @@
+{
+ "title":"【이벤트】 대리전",
+ "startYear":180,
+ "map":{
+ "mapName":"miniche_b"
+ },
+ "history":[
+ "●>180년 1월:【이벤트】 >NPC 군주 뒤에 플레이해보는 이벤트 깃수"
+ ],
+ "const": {
+ "joinRuinedNPCProp":0,
+ "availableGeneralCommand": {
+ "": [
+ "휴식",
+ "che_요양"
+ ],
+ "내정": [
+ "che_농지개간",
+ "che_상업투자",
+ "che_기술연구",
+ "che_수비강화",
+ "che_성벽보수",
+ "che_치안강화",
+ "che_정착장려",
+ "che_주민선정",
+ "che_물자조달"
+ ],
+ "군사": [
+ "che_소집해제",
+ "che_첩보",
+ "che_징병",
+ "che_모병",
+ "che_훈련",
+ "che_사기진작",
+ "che_출병"
+ ],
+ "인사": [
+ "che_이동",
+ "che_강행",
+ "che_인재탐색",
+ "che_집합",
+ "che_귀환",
+ "che_랜덤임관"
+ ],
+ "계략": [
+ "che_화계",
+ "che_파괴",
+ "che_탈취",
+ "che_선동"
+ ],
+ "개인": [
+ "che_내정특기초기화",
+ "che_전투특기초기화",
+ "che_단련",
+ "che_숙련전환",
+ "che_견문",
+ "che_장비매매",
+ "che_군량매매",
+ "che_증여",
+ "che_헌납",
+ "che_하야"
+ ]
+ },
+ "availableChiefCommand": {
+ "휴식": [
+ "휴식"
+ ],
+ "인사": [
+ "che_발령",
+ "che_포상",
+ "che_몰수"
+ ],
+ "특수": [
+ "che_초토화",
+ "che_천도",
+ "che_증축",
+ "che_감축"
+ ],
+ "전략": [
+ "che_필사즉생",
+ "che_백성동원",
+ "che_수몰",
+ "che_허보",
+ "che_의병모집",
+ "che_이호경식",
+ "che_급습"
+ ],
+ "기타": [
+ "che_피장파장",
+ "che_국기변경",
+ "che_국호변경"
+ ]
+ }
+ },
+ "nation":[
+ ["엄백호", "#800080", 10000, 10000, "엄백호", 500, "che_덕가", 1, ["건안"]],
+ ["맹획", "#A0522D", 10000, 10000, "맹획", 500, "che_덕가", 1, ["월수"]],
+ ["유표", "#E0FFFF", 10000, 10000, "유표", 500, "che_도가", 1, ["영릉"]],
+ ["올돌골", "#800000", 10000, 10000, "올돌골", 500, "che_도적", 1, ["남해"]],
+ ["동탁", "#A9A9A9", 10000, 10000, "동탁", 500, "che_도적", 1, ["안정"]],
+ ["유비", "#008000", 10000, 10000, "유비", 500, "che_명가", 1, ["평원"]],
+ ["유기", "#008080", 10000, 10000, "유기", 500, "che_명가", 1, ["강하"]],
+ ["유장", "#483D8B", 10000, 10000, "유장", 500, "che_묵가", 1, ["덕양"]],
+ ["조조", "#000080", 10000, 10000, "조조", 500, "che_법가", 1, ["진류"]],
+ ["원소", "#FF00FF", 10000, 10000, "원소", 500, "che_병가", 1, ["거록"]],
+ ["공손찬", "#87CEEB", 10000, 10000, "공손찬", 500, "che_병가", 1, ["계"]],
+ ["신라", "#FFA500", 10000, 10000, "신라", 500, "che_불가", 1, ["계림"]],
+ ["고구려", "#FF6347", 10000, 10000, "고구려", 500, "che_불가", 1, ["국내"]],
+ ["장로", "#20B2AA", 10000, 10000, "장로", 500, "che_오두미도", 1, ["상용"]],
+ ["도겸", "#00FF00", 10000, 10000, "도겸", 500, "che_오두미도", 1, ["하비"]],
+ ["손권", "#FF0000", 10000, 10000, "손권", 500, "che_유가", 1, ["오"]],
+ ["헌제", "#BA55D3", 10000, 10000, "헌제", 500, "che_유가", 1, ["홍농"]],
+ ["원술", "#FFC0CB", 10000, 10000, "원술", 500, "che_음양가", 1, ["여남"]],
+ ["마등", "#808000", 10000, 10000, "마등", 500, "che_종횡가", 1, ["무도"]],
+ ["목록대왕", "#7CFC00", 10000, 10000, "목록대왕", 500, "che_종횡가", 1, ["건녕"]],
+ ["장량", "#FFD700", 10000, 10000, "장량", 500, "che_태평도", 1, ["하내"]]
+ ],
+ "general":[
+ [999, "엄백호", 1217, 1, null, 85, 85, 85, 12, 150, 250, null, null],
+ [999, "맹획", 1108, 2, null, 85, 85, 85, 12, 150, 250, null, null],
+ [999, "유표", 1293, 3, null, 85, 85, 85, 12, 150, 250, null, null],
+ [999, "올돌골", 1241, 4, null, 85, 85, 85, 12, 150, 250, null, null],
+ [999, "동탁", 1083, 5, null, 85, 85, 85, 12, 150, 250, null, null],
+ [999, "유비", 1281, 6, null, 85, 85, 85, 12, 150, 250, null, null],
+ [999, "유기", 1276, 7, null, 85, 85, 85, 12, 150, 250, null, null],
+ [999, "유장", 1290, 8, null, 85, 85, 85, 12, 150, 250, null, null],
+ [999, "조조", 1392, 9, null, 85, 85, 85, 12, 150, 250, null, null],
+ [999, "원소", 1268, 10, null, 85, 85, 85, 12, 150, 250, null, null],
+ [999, "공손찬", 1033, 11, null, 85, 85, 85, 12, 150, 250, null, null],
+ [999, "석벌휴", null, 12, null, 85, 85, 85, 12, 150, 250, null, null],
+ [999, "고남무", null, 13, null, 85, 85, 85, 12, 150, 250, null, null],
+ [999, "장로", 1319, 14, null, 85, 85, 85, 12, 150, 250, null, null],
+ [999, "도겸", 1074, 15, null, 85, 85, 85, 12, 150, 250, null, null],
+ [999, "손권", 1169, 16, null, 85, 85, 85, 12, 150, 250, null, null],
+ [999, "헌제", 1002, 17, null, 85, 85, 85, 12, 150, 250, null, null],
+ [999, "원술", 1269, 18, null, 85, 85, 85, 12, 150, 250, null, null],
+ [999, "마등", 1094, 19, null, 85, 85, 85, 12, 150, 250, null, null],
+ [999, "목록대왕", 1110, 20, null, 85, 85, 85, 12, 150, 250, null, null],
+ [999, "장량", 1318, 21, null, 85, 85, 85, 12, 150, 250, null, null]
+ ],
+ "events":[
+ [
+ "month", 1000,
+ ["or", ["Date", "==", null, 12], ["Date", "==", null, 6]],
+ ["CreateManyNPC", 10, 10],
+ ["DeleteEvent"]
+ ],
+ [
+ "month", 1000,
+ ["Date", "==", 181, 1],
+ ["OpenNationBetting", 4, 1000],
+ ["OpenNationBetting", 1, 1000],
+ ["DeleteEvent"]
+ ],
+ [
+ "month", 1000,
+ ["and",
+ ["Date", ">=", 183, 1],
+ ["RemainNation", "<=", 16]
+ ],
+ ["OpenNationBetting", 4, 1000],
+ ["OpenNationBetting", 1, 1000],
+ ["DeleteEvent"]
+ ],
+ [
+ "month", 1000,
+ ["and",
+ ["Date", ">=", 183, 1],
+ ["RemainNation", "<=", 8]
+ ],
+ ["OpenNationBetting", 1, 1000],
+ ["DeleteEvent"]
+ ],
+ [
+ "month", 1000,
+ ["and",
+ ["Date", ">=", 183, 1],
+ ["RemainNation", "<=", 4]
+ ],
+ ["OpenNationBetting", 1, 1000],
+ ["DeleteEvent"]
+ ]
+ ]
+}
\ No newline at end of file
diff --git a/hwe/scss/nationBetting.scss b/hwe/scss/nationBetting.scss
new file mode 100644
index 00000000..50f4d698
--- /dev/null
+++ b/hwe/scss/nationBetting.scss
@@ -0,0 +1,62 @@
+@import '@scss/common/bootstrap5.scss';
+@import "@scss/game_bg.scss";
+@import "@scss/util.scss";
+
+
+@include media-1000px {
+ #container {
+ width: 1000px;
+ margin: 0 auto;
+ position: relative;
+ }
+}
+
+@include media-500px {
+ #container {
+ position: relative;
+ width: 500px;
+ margin: auto;
+ overflow-x: hidden;
+ }
+}
+
+.bettingCandidate{
+ border: gray 1px solid;
+ border-radius: 0.5em;
+ overflow: hidden;
+ cursor: pointer;
+
+ .title{
+ background-clip: padding-box;
+ text-align: center;
+ }
+
+ .info{
+ padding: 1ch;
+ }
+
+ .pickRate{
+ padding: 1ch;
+ }
+}
+
+.bettingCandidate.picked{
+ outline: white 1.5px solid;
+ border: white 1px solid;
+ .title{
+ font-weight: bolder;
+ }
+}
+
+.bettingList{
+ margin-top: 1em;
+}
+
+.bettingItem{
+ margin: 0.25em;
+ cursor: pointer;
+
+ &:hover{
+ text-decoration: underline;
+ }
+}
\ No newline at end of file
diff --git a/hwe/sql/reset.sql b/hwe/sql/reset.sql
index a18f0f28..90015539 100644
--- a/hwe/sql/reset.sql
+++ b/hwe/sql/reset.sql
@@ -62,4 +62,6 @@ CREATE TABLE `reserved_open` (
INDEX `date` (`date`)
)
DEFAULT CHARSET=utf8mb4
-ENGINE=Aria;
\ No newline at end of file
+ENGINE=Aria;
+
+DROP TABLE IF EXISTS ng_betting;
\ No newline at end of file
diff --git a/hwe/sql/schema.sql b/hwe/sql/schema.sql
index 3e052ee0..c7753c4c 100644
--- a/hwe/sql/schema.sql
+++ b/hwe/sql/schema.sql
@@ -507,9 +507,14 @@ ENGINE=Aria DEFAULT CHARSET=utf8mb4;
CREATE TABLE `event` (
`id` INT(11) NOT NULL AUTO_INCREMENT,
- `condition` MEDIUMTEXT NOT NULL CHECK (json_valid(`condition`)),
- `action` MEDIUMTEXT NOT NULL CHECK (json_valid(`action`)),
- PRIMARY KEY (`id`)
+ `target` ENUM('MONTH','OCCUPY_CITY','DESTROY_NATION') NOT NULL DEFAULT 'MONTH',
+ `priority` INT(11) NOT NULL DEFAULT '1000',
+ `condition` MEDIUMTEXT NOT NULL,
+ `action` MEDIUMTEXT NOT NULL,
+ PRIMARY KEY (`id`),
+ INDEX `target` (`target`, `priority`, `id`),
+ CONSTRAINT `condition` CHECK (json_valid(`condition`)),
+ CONSTRAINT `action` CHECK (json_valid(`action`))
)
DEFAULT CHARSET=utf8mb4
ENGINE=Aria;
@@ -673,4 +678,21 @@ CREATE TABLE IF NOT EXISTS `user_record` (
)
DEFAULT CHARSET=utf8mb4
ENGINE=Aria
-;
\ No newline at end of file
+;
+
+CREATE TABLE `ng_betting` (
+ `id` INT(11) NOT NULL AUTO_INCREMENT,
+ `betting_id` INT(11) NOT NULL,
+ `general_id` INT(11) NOT NULL,
+ `user_id` INT(11) NULL DEFAULT NULL,
+ `betting_type` VARCHAR(100) NOT NULL COMMENT 'JSON',
+ `amount` INT(11) NOT NULL,
+ PRIMARY KEY (`id`),
+ UNIQUE INDEX `by_general` (`general_id`, `betting_id`, `betting_type`),
+ UNIQUE INDEX `by_bet` (`betting_id`, `betting_type`, `general_id`),
+ INDEX `by_user` (`user_id`, `betting_id`, `betting_type`),
+ CONSTRAINT `type_json` CHECK (json_valid(`betting_type`))
+)
+DEFAULT CHARSET=utf8mb4
+ENGINE=Aria
+;
diff --git a/hwe/templates/allButton.php b/hwe/templates/allButton.php
index f398492f..f1bfd702 100644
--- a/hwe/templates/allButton.php
+++ b/hwe/templates/allButton.php
@@ -5,7 +5,7 @@
=$btnBegin??''?>">연감 =$btnEnd??''?>
=$btnBegin??''?>">명예의전당 =$btnEnd??''?>
=$btnBegin??''?>">왕조일람 =$btnEnd??''?>
-=$btnBegin??''?>">접속량정보 =$btnEnd??''?>
+=$btnBegin??''?>">천통국 베팅 =$btnEnd??''?>
=$btnBegin??''?>">삼모게시판 =$btnEnd??''?>
=$btnBegin??''?>">팁/강좌 =$btnEnd??''?>
=$btnBegin??''?>">삼국 일보 =$btnEnd??''?>
diff --git a/hwe/ts/@types/types__react/index.d.ts b/hwe/ts/@types/types__react/index.d.ts
new file mode 100644
index 00000000..693da49f
--- /dev/null
+++ b/hwe/ts/@types/types__react/index.d.ts
@@ -0,0 +1 @@
+export {}
\ No newline at end of file
diff --git a/hwe/ts/PageInheritPoint.vue b/hwe/ts/PageInheritPoint.vue
index 9518c036..8be38a91 100644
--- a/hwe/ts/PageInheritPoint.vue
+++ b/hwe/ts/PageInheritPoint.vue
@@ -105,7 +105,7 @@
diff --git a/hwe/ts/PageJoin.vue b/hwe/ts/PageJoin.vue
index 8d8298cc..dd79678a 100644
--- a/hwe/ts/PageJoin.vue
+++ b/hwe/ts/PageJoin.vue
@@ -197,7 +197,7 @@
@@ -263,19 +263,19 @@
@@ -533,6 +533,13 @@ export default defineComponent({
async submitForm() {
//검증은 언제 되어야 하는가?
const args = clone(this.args);
+ const totalStat = args.leadership + args.strength + args.intel;
+
+ if(totalStat < stats.total){
+ if(!confirm(`설정한 능력치가 ${totalStat}으로, 실제 최대치인 ${stats.total}보다 적습니다.\r\n그래도 진행할까요?`)){
+ return false;
+ }
+ }
try {
await SammoAPI.General.Join(args);
} catch (e) {
diff --git a/hwe/ts/PageNPCControl.vue b/hwe/ts/PageNPCControl.vue
index 345cbc10..84ad30d6 100644
--- a/hwe/ts/PageNPCControl.vue
+++ b/hwe/ts/PageNPCControl.vue
@@ -472,7 +472,7 @@ import {
ToastType,
} from "@/defs";
import NumberInputWithInfo from "@/components/NumberInputWithInfo.vue";
-import { cloneDeep, isEqual, last } from "lodash";
+import { cloneDeep, isEqual, isNumber, last } from "lodash";
import { unwrap } from "@util/unwrap";
import { convertFormData } from "@util/convertFormData";
import axios from "axios";
@@ -505,7 +505,7 @@ type SetterInfo = {
};
declare const lastSetters: {
- polcy: SetterInfo;
+ policy: SetterInfo;
nation: SetterInfo;
general: SetterInfo;
};
@@ -592,14 +592,18 @@ export default defineComponent({
},
calcPolicyValue(
title: keyof NationPolicy
- ): NationPolicy[keyof NationPolicy] {
+ ): number {
if (!(title in this.nationPolicy)) {
throw `${title}이 NationPolicy key가 아님`;
}
- if (this.nationPolicy[title] == 0) {
- return this.zeroPolicy[title];
+ const policyValue = this.nationPolicy[title];
+ if(!isNumber(policyValue)){
+ throw `${title}에 해당하는 값이 number가 아님`;
}
- return this.nationPolicy[title];
+ if (policyValue == 0) {
+ return this.zeroPolicy[title] as number;
+ }
+ return policyValue;
},
resetNationPriority() {
if (!confirm("초기 설정으로 되돌릴까요?")) {
diff --git a/hwe/ts/PageNationBetting.vue b/hwe/ts/PageNationBetting.vue
new file mode 100644
index 00000000..909bd86d
--- /dev/null
+++ b/hwe/ts/PageNationBetting.vue
@@ -0,0 +1,90 @@
+
+
+
+
+
+
로딩 중...
+
+
베팅 목록
+
+ [{{ parseYearMonth(info.openYearMonth)[0] }}년 {{ parseYearMonth(info.openYearMonth)[1] }}월] {{ info.name }}
+ (종료)
+ ({{ parseYearMonth(info.closeYearMonth)[0] }}년 {{ parseYearMonth(info.closeYearMonth)[1] }}월까지)
+ (베팅 마감)
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/hwe/ts/PageNationStratFinan.vue b/hwe/ts/PageNationStratFinan.vue
index 10f4d5b8..8775cecf 100644
--- a/hwe/ts/PageNationStratFinan.vue
+++ b/hwe/ts/PageNationStratFinan.vue
@@ -44,7 +44,7 @@
= 2) {
return 'cyan';
}
if (npcType == 1) {
return 'skyblue';
}
- return null;
+ return undefined;
}
diff --git a/hwe/ts/components/BettingDetail.vue b/hwe/ts/components/BettingDetail.vue
new file mode 100644
index 00000000..caafdd1f
--- /dev/null
+++ b/hwe/ts/components/BettingDetail.vue
@@ -0,0 +1,436 @@
+
+
+
+ {{ info.name }}
+ (종료)
+ ({{ parseYearMonth(info.closeYearMonth)[0] }}년 {{ parseYearMonth(info.closeYearMonth)[1] }}월까지)
+ (베팅 마감)
+ (총액: {{ bettingAmount.toLocaleString() }})
+
+
+
+
+
+
{{ candidate.title }}
+
+
선택율: {{ ((partialBet.get(idx) ?? 0) / pureBettingAmount * 100).toFixed(1) }}%
+
+
+
+
+
잔여 {{ info.reqInheritancePoint ? '포인트' : '금' }} : {{ bettingDetailInfo.remainPoint.toLocaleString() }}
+
사용 포인트: {{ sum(Array.from(myBettings.values())).toLocaleString() }}
+
대상: {{ getTypeStr(pickedBetTypeKey) }}
+
+
+
+
+ 베팅
+
+
+
+
+
배당 순위
+
+
대상
+
베팅액
+
내 베팅
+
{{ info.finished? '배율':'기대 배율' }}
+
+
+
+
+ {{ getTypeStr(betType) }}
+ {{ amount.toLocaleString() }}
+
+ ({{ subPoint.toLocaleString() }} -> {{ calculatedReward[matchPoint] == 0? 0 : (subPoint * calculatedReward[matchPoint] / (calculatedSubAmount.get(matchPoint)??1)).toFixed(1).toLocaleString() }})
+
+
+ {{ (calculatedReward[matchPoint] == 0? 0 : (calculatedReward[matchPoint] / (calculatedSubAmount.get(matchPoint)??1))).toFixed(1).toLocaleString() }}배
+
+
+
+
+
+
{{ getTypeStr(betType) }}
+
{{ amount.toLocaleString() }}
+
+ ({{ subPoint.toLocaleString() }} -> {{ (subPoint * maxBettingReward / amount).toFixed(1).toLocaleString() }})
+
+
+
{{ (maxBettingReward / amount).toFixed(1).toLocaleString() }}배
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/hwe/ts/components/MyToast.vue b/hwe/ts/components/MyToast.vue
index a6442e3d..bb57c86a 100644
--- a/hwe/ts/components/MyToast.vue
+++ b/hwe/ts/components/MyToast.vue
@@ -6,7 +6,7 @@
{{ toast.title }}
-
{{ toast.content }} {{ toast.visible }}
+
{{ toast.content }}
@@ -64,7 +64,7 @@ export default defineComponent({
doneMap.clear();
toasts.value.length = 0;
- emit("update:modelValue", toasts);
+ emit("update:modelValue", toasts.value);
}
watch(props.modelValue, (values) => {
diff --git a/hwe/ts/defs.ts b/hwe/ts/defs.ts
index c5840288..173e5c22 100644
--- a/hwe/ts/defs.ts
+++ b/hwe/ts/defs.ts
@@ -223,3 +223,25 @@ export const diplomacyStateInfo: Record
= {
2: { name: '통상' },
7: { name: '불가침', color: 'green' },
}
+
+
+export type SelectItem = {
+ title: string;
+ info?: string;
+ isHtml?: boolean;
+ aux?: Record;
+}
+
+export type BettingInfo = {
+ id: number;
+ type: 'nationBetting',
+ name: string;
+ finished: boolean;
+ selectCnt: number;
+ isExclusive?: boolean;
+ reqInheritancePoint: boolean;
+ openYearMonth: number;
+ closeYearMonth: number;
+ candidates: SelectItem[];
+ winner?: number[];
+}
\ No newline at end of file
diff --git a/hwe/ts/extKingdoms.ts b/hwe/ts/extKingdoms.ts
index c03b13ad..51b5d72d 100644
--- a/hwe/ts/extKingdoms.ts
+++ b/hwe/ts/extKingdoms.ts
@@ -3,6 +3,13 @@ import { unwrap } from '@util/unwrap';
import axios from 'axios';
import { setAxiosXMLHttpRequest } from '@util/setAxiosXMLHttpRequest';
+declare const killturn: number;
+declare const autorun_user: undefined|null|{
+ limit_minutes: number;
+ options: Record;
+};
+declare const turnterm: number;
+
type KingdomGeneral = {
html: JQuery,
장수명: string
@@ -83,6 +90,10 @@ $(function () {
}
const runAnalysis = async function () {
+ let realKillturn = killturn;
+ if(autorun_user && autorun_user.limit_minutes){
+ realKillturn -= autorun_user.limit_minutes / turnterm;
+ }
const $content = $('#on_mover .content');
try {
const response = await axios({ url: 'a_genList.php', method: 'get', responseType: 'text' });
@@ -197,7 +208,7 @@ $(function () {
//const 종능 = val.통 + val.무 + val.지;
console.log(val);
if (종류명 != '무능' && 종류명 != '무지') {
- if (val.삭턴 >= 80 && !val.NPC) {
+ if (val.삭턴 >= realKillturn && !val.NPC) {
전투유저장수 += 1;
통솔합 += val.통;
@@ -214,7 +225,7 @@ $(function () {
const $obj2 = $(' ');
$obj.html(val.장수명);
- if (!val.NPC && val.삭턴 < 80) {
+ if (!val.NPC && val.삭턴 < realKillturn) {
$obj.css('text-decoration', 'line-through');
삭턴장수 += 1;
}
diff --git a/hwe/ts/select_npc.ts b/hwe/ts/select_npc.ts
index 092eca73..0757c91c 100644
--- a/hwe/ts/select_npc.ts
+++ b/hwe/ts/select_npc.ts
@@ -306,10 +306,8 @@ function printGeneralList(value: GeneralListResponse) {
if (general.reserved == 1) {
general.userCSS = 'color:violet';
- } else if (general.npc >= 2) {
- general.userCSS = 'color:cyan';
- } else if (general.npc == 1) {
- general.userCSS = 'color:skyblue';
+ } else if (general.npc > 0) {
+ general.userCSS = `color:${getNPCColor(general.npc)}`;
}
if (general.ownerName) {
@@ -458,4 +456,8 @@ $(function ($) {
_printGeneralList();
})
-});
\ No newline at end of file
+});
+
+function getNPCColor(npc: number) {
+ throw new Error('Function not implemented.');
+}
diff --git a/hwe/ts/v_nationBetting.ts b/hwe/ts/v_nationBetting.ts
new file mode 100644
index 00000000..a6269476
--- /dev/null
+++ b/hwe/ts/v_nationBetting.ts
@@ -0,0 +1,12 @@
+import "@scss/nationBetting.scss";
+
+import { createApp } from 'vue'
+import PageNationBetting from '@/PageNationBetting.vue';
+import BootstrapVue3 from 'bootstrap-vue-3';
+import { auto500px } from './util/auto500px';
+
+
+
+
+auto500px();
+createApp(PageNationBetting).use(BootstrapVue3).mount('#app');
\ No newline at end of file
diff --git a/hwe/v_nationBetting.php b/hwe/v_nationBetting.php
new file mode 100644
index 00000000..a24f9a25
--- /dev/null
+++ b/hwe/v_nationBetting.php
@@ -0,0 +1,39 @@
+setReadOnly();
+$userID = Session::getUserID();
+
+$db = DB::db();
+$gameStor = KVStorage::getStorage($db, 'game_env');
+
+$generalID = $session->generalID;
+?>
+
+
+
+
+
+
+
+ = UniqueConst::$serverName ?>: 국가 베팅장
+ = WebUtil::printStaticValues([
+ 'staticValues' => [
+
+ ]
+ ], false) ?>
+ = WebUtil::printJS('../d_shared/common_path.js') ?>
+ = WebUtil::printCSS('../d_shared/common.css') ?>
+
+ = WebUtil::printDist('vue', 'v_nationBetting', true) ?>
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/package.json b/package.json
index 79e82294..5fa1576b 100644
--- a/package.json
+++ b/package.json
@@ -64,6 +64,7 @@
"@types/jquery": "^3.5.11",
"@types/lodash": "^4.14.178",
"@types/node": "^17.0.4",
+ "@types/react": "file:hwe/ts/@types/types__react",
"@typescript-eslint/eslint-plugin": "^5.8.0",
"@typescript-eslint/parser": "^5.8.0",
"@vue/compiler-sfc": "^3.2.26",
diff --git a/vendor/composer/InstalledVersions.php b/vendor/composer/InstalledVersions.php
index b54c107b..936da251 100644
--- a/vendor/composer/InstalledVersions.php
+++ b/vendor/composer/InstalledVersions.php
@@ -29,7 +29,7 @@ private static $installed = array (
'aliases' =>
array (
),
- 'reference' => '872755e57f84720a9c4c63d5455441f83c41f6c6',
+ 'reference' => 'd75f21035d2d747010efd234b5e7b3a42e0a41fd',
'name' => 'sammo-hid/sammo',
),
'versions' =>
@@ -450,7 +450,7 @@ private static $installed = array (
'aliases' =>
array (
),
- 'reference' => '872755e57f84720a9c4c63d5455441f83c41f6c6',
+ 'reference' => 'd75f21035d2d747010efd234b5e7b3a42e0a41fd',
),
'sergeytsalkov/meekrodb' =>
array (
@@ -461,6 +461,15 @@ private static $installed = array (
),
'reference' => 'e30c240d54bc81f58c58507a9ed768032eb494a5',
),
+ 'spatie/data-transfer-object' =>
+ array (
+ 'pretty_version' => '3.7.3',
+ 'version' => '3.7.3.0',
+ 'aliases' =>
+ array (
+ ),
+ 'reference' => '341f72c77e0fce40ea2e0dcb212cb54dc27bbe72',
+ ),
'symfony/console' =>
array (
'pretty_version' => 'v5.3.10',
diff --git a/vendor/composer/autoload_psr4.php b/vendor/composer/autoload_psr4.php
index 6e758f8b..7576aec0 100644
--- a/vendor/composer/autoload_psr4.php
+++ b/vendor/composer/autoload_psr4.php
@@ -27,6 +27,7 @@ return array(
'Symfony\\Component\\String\\' => array($vendorDir . '/symfony/string'),
'Symfony\\Component\\Lock\\' => array($vendorDir . '/symfony/lock'),
'Symfony\\Component\\Console\\' => array($vendorDir . '/symfony/console'),
+ 'Spatie\\DataTransferObject\\' => array($vendorDir . '/spatie/data-transfer-object/src'),
'Sabre\\Event\\' => array($vendorDir . '/sabre/event/lib'),
'Psr\\SimpleCache\\' => array($vendorDir . '/psr/simple-cache/src'),
'Psr\\Log\\' => array($vendorDir . '/psr/log/Psr/Log'),
diff --git a/vendor/composer/autoload_static.php b/vendor/composer/autoload_static.php
index 245fbae9..ce1a8b45 100644
--- a/vendor/composer/autoload_static.php
+++ b/vendor/composer/autoload_static.php
@@ -76,6 +76,7 @@ class ComposerStaticInit67b09c83b85c3bc0027caefe5bba171a
'Symfony\\Component\\String\\' => 25,
'Symfony\\Component\\Lock\\' => 23,
'Symfony\\Component\\Console\\' => 26,
+ 'Spatie\\DataTransferObject\\' => 26,
'Sabre\\Event\\' => 12,
),
'P' =>
@@ -217,6 +218,10 @@ class ComposerStaticInit67b09c83b85c3bc0027caefe5bba171a
array (
0 => __DIR__ . '/..' . '/symfony/console',
),
+ 'Spatie\\DataTransferObject\\' =>
+ array (
+ 0 => __DIR__ . '/..' . '/spatie/data-transfer-object/src',
+ ),
'Sabre\\Event\\' =>
array (
0 => __DIR__ . '/..' . '/sabre/event/lib',
diff --git a/vendor/composer/installed.json b/vendor/composer/installed.json
index ad0ee3c1..35cec1c5 100644
--- a/vendor/composer/installed.json
+++ b/vendor/composer/installed.json
@@ -2722,6 +2722,72 @@
},
"install-path": "../sergeytsalkov/meekrodb"
},
+ {
+ "name": "spatie/data-transfer-object",
+ "version": "3.7.3",
+ "version_normalized": "3.7.3.0",
+ "source": {
+ "type": "git",
+ "url": "https://github.com/spatie/data-transfer-object.git",
+ "reference": "341f72c77e0fce40ea2e0dcb212cb54dc27bbe72"
+ },
+ "dist": {
+ "type": "zip",
+ "url": "https://api.github.com/repos/spatie/data-transfer-object/zipball/341f72c77e0fce40ea2e0dcb212cb54dc27bbe72",
+ "reference": "341f72c77e0fce40ea2e0dcb212cb54dc27bbe72",
+ "shasum": ""
+ },
+ "require": {
+ "php": "^8.0"
+ },
+ "require-dev": {
+ "illuminate/collections": "^8.36",
+ "jetbrains/phpstorm-attributes": "^1.0",
+ "larapack/dd": "^1.1",
+ "phpunit/phpunit": "^9.0"
+ },
+ "time": "2021-12-30T20:31:10+00:00",
+ "type": "library",
+ "installation-source": "dist",
+ "autoload": {
+ "psr-4": {
+ "Spatie\\DataTransferObject\\": "src"
+ }
+ },
+ "notification-url": "https://packagist.org/downloads/",
+ "license": [
+ "MIT"
+ ],
+ "authors": [
+ {
+ "name": "Brent Roose",
+ "email": "brent@spatie.be",
+ "homepage": "https://spatie.be",
+ "role": "Developer"
+ }
+ ],
+ "description": "Data transfer objects with batteries included",
+ "homepage": "https://github.com/spatie/data-transfer-object",
+ "keywords": [
+ "data-transfer-object",
+ "spatie"
+ ],
+ "support": {
+ "issues": "https://github.com/spatie/data-transfer-object/issues",
+ "source": "https://github.com/spatie/data-transfer-object/tree/3.7.3"
+ },
+ "funding": [
+ {
+ "url": "https://spatie.be/open-source/support-us",
+ "type": "custom"
+ },
+ {
+ "url": "https://github.com/spatie",
+ "type": "github"
+ }
+ ],
+ "install-path": "../spatie/data-transfer-object"
+ },
{
"name": "symfony/console",
"version": "v5.3.10",
diff --git a/vendor/composer/installed.php b/vendor/composer/installed.php
index eb067000..c554846f 100644
--- a/vendor/composer/installed.php
+++ b/vendor/composer/installed.php
@@ -6,7 +6,7 @@
'aliases' =>
array (
),
- 'reference' => '872755e57f84720a9c4c63d5455441f83c41f6c6',
+ 'reference' => 'd75f21035d2d747010efd234b5e7b3a42e0a41fd',
'name' => 'sammo-hid/sammo',
),
'versions' =>
@@ -427,7 +427,7 @@
'aliases' =>
array (
),
- 'reference' => '872755e57f84720a9c4c63d5455441f83c41f6c6',
+ 'reference' => 'd75f21035d2d747010efd234b5e7b3a42e0a41fd',
),
'sergeytsalkov/meekrodb' =>
array (
@@ -438,6 +438,15 @@
),
'reference' => 'e30c240d54bc81f58c58507a9ed768032eb494a5',
),
+ 'spatie/data-transfer-object' =>
+ array (
+ 'pretty_version' => '3.7.3',
+ 'version' => '3.7.3.0',
+ 'aliases' =>
+ array (
+ ),
+ 'reference' => '341f72c77e0fce40ea2e0dcb212cb54dc27bbe72',
+ ),
'symfony/console' =>
array (
'pretty_version' => 'v5.3.10',
diff --git a/vendor/composer/platform_check.php b/vendor/composer/platform_check.php
index 580fa960..adfb472f 100644
--- a/vendor/composer/platform_check.php
+++ b/vendor/composer/platform_check.php
@@ -4,8 +4,8 @@
$issues = array();
-if (!(PHP_VERSION_ID >= 70400)) {
- $issues[] = 'Your Composer dependencies require a PHP version ">= 7.4.0". You are running ' . PHP_VERSION . '.';
+if (!(PHP_VERSION_ID >= 80000)) {
+ $issues[] = 'Your Composer dependencies require a PHP version ">= 8.0.0". You are running ' . PHP_VERSION . '.';
}
if ($issues) {
diff --git a/vendor/spatie/data-transfer-object/.github/CONTRIBUTING.md b/vendor/spatie/data-transfer-object/.github/CONTRIBUTING.md
new file mode 100644
index 00000000..b4ae1c4a
--- /dev/null
+++ b/vendor/spatie/data-transfer-object/.github/CONTRIBUTING.md
@@ -0,0 +1,55 @@
+# Contributing
+
+Contributions are **welcome** and will be fully **credited**.
+
+Please read and understand the contribution guide before creating an issue or pull request.
+
+## Etiquette
+
+This project is open source, and as such, the maintainers give their free time to build and maintain the source code
+held within. They make the code freely available in the hope that it will be of use to other developers. It would be
+extremely unfair for them to suffer abuse or anger for their hard work.
+
+Please be considerate towards maintainers when raising issues or presenting pull requests. Let's show the
+world that developers are civilized and selfless people.
+
+It's the duty of the maintainer to ensure that all submissions to the project are of sufficient
+quality to benefit the project. Many developers have different skillsets, strengths, and weaknesses. Respect the maintainer's decision, and do not be upset or abusive if your submission is not used.
+
+## Viability
+
+When requesting or submitting new features, first consider whether it might be useful to others. Open
+source projects are used by many developers, who may have entirely different needs to your own. Think about
+whether or not your feature is likely to be used by other users of the project.
+
+## Procedure
+
+Before filing an issue:
+
+- Attempt to replicate the problem, to ensure that it wasn't a coincidental incident.
+- Check to make sure your feature suggestion isn't already present within the project.
+- Check the pull requests tab to ensure that the bug doesn't have a fix in progress.
+- Check the pull requests tab to ensure that the feature isn't already in progress.
+
+Before submitting a pull request:
+
+- Check the codebase to ensure that your feature doesn't already exist.
+- Check the pull requests to ensure that another person hasn't already submitted the feature or fix.
+
+## Requirements
+
+If the project maintainer has any additional requirements, you will find them listed here.
+
+- **[PSR-2 Coding Standard](https://github.com/php-fig/fig-standards/blob/master/accepted/PSR-2-coding-style-guide.md)** - The easiest way to apply the conventions is to install [PHP Code Sniffer](https://pear.php.net/package/PHP_CodeSniffer).
+
+- **Add tests!** - Your patch won't be accepted if it doesn't have tests.
+
+- **Document any change in behaviour** - Make sure the `README.md` and any other relevant documentation are kept up-to-date.
+
+- **Consider our release cycle** - We try to follow [SemVer v2.0.0](https://semver.org/). Randomly breaking public APIs is not an option.
+
+- **One pull request per feature** - If you want to do more than one thing, send multiple pull requests.
+
+- **Send coherent history** - Make sure each individual commit in your pull request is meaningful. If you had to make multiple intermediate commits while developing, please [squash them](https://www.git-scm.com/book/en/v2/Git-Tools-Rewriting-History#Changing-Multiple-Commit-Messages) before submitting.
+
+**Happy coding**!
diff --git a/vendor/spatie/data-transfer-object/.github/FUNDING.yml b/vendor/spatie/data-transfer-object/.github/FUNDING.yml
new file mode 100644
index 00000000..fe5143b5
--- /dev/null
+++ b/vendor/spatie/data-transfer-object/.github/FUNDING.yml
@@ -0,0 +1,2 @@
+github: spatie
+custom: https://spatie.be/open-source/support-us
diff --git a/vendor/spatie/data-transfer-object/.github/workflows/style.yml b/vendor/spatie/data-transfer-object/.github/workflows/style.yml
new file mode 100644
index 00000000..502dbe70
--- /dev/null
+++ b/vendor/spatie/data-transfer-object/.github/workflows/style.yml
@@ -0,0 +1,23 @@
+name: Check & fix styling
+
+on: [push]
+
+jobs:
+ php-cs-fixer:
+ runs-on: ubuntu-latest
+
+ steps:
+ - name: Checkout code
+ uses: actions/checkout@v2
+ with:
+ ref: ${{ github.head_ref }}
+
+ - name: Run PHP CS Fixer
+ uses: docker://oskarstark/php-cs-fixer-ga
+ with:
+ args: --config=.php-cs-fixer.dist.php --allow-risky=yes
+
+ - name: Commit changes
+ uses: stefanzweifel/git-auto-commit-action@v4
+ with:
+ commit_message: Fix styling
diff --git a/vendor/spatie/data-transfer-object/.github/workflows/update-changelog.yml b/vendor/spatie/data-transfer-object/.github/workflows/update-changelog.yml
new file mode 100644
index 00000000..fa56639f
--- /dev/null
+++ b/vendor/spatie/data-transfer-object/.github/workflows/update-changelog.yml
@@ -0,0 +1,28 @@
+name: "Update Changelog"
+
+on:
+ release:
+ types: [released]
+
+jobs:
+ update:
+ runs-on: ubuntu-latest
+
+ steps:
+ - name: Checkout code
+ uses: actions/checkout@v2
+ with:
+ ref: main
+
+ - name: Update Changelog
+ uses: stefanzweifel/changelog-updater-action@v1
+ with:
+ latest-version: ${{ github.event.release.name }}
+ release-notes: ${{ github.event.release.body }}
+
+ - name: Commit updated CHANGELOG
+ uses: stefanzweifel/git-auto-commit-action@v4
+ with:
+ branch: main
+ commit_message: Update CHANGELOG
+ file_pattern: CHANGELOG.md
diff --git a/vendor/spatie/data-transfer-object/.php-cs-fixer.dist.php b/vendor/spatie/data-transfer-object/.php-cs-fixer.dist.php
new file mode 100644
index 00000000..b9a6b55a
--- /dev/null
+++ b/vendor/spatie/data-transfer-object/.php-cs-fixer.dist.php
@@ -0,0 +1,41 @@
+notPath('docs/*')
+ ->notPath('vendor')
+ ->in([
+ __DIR__.'/src',
+ __DIR__.'/tests',
+ ])
+ ->name('*.php')
+ ->ignoreDotFiles(true)
+ ->ignoreVCS(true);
+
+return (new PhpCsFixer\Config())
+ ->setRules([
+ '@PSR12' => true,
+ 'array_syntax' => ['syntax' => 'short'],
+ 'ordered_imports' => ['sort_algorithm' => 'alpha'],
+ 'no_unused_imports' => true,
+ 'not_operator_with_successor_space' => true,
+ 'trailing_comma_in_multiline' => true,
+ 'phpdoc_scalar' => true,
+ 'unary_operator_spaces' => true,
+ 'binary_operator_spaces' => true,
+ 'logical_operators' => true,
+ 'blank_line_before_statement' => [
+ 'statements' => ['break', 'continue', 'declare', 'return', 'throw', 'try'],
+ ],
+ 'phpdoc_single_line_var_spacing' => true,
+ 'phpdoc_var_without_name' => true,
+ 'class_attributes_separation' => [
+ 'elements' => [
+ 'method' => 'one'
+ ],
+ ],
+ 'method_argument_space' => [
+ 'on_multiline' => 'ensure_fully_multiline',
+ 'keep_multiple_spaces_after_comma' => true,
+ ],
+ ])
+ ->setFinder($finder);
diff --git a/vendor/spatie/data-transfer-object/CHANGELOG.md b/vendor/spatie/data-transfer-object/CHANGELOG.md
new file mode 100644
index 00000000..f498a85b
--- /dev/null
+++ b/vendor/spatie/data-transfer-object/CHANGELOG.md
@@ -0,0 +1,248 @@
+# Changelog
+
+All notable changes to `data-transfer-object` will be documented in this file
+
+## 3.7.2 - 2021-09-17
+
+- `#[Strict]` is passed down the inheritance chain so children are strict when parent is strict (#239)
+
+## 3.7.1 - 2021-09-09
+
+- Cast properties with self or parent type (#236)
+
+## 3.7.0 - 2021-08-26
+
+- Add `#[MapTo]` support (#233)
+
+## 3.6.2 - 2021-08-25
+
+- Correct behavior of Arr::forget with dot keys (#231)
+
+## 3.6.1 - 2021-08-17
+
+- Fix array assignment bug with strict dto's (#225)
+
+## 3.6.0 - 2021-08-12
+
+- Support mapped properties (#224)
+
+## 3.5.0 - 2021-08-11
+
+- Support union types in casters (#210)
+
+## 3.4.0 - 2021-08-10
+
+- Fix for an empty value being created when casting `ArrayAccess` objects (#216)
+- Add logic exception when attempting to cast `ArrayAccess` objects that are not traversable (#216)
+- Allow the `ArrayCaster` to retain values that are already instances of the `itemType` (#217)
+
+## 3.3.0 - 2021-06-01
+
+- Expose DTO and validation error array in ValidationException (#213)
+
+## 3.2.0 - 2021-05-31
+
+- Support generic casters (#199)
+- Add `ArrayCaster`
+- Add casting of objects that implement `ArrayAccess` to the `ArrayCaster` (#206)
+- Fix for caster subclass check (#204)
+
+## 3.1.1 - 2021-04-26
+
+- Make `DefaultCast` repeatable (#202)
+
+## 3.1.0 - 2021-04-21
+
+- Add `DataTransferObject::clone(...$args)`
+
+## 3.0.4 - 2021-04-14
+
+- Support union types (#185)
+- Resolve default cast from parent classes (#189)
+- Support default values (#191)
+
+## 3.0.3 - 2021-04-08
+
+- Fix when nested DTO have casted field (#178)
+
+## 3.0.2 - 2021-04-02
+
+- Allow valid DTOs to be passed to caster (#177)
+
+## 3.0.1 - 2021-04-02
+
+- Fix for null values with casters
+
+## 3.0.0 - 2021-04-02
+
+This package now focuses only on object creation by adding easy-to-use casting and data validation functionality. All runtime type checks are gone in favour of the improved type system in PHP 8.
+
+- Require `php:^8.0`
+- Removed all runtime type checking functionality, you should use typed properties and a static analysis tool like Psalm or PhpStan
+- Removed `Spatie\DataTransferObject\DataTransferObjectCollection`
+- Removed `Spatie\DataTransferObject\FlexibleDataTransferObject`, all DTOs are now considered flexible
+- Removed runtime immutable DTOs, you should use static analysis instead
+- Added `Spatie\DataTransferObject\Validator`
+- Added `Spatie\DataTransferObject\Validation\ValidationResult`
+- Added `#[DefaultCast]`
+- Added `#[CastWith]`
+- Added `Spatie\DataTransferObject\Caster`
+- Added `#[Strict]`
+
+## 2.8.3 - 2021-02-12
+
+- Add support for using `collection` internally
+
+## 2.8.2 - 2021-02-11
+
+This might be a breaking change, but it was required for a bugfix
+
+- Prevent DataTransferObjectCollection from iterating over array copy (#166)
+
+## 2.8.1 - 2021-02-10
+
+- Fix for incorrect return type (#164)
+
+## 2.8.0 - 2021-01-27
+
+- Allow the traversal of collections with string keys
+
+## 2.7.0 - 2021-01-21
+
+- Cast nested collections (#117)
+
+## 2.6.0 - 2020-11-26
+
+- Support PHP 8
+
+## 2.5.0 - 2020-08-28
+
+- Group type errors (#130)
+
+## 2.4.0 - 2020-08-28
+
+- Support for `array` syntax (#136)
+
+## 2.3.0 - 2020-08-19
+
+- Add PHPStan extension to support `checkUninitializedProperties: true` (#135)
+
+## 2.2.1 - 2020-05-13
+
+- Validator for typed 7.4 properties (#109)
+
+## 2.2.0 - 2020-05-08
+
+- Add support for typed properties to DTO casting in PHP 7.4
+
+## 2.0.0 - 2020-04-28
+
+- Bump minimum required PHP version to 7.4
+- Support for nested immutable DTOs (#86)
+
+## 1.13.3 - 2020-01-29
+
+- Ignore static properties when serializing (#88)
+
+## 1.13.2 - 2020-01-08
+
+- DataTransferObjectError::invalidType : get actual type before mutating $value for the error message (#81)
+
+## 1.13.1 - 2020-01-08
+
+- Improve extendability of DTOs (#80)
+
+## 1.13.0 - 2020-01-08
+
+- Ignore static properties (#82)
+- Add `DataTransferObject::arrayOf` (#83)
+
+## 1.12.0 - 2019-12-19
+
+- Improved performance by adding a cache (#79)
+- Add `FlexibleDataTransferObject` which allows for unknown properties to be ignored
+
+## 1.11.0 - 2019-11-28 (#71)
+
+- Add `iterable` and `iterable<\Type>` support
+
+## 1.10.0 - 2019-10-16
+
+- Allow a DTO to be constructed without an array (#68)
+
+## 1.9.1 - 2019-10-03
+
+- Improve type error message
+
+## 1.9.0 - 2019-08-30
+
+- Add DataTransferObjectCollection::items()
+
+## 1.8.0 - 2019-03-18
+
+- Support immutability
+
+## 1.7.1 - 2019-02-11
+
+- Fixes #47, allowing empty dto's to be cast to using an empty array.
+
+## 1.7.0 - 2019-02-04
+
+- Nested array DTO casting supported.
+
+## 1.6.6 - 2018-12-04
+
+- Properly support `float`.
+
+## 1.6.5 - 2018-11-20
+
+- Fix uninitialised error with default value.
+
+## 1.6.4 - 2018-11-15
+
+- Don't use `allValues` anymore.
+
+## 1.6.3 - 2018-11-14
+
+- Support nested collections in collections
+- Cleanup code
+
+## 1.6.2 - 2018-11-14
+
+- Remove too much magic in nested array casting
+
+## 1.6.1 - 2018-11-14
+
+- Support nested `toArray` in collections.
+
+## 1.6.0 - 2018-11-14
+
+- Support nested `toArray`.
+
+## 1.5.1 - 2018-11-07
+
+- Add strict type declarations
+
+## 1.5.0 - 2018-11-07
+
+- Add auto casting of nested DTOs
+
+## 1.4.0 - 2018-11-05
+
+- Rename to data-transfer-object
+
+## 1.2.0 - 2018-10-30
+
+- Add uninitialized errors.
+
+## 1.1.1 - 2018-10-25
+
+- Support instanceof on interfaces when type checking
+
+## 1.1.0 - 2018-10-24
+
+- proper support for collections of value objects
+
+## 1.0.0 - 2018-10-24
+
+- initial release
diff --git a/vendor/spatie/data-transfer-object/LICENSE.md b/vendor/spatie/data-transfer-object/LICENSE.md
new file mode 100644
index 00000000..59e5ec59
--- /dev/null
+++ b/vendor/spatie/data-transfer-object/LICENSE.md
@@ -0,0 +1,21 @@
+The MIT License (MIT)
+
+Copyright (c) Spatie bvba
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in
+all copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+THE SOFTWARE.
diff --git a/vendor/spatie/data-transfer-object/README.md b/vendor/spatie/data-transfer-object/README.md
new file mode 100644
index 00000000..e43ee4b6
--- /dev/null
+++ b/vendor/spatie/data-transfer-object/README.md
@@ -0,0 +1,504 @@
+# Data transfer objects with batteries included
+
+[](https://packagist.org/packages/spatie/data-transfer-object)
+
+[](https://packagist.org/packages/spatie/data-transfer-object)
+
+## Installation
+
+You can install the package via composer:
+
+```bash
+composer require spatie/data-transfer-object
+```
+
+* **Note**: v3 of this package only supports `php:^8.0`. If you're looking for the older version, check out [v2](https://github.com/spatie/data-transfer-object/tree/v2).
+
+## Support us
+
+[ ](https://spatie.be/github-ad-click/data-transfer-object)
+
+We invest a lot of resources into creating [best in class open source packages](https://spatie.be/open-source). You can support us by [buying one of our paid products](https://spatie.be/open-source/support-us).
+
+We highly appreciate you sending us a postcard from your hometown, mentioning which of our package(s) you are using. You'll find our address on [our contact page](https://spatie.be/about-us). We publish all received postcards on [our virtual postcard wall](https://spatie.be/open-source/postcards).
+
+## Usage
+
+The goal of this package is to make constructing objects from arrays of (serialized) data as easy as possible. Here's what a DTO looks like:
+
+```php
+use Spatie\DataTransferObject\DataTransferObject;
+
+class MyDTO extends DataTransferObject
+{
+ public OtherDTO $otherDTO;
+
+ public OtherDTOCollection $collection;
+
+ #[CastWith(ComplexObjectCaster::class)]
+ public ComplexObject $complexObject;
+
+ public ComplexObjectWithCast $complexObjectWithCast;
+
+ #[NumberBetween(1, 100)]
+ public int $a;
+
+ #[MapFrom('address.city')]
+ public string $city;
+}
+```
+
+You could construct this DTO like so:
+
+```php
+$dto = new MyDTO(
+ a: 5,
+ collection: [
+ ['id' => 1],
+ ['id' => 2],
+ ['id' => 3],
+ ],
+ complexObject: [
+ 'name' => 'test',
+ ],
+ complexObjectWithCast: [
+ 'name' => 'test',
+ ],
+ otherDTO: ['id' => 5],
+);
+```
+
+Let's discuss all possibilities one by one.
+
+## Named arguments
+
+Constructing a DTO can be done with named arguments. It's also possible to still use the old array notation. This example is equivalent to the one above.
+
+```php
+$dto = new MyDTO([
+ 'a' => 5,
+ 'collection' => [
+ ['id' => 1],
+ ['id' => 2],
+ ['id' => 3],
+ ],
+ 'complexObject' => [
+ 'name' => 'test',
+ ],
+ 'complexObjectWithCast' => [
+ 'name' => 'test',
+ ],
+ 'otherDTO' => ['id' => 5],
+]);
+```
+
+## Value casts
+
+If a DTO has a property that is another DTO or a DTO collection, the package will take care of automatically casting arrays of data to those DTOs:
+
+```php
+$dto = new MyDTO(
+ collection: [ // This will become an object of class OtherDTOCollection
+ ['id' => 1],
+ ['id' => 2], // Each item will be an instance of OtherDTO
+ ['id' => 3],
+ ],
+ otherDTO: ['id' => 5], // This data will be cast to OtherDTO
+);
+```
+
+### Custom casters
+
+You can build your own caster classes, which will take whatever input they are given, and will cast that input to the desired result.
+
+Take a look at the `ComplexObject`:
+
+```php
+class ComplexObject
+{
+ public string $name;
+}
+```
+
+And its caster `ComplexObjectCaster`:
+
+```php
+use Spatie\DataTransferObject\Caster;
+
+class ComplexObjectCaster implements Caster
+{
+ /**
+ * @param array|mixed $value
+ *
+ * @return mixed
+ */
+ public function cast(mixed $value): ComplexObject
+ {
+ return new ComplexObject(
+ name: $value['name']
+ );
+ }
+}
+```
+
+### Class-specific casters
+
+Instead of specifying which caster should be used for each property, you can also define that caster on the target class itself:
+
+```php
+class MyDTO extends DataTransferObject
+{
+ public ComplexObjectWithCast $complexObjectWithCast;
+}
+```
+
+```php
+#[CastWith(ComplexObjectWithCastCaster::class)]
+class ComplexObjectWithCast
+{
+ public string $name;
+}
+```
+
+### Default casters
+
+It's possible to define default casters on a DTO class itself. These casters will be used whenever a property with a given type is encountered within the DTO class.
+
+```php
+#[
+ DefaultCast(DateTimeImmutable::class, DateTimeImmutableCaster::class),
+ DefaultCast(MyEnum::class, EnumCaster::class),
+]
+abstract class BaseDataTransferObject extends DataTransferObject
+{
+ public MyEnum $status; // EnumCaster will be used
+
+ public DateTimeImmutable $date; // DateTimeImmutableCaster will be used
+}
+```
+
+### Using custom caster arguments
+
+Any caster can be passed custom arguments, the built-in [`ArrayCaster` implementation](https://github.com/spatie/data-transfer-object/blob/master/src/Casters/ArrayCaster.php) is a good example of how this may be used.
+
+Using named arguments when passing input to your caster will help make your code more clear, but they are not required.
+
+For example:
+
+```php
+ /** @var \Spatie\DataTransferObject\Tests\Foo[] */
+ #[CastWith(ArrayCaster::class, itemType: Foo::class)]
+ public array $collectionWithNamedArguments;
+
+ /** @var \Spatie\DataTransferObject\Tests\Foo[] */
+ #[CastWith(ArrayCaster::class, Foo::class)]
+ public array $collectionWithoutNamedArguments;
+```
+
+Note that the first argument passed to the caster constructor is always the array with type(s) of the value being casted.
+All other arguments will be the ones passed as extra arguments in the `CastWith` attribute.
+
+## Validation
+
+This package doesn't offer any specific validation functionality, but it does give you a way to build your own validation attributes. For example, `NumberBetween` is a user-implemented validation attribute:
+
+```php
+class MyDTO extends DataTransferObject
+{
+ #[NumberBetween(1, 100)]
+ public int $a;
+}
+```
+
+It works like this under the hood:
+
+```php
+#[Attribute(Attribute::TARGET_PROPERTY | Attribute::IS_REPEATABLE)]
+class NumberBetween implements Validator
+{
+ public function __construct(
+ private int $min,
+ private int $max
+ ) {
+ }
+
+ public function validate(mixed $value): ValidationResult
+ {
+ if ($value < $this->min) {
+ return ValidationResult::invalid("Value should be greater than or equal to {$this->min}");
+ }
+
+ if ($value > $this->max) {
+ return ValidationResult::invalid("Value should be less than or equal to {$this->max}");
+ }
+
+ return ValidationResult::valid();
+ }
+}
+```
+
+## Mapping
+
+You can map a DTO property from a source property with a different name using the `#[MapFrom]` attribute.
+
+It works with a "dot" notation property name or an index.
+
+```php
+class PostDTO extends DataTransferObject
+{
+ #[MapFrom('postTitle')]
+ public string $title;
+
+ #[MapFrom('user.name')]
+ public string $author;
+}
+
+$dto = new PostDTO([
+ 'postTitle' => 'Hello world',
+ 'user' => [
+ 'name' => 'John Doe'
+ ]
+]);
+```
+
+```php
+class UserDTO extends DataTransferObject
+{
+
+ #[MapFrom(0)]
+ public string $firstName;
+
+ #[MapFrom(1)]
+ public string $lastName;
+}
+
+$dto = new UserDTO(['John', 'Doe']);
+```
+
+Sometimes you also want to map them during the transformation to Array.
+A typical usecase would be transformation from camel case to snake case.
+For that you can use the `#[MapTo]` attribute.
+
+```php
+class UserDTO extends DataTransferObject
+{
+
+ #[MapFrom(0)]
+ #[MapTo('first_name')]
+ public string $firstName;
+
+ #[MapFrom(1)]
+ #[MapTo('last_name')]
+ public string $lastName;
+}
+
+$dto = new UserDTO(['John', 'Doe']);
+$dto->toArray() // ['first_name' => 'John', 'last_name'=> 'Doe'];
+$dto->only('first_name')->toArray() // ['first_name' => 'John'];
+```
+
+## Strict DTOs
+
+The previous version of this package added the `FlexibleDataTransferObject` class which allowed you to ignore properties that didn't exist on the DTO. This behaviour has been changed, all DTOs are flexible now by default, but you can make them strict by using the `#[Strict]` attribute:
+
+
+```php
+class NonStrictDto extends DataTransferObject
+{
+ public string $name;
+}
+
+// This works
+new NonStrictDto(
+ name: 'name',
+ unknown: 'unknown'
+);
+```
+
+```php
+use \Spatie\DataTransferObject\Attributes\Strict;
+
+#[Strict]
+class StrictDto extends DataTransferObject
+{
+ public string $name;
+}
+
+// This throws a \Spatie\DataTransferObject\Exceptions\UnknownProperties exception
+new StrictDto(
+ name: 'name',
+ unknown: 'unknown'
+);
+```
+
+## Helper functions
+
+There are also some helper functions provided for working with multiple properties at once.
+
+```php
+$postData->all();
+
+$postData
+ ->only('title', 'body')
+ ->toArray();
+
+$postData
+ ->except('author')
+ ->toArray();
+```
+
+Note that `all()` will simply return all properties, while `toArray()` will cast nested DTOs to arrays as well.
+
+You can chain the `except()` and `only()` methods:
+
+```php
+$postData
+ ->except('title')
+ ->except('body')
+ ->toArray();
+```
+
+It's important to note that `except()` and `only()` are immutable, they won't change the original data transfer object.
+
+## Immutable DTOs and cloning
+
+This package doesn't force immutable objects since PHP doesn't support them, but you're always encouraged to keep your DTOs immutable. To help you, there's a `clone` method on every DTO which accepts data to override:
+
+```php
+$clone = $original->clone(other: ['name' => 'a']);
+```
+
+Note that no data in `$original` is changed.
+
+## Collections of DTOs
+
+This version removes the `DataTransferObjectCollection` class. Instead you can use simple casters and your own collection classes.
+
+Here's an example of casting a collection of DTOs to an array of DTOs:
+
+```php
+class Bar extends DataTransferObject
+{
+ /** @var \Spatie\DataTransferObject\Tests\Foo[] */
+ #[CastWith(FooArrayCaster::class)]
+ public array $collectionOfFoo;
+}
+
+class Foo extends DataTransferObject
+{
+ public string $name;
+}
+```
+
+```php
+class FooArrayCaster implements Caster
+{
+ public function cast(mixed $value): array
+ {
+ if (! is_array($value)) {
+ throw new Exception("Can only cast arrays to Foo");
+ }
+
+ return array_map(
+ fn (array $data) => new Foo(...$data),
+ $value
+ );
+ }
+}
+```
+
+If you don't want the redundant typehint, or want extended collection functionality; you could create your own collection classes using any collection implementation. In this example, we use Laravel's:
+
+```php
+class Bar extends DataTransferObject
+{
+ #[CastWith(FooCollectionCaster::class)]
+ public CollectionOfFoo $collectionOfFoo;
+}
+
+class Foo extends DataTransferObject
+{
+ public string $name;
+}
+```
+
+```php
+use Illuminate\Support\Collection;
+
+class CollectionOfFoo extends Collection
+{
+ // Add the correct return type here for static analyzers to know which type of array this is
+ public function offsetGet($key): Foo
+ {
+ return parent::offsetGet($key);
+ }
+}
+```
+
+```php
+class FooCollectionCaster implements Caster
+{
+ public function cast(mixed $value): CollectionOfFoo
+ {
+ return new CollectionOfFoo(array_map(
+ fn (array $data) => new Foo(...$data),
+ $value
+ ));
+ }
+}
+```
+
+## Simple arrays of DTOs
+
+For a simple array of DTOs, or an object that implements PHP's built-in `ArrayAccess`, consider using the `ArrayCaster` which requires an item type to be provided:
+
+```php
+class Bar extends DataTransferObject
+{
+ /** @var \Spatie\DataTransferObject\Tests\Foo[] */
+ #[CastWith(ArrayCaster::class, itemType: Foo::class)]
+ public array $collectionOfFoo;
+}
+```
+
+## Testing
+
+``` bash
+composer test
+```
+
+### Changelog
+
+Please see [CHANGELOG](CHANGELOG.md) for more information on what has changed recently.
+
+## Contributing
+
+Please see [CONTRIBUTING](.github/CONTRIBUTING.md) for details.
+
+### Security
+
+If you discover any security related issues, please email freek@spatie.be instead of using the issue tracker.
+
+## Postcardware
+
+You're free to use this package, but if it makes it to your production environment we highly appreciate you sending us a postcard from your hometown, mentioning which of our package(s) you are using.
+
+Our address is: Spatie, Kruikstraat 22, 2018 Antwerp, Belgium.
+
+We publish all received postcards [on our company website](https://spatie.be/en/opensource/postcards).
+
+## External tools
+
+- [json2dto](https://json2dto.atymic.dev): a GUI to convert JSON objects to DTO classes (with nesting support). Also provides a [CLI tool](https://github.com/atymic/json2dto#cli-tool) for local usage.
+- [Data Transfer Object Factory](https://github.com/anteris-dev/data-transfer-object-factory): Intelligently generates a DTO instance using the correct content for your properties based on its name and type.
+
+## Credits
+
+- [Brent Roose](https://github.com/brendt)
+- [All Contributors](../../contributors)
+
+Our `Arr` class contains functions copied from Laravels `Arr` helper.
+
+## License
+
+The MIT License (MIT). Please see [License File](LICENSE.md) for more information.
diff --git a/vendor/spatie/data-transfer-object/composer.json b/vendor/spatie/data-transfer-object/composer.json
new file mode 100644
index 00000000..2bf0b517
--- /dev/null
+++ b/vendor/spatie/data-transfer-object/composer.json
@@ -0,0 +1,44 @@
+{
+ "name": "spatie/data-transfer-object",
+ "description": "Data transfer objects with batteries included",
+ "keywords": [
+ "spatie",
+ "data-transfer-object"
+ ],
+ "homepage": "https://github.com/spatie/data-transfer-object",
+ "license": "MIT",
+ "authors": [
+ {
+ "name": "Brent Roose",
+ "email": "brent@spatie.be",
+ "homepage": "https://spatie.be",
+ "role": "Developer"
+ }
+ ],
+ "require": {
+ "php": "^8.0"
+ },
+ "require-dev": {
+ "illuminate/collections": "^8.36",
+ "larapack/dd": "^1.1",
+ "phpunit/phpunit": "^9.0",
+ "jetbrains/phpstorm-attributes": "^1.0"
+ },
+ "autoload": {
+ "psr-4": {
+ "Spatie\\DataTransferObject\\": "src"
+ }
+ },
+ "autoload-dev": {
+ "psr-4": {
+ "Spatie\\DataTransferObject\\Tests\\": "tests"
+ }
+ },
+ "scripts": {
+ "test": "vendor/bin/phpunit",
+ "test-coverage": "vendor/bin/phpunit --coverage-html coverage"
+ },
+ "config": {
+ "sort-packages": true
+ }
+}
diff --git a/vendor/spatie/data-transfer-object/src/Arr.php b/vendor/spatie/data-transfer-object/src/Arr.php
new file mode 100644
index 00000000..e3eb70ce
--- /dev/null
+++ b/vendor/spatie/data-transfer-object/src/Arr.php
@@ -0,0 +1,98 @@
+offsetExists($key);
+ }
+
+ return array_key_exists($key, $array);
+ }
+}
diff --git a/vendor/spatie/data-transfer-object/src/Attributes/CastWith.php b/vendor/spatie/data-transfer-object/src/Attributes/CastWith.php
new file mode 100644
index 00000000..5fc46852
--- /dev/null
+++ b/vendor/spatie/data-transfer-object/src/Attributes/CastWith.php
@@ -0,0 +1,24 @@
+casterClass, Caster::class)) {
+ throw new InvalidCasterClass($this->casterClass);
+ }
+
+ $this->args = $args;
+ }
+}
diff --git a/vendor/spatie/data-transfer-object/src/Attributes/DefaultCast.php b/vendor/spatie/data-transfer-object/src/Attributes/DefaultCast.php
new file mode 100644
index 00000000..47cc76a9
--- /dev/null
+++ b/vendor/spatie/data-transfer-object/src/Attributes/DefaultCast.php
@@ -0,0 +1,53 @@
+getType();
+
+ /** @var \ReflectionNamedType[]|null $types */
+ $types = match ($type::class) {
+ ReflectionNamedType::class => [$type],
+ ReflectionUnionType::class => $type->getTypes(),
+ default => null,
+ };
+
+ if (! $types) {
+ return false;
+ }
+
+ foreach ($types as $type) {
+ if ($type->getName() !== $this->targetClass) {
+ continue;
+ }
+
+ return true;
+ }
+
+ return false;
+ }
+
+ public function resolveCaster(): Caster
+ {
+ return new $this->casterClass();
+ }
+}
diff --git a/vendor/spatie/data-transfer-object/src/Attributes/MapFrom.php b/vendor/spatie/data-transfer-object/src/Attributes/MapFrom.php
new file mode 100644
index 00000000..96298b41
--- /dev/null
+++ b/vendor/spatie/data-transfer-object/src/Attributes/MapFrom.php
@@ -0,0 +1,14 @@
+types as $type) {
+ if ($type == 'array') {
+ return $this->mapInto(
+ destination: [],
+ items: $value
+ );
+ }
+
+ if (is_subclass_of($type, ArrayAccess::class)) {
+ return $this->mapInto(
+ destination: new $type(),
+ items: $value
+ );
+ }
+ }
+
+ throw new LogicException(
+ "Caster [ArrayCaster] may only be used to cast arrays or objects that implement ArrayAccess."
+ );
+ }
+
+ private function mapInto(array | ArrayAccess $destination, mixed $items): array | ArrayAccess
+ {
+ if ($destination instanceof ArrayAccess && ! is_subclass_of($destination, Traversable::class)) {
+ throw new LogicException(
+ "Caster [ArrayCaster] may only be used to cast ArrayAccess objects that are traversable."
+ );
+ }
+
+ foreach ($items as $key => $item) {
+ $destination[$key] = $this->castItem($item);
+ }
+
+ return $destination;
+ }
+
+ private function castItem(mixed $data)
+ {
+ if ($data instanceof $this->itemType) {
+ return $data;
+ }
+
+ if (is_array($data)) {
+ return new $this->itemType(...$data);
+ }
+
+ throw new LogicException(
+ "Caster [ArrayCaster] each item must be an array or an instance of the specified item type [{$this->itemType}]."
+ );
+ }
+}
diff --git a/vendor/spatie/data-transfer-object/src/Casters/DataTransferObjectCaster.php b/vendor/spatie/data-transfer-object/src/Casters/DataTransferObjectCaster.php
new file mode 100644
index 00000000..4f1913e9
--- /dev/null
+++ b/vendor/spatie/data-transfer-object/src/Casters/DataTransferObjectCaster.php
@@ -0,0 +1,25 @@
+classNames as $className) {
+ if ($value instanceof $className) {
+ return $value;
+ }
+ }
+
+ return new $this->classNames[0](...$value);
+ }
+}
diff --git a/vendor/spatie/data-transfer-object/src/DataTransferObject.php b/vendor/spatie/data-transfer-object/src/DataTransferObject.php
new file mode 100644
index 00000000..d1ecefff
--- /dev/null
+++ b/vendor/spatie/data-transfer-object/src/DataTransferObject.php
@@ -0,0 +1,125 @@
+getProperties() as $property) {
+ $property->setValue(Arr::get($args, $property->name) ?? $this->{$property->name} ?? null);
+
+ $args = Arr::forget($args, $property->name);
+ }
+
+ if ($class->isStrict() && count($args)) {
+ throw UnknownProperties::new(static::class, array_keys($args));
+ }
+
+ $class->validate();
+ }
+
+ public static function arrayOf(array $arrayOfParameters): array
+ {
+ return array_map(
+ fn (mixed $parameters) => new static($parameters),
+ $arrayOfParameters
+ );
+ }
+
+ public function all(): array
+ {
+ $data = [];
+
+ $class = new ReflectionClass(static::class);
+
+ $properties = $class->getProperties(ReflectionProperty::IS_PUBLIC);
+
+ foreach ($properties as $property) {
+ if ($property->isStatic()) {
+ continue;
+ }
+
+ $mapToAttribute = $property->getAttributes(MapTo::class);
+ $name = count($mapToAttribute) ? $mapToAttribute[0]->newInstance()->name : $property->getName();
+
+ $data[$name] = $property->getValue($this);
+ }
+
+ return $data;
+ }
+
+ public function only(string ...$keys): static
+ {
+ $dataTransferObject = clone $this;
+
+ $dataTransferObject->onlyKeys = [...$this->onlyKeys, ...$keys];
+
+ return $dataTransferObject;
+ }
+
+ public function except(string ...$keys): static
+ {
+ $dataTransferObject = clone $this;
+
+ $dataTransferObject->exceptKeys = [...$this->exceptKeys, ...$keys];
+
+ return $dataTransferObject;
+ }
+
+ public function clone(...$args): static
+ {
+ return new static(...array_merge($this->toArray(), $args));
+ }
+
+ public function toArray(): array
+ {
+ if (count($this->onlyKeys)) {
+ $array = Arr::only($this->all(), $this->onlyKeys);
+ } else {
+ $array = Arr::except($this->all(), $this->exceptKeys);
+ }
+
+ $array = $this->parseArray($array);
+
+ return $array;
+ }
+
+ protected function parseArray(array $array): array
+ {
+ foreach ($array as $key => $value) {
+ if ($value instanceof DataTransferObject) {
+ $array[$key] = $value->toArray();
+
+ continue;
+ }
+
+ if (! is_array($value)) {
+ continue;
+ }
+
+ $array[$key] = $this->parseArray($value);
+ }
+
+ return $array;
+ }
+}
diff --git a/vendor/spatie/data-transfer-object/src/Exceptions/InvalidCasterClass.php b/vendor/spatie/data-transfer-object/src/Exceptions/InvalidCasterClass.php
new file mode 100644
index 00000000..7efebf41
--- /dev/null
+++ b/vendor/spatie/data-transfer-object/src/Exceptions/InvalidCasterClass.php
@@ -0,0 +1,18 @@
+ $errorsForField) {
+ /** @var \Spatie\DataTransferObject\Validation\ValidationResult $errorForField */
+ foreach ($errorsForField as $errorForField) {
+ $messages[] = "\t - `{$className}->{$fieldName}`: {$errorForField->message}";
+ }
+ }
+
+ parent::__construct("Validation errors:" . PHP_EOL . implode(PHP_EOL, $messages));
+ }
+}
diff --git a/vendor/spatie/data-transfer-object/src/Reflection/DataTransferObjectClass.php b/vendor/spatie/data-transfer-object/src/Reflection/DataTransferObjectClass.php
new file mode 100644
index 00000000..dd35f859
--- /dev/null
+++ b/vendor/spatie/data-transfer-object/src/Reflection/DataTransferObjectClass.php
@@ -0,0 +1,84 @@
+reflectionClass = new ReflectionClass($dataTransferObject);
+ $this->dataTransferObject = $dataTransferObject;
+ }
+
+ /**
+ * @return \Spatie\DataTransferObject\Reflection\DataTransferObjectProperty[]
+ */
+ public function getProperties(): array
+ {
+ $publicProperties = array_filter(
+ $this->reflectionClass->getProperties(ReflectionProperty::IS_PUBLIC),
+ fn (ReflectionProperty $property) => ! $property->isStatic()
+ );
+
+ return array_map(
+ fn (ReflectionProperty $property) => new DataTransferObjectProperty(
+ $this->dataTransferObject,
+ $property
+ ),
+ $publicProperties
+ );
+ }
+
+ public function validate(): void
+ {
+ $validationErrors = [];
+
+ foreach ($this->getProperties() as $property) {
+ $validators = $property->getValidators();
+
+ foreach ($validators as $validator) {
+ $result = $validator->validate($property->getValue());
+
+ if ($result->isValid) {
+ continue;
+ }
+
+ $validationErrors[$property->name][] = $result;
+ }
+ }
+
+ if (count($validationErrors)) {
+ throw new ValidationException($this->dataTransferObject, $validationErrors);
+ }
+ }
+
+ public function isStrict(): bool
+ {
+ if (! isset($this->isStrict)) {
+ $attribute = null;
+
+ $reflectionClass = $this->reflectionClass;
+ while ($attribute === null && $reflectionClass !== false) {
+ $attribute = $reflectionClass->getAttributes(Strict::class)[0] ?? null;
+
+ $reflectionClass = $reflectionClass->getParentClass();
+ }
+
+ $this->isStrict = $attribute !== null;
+ }
+
+ return $this->isStrict;
+ }
+}
diff --git a/vendor/spatie/data-transfer-object/src/Reflection/DataTransferObjectProperty.php b/vendor/spatie/data-transfer-object/src/Reflection/DataTransferObjectProperty.php
new file mode 100644
index 00000000..abdf313d
--- /dev/null
+++ b/vendor/spatie/data-transfer-object/src/Reflection/DataTransferObjectProperty.php
@@ -0,0 +1,182 @@
+dataTransferObject = $dataTransferObject;
+ $this->reflectionProperty = $reflectionProperty;
+
+ $this->name = $this->resolveMappedProperty();
+
+ $this->caster = $this->resolveCaster();
+ }
+
+ public function setValue(mixed $value): void
+ {
+ if ($this->caster && $value !== null) {
+ $value = $this->caster->cast($value);
+ }
+
+ $this->reflectionProperty->setValue($this->dataTransferObject, $value);
+ }
+
+ /**
+ * @return \Spatie\DataTransferObject\Validator[]
+ */
+ public function getValidators(): array
+ {
+ $attributes = $this->reflectionProperty->getAttributes(
+ Validator::class,
+ ReflectionAttribute::IS_INSTANCEOF
+ );
+
+ return array_map(
+ fn (ReflectionAttribute $attribute) => $attribute->newInstance(),
+ $attributes
+ );
+ }
+
+ public function getValue(): mixed
+ {
+ return $this->reflectionProperty->getValue($this->dataTransferObject);
+ }
+
+ private function resolveCaster(): ?Caster
+ {
+ $attributes = $this->reflectionProperty->getAttributes(CastWith::class);
+
+ if (! count($attributes)) {
+ $attributes = $this->resolveCasterFromType();
+ }
+
+ if (! count($attributes)) {
+ return $this->resolveCasterFromDefaults();
+ }
+
+ /** @var \Spatie\DataTransferObject\Attributes\CastWith $attribute */
+ $attribute = $attributes[0]->newInstance();
+
+ return new $attribute->casterClass(
+ array_map(fn ($type) => $this->resolveTypeName($type), $this->extractTypes()),
+ ...$attribute->args
+ );
+ }
+
+ private function resolveCasterFromType(): array
+ {
+ foreach ($this->extractTypes() as $type) {
+ $name = $this->resolveTypeName($type);
+
+ if (! class_exists($name)) {
+ continue;
+ }
+
+ $reflectionClass = new ReflectionClass($name);
+
+ do {
+ $attributes = $reflectionClass->getAttributes(CastWith::class);
+
+ $reflectionClass = $reflectionClass->getParentClass();
+ } while (! count($attributes) && $reflectionClass);
+
+ if (count($attributes) > 0) {
+ return $attributes;
+ }
+ }
+
+ return [];
+ }
+
+ private function resolveCasterFromDefaults(): ?Caster
+ {
+ $defaultCastAttributes = [];
+
+ $class = $this->reflectionProperty->getDeclaringClass();
+
+ do {
+ array_push($defaultCastAttributes, ...$class->getAttributes(DefaultCast::class));
+
+ $class = $class->getParentClass();
+ } while ($class !== false);
+
+ if (! count($defaultCastAttributes)) {
+ return null;
+ }
+
+ foreach ($defaultCastAttributes as $defaultCastAttribute) {
+ /** @var \Spatie\DataTransferObject\Attributes\DefaultCast $defaultCast */
+ $defaultCast = $defaultCastAttribute->newInstance();
+
+ if ($defaultCast->accepts($this->reflectionProperty)) {
+ return $defaultCast->resolveCaster();
+ }
+ }
+
+ return null;
+ }
+
+ private function resolveMappedProperty(): string | int
+ {
+ $attributes = $this->reflectionProperty->getAttributes(MapFrom::class);
+
+ if (! count($attributes)) {
+ return $this->reflectionProperty->name;
+ }
+
+ return $attributes[0]->newInstance()->name;
+ }
+
+ /**
+ * @return ReflectionNamedType[]
+ */
+ private function extractTypes(): array
+ {
+ $type = $this->reflectionProperty->getType();
+
+ if (! $type) {
+ return [];
+ }
+
+ return match ($type::class) {
+ ReflectionNamedType::class => [$type],
+ ReflectionUnionType::class => $type->getTypes(),
+ };
+ }
+
+ private function resolveTypeName(ReflectionType $type): string
+ {
+ return match ($type->getName()) {
+ 'self' => $this->dataTransferObject::class,
+ 'parent' => get_parent_class($this->dataTransferObject),
+ default => $type->getName(),
+ };
+ }
+}
diff --git a/vendor/spatie/data-transfer-object/src/Validation/ValidationResult.php b/vendor/spatie/data-transfer-object/src/Validation/ValidationResult.php
new file mode 100644
index 00000000..43d2eea3
--- /dev/null
+++ b/vendor/spatie/data-transfer-object/src/Validation/ValidationResult.php
@@ -0,0 +1,31 @@
+ {
moduleIds: 'deterministic',
};
+ const performance = {
+ maxAssetSize: 5*1024*1024,
+ maxEntrypointSize: 3*1024*1024,
+ }
+
const ingame_vue = {
name: `ingame_${versionTarget}_vue`,
resolve: {
@@ -200,6 +205,7 @@ module.exports = (env, argv) => {
cacheDirectory,
cacheLocation: path.resolve(cacheDirectory, `ingame_vue_${mode}`)
},
+ performance,
};
const ingame = {
name: `ingame_${versionTarget}`,
@@ -275,6 +281,7 @@ module.exports = (env, argv) => {
cacheDirectory,
cacheLocation: path.resolve(cacheDirectory, `ingame_ts_${mode}`)
},
+ performance,
};
const gateway = {
name: `gateway`,
@@ -355,6 +362,7 @@ module.exports = (env, argv) => {
cacheDirectory,
cacheLocation: path.resolve(cacheDirectory, `gateway_ts_${mode}`)
},
+ performance,
};
if (env.WEBPACK_WATCH || !versionValue) {