Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.
Common duplication problems, and corresponding solutions are:
Complex classes like ServerRepository often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes. You can also have a look at the cohesion graph to spot any un-connected, or weakly-connected components.
Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.
While breaking up the class, it is a good idea to analyze how other classes use ServerRepository, and based on these observations, apply Extract Interface, too.
| 1 | <?php |
||
| 38 | class ServerRepository |
||
| 39 | { |
||
| 40 | protected $daemonPermissions = [ |
||
| 41 | 's:*', |
||
| 42 | ]; |
||
| 43 | |||
| 44 | public function __construct() |
||
| 48 | |||
| 49 | /** |
||
| 50 | * Generates a SFTP username for a server given a server name. |
||
| 51 | * format: mumble_67c7a4b0. |
||
| 52 | * |
||
| 53 | * @param string $name |
||
| 54 | * @param string $identifier |
||
| 55 | * @return string |
||
| 56 | */ |
||
| 57 | protected function generateSFTPUsername($name, $identifier = null) |
||
| 75 | |||
| 76 | /** |
||
| 77 | * Adds a new server to the system. |
||
| 78 | * @param array $data An array of data descriptors for creating the server. These should align to the columns in the database. |
||
| 79 | * @return int |
||
| 80 | */ |
||
| 81 | public function create(array $data) |
||
| 82 | { |
||
| 83 | |||
| 84 | // Validate Fields |
||
| 85 | $validator = Validator::make($data, [ |
||
| 86 | 'user_id' => 'required|exists:users,id', |
||
| 87 | 'name' => 'required|regex:/^([\w .-]{1,200})$/', |
||
| 88 | 'memory' => 'required|numeric|min:0', |
||
| 89 | 'swap' => 'required|numeric|min:-1', |
||
| 90 | 'io' => 'required|numeric|min:10|max:1000', |
||
| 91 | 'cpu' => 'required|numeric|min:0', |
||
| 92 | 'disk' => 'required|numeric|min:0', |
||
| 93 | 'service_id' => 'required|numeric|min:1|exists:services,id', |
||
| 94 | 'option_id' => 'required|numeric|min:1|exists:service_options,id', |
||
| 95 | 'location_id' => 'required|numeric|min:1|exists:locations,id', |
||
| 96 | 'pack_id' => 'sometimes|nullable|numeric|min:0', |
||
| 97 | 'startup' => 'string', |
||
| 98 | 'auto_deploy' => 'sometimes|boolean', |
||
| 99 | 'custom_id' => 'sometimes|required|numeric|unique:servers,id', |
||
| 100 | ]); |
||
| 101 | |||
| 102 | $validator->sometimes('node_id', 'required|numeric|min:1|exists:nodes,id', function ($input) { |
||
| 103 | return ! ($input->auto_deploy); |
||
| 104 | }); |
||
| 105 | |||
| 106 | $validator->sometimes('allocation_id', 'required|numeric|exists:allocations,id', function ($input) { |
||
| 107 | return ! ($input->auto_deploy); |
||
| 108 | }); |
||
| 109 | |||
| 110 | $validator->sometimes('allocation_additional.*', 'sometimes|required|numeric|exists:allocations,id', function ($input) { |
||
| 111 | return ! ($input->auto_deploy); |
||
| 112 | }); |
||
| 113 | |||
| 114 | // Run validator, throw catchable and displayable exception if it fails. |
||
| 115 | // Exception includes a JSON result of failed validation rules. |
||
| 116 | if ($validator->fails()) { |
||
| 117 | throw new DisplayValidationException($validator->errors()); |
||
| 118 | } |
||
| 119 | |||
| 120 | $user = Models\User::findOrFail($data['user_id']); |
||
| 121 | |||
| 122 | $autoDeployed = false; |
||
| 123 | if (isset($data['auto_deploy']) && $data['auto_deploy']) { |
||
| 124 | // This is an auto-deployment situation |
||
| 125 | // Ignore any other passed node data |
||
| 126 | unset($data['node_id'], $data['allocation_id']); |
||
| 127 | |||
| 128 | $autoDeployed = true; |
||
| 129 | $node = DeploymentService::smartRandomNode($data['memory'], $data['disk'], $data['location_id']); |
||
| 130 | $allocation = DeploymentService::randomAllocation($node->id); |
||
|
|
|||
| 131 | } else { |
||
| 132 | $node = Models\Node::findOrFail($data['node_id']); |
||
| 133 | } |
||
| 134 | |||
| 135 | // Verify IP & Port are a.) free and b.) assigned to the node. |
||
| 136 | // We know the node exists because of 'exists:nodes,id' in the validation |
||
| 137 | if (! $autoDeployed) { |
||
| 138 | $allocation = Models\Allocation::where('id', $data['allocation_id'])->where('node_id', $data['node_id'])->whereNull('server_id')->first(); |
||
| 139 | } |
||
| 140 | |||
| 141 | // Something failed in the query, either that combo doesn't exist, or it is in use. |
||
| 142 | if (! $allocation) { |
||
| 143 | throw new DisplayException('The selected Allocation ID is either already in use, or unavaliable for this node.'); |
||
| 144 | } |
||
| 145 | |||
| 146 | // Validate those Service Option Variables |
||
| 147 | // We know the service and option exists because of the validation. |
||
| 148 | // We need to verify that the option exists for the service, and then check for |
||
| 149 | // any required variable fields. (fields are labeled env_<env_variable>) |
||
| 150 | $option = Models\ServiceOption::where('id', $data['option_id'])->where('service_id', $data['service_id'])->first(); |
||
| 151 | if (! $option) { |
||
| 152 | throw new DisplayException('The requested service option does not exist for the specified service.'); |
||
| 153 | } |
||
| 154 | |||
| 155 | // Validate the Pack |
||
| 156 | if (! isset($data['pack_id']) || (int) $data['pack_id'] < 1) { |
||
| 157 | $data['pack_id'] = null; |
||
| 158 | } else { |
||
| 159 | $pack = Models\ServicePack::where('id', $data['pack_id'])->where('option_id', $data['option_id'])->first(); |
||
| 160 | if (! $pack) { |
||
| 161 | throw new DisplayException('The requested service pack does not seem to exist for this combination.'); |
||
| 162 | } |
||
| 163 | } |
||
| 164 | |||
| 165 | // Load up the Service Information |
||
| 166 | $service = Models\Service::find($option->service_id); |
||
| 167 | |||
| 168 | // Check those Variables |
||
| 169 | $variables = Models\ServiceVariable::where('option_id', $data['option_id'])->get(); |
||
| 170 | $variableList = []; |
||
| 171 | if ($variables) { |
||
| 172 | foreach ($variables as $variable) { |
||
| 173 | |||
| 174 | // Is the variable required? |
||
| 175 | if (! isset($data['env_' . $variable->env_variable])) { |
||
| 176 | if ($variable->required) { |
||
| 177 | throw new DisplayException('A required service option variable field (env_' . $variable->env_variable . ') was missing from the request.'); |
||
| 178 | } |
||
| 179 | $variableList[] = [ |
||
| 180 | 'id' => $variable->id, |
||
| 181 | 'env' => $variable->env_variable, |
||
| 182 | 'val' => $variable->default_value, |
||
| 183 | ]; |
||
| 184 | continue; |
||
| 185 | } |
||
| 186 | |||
| 187 | // Check aganist Regex Pattern |
||
| 188 | if (! is_null($variable->regex) && ! preg_match($variable->regex, $data['env_' . $variable->env_variable])) { |
||
| 189 | throw new DisplayException('Failed to validate service option variable field (env_' . $variable->env_variable . ') aganist regex (' . $variable->regex . ').'); |
||
| 190 | } |
||
| 191 | |||
| 192 | $variableList[] = [ |
||
| 193 | 'id' => $variable->id, |
||
| 194 | 'env' => $variable->env_variable, |
||
| 195 | 'val' => $data['env_' . $variable->env_variable], |
||
| 196 | ]; |
||
| 197 | continue; |
||
| 198 | } |
||
| 199 | } |
||
| 200 | |||
| 201 | // Check Overallocation |
||
| 202 | if (! $autoDeployed) { |
||
| 203 | if (is_numeric($node->memory_overallocate) || is_numeric($node->disk_overallocate)) { |
||
| 204 | $totals = Models\Server::select(DB::raw('SUM(memory) as memory, SUM(disk) as disk'))->where('node_id', $node->id)->first(); |
||
| 205 | |||
| 206 | // Check memory limits |
||
| 207 | View Code Duplication | if (is_numeric($node->memory_overallocate)) { |
|
| 208 | $newMemory = $totals->memory + $data['memory']; |
||
| 209 | $memoryLimit = ($node->memory * (1 + ($node->memory_overallocate / 100))); |
||
| 210 | if ($newMemory > $memoryLimit) { |
||
| 211 | throw new DisplayException('The amount of memory allocated to this server would put the node over its allocation limits. This node is allowed ' . ($node->memory_overallocate + 100) . '% of its assigned ' . $node->memory . 'Mb of memory (' . $memoryLimit . 'Mb) of which ' . (($totals->memory / $node->memory) * 100) . '% (' . $totals->memory . 'Mb) is in use already. By allocating this server the node would be at ' . (($newMemory / $node->memory) * 100) . '% (' . $newMemory . 'Mb) usage.'); |
||
| 212 | } |
||
| 213 | } |
||
| 214 | |||
| 215 | // Check Disk Limits |
||
| 216 | View Code Duplication | if (is_numeric($node->disk_overallocate)) { |
|
| 217 | $newDisk = $totals->disk + $data['disk']; |
||
| 218 | $diskLimit = ($node->disk * (1 + ($node->disk_overallocate / 100))); |
||
| 219 | if ($newDisk > $diskLimit) { |
||
| 220 | throw new DisplayException('The amount of disk allocated to this server would put the node over its allocation limits. This node is allowed ' . ($node->disk_overallocate + 100) . '% of its assigned ' . $node->disk . 'Mb of disk (' . $diskLimit . 'Mb) of which ' . (($totals->disk / $node->disk) * 100) . '% (' . $totals->disk . 'Mb) is in use already. By allocating this server the node would be at ' . (($newDisk / $node->disk) * 100) . '% (' . $newDisk . 'Mb) usage.'); |
||
| 221 | } |
||
| 222 | } |
||
| 223 | } |
||
| 224 | } |
||
| 225 | |||
| 226 | DB::beginTransaction(); |
||
| 227 | |||
| 228 | try { |
||
| 229 | $uuid = new UuidService; |
||
| 230 | |||
| 231 | // Add Server to the Database |
||
| 232 | $server = new Models\Server; |
||
| 233 | $genUuid = $uuid->generate('servers', 'uuid'); |
||
| 234 | $genShortUuid = $uuid->generateShort('servers', 'uuidShort', $genUuid); |
||
| 235 | |||
| 236 | if (isset($data['custom_id'])) { |
||
| 237 | $server->id = $data['custom_id']; |
||
| 238 | } |
||
| 239 | |||
| 240 | $server->fill([ |
||
| 241 | 'uuid' => $genUuid, |
||
| 242 | 'uuidShort' => $genShortUuid, |
||
| 243 | 'node_id' => $node->id, |
||
| 244 | 'name' => $data['name'], |
||
| 245 | 'suspended' => 0, |
||
| 246 | 'owner_id' => $user->id, |
||
| 247 | 'memory' => $data['memory'], |
||
| 248 | 'swap' => $data['swap'], |
||
| 249 | 'disk' => $data['disk'], |
||
| 250 | 'io' => $data['io'], |
||
| 251 | 'cpu' => $data['cpu'], |
||
| 252 | 'oom_disabled' => (isset($data['oom_disabled'])) ? true : false, |
||
| 253 | 'allocation_id' => $allocation->id, |
||
| 254 | 'service_id' => $data['service_id'], |
||
| 255 | 'option_id' => $data['option_id'], |
||
| 256 | 'pack_id' => $data['pack_id'], |
||
| 257 | 'startup' => $data['startup'], |
||
| 258 | 'daemonSecret' => $uuid->generate('servers', 'daemonSecret'), |
||
| 259 | 'image' => (isset($data['custom_container'])) ? $data['custom_container'] : $option->docker_image, |
||
| 260 | 'username' => $this->generateSFTPUsername($data['name'], $genShortUuid), |
||
| 261 | 'sftp_password' => Crypt::encrypt('not set'), |
||
| 262 | ]); |
||
| 263 | $server->save(); |
||
| 264 | |||
| 265 | // Mark Allocation in Use |
||
| 266 | $allocation->server_id = $server->id; |
||
| 267 | $allocation->save(); |
||
| 268 | |||
| 269 | // Add Additional Allocations |
||
| 270 | if (isset($data['allocation_additional']) && is_array($data['allocation_additional'])) { |
||
| 271 | foreach ($data['allocation_additional'] as $allocation) { |
||
| 272 | $model = Models\Allocation::where('id', $allocation)->where('node_id', $data['node_id'])->whereNull('server_id')->first(); |
||
| 273 | if (! $model) { |
||
| 274 | continue; |
||
| 275 | } |
||
| 276 | |||
| 277 | $model->server_id = $server->id; |
||
| 278 | $model->save(); |
||
| 279 | } |
||
| 280 | } |
||
| 281 | |||
| 282 | // Add Variables |
||
| 283 | $environmentVariables = [ |
||
| 284 | 'STARTUP' => $data['startup'], |
||
| 285 | ]; |
||
| 286 | |||
| 287 | foreach ($variableList as $item) { |
||
| 288 | $environmentVariables[$item['env']] = $item['val']; |
||
| 289 | |||
| 290 | Models\ServerVariable::create([ |
||
| 291 | 'server_id' => $server->id, |
||
| 292 | 'variable_id' => $item['id'], |
||
| 293 | 'variable_value' => $item['val'], |
||
| 294 | ]); |
||
| 295 | } |
||
| 296 | |||
| 297 | $server->load('allocation', 'allocations'); |
||
| 298 | $node->guzzleClient(['X-Access-Token' => $node->daemonSecret])->request('POST', '/servers', [ |
||
| 299 | 'json' => [ |
||
| 300 | 'uuid' => (string) $server->uuid, |
||
| 301 | 'user' => $server->username, |
||
| 302 | 'build' => [ |
||
| 303 | 'default' => [ |
||
| 304 | 'ip' => $server->allocation->ip, |
||
| 305 | 'port' => $server->allocation->port, |
||
| 306 | ], |
||
| 307 | 'ports' => $server->allocations->groupBy('ip')->map(function ($item) { |
||
| 308 | return $item->pluck('port'); |
||
| 309 | })->toArray(), |
||
| 310 | 'env' => $environmentVariables, |
||
| 311 | 'memory' => (int) $server->memory, |
||
| 312 | 'swap' => (int) $server->swap, |
||
| 313 | 'io' => (int) $server->io, |
||
| 314 | 'cpu' => (int) $server->cpu, |
||
| 315 | 'disk' => (int) $server->disk, |
||
| 316 | 'image' => (isset($data['custom_container'])) ? $data['custom_container'] : $option->docker_image, |
||
| 317 | ], |
||
| 318 | 'service' => [ |
||
| 319 | 'type' => $service->file, |
||
| 320 | 'option' => $option->tag, |
||
| 321 | 'pack' => (isset($pack)) ? $pack->uuid : null, |
||
| 322 | ], |
||
| 323 | 'keys' => [ |
||
| 324 | (string) $server->daemonSecret => $this->daemonPermissions, |
||
| 325 | ], |
||
| 326 | 'rebuild' => false, |
||
| 327 | ], |
||
| 328 | ]); |
||
| 329 | |||
| 330 | DB::commit(); |
||
| 331 | |||
| 332 | return $server; |
||
| 333 | } catch (TransferException $ex) { |
||
| 334 | DB::rollBack(); |
||
| 335 | throw new DisplayException('There was an error while attempting to connect to the daemon to add this server.', $ex); |
||
| 336 | } catch (\Exception $ex) { |
||
| 337 | DB::rollBack(); |
||
| 338 | throw $ex; |
||
| 339 | } |
||
| 340 | } |
||
| 341 | |||
| 342 | /** |
||
| 343 | * [updateDetails description]. |
||
| 344 | * @param int $id |
||
| 345 | * @param array $data |
||
| 346 | * @return bool |
||
| 347 | */ |
||
| 348 | public function updateDetails($id, array $data) |
||
| 349 | { |
||
| 350 | $uuid = new UuidService; |
||
| 351 | $resetDaemonKey = false; |
||
| 352 | |||
| 353 | // Validate Fields |
||
| 354 | $validator = Validator::make($data, [ |
||
| 355 | 'owner_id' => 'sometimes|required|integer|exists:users,id', |
||
| 356 | 'name' => 'sometimes|required|regex:([\w .-]{1,200})', |
||
| 357 | 'reset_token' => 'sometimes|required|accepted', |
||
| 358 | ]); |
||
| 359 | |||
| 360 | // Run validator, throw catchable and displayable exception if it fails. |
||
| 361 | // Exception includes a JSON result of failed validation rules. |
||
| 362 | if ($validator->fails()) { |
||
| 363 | throw new DisplayValidationException($validator->errors()); |
||
| 364 | } |
||
| 365 | |||
| 366 | DB::beginTransaction(); |
||
| 367 | |||
| 368 | try { |
||
| 369 | $server = Models\Server::with('user')->findOrFail($id); |
||
| 370 | |||
| 371 | // Update daemon secret if it was passed. |
||
| 372 | if (isset($data['reset_token']) || (isset($data['owner_id']) && (int) $data['owner_id'] !== $server->user->id)) { |
||
| 373 | $oldDaemonKey = $server->daemonSecret; |
||
| 374 | $server->daemonSecret = $uuid->generate('servers', 'daemonSecret'); |
||
| 375 | $resetDaemonKey = true; |
||
| 376 | } |
||
| 377 | |||
| 378 | // Update Server Owner if it was passed. |
||
| 379 | if (isset($data['owner_id']) && (int) $data['owner_id'] !== $server->user->id) { |
||
| 380 | $server->owner_id = $data['owner_id']; |
||
| 381 | } |
||
| 382 | |||
| 383 | // Update Server Name if it was passed. |
||
| 384 | if (isset($data['name'])) { |
||
| 385 | $server->name = $data['name']; |
||
| 386 | } |
||
| 387 | |||
| 388 | // Save our changes |
||
| 389 | $server->save(); |
||
| 390 | |||
| 391 | // Do we need to update? If not, return successful. |
||
| 392 | if (! $resetDaemonKey) { |
||
| 393 | DB::commit(); |
||
| 394 | |||
| 395 | return true; |
||
| 396 | } |
||
| 397 | |||
| 398 | $res = $server->node->guzzleClient([ |
||
| 399 | 'X-Access-Server' => $server->uuid, |
||
| 400 | 'X-Access-Token' => $server->node->daemonSecret, |
||
| 401 | ])->request('PATCH', '/server', [ |
||
| 402 | 'exceptions' => false, |
||
| 403 | 'json' => [ |
||
| 404 | 'keys' => [ |
||
| 405 | (string) $oldDaemonKey => [], |
||
| 406 | (string) $server->daemonSecret => $this->daemonPermissions, |
||
| 407 | ], |
||
| 408 | ], |
||
| 409 | ]); |
||
| 410 | |||
| 411 | if ($res->getStatusCode() === 204) { |
||
| 412 | DB::commit(); |
||
| 413 | |||
| 414 | return true; |
||
| 415 | } else { |
||
| 416 | throw new DisplayException('Daemon returned a a non HTTP/204 error code. HTTP/' + $res->getStatusCode()); |
||
| 417 | } |
||
| 418 | } catch (\Exception $ex) { |
||
| 419 | DB::rollBack(); |
||
| 420 | Log::error($ex); |
||
| 421 | throw new DisplayException('An error occured while attempting to update this server\'s information.'); |
||
| 422 | } |
||
| 423 | } |
||
| 424 | |||
| 425 | /** |
||
| 426 | * [updateContainer description]. |
||
| 427 | * @param int $id |
||
| 428 | * @param array $data |
||
| 429 | * @return bool |
||
| 430 | */ |
||
| 431 | View Code Duplication | public function updateContainer($id, array $data) |
|
| 472 | |||
| 473 | /** |
||
| 474 | * [changeBuild description]. |
||
| 475 | * @param int $id |
||
| 476 | * @param array $data |
||
| 477 | * @return bool |
||
| 478 | */ |
||
| 479 | public function changeBuild($id, array $data) |
||
| 615 | |||
| 616 | public function updateStartup($id, array $data, $admin = false) |
||
| 690 | |||
| 691 | View Code Duplication | public function queueDeletion($id, $force = false) |
|
| 710 | |||
| 711 | public function delete($id, $force = false) |
||
| 776 | |||
| 777 | public function cancelDeletion($id) |
||
| 785 | |||
| 786 | public function toggleInstall($id) |
||
| 796 | |||
| 797 | /** |
||
| 798 | * Suspends a server instance making it unable to be booted or used by a user. |
||
| 799 | * @param int $id |
||
| 800 | * @return bool |
||
| 801 | */ |
||
| 802 | View Code Duplication | public function suspend($id, $deleted = false) |
|
| 832 | |||
| 833 | /** |
||
| 834 | * Unsuspends a server instance. |
||
| 835 | * @param int $id |
||
| 836 | * @return bool |
||
| 837 | */ |
||
| 838 | View Code Duplication | public function unsuspend($id) |
|
| 868 | |||
| 869 | View Code Duplication | public function updateSFTPPassword($id, $password) |
|
| 905 | } |
||
| 906 |
Since your code implements the magic getter
_get, this function will be called for any read access on an undefined variable. You can add the@propertyannotation to your class or interface to document the existence of this variable.If the property has read access only, you can use the @property-read annotation instead.
Of course, you may also just have mistyped another name, in which case you should fix the error.
See also the PhpDoc documentation for @property.