DeploynautAPIFormatter::getDeploymentData()   F
last analyzed

Complexity

Conditions 13
Paths 1024

Size

Total Lines 91
Code Lines 71

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 91
rs 2
c 0
b 0
f 0
cc 13
eloc 71
nc 1024
nop 1

How to fix   Long Method    Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
3
class DeploynautAPIFormatter {
0 ignored issues
show
Coding Style introduced by
The property $_cache_project_members is not named in camelCase.

This check marks property names that have not been written in camelCase.

In camelCase names are written without any punctuation, the start of each new word being marked by a capital letter. Thus the name database connection string becomes databaseConnectionString.

Loading history...
Coding Style introduced by
The property $_cache_current_build is not named in camelCase.

This check marks property names that have not been written in camelCase.

In camelCase names are written without any punctuation, the start of each new word being marked by a capital letter. Thus the name database connection string becomes databaseConnectionString.

Loading history...
Coding Style Compatibility introduced by
PSR1 recommends that each class must be in a namespace of at least one level to avoid collisions.

You can fix this by adding a namespace to your class:

namespace YourVendor;

class YourClass { }

When choosing a vendor namespace, try to pick something that is not too generic to avoid conflicts with other libraries.

Loading history...
Coding Style introduced by
The property $_cache_members is not named in camelCase.

This check marks property names that have not been written in camelCase.

In camelCase names are written without any punctuation, the start of each new word being marked by a capital letter. Thus the name database connection string becomes databaseConnectionString.

Loading history...
4
5
	/**
6
	 * This is a per request cache of $project()->listMembers()
7
	 * @var null|array
8
	 */
9
	private static $_cache_project_members = null;
10
11
	/**
12
	 * This is a per request cache of Members
13
	 * @var null|array
14
	 */
15
	private static $_cache_members = null;
16
17
	/**
18
	 * This is a per request cache of $environment->CurrentBuild();
19
	 * @var null|DNDeployment
20
	 */
21
	private static $_cache_current_build = null;
22
23
	/**
24
	 * Return data about a single deployment for use in API response.
25
	 * @param \DNDeployment $deployment
26
	 * @return array
27
	 */
28
	public function getDeploymentData(\DNDeployment $deployment) {
29
		if (empty(self::$_cache_current_build[$deployment->EnvironmentID])) {
30
			self::$_cache_current_build[$deployment->EnvironmentID] = $deployment->Environment()->CurrentBuild();
31
		}
32
33
		$environment = $deployment->Environment();
34
		$project = $environment->Project();
35
36
		$deployerData = $this->getStackMemberData($project, $deployment->DeployerID);
37
		$approverData = $this->getStackMemberData($project, $deployment->ApproverID);
0 ignored issues
show
Documentation introduced by
The property ApproverID does not exist on object<DNDeployment>. Since you implemented __get, maybe consider adding a @property annotation.

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 @property annotation to your class or interface to document the existence of this variable.

<?php

/**
 * @property int $x
 * @property int $y
 * @property string $text
 */
class MyLabel
{
    private $properties;

    private $allowedProperties = array('x', 'y', 'text');

    public function __get($name)
    {
        if (isset($properties[$name]) && in_array($name, $this->allowedProperties)) {
            return $properties[$name];
        } else {
            return null;
        }
    }

    public function __set($name, $value)
    {
        if (in_array($name, $this->allowedProperties)) {
            $properties[$name] = $value;
        } else {
            throw new \LogicException("Property $name is not defined.");
        }
    }

}

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.

Loading history...
38
39
		$started = null;
0 ignored issues
show
Unused Code introduced by
$started is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
40
		$startedNice = null;
0 ignored issues
show
Unused Code introduced by
$startedNice is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
41
		$startedAgo = null;
0 ignored issues
show
Unused Code introduced by
$startedAgo is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
42
		// we check first, before we do a expensive ->Nice() and ->Ago()
43
		if(!$deployment->DeployStarted) {
44
			$started = $deployment->Created;
45
			$startedNice = $deployment->obj('Created')->Nice();
46
			$startedAgo = $deployment->obj('Created')->Ago();
47
		} else {
48
			$started = $deployment->DeployStarted;
49
			$startedNice = $deployment->obj('DeployStarted')->Nice();
50
			$startedAgo = $deployment->obj('DeployStarted')->Ago();
51
		}
52
53
		$isCurrentBuild = self::$_cache_current_build[$deployment->EnvironmentID]
54
			? ($deployment->ID === self::$_cache_current_build[$deployment->EnvironmentID]->ID)
55
			: false;
56
57
		$supportedOptions = $environment->getSupportedOptions();
58
		$setOptions = $deployment->getDeploymentStrategy() ? $deployment->getDeploymentStrategy()->getOptions() : [];
59
		$options = [];
60
61
		foreach ($supportedOptions as $option) {
62
			if (!isset($setOptions[$option->getName()])) {
63
				continue;
64
			}
65
			if ($setOptions[$option->getName()] === 'true' || $setOptions[$option->getName()] === true) {
66
				$options[$option->getName()] = true;
67
			}
68
		}
69
70
		$tags = [];
71
		try {
72
			$tags = $deployment->getTags()->toArray();
73
		} catch (\Exception $e) {
74
			// gitonomy exception
75
		}
76
77
		$type = 'full';
78
		if ($deployment->getDeploymentStrategy()->getActionCode() === 'fast') {
79
			$type = 'code-only';
80
		}
81
82
		return [
83
			'id' => $deployment->ID,
84
			'date_created' => $deployment->Created,
85
			'date_created_nice' => $deployment->obj('Created')->Nice(),
86
			'date_created_ago' => $deployment->obj('Created')->Ago(),
87
			'date_started' => $started,
88
			'date_started_nice' => $startedNice,
89
			'date_started_ago' => $startedAgo,
90
			'date_requested' => $deployment->DeployRequested,
91
			'date_requested_nice' => $deployment->obj('DeployRequested')->Nice(),
92
			'date_requested_ago' => $deployment->obj('DeployRequested')->Ago(),
93
			'date_updated' => $deployment->LastEdited,
94
			'date_updated_nice' => $deployment->obj('LastEdited')->Nice(),
95
			'date_updated_ago' => $deployment->obj('LastEdited')->Ago(),
96
			'title' => $deployment->Title,
0 ignored issues
show
Documentation introduced by
The property Title does not exist on object<DNDeployment>. Since you implemented __get, maybe consider adding a @property annotation.

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 @property annotation to your class or interface to document the existence of this variable.

<?php

/**
 * @property int $x
 * @property int $y
 * @property string $text
 */
class MyLabel
{
    private $properties;

    private $allowedProperties = array('x', 'y', 'text');

    public function __get($name)
    {
        if (isset($properties[$name]) && in_array($name, $this->allowedProperties)) {
            return $properties[$name];
        } else {
            return null;
        }
    }

    public function __set($name, $value)
    {
        if (in_array($name, $this->allowedProperties)) {
            $properties[$name] = $value;
        } else {
            throw new \LogicException("Property $name is not defined.");
        }
    }

}

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.

Loading history...
97
			'summary' => $deployment->Summary,
0 ignored issues
show
Bug introduced by
The property Summary does not seem to exist. Did you mean summary_fields?

An attempt at access to an undefined property has been detected. This may either be a typographical error or the property has been renamed but there are still references to its old name.

If you really want to allow access to undefined properties, you can define magic methods to allow access. See the php core documentation on Overloading.

Loading history...
98
			'ref_type' => $deployment->RefType,
99
			'ref_name' => $deployment->RefName,
100
			'rejected_reason' => $deployment->RejectedReason ?: '',
0 ignored issues
show
Documentation introduced by
The property RejectedReason does not exist on object<DNDeployment>. Since you implemented __get, maybe consider adding a @property annotation.

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 @property annotation to your class or interface to document the existence of this variable.

<?php

/**
 * @property int $x
 * @property int $y
 * @property string $text
 */
class MyLabel
{
    private $properties;

    private $allowedProperties = array('x', 'y', 'text');

    public function __get($name)
    {
        if (isset($properties[$name]) && in_array($name, $this->allowedProperties)) {
            return $properties[$name];
        } else {
            return null;
        }
    }

    public function __set($name, $value)
    {
        if (in_array($name, $this->allowedProperties)) {
            $properties[$name] = $value;
        } else {
            throw new \LogicException("Property $name is not defined.");
        }
    }

}

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.

Loading history...
101
			'tags' => $tags,
102
			'changes' => $deployment->getDeploymentStrategy()->getChanges(),
103
			'deployment_type' => $type,
104
			'deployment_estimate' => $deployment->getDeploymentStrategy()->getEstimatedTime(),
105
			'sha' => $deployment->SHA,
106
			'short_sha' => substr($deployment->SHA, 0, 7),
107
			'options' => $options,
108
			'commit_subject' => $deployment->getCommitSubjectMessage(),
109
			'commit_message' => $deployment->getCommitMessage(),
110
			'commit_url' => $deployment->getCommitURL(),
111
			'deployer' => $deployerData,
112
			'approver_id' => $deployment->ApproverID ?: '',
0 ignored issues
show
Documentation introduced by
The property ApproverID does not exist on object<DNDeployment>. Since you implemented __get, maybe consider adding a @property annotation.

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 @property annotation to your class or interface to document the existence of this variable.

<?php

/**
 * @property int $x
 * @property int $y
 * @property string $text
 */
class MyLabel
{
    private $properties;

    private $allowedProperties = array('x', 'y', 'text');

    public function __get($name)
    {
        if (isset($properties[$name]) && in_array($name, $this->allowedProperties)) {
            return $properties[$name];
        } else {
            return null;
        }
    }

    public function __set($name, $value)
    {
        if (in_array($name, $this->allowedProperties)) {
            $properties[$name] = $value;
        } else {
            throw new \LogicException("Property $name is not defined.");
        }
    }

}

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.

Loading history...
113
			'approver' => $approverData,
114
			'state' => $deployment->State,
115
			'is_current_build' => $isCurrentBuild,
116
			'dirty' => false,
117
		];
118
	}
119
120
	/**
121
	 * Return data about a particular {@link Member} of the stack for use in API response.
122
123
	 * Notes:
124
	 * 1) This method returns null instead of an array if the member doesn't exists anymore
125
	 * 2) 'role' can be null in the response. This is the case of an admin, or an operations
126
	 * user who can create the deployment but is not part of the stack roles.
127
	 *
128
	 * @param \DNProject $project
129
	 * @param int $memberID
130
	 * @return null|array
131
	 */
132
	public function getStackMemberData(\DNProject $project, $memberID) {
133
		if (empty(self::$_cache_project_members[$project->ID])) {
134
			self::$_cache_project_members[$project->ID] = $project->listMembers();
0 ignored issues
show
Documentation Bug introduced by
The method listMembers does not exist on object<DNProject>? Since you implemented __call, maybe consider adding a @method annotation.

If you implement __call and you know which methods are available, you can improve IDE auto-completion and static analysis by adding a @method annotation to the class.

This is often the case, when __call is implemented by a parent class and only the child class knows which methods exist:

class ParentClass {
    private $data = array();

    public function __call($method, array $args) {
        if (0 === strpos($method, 'get')) {
            return $this->data[strtolower(substr($method, 3))];
        }

        throw new \LogicException(sprintf('Unsupported method: %s', $method));
    }
}

/**
 * If this class knows which fields exist, you can specify the methods here:
 *
 * @method string getName()
 */
class SomeClass extends ParentClass { }
Loading history...
135
		}
136
137
		// we cache all member lookup, even the false results
138 View Code Duplication
		if (!isset(self::$_cache_members[$memberID])) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
139
			self::$_cache_members[$memberID] = \Member::get()->byId($memberID);
140
		}
141
		if(!self::$_cache_members[$memberID]) {
142
			return null;
143
		}
144
145
		$role = null;
146
		foreach (self::$_cache_project_members[$project->ID] as $stackMember) {
147
			if ($stackMember['MemberID'] !== $memberID) {
148
				continue;
149
			}
150
			$role = $stackMember['RoleTitle'];
151
		}
152
153
		// if an administator is approving, they should be shown as one
154
		if ($role === null && \Permission::checkMember(self::$_cache_members[$memberID], 'ADMIN')) {
155
			$role = 'Administrator';
156
		}
157
158
		return [
159
			'id' => $memberID,
160
			'email' => self::$_cache_members[$memberID]->Email,
161
			'role' => $role,
162
			'name' => self::$_cache_members[$memberID]->getName()
163
		];
164
	}
165
166
}
167