Completed
Push — master ( e7547f...7207e0 )
by Sean
01:20
created

DeploynautAPIFormatter::getDeploymentData()   F

Complexity

Conditions 13
Paths 384

Size

Total Lines 77
Code Lines 58

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 77
rs 3.9261
c 0
b 0
f 0
cc 13
eloc 58
nc 384
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...
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 $environment->CurrentBuild();
13
	 * @var null|DNDeployment
14
	 */
15
	private static $_cache_current_build = null;
16
17
	/**
18
	 * Return data about a single deployment for use in API response.
19
	 * @param DNDeployment $deployment
20
	 * @return array
21
	 */
22
	public function getDeploymentData(DNDeployment $deployment) {
23
		if (empty(self::$_cache_current_build[$deployment->EnvironmentID])) {
24
			self::$_cache_current_build[$deployment->EnvironmentID] = $deployment->Environment()->CurrentBuild();
25
		}
26
27
		$environment = $deployment->Environment();
28
		$project = $environment->Project();
29
30
		$deployer = $deployment->Deployer();
31
		$deployerData = null;
32
		if ($deployer && $deployer->exists()) {
33
			$deployerData = $this->getStackMemberData($project, $deployer);
34
		}
35
		$approver = $deployment->Approver();
0 ignored issues
show
Documentation Bug introduced by
The method Approver does not exist on object<DNDeployment>? 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...
36
		$approverData = null;
37
		if ($approver && $approver->exists()) {
38
			$approverData = $this->getStackMemberData($project, $approver);
39
		}
40
41
		// failover for older deployments
42
		$started = $deployment->Created;
43
		$startedNice = $deployment->obj('Created')->Nice();
44
		if($deployment->DeployStarted) {
45
			$started = $deployment->DeployStarted;
46
			$startedNice = $deployment->obj('DeployStarted')->Nice();
47
		}
48
49
		$isCurrentBuild = self::$_cache_current_build[$deployment->EnvironmentID]
50
			? ($deployment->ID === self::$_cache_current_build[$deployment->EnvironmentID]->ID)
51
			: false;
52
53
		$supportedOptions = $deployment->Environment()->Backend()->getDeployOptions($deployment->Environment());
54
		$setOptions = $deployment->getDeploymentStrategy() ? $deployment->getDeploymentStrategy()->getOptions() : [];
55
		$options = [];
56
57
		foreach ($supportedOptions as $option) {
58
			if (isset($setOptions[$option->getName()]) && $setOptions[$option->getName()] === 'true') {
59
				$options[$option->getName()] = 'true';
60
			}
61
		}
62
63
		$tags = [];
64
		try {
65
			$tags = $deployment->getTags()->toArray();
66
		} catch (\Exception $e) {
67
			// gitonomy exception
68
		}
69
70
		return [
71
			'id' => $deployment->ID,
72
			'date_created' => $deployment->Created,
73
			'date_created_nice' => $deployment->obj('Created')->Nice(),
74
			'date_started' => $started,
75
			'date_started_nice' => $startedNice,
76
			'date_requested' => $deployment->DeployRequested,
77
			'date_requested_nice' => $deployment->obj('DeployRequested')->Nice(),
78
			'date_updated' => $deployment->LastEdited,
79
			'date_updated_nice' => $deployment->obj('LastEdited')->Nice(),
80
			'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...
81
			'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...
82
			'branch' => $deployment->Branch,
0 ignored issues
show
Documentation introduced by
The property Branch 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...
83
			'tags' => $tags,
84
			'changes' => $deployment->getDeploymentStrategy()->getChanges(),
85
			'deployment_type' => $deployment->getDeploymentStrategy()->getActionCode(),
86
			'deployment_estimate' => $deployment->getDeploymentStrategy()->getEstimatedTime(),
87
			'sha' => $deployment->SHA,
88
			'short_sha' => substr($deployment->SHA, 0, 7),
89
			'ref_type' => $deployment->RefType,
90
			'options' => $options,
91
			'commit_message' => $deployment->getCommitMessage(),
92
			'commit_url' => $deployment->getCommitURL(),
93
			'deployer' => $deployerData,
94
			'approver' => $approverData,
95
			'state' => $deployment->State,
96
			'is_current_build' => $isCurrentBuild
97
		];
98
	}
99
100
	/**
101
	 * Return data about a particular {@link Member} of the stack for use in API response.
102
	 * Note that role can be null in the response. This is the case of an admin, or an operations
103
	 * user who can create the deployment but is not part of the stack roles.
104
	 *
105
	 * @param DNProject $project
106
	 * @param Member $member
107
	 * @return array
108
	 */
109
	public function getStackMemberData(DNProject $project, Member $member) {
110
		if (empty(self::$_cache_project_members[$project->ID])) {
111
			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...
112
		}
113
114
		$role = null;
115
		foreach (self::$_cache_project_members[$project->ID] as $stackMember) {
116
			if ($stackMember['MemberID'] !== $member->ID) {
117
				continue;
118
			}
119
			$role = $stackMember['RoleTitle'];
120
		}
121
122
		return [
123
			'id' => $member->ID,
124
			'email' => $member->Email,
125
			'role' => $role,
126
			'name' => $member->getName()
127
		];
128
	}
129
130
}
131