Completed
Pull Request — master (#371)
by De Cramer
16:01
created

AutomaticServerSettingsSave::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 11
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 0
Metric Value
c 0
b 0
f 0
dl 0
loc 11
ccs 0
cts 11
cp 0
rs 9.4285
cc 1
eloc 9
nc 1
nop 4
crap 2
1
<?php
2
3
namespace eXpansion\Framework\Core\Plugins;
4
5
use eXpansion\Framework\Config\Model\TextConfig;
6
use eXpansion\Framework\Core\Helpers\FileSystem;
7
use eXpansion\Framework\Core\Storage\GameDataStorage;
8
use eXpansion\Framework\GameManiaplanet\DataProviders\Listener\ListenerInterfaceMpLegacyMap;
9
use Maniaplanet\DedicatedServer\Structures\Map;
10
use Psr\Log\LoggerInterface;
11
12
/**
13
 * Class AutomaticServerSettingsSave
14
 *
15
 * @author    de Cramer Oliver<[email protected]>
16
 * @copyright 2018 Oliverde8
17
 * @package eXpansion\Framework\Core\Plugins
18
 */
19
class AutomaticServerSettingsSave implements ListenerInterfaceMpLegacyMap, StatusAwarePluginInterface
20
{
21
    /** @var FileSystem */
22
    protected $fileSystem;
23
24
    /** @var GameDataStorage */
25
    protected $gameDataStorage;
26
27
    /** @var LoggerInterface */
28
    protected $logger;
29
30
    /** @var TextConfig */
31
    protected $fileName;
32
33
    /**
34
     * AutomaticServerSettingsSave constructor.
35
     *
36
     * @param FileSystem $fileSystem
37
     * @param GameDataStorage $gameDataStorage
38
     * @param $fileName
39
     */
40
    public function __construct(
41
        FileSystem $fileSystem,
42
        GameDataStorage $gameDataStorage,
43
        LoggerInterface $logger,
44
        $fileName
45
    ) {
46
        $this->fileSystem = $fileSystem;
47
        $this->gameDataStorage = $gameDataStorage;
48
        $this->logger = $logger;
49
        $this->fileName = $fileName;
50
    }
51
52
53
54
    public function saveFile()
55
    {
56
        if (!$this->fileName->get()) {
57
            return;
58
        }
59
60
        $path = 'Config/' . $this->fileName->get();
61
        $fileSystem = $this->fileSystem->getUserData();
62
63
        if (!$fileSystem->has($path)) {
64
            $this->logger->warning("Can't find file '$path'! Won't save server settings!");
65
            return;
66
        }
67
68
        /** @var \SimpleXMLElement */
69
        $oldXml = simplexml_load_string($fileSystem->read($path));
70
        if ($oldXml === false) {
71
            $this->logger->error("Invalid xml in source file '$path'! Won't save server settings!");
72
            return;
73
        }
74
75
        $adapter = array("name" => "name",
76
            "password" => "password",
77
            "comment" => "comment",
78
            "passwordForSpectator" => "password_spectator",
79
            "hideServer" => "hide_server",
80
            "nextMaxPlayers" => "max_players",
81
            "nextMaxSpectatos" => "max_spectators",
82
            "isP2PUpload" => "enable_p2p_upload",
83
            "isP2PDownload" => "enable_p2p_download",
84
            "nextLadderMode" => "ladder_mode",
85
            "nextCallVoteTimeOut" => "callvote_timeout",
86
            "callVoteRatio" => "callvote_ratio",
87
            "allowMapDownload" => "allow_map_download",
88
            "autoSaveReplays" => "autosave_replays",
89
            "autoSaveValidationReplays" => "autosave_validation_replays",
90
            "refereePassword" => "referee_password",
91
            "refereeMode" => "referee_validation_mode",
92
            "disableHorns" => "disable_horns",
93
            "clientInputsMaxLatency" => "clientinputs_maxlatency",
94
            "keepPlayerSlots" => "keep_player_slots",
95
        );
96
97
        $new = $this->gameDataStorage->getServerOptions();
98
        foreach ($this->gameDataStorage->getServerOptions() as $key => $value) {
0 ignored issues
show
Bug introduced by
The expression $this->gameDataStorage->getServerOptions() of type object<Maniaplanet\Dedic...ructures\ServerOptions> is not traversable.
Loading history...
99
            //           $search = $key;
0 ignored issues
show
Unused Code Comprehensibility introduced by
43% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
100
            if (array_key_exists($key, $adapter)) {
101
                $search = $adapter[$key];
102
            } else {
103
                continue;
104
            }
105
            $out = $new->{$key};
106
            if (is_bool($value)) {
107
                $out = "False";
108
                if ($value) {
109
                    $out = "True";
110
                }
111
            }
112
            $oldXml->server_options->{$search}[0] = $out;
113
        }
114
        $this->logger->info('Saving server settings to : ' . $path);
115
        $xml = $oldXml->asXML();
116
117
        $fileSystem->update($path, $xml);
0 ignored issues
show
Security Bug introduced by
It seems like $xml defined by $oldXml->asXML() on line 115 can also be of type false; however, League\Flysystem\FilesystemInterface::update() does only seem to accept string, did you maybe forget to handle an error condition?

This check looks for type mismatches where the missing type is false. This is usually indicative of an error condtion.

Consider the follow example

<?php

function getDate($date)
{
    if ($date !== null) {
        return new DateTime($date);
    }

    return false;
}

This function either returns a new DateTime object or false, if there was an error. This is a typical pattern in PHP programming to show that an error has occurred without raising an exception. The calling code should check for this returned false before passing on the value to another function or method that may not be able to handle a false.

Loading history...
118
    }
119
120
    /**
121
     * @param Map $map
122
     *
123
     * @return void
124
     */
125
    public function onBeginMap(Map $map)
126
    {
127
        $this->saveFile();
128
    }
129
130
    /**
131
     * @param Map $map
132
     *
133
     * @return void
134
     */
135
    public function onEndMap(Map $map)
136
    {
137
        // Nothing to do.
138
    }
139
140
    /**
141
     * Set the status of the plugin
142
     *
143
     * @param boolean $status
144
     *
145
     * @return null
146
     */
147
    public function setStatus($status)
148
    {
149
        $this->saveFile();
150
    }
151
}