ApiCrudOperationGenerator::generateIdParam()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 7
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 7
rs 9.4285
c 0
b 0
f 0
cc 1
eloc 6
nc 1
nop 2
1
<?php
2
namespace keeko\tools\generator\api;
3
4
use keeko\tools\generator\AbstractGenerator;
5
use keeko\framework\utils\NameUtils;
6
use keeko\tools\generator\Types;
7
use gossi\swagger\collections\Paths;
8
use gossi\swagger\collections\Responses;
9
use gossi\swagger\collections\Parameters;
10
use Propel\Generator\Model\Table;
11
12
class ApiCrudOperationGenerator extends AbstractGenerator {
13
14
	public function generate(Paths $paths, $actionName) {
15
		$action = $this->packageService->getAction($actionName);
16
		$modelName = $this->modelService->getModelNameByAction($action);
0 ignored issues
show
Bug introduced by
It seems like $action defined by $this->packageService->getAction($actionName) on line 15 can be null; however, keeko\tools\services\Mod...:getModelNameByAction() does not accept null, maybe add an additional type check?

Unless you are absolutely sure that the expression can never be null because of other conditions, we strongly recommend to add an additional type check to your code:

/** @return stdClass|null */
function mayReturnNull() { }

function doesNotAcceptNull(stdClass $x) { }

// With potential error.
function withoutCheck() {
    $x = mayReturnNull();
    doesNotAcceptNull($x); // Potential error here.
}

// Safe - Alternative 1
function withCheck1() {
    $x = mayReturnNull();
    if ( ! $x instanceof stdClass) {
        throw new \LogicException('$x must be defined.');
    }
    doesNotAcceptNull($x);
}

// Safe - Alternative 2
function withCheck2() {
    $x = mayReturnNull();
    if ($x instanceof stdClass) {
        doesNotAcceptNull($x);
    }
}
Loading history...
17
		$model = $this->modelService->getModel($modelName);
18
19
		if ($model === null) {
20
			return;
21
		}
22
23
		$generatorDefinition = $this->project->getGeneratorDefinition();
24
		if ($generatorDefinition->getExcludedApi()->contains($modelName)) {
25
			return;
26
		}
27
28
		$type = $this->packageService->getActionType($actionName, $modelName);
29
		if (!Types::isModelType($type)) {
30
			throw new \RuntimeException(sprintf('Unknown type (%s).', $type));
31
		}
32
33
		$modelPluralName = NameUtils::pluralize($modelName);
34
35
		// find path branch
36
		switch ($type) {
37
			case Types::PAGINATE:
38
			case Types::CREATE:
39
				$endpoint = '/' . NameUtils::dasherize($modelPluralName);
40
				break;
41
42
			case Types::READ:
43
			case Types::UPDATE:
44
			case Types::DELETE:
45
				$endpoint = '/' . NameUtils::dasherize($modelPluralName) . '/{id}';
46
				break;
47
		}
48
49
		$path = $paths->get($endpoint);
0 ignored issues
show
Bug introduced by
The variable $endpoint does not seem to be defined for all execution paths leading up to this point.

If you define a variable conditionally, it can happen that it is not defined for all execution paths.

Let’s take a look at an example:

function myFunction($a) {
    switch ($a) {
        case 'foo':
            $x = 1;
            break;

        case 'bar':
            $x = 2;
            break;
    }

    // $x is potentially undefined here.
    echo $x;
}

In the above example, the variable $x is defined if you pass “foo” or “bar” as argument for $a. However, since the switch statement has no default case statement, if you pass any other value, the variable $x would be undefined.

Available Fixes

  1. Check for existence of the variable explicitly:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        if (isset($x)) { // Make sure it's always set.
            echo $x;
        }
    }
    
  2. Define a default value for the variable:

    function myFunction($a) {
        $x = ''; // Set a default which gets overridden for certain paths.
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        echo $x;
    }
    
  3. Add a value for the missing path:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
    
            // We add support for the missing case.
            default:
                $x = '';
                break;
        }
    
        echo $x;
    }
    
Loading history...
50
		$method = $this->getMethod($type);
51
		$operation = $path->getOperation($method);
52
		$operation->setDescription($action->getTitle());
53
		$operation->setOperationId($action->getName());
54
// 		$operation->getTags()->clear();
0 ignored issues
show
Unused Code Comprehensibility introduced by
70% 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...
55
// 		$operation->getTags()->add(new Tag($this->package->getKeeko()->getModule()->getSlug()));
56
57
		$this->generateParams($operation->getParameters(), $model);
58
		$this->generateResponses($operation->getResponses(), $model);
59
	}
60
61
	private function getMethod($type) {
62
		$methods = [
63
			Types::PAGINATE => 'get',
64
			Types::CREATE => 'post',
65
			Types::READ => 'get',
66
			Types::UPDATE => 'patch',
67
			Types::DELETE => 'delete',
68
			Types::ADD => 'post',
69
			Types::REMOVE => 'delete'
70
		];
71
72
		return $methods[$type];
73
	}
74
75
	protected function generateParams(Parameters $params, Table $model) {
76
		// Overwrite this method in a subclass to provide functionality
77
	}
78
79
	protected function generateResponses(Responses $responses, Table $model) {
80
		// Overwrite this method in a subclass to provide functionality
81
	}
82
83
	protected function generateIdParam(Parameters $params, Table $model) {
84
		$id = $params->getByName('id');
85
		$id->setIn('path');
86
		$id->setDescription(sprintf('The %s id', $model->getOriginCommonName()));
87
		$id->setRequired(true);
88
		$id->setType('integer');
89
	}
90
91
	protected function generateInvalidResponse(Responses $responses) {
92
		$invalid = $responses->get('400');
93
		$invalid->setDescription('Invalid ID supplied');
94
		$invalid->getSchema()->setRef('#/definitions/Errors');
95
	}
96
97
	protected function generateNotFoundResponse(Responses $responses, Table $model) {
98
		$notfound = $responses->get('404');
99
		$notfound->setDescription(sprintf('No %s found', $model->getOriginCommonName()));
100
		$notfound->getSchema()->setRef('#/definitions/Errors');
101
	}
102
}