feat: 베팅 시스템 재 설계, 이벤트 테이블 수정 #205

Merged
Hide_D merged 45 commits from ng_bet into devel 2022-02-05 16:43:28 +09:00
98 changed files with 4289 additions and 385 deletions
+2 -1
View File
@@ -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": {
Generated
+64 -1
View File
@@ -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",
+4 -4
View File
@@ -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 "
+4 -7
View File
@@ -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 "
+1 -7
View File
@@ -155,13 +155,7 @@ if ($gameStor->isunited) {
if ($general['npc'] >= 2) {
$name = "<font color=cyan>{$general['name']}</font>";
} elseif ($general['npc'] == 1) {
$name = "<font color=skyblue>{$general['name']}</font>";
} else {
$name = "{$general['name']}";
}
$name = formatName($general['name'], $general['npc']);
if (key_exists($general['owner'], $ownerNameList)) {
$name = $name . '<br><small>(' . $ownerNameList[$general['owner']] . ')</small>';
+3 -8
View File
@@ -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') ?>
<link rel="stylesheet" type="text/css" href="https://cdn.jsdelivr.net/gh/orioncactus/pretendard/dist/web/static/pretendard.css" />
<?= WebUtil::printDist('ts', ['common', 'extKingdoms']) ?>
<?= WebUtil::printStaticValues($gameStor->getValues(['killturn', 'autorun_user', 'turnterm'])) ?>
</head>
<body>
@@ -144,13 +145,7 @@ if ($con >= 2) {
<tr>
<td colspan=8> 장수 일람 : ";
foreach ($generals as $general) {
if ($general['npc'] >= 2) {
echo "<font color=cyan>{$general['name']}</font>, ";
} elseif ($general['npc'] == 1) {
echo "<font color=skyblue>{$general['name']}</font>, ";
} else {
echo "{$general['name']}, ";
}
echo formatName($general['name'], $general['npc']).', ';
}
echo "
</td>
+7 -26
View File
@@ -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'] = "<font color=cyan>" . $general['name'] . "</font>";
} elseif ($general['npc'] == 1) {
$general['name'] = "<font color=skyblue>" . $general['name'] . "</font>";
}
$general['name'] = formatName($general['name'], $general['npc']);
echo "<td colspan=16>{$general['name']}</td>";
}
@@ -162,11 +159,7 @@ if ($str3) {
if ($general['name'] == "") {
$general['name'] = "-";
}
if ($general['npc'] >= 2) {
$general['name'] = "<font color=cyan>" . $general['name'] . "</font>";
} elseif ($general['npc'] == 1) {
$general['name'] = "<font color=skyblue>" . $general['name'] . "</font>";
}
$general['name'] = formatName($general['name'], $general['npc']);
if ($general['win'] > 0) {
$line[$i] = "<font color=red>";
$cent[intdiv($i, 2)] = "<font color=red>";
@@ -208,11 +201,7 @@ if ($str3) {
if ($general['name'] == "") {
$general['name'] = "-";
}
if ($general['npc'] >= 2) {
$general['name'] = "<font color=cyan>" . $general['name'] . "</font>";
} elseif ($general['npc'] == 1) {
$general['name'] = "<font color=skyblue>" . $general['name'] . "</font>";
}
$general['name'] = formatName($general['name'], $general['npc']);
if ($general['win'] > 0) {
$line[$i] = "<font color=red>";
$cent[intdiv($i, 2)] = "<font color=red>";
@@ -254,11 +243,7 @@ if ($str3) {
if ($general['name'] == "") {
$general['name'] = "-";
}
if ($general['npc'] >= 2) {
$general['name'] = "<font color=cyan>" . $general['name'] . "</font>";
} elseif ($general['npc'] == 1) {
$general['name'] = "<font color=skyblue>" . $general['name'] . "</font>";
}
$general['name'] = formatName($general['name'], $general['npc']);
if ($general['win'] > 0) {
$line[$i] = "<font color=red>";
$cent[intdiv($i, 2)] = "<font color=red>";
@@ -300,11 +285,7 @@ if ($str3) {
if ($general['name'] == "") {
$general['name'] = "-";
}
if ($general['npc'] >= 2) {
$general['name'] = "<font color=cyan>" . $general['name'] . "</font>";
} elseif ($general['npc'] == 1) {
$general['name'] = "<font color=skyblue>" . $general['name'] . "</font>";
}
$general['name'] = formatName($general['name'], $general['npc']);
if ($general['win'] > 0) {
$line[$i] = "<font color=red>";
$cent[intdiv($i, 2)] = "<font color=red>";
+1 -7
View File
@@ -146,13 +146,7 @@ if ($gameStor->isunited) {
$intel = "{$general['intel']}";
}
if ($general['npc'] >= 2) {
$name = "<font color=cyan>{$general['name']}</font>";
} elseif ($general['npc'] == 1) {
$name = "<font color=skyblue>{$general['name']}</font>";
} else {
$name = "{$general['name']}";
}
$name = formatName($general['name'], $general['npc']);
if (key_exists($general['owner'], $ownerNameList)) {
$name = $name . '<br><small>(' . $ownerNameList[$general['owner']] . ')</small>';
+6 -26
View File
@@ -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'] = "<font color=cyan>" . $general['name'] . "</font>";
} elseif ($general['npc'] == 1) {
$general['name'] = "<font color=skyblue>" . $general['name'] . "</font>";
}
$general['name'] = formatName($general['name'], $general['npc']);
echo "<td colspan=16>{$general['name']}</td>";
}
@@ -270,11 +266,7 @@ switch ($admin['tnmt_type']) {
if ($general['name'] == "") {
$general['name'] = "-";
}
if ($general['npc'] >= 2) {
$general['name'] = "<font color=cyan>" . $general['name'] . "</font>";
} elseif ($general['npc'] == 1) {
$general['name'] = "<font color=skyblue>" . $general['name'] . "</font>";
}
$general['name'] = formatName($general['name'], $general['npc']);
if ($general['win'] > 0) {
$line[$i] = "<font color=red>";
$cent[intdiv($i, 2)] = "<font color=red>";
@@ -316,11 +308,7 @@ switch ($admin['tnmt_type']) {
if ($general['name'] == "") {
$general['name'] = "-";
}
if ($general['npc'] >= 2) {
$general['name'] = "<font color=cyan>" . $general['name'] . "</font>";
} elseif ($general['npc'] == 1) {
$general['name'] = "<font color=skyblue>" . $general['name'] . "</font>";
}
$general['name'] = formatName($general['name'], $general['npc']);
if ($general['win'] > 0) {
$line[$i] = "<font color=red>";
$cent[intdiv($i, 2)] = "<font color=red>";
@@ -363,11 +351,7 @@ switch ($admin['tnmt_type']) {
if ($general['name'] == "") {
$general['name'] = "-";
}
if ($general['npc'] >= 2) {
$general['name'] = "<font color=cyan>" . $general['name'] . "</font>";
} elseif ($general['npc'] == 1) {
$general['name'] = "<font color=skyblue>" . $general['name'] . "</font>";
}
$general['name'] = formatName($general['name'], $general['npc']);
if ($general['win'] > 0) {
$line[$i] = "<font color=red>";
$cent[intdiv($i, 2)] = "<font color=red>";
@@ -409,11 +393,7 @@ switch ($admin['tnmt_type']) {
if ($general['name'] == "") {
$general['name'] = "-";
}
if ($general['npc'] >= 2) {
$general['name'] = "<font color=cyan>" . $general['name'] . "</font>";
} elseif ($general['npc'] == 1) {
$general['name'] = "<font color=skyblue>" . $general['name'] . "</font>";
}
$general['name'] = formatName($general['name'], $general['npc']);
if ($general['win'] > 0) {
$line[$i] = "<font color=red>";
$cent[intdiv($i, 2)] = "<font color=red>";
+16 -18
View File
@@ -1,18 +1,16 @@
<div class="buttonPlate">
<a href="a_status.php" target="_blank" class="open-window"><button type="button" class="toolbarButton">세력도</button></a>
<a href="a_kingdomList.php" target="_blank" class="open-window"><button type="button" class="toolbarButton">세력일람</button></a>
<a href="a_genList.php" target="_blank" class="open-window"><button type="button" class="toolbarButton">장수일람</button></a>
<a href="a_bestGeneral.php" target="_blank" class="open-window"><button type="button" class="toolbarButton">명장일람</button></a>
<a href="a_history.php" target="_blank" class="open-window"><button type="button" class="toolbarButton">연감</button></a>
<a href="a_hallOfFame.php" target="_blank" class="open-window"><button type="button" class="toolbarButton">명예의전당</button></a>
<a href="a_emperior.php" target="_blank" class="open-window"><button type="button" class="toolbarButton">왕조일람</button></a>
<a href="a_traffic.php" target="_blank" class="open-window"><button type="button" class="toolbarButton">접속량정보</button></a>
<a href="/bbs/board" target="_blank"><button type="button" class="toolbarButton2">삼모게시판</button></a>
<a href="/bbs/tip" target="_blank"><button type="button" class="toolbarButton">팁/강좌</button></a>
<a href="/bbs/news" target="_blank"><button type="button" class="toolbarButton">삼국 일보</button></a>
<a href="/bbs/history2" target="_blank"><button type="button" class="toolbarButton">개인 열전</button></a>
<a href="/bbs/history3" target="_blank"><button type="button" class="toolbarButton">국가 열전</button></a>
<a href="/bbs/patch" target="_blank"><button type="button" class="toolbarButton">패치 내역</button></a>
<a href="battle_simulator.php" target="_blank"><button type="button" class="toolbarButton">전투 시뮬레이터</button></a>
<a href="<?=$site?>" target="_blank" class="open-window"><button type="button" class="toolbarButton"><?=$call?></button></a>
</div>
<?=$btnBegin??''?><a href="a_status.php" target="_blank" class="open-window toolbarButton <?=$btnClass??""?>">세력도</a><?=$btnEnd??''?>
<?=$btnBegin??''?><a href="a_kingdomList.php" target="_blank" class="open-window toolbarButton <?=$btnClass??""?>">세력일람</a><?=$btnEnd??''?>
<?=$btnBegin??''?><a href="a_genList.php" target="_blank" class="open-window toolbarButton <?=$btnClass??""?>">장수일람</a><?=$btnEnd??''?>
<?=$btnBegin??''?><a href="a_bestGeneral.php" target="_blank" class="open-window toolbarButton <?=$btnClass??""?>">명장일람</a><?=$btnEnd??''?>
<?=$btnBegin??''?><a href="a_history.php" target="_blank" class="open-window toolbarButton <?=$btnClass??""?>">연감</a><?=$btnEnd??''?>
<?=$btnBegin??''?><a href="a_hallOfFame.php" target="_blank" class="open-window toolbarButton <?=$btnClass??""?>">명예의전당</a><?=$btnEnd??''?>
<?=$btnBegin??''?><a href="a_emperior.php" target="_blank" class="open-window toolbarButton <?=$btnClass??""?>">왕조일람</a><?=$btnEnd??''?>
<?=$btnBegin??''?><a href="v_nationBetting.php" target="_blank" class="open-window toolbarButton <?=$btnClass??""?>">천통국 베팅</a><?=$btnEnd??''?>
<?=$btnBegin??''?><a href="/bbs/board" target="_blank" class="toolbarButton2 <?=$btnClass??""?>">삼모게시판</a><?=$btnEnd??''?>
<?=$btnBegin??''?><a href="/bbs/tip" target="_blank" class="toolbarButton <?=$btnClass??""?>">팁/강좌</a><?=$btnEnd??''?>
<?=$btnBegin??''?><a href="/bbs/news" target="_blank" class="toolbarButton <?=$btnClass??""?>">삼국 일보</a><?=$btnEnd??''?>
<?=$btnBegin??''?><a href="/bbs/history2" target="_blank" class="toolbarButton <?=$btnClass??""?>">개인 열전</a><?=$btnEnd??''?>
<?=$btnBegin??''?><a href="/bbs/history3" target="_blank" class="toolbarButton <?=$btnClass??""?>">국가 열전</a><?=$btnEnd??''?>
<?=$btnBegin??''?><a href="/bbs/patch" target="_blank" class="toolbarButton <?=$btnClass??""?>">패치 내역</a><?=$btnEnd??''?>
<?=$btnBegin??''?><a href="battle_simulator.php" target="_blank" class="toolbarButton <?=$btnClass??""?>">전투 시뮬레이터</a><?=$btnEnd??''?>
<?=$btnBegin??''?><a href="<?= $site ?>" target="_blank" class="open-window toolbarButton <?=$btnClass??""?>"><?= $call ?></a><?=$btnEnd??''?>
+26 -5
View File
@@ -215,14 +215,35 @@ function formatLeadershipBonus(int $value): string
return "<font color=cyan>+{$value}</font>";
}
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 = "<font color='skyblue'>$name</font>";
} else if ($npc > 1) {
$name = "<font color='cyan'>$name</font>";
$color = getNPCColor($npc);
if($color === null){
return $name;
}
return $name;
return "<span style='color:{$color}'>$name</span>";
}
function getMapTheme(): string
+35 -33
View File
@@ -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 = "<font color=orange>" . $name . "</font>";
} elseif ($npc >= 2) {
$name = "<font color=cyan>" . $name . "</font>";
} elseif ($npc == 1) {
$name = "<font color=skyblue>" . $name . "</font>";
} else if($npc > 0){
$name = formatName($name, $npc);
}
echo "<tr align=center><td class='bg2'>$k</td><td style='font-size:80%;'>$name</td><td>$abil</td><td>$tgame</td><td>$win</td><td>$draw</td><td>$lose</td><td>$gd</td><td>$gl</td></tr>";
}
+4 -4
View File
@@ -149,14 +149,14 @@ if (!$otherTextInfo) {
<?= $scenario ?>
</div>
<div class="s-border-t col py-2 col-4 col-md-2" style="color:<?= $color ?>;">
NPC : <?= $extend ?>
</div>
<div class="s-border-t col py-2 col-4 col-md-2" style="color:<?= $color ?>;">
NPC상성 : <?= $fiction ?>
NPC 수, 상성 : <?= $extend ?>,<?= $fiction ?>
</div>
<div class="s-border-t col py-2 col-4 col-md-2" style="color:<?= $color ?>;">
NPC선택 : <?= $npcmode ?>
</div>
<div class="s-border-t col py-2 col-4 col-md-2" style="color:<?= $color ?>;">
토너먼트 : <?= getTournamentTermText() ?>
</div>
<div class="s-border-t col py-2 col-4 col-md-2" style="color:<?= $color ?>;">
기타 설정: <?= $otherTextInfo ?>
</div>
+183 -148
View File
@@ -1,28 +1,29 @@
<?php
namespace sammo;
function processWar(General $attackerGeneral, array $rawAttackerNation, array $rawDefenderCity){
function processWar(General $attackerGeneral, array $rawAttackerNation, array $rawDefenderCity)
{
$db = DB::db();
$attackerNationID = $attackerGeneral->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("<D><b>{$attacker->getNationVar('name')}</b></>의 <Y>{$attacker->getName()}</>{$josaYi} <G><b>{$city->getName()}</b></>{$josaRo} 진격합니다.");
$logger->pushGeneralActionLog("<G><b>{$city->getName()}</b></>{$josaRo} <M>진격</>합니다. <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} <Y>{$attackerName}</>의 {$attackerCrewTypeName}{$josaUl} <M>수비</>합니다.");
}
else{
} else {
$josaYi = JosaUtil::pick($attackerName, '이');
$josaRo = JosaUtil::pick($attackerCrewTypeName, '로');
$logger->pushGlobalActionLog("<Y>{$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 : <Y1>【{$attacker->getName()}】</> <C>{$attacker->getHP()} (-$deadAttacker)</> VS <C>{$defender->getHP()} (-$deadDefender)</> <Y1>【{$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("<Y>{$attacker->getName()}</>의 {$attacker->getCrewTypeName()}{$josaYi} 퇴각했습니다.");
if($noRice){
if ($noRice) {
$attacker->getLogger()->pushGeneralActionLog("군량 부족으로 퇴각합니다.", ActionLogger::PLAIN);
}
else{
} else {
$attacker->getLogger()->pushGeneralActionLog("퇴각했습니다.", ActionLogger::PLAIN);
}
$defender->getLogger()->pushGeneralActionLog("<Y>{$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("<Y>{$defender->getName()}</>의 {$defender->getCrewTypeName()}{$josaYi} 패퇴했습니다.");
$attacker->getLogger()->pushGeneralActionLog("<Y>{$defender->getName()}</>의 {$defender->getCrewTypeName()}{$josaYi} 패퇴했습니다.", ActionLogger::PLAIN);
$attacker->getLogger()->pushGeneralActionLog("<Y>{$defender->getName()}</>의 {$defender->getCrewTypeName()}{$josaYi} 패퇴했습니다.", ActionLogger::PLAIN);
$defender->getLogger()->pushGeneralActionLog("군량 부족으로 패퇴합니다.", ActionLogger::PLAIN);
}
else{
} else {
$logger->pushGlobalActionLog("<Y>{$defender->getName()}</>의 {$defender->getCrewTypeName()}{$josaYi} 전멸했습니다.");
$attacker->getLogger()->pushGeneralActionLog("<Y>{$defender->getName()}</>의 {$defender->getCrewTypeName()}{$josaYi} 전멸했습니다.", ActionLogger::PLAIN);
$attacker->getLogger()->pushGeneralActionLog("<Y>{$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("<M><b>【분쟁】</b></><D><b>{$nationName}</b></>{$josaYi} <G><b>{$defender->getName()}</b></> 공략에 가담하여 분쟁이 발생하고 있습니다.");
@@ -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 = "<D><b>{$defenderNationName}</b></>의";
} else {
$defenderNationDecoration = "공백지인";
@@ -524,8 +521,29 @@ function ConquerCity(array $admin, General $general, array $city) {
$defenderNationLogger->pushNationalHistoryLog("<D><b>{$attackerNationName}</b></>의 <Y>{$attackerGeneralName}</>에 의해 <G><b>{$cityName}</b></>{$josaYiCity} <O>함락</>");
$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(
"도주하며 금<C>$loseGold</> 쌀<C>$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 = "<D><b>{$defenderNationName}</b></> 정복으로 금<C>{$loseNationGoldText}</> 쌀<C>{$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 = "수도가 함락되어 <G><b>$minCityName</b></>으로 <M>긴급천도</>합니다.";
//아국 수뇌부에게 로그 전달
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('도시가 남지 않았는데 긴천을 시도하고 있습니다');
}
}
+63
View File
@@ -0,0 +1,63 @@
<?php
namespace sammo\API\Betting;
use sammo\Session;
use DateTimeInterface;
use sammo\Betting;
use sammo\DB;
use sammo\DTO\BettingItem;
use sammo\Validator;
use sammo\GameConst;
use sammo\KVStorage;
use sammo\UserLogger;
use sammo\Util;
class Bet extends \sammo\BaseAPI
{
public function validateArgs(): ?string
{
$v = new Validator($this->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
];
}
}
@@ -0,0 +1,97 @@
<?php
namespace sammo\API\Betting;
use sammo\Session;
use DateTimeInterface;
use sammo\DB;
use sammo\DTO\BettingInfo;
use sammo\General;
use sammo\KVStorage;
use sammo\Util;
use sammo\Validator;
use function sammo\increaseRefresh;
class GetBettingDetail extends \sammo\BaseAPI
{
public function validateArgs(): ?string
{
$v = new Validator($this->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,
];
}
}
+81
View File
@@ -0,0 +1,81 @@
<?php
namespace sammo\API\Betting;
use sammo\Session;
use DateTimeInterface;
use sammo\DB;
use sammo\DTO\BettingInfo;
use sammo\KVStorage;
use function sammo\checkLimit;
use function sammo\increaseRefresh;
class GetBettingList extends \sammo\BaseAPI
{
public function validateArgs(): ?string
{
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();
increaseRefresh("베팅장", 1);
$gameStor = KVStorage::getStorage($db, 'game_env');
$bettingStor = KVStorage::getStorage($db, 'betting');
$userID = $session->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,
];
}
}
+65
View File
@@ -0,0 +1,65 @@
<?php
namespace sammo\API\Global;
use sammo\Session;
use DateTimeInterface;
use sammo\DB;
use function sammo\getAllNationStaticInfo;
use function sammo\getNationStaticInfo;
class GetNationList extends \sammo\BaseAPI
{
public function validateArgs(): ?string
{
return null;
}
public function getRequiredSessionMode(): int
{
return static::REQ_LOGIN | static::REQ_READ_ONLY;
}
public function launch(Session $session, ?DateTimeInterface $modifiedSince, ?string $reqEtag)
{
$db = DB::db();
$nations = getAllNationStaticInfo();
uasort($nations, function ($lhs, $rhs) {
return $rhs['power'] <=> $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,
];
}
}
+361
View File
@@ -0,0 +1,361 @@
<?php
namespace sammo;
use sammo\DTO\BettingInfo;
use sammo\DTO\BettingItem;
class Betting
{
private BettingInfo $info;
public function __construct(private $bettingID)
{
$db = DB::db();
$bettingStor = KVStorage::getStorage($db, 'betting');
$rawBettingInfo = $bettingStor->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("<C>{$this->info->name}</>의 {$partialText} 보상으로 <C>{$rewardText}</>의 <S>금</> 획득!", 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());
}
}
+25 -1
View File
@@ -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;
}
@@ -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);
+46
View File
@@ -0,0 +1,46 @@
<?php
namespace sammo\DTO;
use sammo\DTO\SelectItem;
use Spatie\DataTransferObject\Attributes\CastWith;
use Spatie\DataTransferObject\Attributes\Strict;
use Spatie\DataTransferObject\DataTransferObject;
use Spatie\DataTransferObject\Casters\ArrayCaster;
//https://json2dto.atymic.dev/
#[Strict]
class BettingInfo extends DataTransferObject
{
public int $id;
public string $type;
public string $name;
public bool $finished;
public int $selectCnt;
public ?bool $isExlusive;
public bool $reqInheritancePoint;
public int $openYearMonth;
public int $closeYearMonth;
/** @var \sammo\DTO\SelectItem[] */
#[CastWith(ArrayCaster::class, itemType: SelectItem::class)]
public array $candidates;
public ?array $winner;
}
/*
{
"id": 45,
"name": "1차전",
"finished": false,
"selectCnt": 1,
"reqInheritancePoint": true,
"openYearMonth": 110,
"closeYearMonth": 120
}
*/
+33
View File
@@ -0,0 +1,33 @@
<?php
namespace sammo\DTO;
use Spatie\DataTransferObject\Attributes\MapFrom;
use Spatie\DataTransferObject\Attributes\MapTo;
use Spatie\DataTransferObject\Attributes\Strict;
use Spatie\DataTransferObject\DataTransferObject;
#[Strict]
class BettingItem extends DataTransferObject
{
#[MapFrom('id')]
#[MapTo('id')]
public null|int $rowID = null;
#[MapFrom('betting_id')]
#[MapTo('betting_id')]
public int $bettingID;
#[MapFrom('general_id')]
#[MapTo('general_id')]
public int $generalID;
#[MapFrom('user_id')]
#[MapTo('user_id')]
public null|int $userID;
#[MapFrom('betting_type')]
#[MapTo('betting_type')]
public string $bettingType;
public int $amount;
}
+15
View File
@@ -0,0 +1,15 @@
<?php
namespace sammo\DTO;
use Spatie\DataTransferObject\Attributes\Strict;
use Spatie\DataTransferObject\DataTransferObject;
#[Strict]
class SelectItem extends DataTransferObject
{
public string $title;
public ?string $info;
public ?bool $isHtml;
public ?array $aux;
}
+1 -1
View File
@@ -54,7 +54,7 @@ class CreateManyNPC extends \sammo\Event\Action{
$moreGenCnt = 0;
if($this->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;
}
@@ -0,0 +1,64 @@
<?php
namespace sammo\Event\Action;
use sammo\ActionLogger;
use sammo\Betting;
use \sammo\GameConst;
use \sammo\Util;
use \sammo\DB;
use sammo\DTO\BettingInfo;
use sammo\Json;
use sammo\KVStorage;
class FinishNationBetting extends \sammo\Event\Action
{
public function __construct(private int $bettingID)
{
}
public function run(array $env)
{
$db = DB::db();
try {
$bettingHelper = new Betting($this->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("<B><b>【내기】</b></> {$year}{$month}월에 열렸던 {$bettingInfo->name} 내기의 결과가 나왔습니다!");
return [__CLASS__, true];
}
}
@@ -0,0 +1,126 @@
<?php
namespace sammo\Event\Action;
use \sammo\GameConst;
use \sammo\Util;
use \sammo\DB;
use sammo\DTO\BettingInfo;
use sammo\DTO\SelectItem;
use sammo\Json;
use sammo\KVStorage;
use function sammo\getAllNationStaticInfo;
class OpenNationBetting extends \sammo\Event\Action
{
public function __construct(private int $nationCnt = 1, private int $bonusPoint = 0)
{
if ($nationCnt < 1) {
throw new \RuntimeException("1 미만의 숫자");
}
if ($bonusPoint < 0) {
throw new \RuntimeException("0 미만의 보너스 포인트");
}
}
public function run(array $env)
{
$db = DB::db();
$gameStor = KVStorage::getStorage($db, 'game_env');
$gameStor->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("<br>", $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("<B><b>【내기】</b></>중원의 강자를 점치는 <C>내기</>가 진행중입니다! 호사가의 참여를 기다립니다!");
} else {
$logger->pushGlobalHistoryLog("<B><b>【내기】</b></>천하통일 후보를 점치는 <C>내기</>가 진행중입니다! 호사가의 참여를 기다립니다!");
}
$logger->flush();
return [__CLASS__, true];
}
}
+4
View File
@@ -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"]]),
]);
@@ -0,0 +1,50 @@
<?php
namespace sammo\Event\Condition;
use function sammo\getAllNationStaticInfo;
class RemainNation extends \sammo\Event\Condition{
const AVAILABLE_CMP = [
'=='=>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__]
];
}
}
+1 -1
View File
@@ -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);
+2
View File
@@ -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();
+54 -40
View File
@@ -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;
}
+1
View File
@@ -671,6 +671,7 @@ class GeneralBuilder{
'intel'=>$this->intel,
'experience'=>$experience,
'dedication'=>$dedication,
'dedlevel'=>1,
'officer_level'=>$officerLevel,
'gold'=>$this->gold,
'rice'=>$this->rice,
+4 -4
View File
@@ -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();
}
}
+2
View File
@@ -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"]
+2
View File
@@ -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"]
+2 -2
View File
@@ -12,7 +12,7 @@
]],
["황건적", "#FFD700", 10000, 10000, "황건적", 500, "태평도", 2, [
"업","계교","진류","관도","정도","평원","복양","패","허창","초"
]]
]]
],
"diplomacy":[
],
@@ -703,7 +703,7 @@
],
"history":[
"<C>●</>184년 1월:<L><b>【역사모드1】</b></>황건적의 난",
"<C>●</>184년 1월:<Y><b>【황건적】</b></>전국 각지에서 황건적이 들고 일어서고 있습니다."
"<C>●</>184년 1월:<Y><b>【황건적】</b></>전국 각지에서 황건적이 들고 일어서고 있습니다."
],
"initialEvents":[
[
+2 -2
View File
@@ -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],
+2 -2
View File
@@ -8,8 +8,8 @@
},
"nation":[
["조조", "#000080", 10000, 10000, "하북을 제패하고 대군을 이끌고 남하하는 조조", 1000, "병가", 6, [
"허창", "역경", "계교", "관도", "호관", "정도", "호로", "사곡", "함곡", "사수", "서주", "계",
"북평", "진양", "남피", "평원", "하내", "업", "북해", "복양", "장안", "홍농", "낙양", "진류",
"허창", "역경", "계교", "관도", "호관", "정도", "호로", "사곡", "함곡", "사수", "서주", "계",
"북평", "진양", "남피", "평원", "하내", "업", "북해", "복양", "장안", "홍농", "낙양", "진류",
"패", "초", "하비", "완", "여남", "수춘", "신야", "양양", "강릉", "장판"
]],
["손권", "#FF0000", 10000, 10000, "조조의 남하에 유비와 불가침으로 맞서는 손권", 1000, "덕가", 4, [
+2
View File
@@ -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"]
+2
View File
@@ -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"]
+3
View File
@@ -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
+2
View File
@@ -11,11 +11,13 @@
],
"events": [
[
"month", 1000,
["Date", "==", null, 12],
["CreateManyNPC", 100, 0],
["DeleteEvent"]
],
[
"month", 1000,
["Date", "==", 181, 12],
["ChangeCity", "occupied", {
"pop": "+60000",
+184
View File
@@ -0,0 +1,184 @@
{
"title":"【이벤트】 대리전",
"startYear":180,
"map":{
"mapName":"miniche_b"
},
"history":[
"<C>●</>180년 1월:<L><b>【이벤트】</b></>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"]
]
]
}
+62
View File
@@ -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;
}
}
+3 -1
View File
@@ -62,4 +62,6 @@ CREATE TABLE `reserved_open` (
INDEX `date` (`date`)
)
DEFAULT CHARSET=utf8mb4
ENGINE=Aria;
ENGINE=Aria;
DROP TABLE IF EXISTS ng_betting;
+26 -4
View File
@@ -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
;
;
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
;
+1 -1
View File
@@ -5,7 +5,7 @@
<?=$btnBegin??''?><a href="a_history.php" target="_blank" class="open-window toolbarButton <?=$btnClass??""?>">연감</a><?=$btnEnd??''?>
<?=$btnBegin??''?><a href="a_hallOfFame.php" target="_blank" class="open-window toolbarButton <?=$btnClass??""?>">명예의전당</a><?=$btnEnd??''?>
<?=$btnBegin??''?><a href="a_emperior.php" target="_blank" class="open-window toolbarButton <?=$btnClass??""?>">왕조일람</a><?=$btnEnd??''?>
<?=$btnBegin??''?><a href="a_traffic.php" target="_blank" class="open-window toolbarButton <?=$btnClass??""?>">접속량정보</a><?=$btnEnd??''?>
<?=$btnBegin??''?><a href="v_nationBetting.php" target="_blank" class="open-window toolbarButton <?=$btnClass??""?>">천통국 베팅</a><?=$btnEnd??''?>
<?=$btnBegin??''?><a href="/bbs/board" target="_blank" class="toolbarButton2 <?=$btnClass??""?>">삼모게시판</a><?=$btnEnd??''?>
<?=$btnBegin??''?><a href="/bbs/tip" target="_blank" class="toolbarButton <?=$btnClass??""?>">팁/강좌</a><?=$btnEnd??''?>
<?=$btnBegin??''?><a href="/bbs/news" target="_blank" class="toolbarButton <?=$btnClass??""?>">삼국 일보</a><?=$btnEnd??''?>
+1
View File
@@ -0,0 +1 @@
export {}
+1 -1
View File
@@ -105,7 +105,7 @@
<NumberInputWithInfo
title="입찰 포인트"
:min="inheritActionCost.minSpecificUnique"
:max="this.items.previous"
:max="items.previous"
v-model="specificUniqueAmount"
/>
</div>
+11 -4
View File
@@ -197,7 +197,7 @@
<small
class="text-muted"
v-html="
(availableInheritSpecial[args.inheritSpecial] ?? { info: '' })
(availableInheritSpecial[args.inheritSpecial??''] ?? { info: '' })
.info
"
/>
@@ -263,19 +263,19 @@
<div class="col">
<NumberInputWithInfo
title="통솔"
v-model="args.inheritBonusStat[0]"
v-model="(args.inheritBonusStat??[0,0,0])[0]"
/>
</div>
<div class="col">
<NumberInputWithInfo
title="무력"
v-model="args.inheritBonusStat[1]"
v-model="(args.inheritBonusStat??[0,0,0])[1]"
/>
</div>
<div class="col">
<NumberInputWithInfo
title="지력"
v-model="args.inheritBonusStat[2]"
v-model="(args.inheritBonusStat??[0,0,0])[2]"
/>
</div>
</div>
@@ -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) {
+10 -6
View File
@@ -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("초기 설정으로 되돌릴까요?")) {
+90
View File
@@ -0,0 +1,90 @@
<template>
<MyToast v-model="toasts" />
<div id="container" class="pageNationBetting bg0">
<TopBackBar :title="title" />
<BettingDetail v-if="targetBettingID !== undefined" :bettingID="targetBettingID" @reqToast="addToast" />
<div v-if="bettingList === undefined">로딩 중...</div>
<div class="bettingList" v-else>
<div class="bg2">베팅 목록</div>
<div
class="bettingItem"
v-for="info of Object.values(bettingList).reverse()"
:key="info.id"
@click="targetBettingID = info.id"
>
[{{ parseYearMonth(info.openYearMonth)[0] }} {{ parseYearMonth(info.openYearMonth)[1] }}] {{ info.name }}
<span
v-if="info.finished"
>(종료)</span>
<span
v-else-if="(yearMonth ?? 0) <= info.closeYearMonth"
>({{ parseYearMonth(info.closeYearMonth)[0] }} {{ parseYearMonth(info.closeYearMonth)[1] }}월까지)</span>
<span v-else>(베팅 마감)</span>
</div>
</div>
<BottomBar />
</div>
</template>
<script lang="ts" setup>
import MyToast from "@/components/MyToast.vue";
import TopBackBar from "@/components/TopBackBar.vue";
import BottomBar from "@/components/BottomBar.vue";
import { BettingInfo, ToastType } from "@/defs";
import { onMounted, ref } from "vue";
import { SammoAPI, ValidResponse } from "./SammoAPI";
import { isString } from "lodash";
import { parseYearMonth } from "@/util/parseYearMonth";
import { joinYearMonth } from "./util/joinYearMonth";
import BettingDetail from "@/components/BettingDetail.vue";
type BettingListResponse = ValidResponse & {
bettingList: Record<number, Omit<BettingInfo & { totalAmount: number }, 'candidates'>>,
year: number,
month: number,
};
const toasts = ref<ToastType[]>([]);
const year = ref<number>();
const month = ref<number>();
const yearMonth = ref<number>();
const bettingList = ref<BettingListResponse['bettingList']>();
const targetBettingID = ref<number>();
function addToast(msg: ToastType){
toasts.value.push(msg);
}
console.log('시작!');
onMounted(async () => {
try {
const result = await SammoAPI.Betting.GetBettingList<BettingListResponse>();
year.value = result.year;
month.value = result.month;
yearMonth.value = joinYearMonth(result.year, result.month);
bettingList.value = result.bettingList;
console.log(result);
} catch (e) {
if (isString(e)) {
toasts.value.push({
title: "에러",
content: e,
type: "danger",
});
}
console.error(e);
}
});
const title = '국가 베팅장';
</script>
+1 -1
View File
@@ -44,7 +44,7 @@
<div
v-for="([endYear, endMonth], _idx) in [
parseYearMonth(
joinYearMonth(year, month) + nation.diplomacy.term
joinYearMonth(year, month) + (nation.diplomacy.term??0)
),
]"
:key="_idx"
+5
View File
@@ -13,6 +13,11 @@ async function done<ResultType extends ValidResponse, ErrorType extends InvalidR
}
const apiRealPath = {
Betting:{
Bet: done,
GetBettingDetail: done,
GetBettingList: done,
},
Command: {
GetReservedCommand: done,
PushCommand: done,
+2 -1
View File
@@ -27,6 +27,7 @@
"v_join": "v_join.ts",
"v_main": "v_main.ts",
"v_nationStratFinan": "v_nationStratFinan.ts",
"v_processing": "v_processing.ts"
"v_processing": "v_processing.ts",
"v_nationBetting": "v_nationBetting.ts"
}
}
+11 -2
View File
@@ -79,12 +79,21 @@ function br2nl (text) {
}
*/
export function getNpcColor(npcType: number): 'cyan' | 'skyblue' | null {
export function getNpcColor(npcType: number): 'skyblue' | 'cyan' | 'deepskyblue' | 'darkcyan' | 'mediumaquamarine' | undefined {
if (npcType == 6){
return 'mediumaquamarine';
}
if (npcType == 5){
return 'darkcyan';
}
if (npcType == 4){
return 'deepskyblue';
}
if (npcType >= 2) {
return 'cyan';
}
if (npcType == 1) {
return 'skyblue';
}
return null;
return undefined;
}
+436
View File
@@ -0,0 +1,436 @@
<template>
<div v-if="bettingDetailInfo !== undefined && info !== undefined">
<div class="bg2">
{{ info.name }}
<span v-if="info.finished">(종료)</span>
<span
v-else-if="(yearMonth ?? 0) <= info.closeYearMonth"
>({{ parseYearMonth(info.closeYearMonth)[0] }} {{ parseYearMonth(info.closeYearMonth)[1] }}월까지)</span>
<span v-else>(베팅 마감)</span>
(총액: {{ bettingAmount.toLocaleString() }})
</div>
<div class="row bettingCandidates gx-1 gy-1">
<div
class="col-4 col-md-2"
v-for="(candidate, idx) in info.candidates"
:key="idx"
@click="toggleCandidate(idx)"
>
<div
:class="[
'bettingCandidate',
pickedBetType.has(idx) ? 'picked' : undefined,
(info.finished && winner.has(idx)) ? 'picked' : undefined,
]"
>
<div class="title bg1">{{ candidate.title }}</div>
<div class="info" v-if="candidate.isHtml" v-html="candidate.info"></div>
<div
class="pickRate"
>선택율: {{ ((partialBet.get(idx) ?? 0) / pureBettingAmount * 100).toFixed(1) }}%</div>
</div>
</div>
</div>
<div v-if="!info.finished && (yearMonth ?? 0) <= info.closeYearMonth" class="row gx-0">
<div
class="col-6 col-md-3 align-self-center"
>잔여 {{ info.reqInheritancePoint ? '포인트' : '금' }} : {{ bettingDetailInfo.remainPoint.toLocaleString() }}</div>
<div
class="col-6 col-md-3 align-self-center"
>사용 포인트: {{ sum(Array.from(myBettings.values())).toLocaleString() }}</div>
<div class="col-6 col-md-3 align-self-center">대상: {{ getTypeStr(pickedBetTypeKey) }}</div>
<div class="col-4 col-md-2 d-grid">
<b-form-input
class="d-grid"
type="number"
v-model="betPoint"
:min="10"
:max="1000"
:step="10"
></b-form-input>
</div>
<div class="col-2 col-md-1 d-grid">
<b-button class="d-grid" @click="submitBet">베팅</b-button>
</div>
</div>
<div>
<div class="bg2">배당 순위</div>
<div
class="row"
:style="{
borderBottom: 'gray solid 1px'
}"
>
<div class="col-5 text-center">대상</div>
<div class="col-2 text-center">베팅액</div>
<div class="col-3 text-center"> 베팅</div>
<div class="col-2 text-center">{{ info.finished? '배율':'기대 배율' }}</div>
</div>
<template v-if="info.finished">
<div class="row" v-for="[betType, amount] of detailBet" :key="betType">
<template
v-for="[matchPoint, color] of [calcMatchPointWithColor(betType)]"
:key="matchPoint"
>
<div
class="col-5"
:style="{
fontWeight: myBettings.has(betType) ? 'bold' : undefined,
color: color
}"
>{{ getTypeStr(betType) }}</div>
<div class="col-2 text-end">{{ amount.toLocaleString() }}</div>
<div class="col-3 text-center" v-if="myBettings.has(betType)">
<template
v-for="subPoint of [myBettings.get(betType) ?? 0]"
>({{ subPoint.toLocaleString() }} -> {{ calculatedReward[matchPoint] == 0? 0 : (subPoint * calculatedReward[matchPoint] / (calculatedSubAmount.get(matchPoint)??1)).toFixed(1).toLocaleString() }})</template>
</div>
<div class="col-3 text-center" v-else></div>
<div class="col-2 text-end">{{ (calculatedReward[matchPoint] == 0? 0 : (calculatedReward[matchPoint] / (calculatedSubAmount.get(matchPoint)??1))).toFixed(1).toLocaleString() }}</div>
</template>
</div>
</template>
<template v-else>
<div class="row" v-for="[betType, amount] of detailBet" :key="betType">
<div
class="col-5"
:style="{
fontWeight: myBettings.has(betType) ? 'bold' : undefined,
}"
>{{ getTypeStr(betType) }}</div>
<div class="col-2 text-end">{{ amount.toLocaleString() }}</div>
<div class="col-3 text-center" v-if="myBettings.has(betType)">
<template
v-for="subPoint of [myBettings.get(betType) ?? 0]"
>({{ subPoint.toLocaleString() }} -> {{ (subPoint * maxBettingReward / amount).toFixed(1).toLocaleString() }})</template>
</div>
<div class="col-3 text-center" v-else></div>
<div class="col-2 text-end">{{ (maxBettingReward / amount).toFixed(1).toLocaleString() }}</div>
</div>
</template>
</div>
</div>
</template>
<script setup lang="ts">import { BettingInfo, ToastType } from '@/defs';
import { SammoAPI, ValidResponse } from "@/SammoAPI";
import { joinYearMonth } from '@/util/joinYearMonth';
import { parseYearMonth } from '@/util/parseYearMonth';
import { isString, range, sum } from 'lodash';
import { ref, defineProps, defineEmits, PropType, watch } from "vue";
type BettingDetailResponse = ValidResponse & {
bettingInfo: BettingInfo;
bettingDetail: [string, number][];
myBetting: [string, number][];
remainPoint: number;
year: number;
month: number;
}
const props = defineProps({
bettingID: {
type: Number as PropType<number>,
required: true,
}
});
const emit = defineEmits<{
(event: 'reqToast', content: ToastType): void,
}>();
const year = ref<number>(0);
const month = ref<number>(0);
const yearMonth = ref<number>(0);
const bettingDetailInfo = ref<BettingDetailResponse>();
const info = ref<BettingInfo>();
const bettingAmount = ref<number>(0);
const maxBettingReward = ref<number>(1);
const pureBettingAmount = ref<number>(0);
const partialBet = ref(new Map<number, number>());
const detailBet = ref<[string, number][]>([]);
const typeMap = ref(new Map<string, string>());
function getTypeStr(type: string): string {
const typeResult = typeMap.value.get(type);
if (typeResult !== undefined) {
return typeResult;
}
const bettingSubTypes = JSON.parse(type) as number[];
if (bettingSubTypes[0] < -1) {
return 'Invalid';
}
const textBettingType = bettingSubTypes.map((idx) => {
return bettingDetailInfo.value?.bettingInfo.candidates[idx].title;
}).join(', ');
typeMap.value.set(type, textBettingType);
return textBettingType;
}
const pickedBetType = ref(new Set<number>());
const pickedBetTypeKey = ref('[]');
const betPoint = ref(0);
const myBettings = ref(new Map<string, number>());
const winner = ref(new Set<number>());
const calculatedReward = ref<number[]>([]);
const calculatedSubAmount = ref(new Map<number, number>());
function calcMatchPointWithColor(type: string): [number, 'green' | 'yellow' | 'red' | undefined] {
if (!info.value?.finished) {
return [0, undefined];
}
const bettingSubTypes = JSON.parse(type) as number[];
if (bettingSubTypes[0] < -1) {
return [0, undefined];
}
let matchPoint = 0;
for (const subType of bettingSubTypes) {
if (winner.value.has(subType)) {
matchPoint += 1;
}
}
if (info.value.isExclusive) {
if (matchPoint == info.value.selectCnt) {
return [matchPoint, 'green'];
}
else {
return [matchPoint, 'red'];
}
}
let color: 'green' | 'red' | 'yellow' = 'green';
if (matchPoint == 0) {
color = 'red';
}
else if (matchPoint < info.value.selectCnt) {
color = 'yellow';
}
return [matchPoint, color];
}
function calcReward() {
if (info.value === undefined || bettingDetailInfo.value === undefined) {
throw 'no info';
}
const selectCnt = info.value.selectCnt;
const rewardAmount = new Array<number>(selectCnt).fill(0);
const subAmount = new Map<number, number>();
for (const [bettingTypeStr, amount] of bettingDetailInfo.value.bettingDetail) {
if (amount == 0) {
continue;
}
const [matchPoint,] = calcMatchPointWithColor(bettingTypeStr);
subAmount.set(matchPoint, (subAmount.get(matchPoint) ?? 0) + amount);
}
calculatedSubAmount.value = subAmount;
if (info.value.isExclusive) {
rewardAmount[selectCnt - 1] = bettingAmount.value;
calculatedReward.value = rewardAmount;
return;
}
let remainRewardAmount = bettingAmount.value;
for (const matchPoint of range(selectCnt, 0, -1)) {
if (!subAmount.has(matchPoint)) {
continue;
}
const givenRewardAmount = remainRewardAmount / 2;
rewardAmount[matchPoint] = givenRewardAmount;
remainRewardAmount -= givenRewardAmount; // /2가 아니라 다른 값이 될 경우를 대비..
}
for (const matchPoint of range(1, selectCnt + 1)) {
if (!subAmount.has(matchPoint)) {
continue;
}
rewardAmount[matchPoint] += remainRewardAmount;
break;
}
calculatedReward.value = rewardAmount;
}
async function loadBetting(bettingID: number) {
try {
const result = await SammoAPI.Betting.GetBettingDetail<BettingDetailResponse>({
betting_id: bettingID
});
year.value = result.year;
month.value = result.month;
yearMonth.value = joinYearMonth(result.year, result.month);
bettingDetailInfo.value = result;
info.value = result.bettingInfo;
partialBet.value.clear();
const betSort = new Map<string, number>();
let _bettingAmount = 0;
let adminBettingAmount = 0;
for (const [bettingType, amount] of result.bettingDetail) {
console.log(amount, typeof (amount));
let userBet = true;
const bettingSubTypes = JSON.parse(bettingType) as number[];
for (const bettingSubType of bettingSubTypes) {
if (bettingSubType < 0) {
userBet = false;
continue;
}
const oldValue = partialBet.value.get(bettingSubType) ?? 0;
partialBet.value.set(bettingSubType, oldValue + amount);
}
if (userBet) {
const oldValue = betSort.get(bettingType) ?? 0;
betSort.set(bettingType, oldValue + amount);
}
_bettingAmount += amount;
if (!userBet) {
adminBettingAmount += amount;
}
}
console.log(_bettingAmount);
bettingAmount.value = _bettingAmount;
pureBettingAmount.value = _bettingAmount - adminBettingAmount;
if (info.value.isExclusive && info.value.selectCnt > 1) {
maxBettingReward.value = _bettingAmount;
} else {
maxBettingReward.value = _bettingAmount / 2;
}
detailBet.value = Array.from(betSort.entries());
detailBet.value.sort(([, lhsVal], [, rhsVal]) => {
return rhsVal - lhsVal;
})
pickedBetType.value.clear();
pickedBetTypeKey.value = '[]';
myBettings.value.clear();
if (result.bettingInfo.winner) {
winner.value = new Set(result.bettingInfo.winner);
}
else {
winner.value.clear();
}
for (const [betType, amount] of result.myBetting) {
myBettings.value.set(betType, amount);
}
calcReward();
} catch (e) {
if (isString(e)) {
emit('reqToast', {
title: "에러",
content: e,
type: "danger",
});
}
console.error(e);
}
}
void loadBetting(props.bettingID);
watch(() => props.bettingID, (newBettingID) => {
void loadBetting(newBettingID);
});
function toggleCandidate(idx: number) {
if (info.value === undefined) {
return;
}
if (bettingDetailInfo.value === undefined) {
return;
}
if (info.value.closeYearMonth < yearMonth.value) {
return;
}
if (info.value.finished) {
return;
}
const selectCnt = bettingDetailInfo.value.bettingInfo.selectCnt;
if (selectCnt == 1) {
pickedBetType.value.clear();
pickedBetType.value.add(idx);
pickedBetTypeKey.value = JSON.stringify([idx]);
return;
}
if (pickedBetType.value.has(idx)) {
pickedBetType.value.delete(idx);
}
else if (pickedBetType.value.size < selectCnt) {
pickedBetType.value.add(idx);
}
else {
emit('reqToast', {
title: '오류',
type: 'warning',
content: `이미 ${selectCnt}개를 선택했습니다.`,
});
return;
}
const typeArr = Array.from(pickedBetType.value.values());
pickedBetTypeKey.value = JSON.stringify(typeArr.sort((lhs, rhs) => lhs - rhs));
}
async function submitBet(): Promise<void> {
const bettingInfo = info.value;
if (bettingInfo === undefined) {
return;
}
const bettingID = bettingInfo.id;
const bettingType = JSON.parse(pickedBetTypeKey.value);
const amount = betPoint.value;
try {
await SammoAPI.Betting.Bet({
bettingID,
bettingType,
amount,
});
emit('reqToast', {
title: '완료',
content: '베팅했습니다',
type: 'success'
});
await loadBetting(bettingInfo.id);
} catch (e) {
if (isString(e)) {
emit('reqToast', {
title: "에러",
content: e,
type: "danger",
});
}
console.error(e);
}
}
</script>
+2 -2
View File
@@ -6,7 +6,7 @@
<span class="me-auto fw-bold">{{ toast.title }}</span>
<CToastClose class="my-close" color="secondary" size="sm" />
</CToastHeader>
<CToastBody> {{ toast.content }} {{ toast.visible }} </CToastBody>
<CToastBody> {{ toast.content }} </CToastBody>
</CToast>
</template>
</CToaster>
@@ -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) => {
+22
View File
@@ -223,3 +223,25 @@ export const diplomacyStateInfo: Record<diplomacyState, diplomacyInfo> = {
2: { name: '통상' },
7: { name: '불가침', color: 'green' },
}
export type SelectItem = {
title: string;
info?: string;
isHtml?: boolean;
aux?: Record<string, unknown>;
}
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[];
}
+13 -2
View File
@@ -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<string, number>;
};
declare const turnterm: number;
type KingdomGeneral = {
html: JQuery<HTMLElement>,
장수명: 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 = $('<span></span>');
$obj.html(val.);
if (!val.NPC && val. < 80) {
if (!val.NPC && val. < realKillturn) {
$obj.css('text-decoration', 'line-through');
+= 1;
}
+7 -5
View File
@@ -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();
})
});
});
function getNPCColor(npc: number) {
throw new Error('Function not implemented.');
}
+12
View File
@@ -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');
+39
View File
@@ -0,0 +1,39 @@
<?php
namespace sammo;
include "lib.php";
include "func.php";
//로그인 검사
$session = Session::requireGameLogin()->setReadOnly();
$userID = Session::getUserID();
$db = DB::db();
$gameStor = KVStorage::getStorage($db, 'game_env');
$generalID = $session->generalID;
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=500" />
<title><?= UniqueConst::$serverName ?>: 국가 베팅장</title>
<?= WebUtil::printStaticValues([
'staticValues' => [
]
], false) ?>
<?= WebUtil::printJS('../d_shared/common_path.js') ?>
<?= WebUtil::printCSS('../d_shared/common.css') ?>
<link rel="stylesheet" type="text/css" href="https://cdn.jsdelivr.net/gh/orioncactus/pretendard/dist/web/static/pretendard.css" />
<?= WebUtil::printDist('vue', 'v_nationBetting', true) ?>
</head>
<body>
<div id="app"></div>
</body>
</html>
+1
View File
@@ -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",
+11 -2
View File
@@ -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',
+1
View File
@@ -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'),
+5
View File
@@ -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',
+66
View File
@@ -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",
+11 -2
View File
@@ -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',
+2 -2
View File
@@ -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) {
@@ -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**!
@@ -0,0 +1,2 @@
github: spatie
custom: https://spatie.be/open-source/support-us
@@ -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
@@ -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
@@ -0,0 +1,41 @@
<?php
$finder = Symfony\Component\Finder\Finder::create()
->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);
+248
View File
@@ -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<int, string>` 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
+21
View File
@@ -0,0 +1,21 @@
The MIT License (MIT)
Copyright (c) Spatie bvba <info@spatie.be>
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.
+504
View File
@@ -0,0 +1,504 @@
# Data transfer objects with batteries included
[![Latest Version on Packagist](https://img.shields.io/packagist/v/spatie/data-transfer-object.svg?style=flat-square)](https://packagist.org/packages/spatie/data-transfer-object)
![Test](https://github.com/spatie/data-transfer-object/workflows/Test/badge.svg)
[![Total Downloads](https://img.shields.io/packagist/dt/spatie/data-transfer-object.svg?style=flat-square)](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
[<img src="https://github-ads.s3.eu-central-1.amazonaws.com/data-transfer-object.jpg?t=1" width="419px" />](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.
+44
View File
@@ -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
}
}
+98
View File
@@ -0,0 +1,98 @@
<?php
namespace Spatie\DataTransferObject;
use ArrayAccess;
class Arr
{
public static function only($array, $keys): array
{
return array_intersect_key($array, array_flip((array) $keys));
}
public static function except($array, $keys): array
{
return static::forget($array, $keys);
}
public static function forget($array, $keys): array
{
$keys = (array) $keys;
if (count($keys) === 0) {
return $array;
}
foreach ($keys as $key) {
// If the exact key exists in the top-level, remove it
if (static::exists($array, $key)) {
unset($array[$key]);
continue;
}
// Check if the key is using dot-notation
if (! str_contains($key, '.')) {
continue;
}
// If we are dealing with dot-notation, recursively handle i
$parts = explode('.', $key);
$key = array_shift($parts);
if (static::exists($array, $key) && static::accessible($array[$key])) {
$array[$key] = static::forget($array[$key], implode('.', $parts));
if (count($array[$key]) === 0) {
unset($array[$key]);
}
}
}
return $array;
}
public static function get($array, $key, $default = null)
{
if (! static::accessible($array)) {
return $default;
}
if (is_null($key)) {
return $array;
}
if (static::exists($array, $key)) {
return $array[$key];
}
if (strpos($key, '.') === false) {
return $array[$key] ?? $default;
}
foreach (explode('.', $key) as $segment) {
if (static::accessible($array) && static::exists($array, $segment)) {
$array = $array[$segment];
} else {
return $default;
}
}
return $array;
}
public static function accessible($value)
{
return is_array($value) || $value instanceof ArrayAccess;
}
public static function exists($array, $key): bool
{
if ($array instanceof ArrayAccess) {
return $array->offsetExists($key);
}
return array_key_exists($key, $array);
}
}
@@ -0,0 +1,24 @@
<?php
namespace Spatie\DataTransferObject\Attributes;
use Attribute;
use Spatie\DataTransferObject\Caster;
use Spatie\DataTransferObject\Exceptions\InvalidCasterClass;
#[Attribute(Attribute::TARGET_CLASS | Attribute::TARGET_PROPERTY)]
class CastWith
{
public array $args;
public function __construct(
public string $casterClass,
mixed ...$args
) {
if (! is_subclass_of($this->casterClass, Caster::class)) {
throw new InvalidCasterClass($this->casterClass);
}
$this->args = $args;
}
}
@@ -0,0 +1,53 @@
<?php
namespace Spatie\DataTransferObject\Attributes;
use Attribute;
use JetBrains\PhpStorm\Immutable;
use ReflectionNamedType;
use ReflectionProperty;
use ReflectionUnionType;
use Spatie\DataTransferObject\Caster;
#[Attribute(Attribute::TARGET_CLASS | Attribute::IS_REPEATABLE)]
class DefaultCast
{
public function __construct(
#[Immutable]
private string $targetClass,
#[Immutable]
private string $casterClass,
) {
}
public function accepts(ReflectionProperty $property): bool
{
$type = $property->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();
}
}
@@ -0,0 +1,14 @@
<?php
namespace Spatie\DataTransferObject\Attributes;
use Attribute;
#[Attribute(Attribute::TARGET_CLASS | Attribute::TARGET_PROPERTY)]
class MapFrom
{
public function __construct(
public string | int $name,
) {
}
}
@@ -0,0 +1,14 @@
<?php
namespace Spatie\DataTransferObject\Attributes;
use Attribute;
#[Attribute(Attribute::TARGET_CLASS | Attribute::TARGET_PROPERTY)]
class MapTo
{
public function __construct(
public string $name,
) {
}
}
@@ -0,0 +1,10 @@
<?php
namespace Spatie\DataTransferObject\Attributes;
use Attribute;
#[Attribute(Attribute::TARGET_CLASS)]
class Strict
{
}
+8
View File
@@ -0,0 +1,8 @@
<?php
namespace Spatie\DataTransferObject;
interface Caster
{
public function cast(mixed $value): mixed;
}
@@ -0,0 +1,70 @@
<?php
namespace Spatie\DataTransferObject\Casters;
use ArrayAccess;
use LogicException;
use Spatie\DataTransferObject\Caster;
use Traversable;
class ArrayCaster implements Caster
{
public function __construct(
private array $types,
private string $itemType,
) {
}
public function cast(mixed $value): array | ArrayAccess
{
foreach ($this->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}]."
);
}
}
@@ -0,0 +1,25 @@
<?php
namespace Spatie\DataTransferObject\Casters;
use Spatie\DataTransferObject\Caster;
use Spatie\DataTransferObject\DataTransferObject;
class DataTransferObjectCaster implements Caster
{
public function __construct(
private array $classNames
) {
}
public function cast(mixed $value): DataTransferObject
{
foreach ($this->classNames as $className) {
if ($value instanceof $className) {
return $value;
}
}
return new $this->classNames[0](...$value);
}
}
@@ -0,0 +1,125 @@
<?php
namespace Spatie\DataTransferObject;
use ReflectionClass;
use ReflectionProperty;
use Spatie\DataTransferObject\Attributes\CastWith;
use Spatie\DataTransferObject\Attributes\MapTo;
use Spatie\DataTransferObject\Casters\DataTransferObjectCaster;
use Spatie\DataTransferObject\Exceptions\UnknownProperties;
use Spatie\DataTransferObject\Reflection\DataTransferObjectClass;
#[CastWith(DataTransferObjectCaster::class)]
abstract class DataTransferObject
{
protected array $exceptKeys = [];
protected array $onlyKeys = [];
public function __construct(...$args)
{
if (is_array($args[0] ?? null)) {
$args = $args[0];
}
$class = new DataTransferObjectClass($this);
foreach ($class->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;
}
}
@@ -0,0 +1,18 @@
<?php
namespace Spatie\DataTransferObject\Exceptions;
use Exception;
use Spatie\DataTransferObject\Caster;
class InvalidCasterClass extends Exception
{
public function __construct(string $className)
{
$expected = Caster::class;
parent::__construct(
"Class `{$className}` doesn't implement {$expected} and can't be used as a caster"
);
}
}
@@ -0,0 +1,15 @@
<?php
namespace Spatie\DataTransferObject\Exceptions;
use Exception;
class UnknownProperties extends Exception
{
public static function new(string $dtoClass, array $fields): self
{
$properties = json_encode($fields);
return new self("Unknown properties provided to `{$dtoClass}`: {$properties}");
}
}
@@ -0,0 +1,27 @@
<?php
namespace Spatie\DataTransferObject\Exceptions;
use Exception;
use Spatie\DataTransferObject\DataTransferObject;
class ValidationException extends Exception
{
public function __construct(
public DataTransferObject $dataTransferObject,
public array $validationErrors,
) {
$className = $dataTransferObject::class;
$messages = [];
foreach ($validationErrors as $fieldName => $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));
}
}
@@ -0,0 +1,84 @@
<?php
namespace Spatie\DataTransferObject\Reflection;
use ReflectionClass;
use ReflectionProperty;
use Spatie\DataTransferObject\Attributes\Strict;
use Spatie\DataTransferObject\DataTransferObject;
use Spatie\DataTransferObject\Exceptions\ValidationException;
class DataTransferObjectClass
{
private ReflectionClass $reflectionClass;
private DataTransferObject $dataTransferObject;
private bool $isStrict;
public function __construct(DataTransferObject $dataTransferObject)
{
$this->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;
}
}
@@ -0,0 +1,182 @@
<?php
namespace Spatie\DataTransferObject\Reflection;
use JetBrains\PhpStorm\Immutable;
use ReflectionAttribute;
use ReflectionClass;
use ReflectionNamedType;
use ReflectionProperty;
use ReflectionType;
use ReflectionUnionType;
use Spatie\DataTransferObject\Attributes\CastWith;
use Spatie\DataTransferObject\Attributes\DefaultCast;
use Spatie\DataTransferObject\Attributes\MapFrom;
use Spatie\DataTransferObject\Caster;
use Spatie\DataTransferObject\DataTransferObject;
use Spatie\DataTransferObject\Validator;
class DataTransferObjectProperty
{
#[Immutable]
public string $name;
private DataTransferObject $dataTransferObject;
private ReflectionProperty $reflectionProperty;
private ?Caster $caster;
public function __construct(
DataTransferObject $dataTransferObject,
ReflectionProperty $reflectionProperty
) {
$this->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(),
};
}
}
@@ -0,0 +1,31 @@
<?php
namespace Spatie\DataTransferObject\Validation;
use JetBrains\PhpStorm\Immutable;
class ValidationResult
{
public function __construct(
#[Immutable]
public bool $isValid,
#[Immutable]
public ?string $message = null
) {
}
public static function valid(): self
{
return new self(
isValid: true,
);
}
public static function invalid(string $message): self
{
return new self(
isValid: false,
message: $message,
);
}
}
+10
View File
@@ -0,0 +1,10 @@
<?php
namespace Spatie\DataTransferObject;
use Spatie\DataTransferObject\Validation\ValidationResult;
interface Validator
{
public function validate(mixed $value): ValidationResult;
}
+8
View File
@@ -89,6 +89,11 @@ module.exports = (env, argv) => {
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) {