Completed
Push — master ( 2e4e41...695b69 )
by Stig
05:38 queued 01:25
created

DeploynautAPIFormatter   A

Complexity

Total Complexity 21

Size/Duplication

Total Lines 162
Duplicated Lines 1.85 %

Coupling/Cohesion

Components 1
Dependencies 8

Importance

Changes 0
Metric Value
wmc 21
lcom 1
cbo 8
dl 3
loc 162
rs 10
c 0
b 0
f 0

2 Methods

Rating   Name   Duplication   Size   Complexity  
F getDeploymentData() 0 89 13
C getStackMemberData() 3 33 8

How to fix   Duplicated Code   

Duplicated Code

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:

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
			'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...
99
			'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...
100
			'tags' => $tags,
101
			'changes' => $deployment->getDeploymentStrategy()->getChanges(),
102
			'deployment_type' => $type,
103
			'deployment_estimate' => $deployment->getDeploymentStrategy()->getEstimatedTime(),
104
			'sha' => $deployment->SHA,
105
			'short_sha' => substr($deployment->SHA, 0, 7),
106
			'ref_type' => $deployment->RefType,
107
			'options' => $options,
108
			'commit_message' => $deployment->getCommitMessage(),
109
			'commit_url' => $deployment->getCommitURL(),
110
			'deployer' => $deployerData,
111
			'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...
112
			'approver' => $approverData,
113
			'state' => $deployment->State,
114
			'is_current_build' => $isCurrentBuild
115
		];
116
	}
117
118
	/**
119
	 * Return data about a particular {@link Member} of the stack for use in API response.
120
121
	 * Notes:
122
	 * 1) This method returns null instead of an array if the member doesn't exists anymore
123
	 * 2) 'role' can be null in the response. This is the case of an admin, or an operations
124
	 * user who can create the deployment but is not part of the stack roles.
125
	 *
126
	 * @param \DNProject $project
127
	 * @param int $memberID
128
	 * @return null|array
129
	 */
130
	public function getStackMemberData(\DNProject $project, $memberID) {
131
		if (empty(self::$_cache_project_members[$project->ID])) {
132
			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...
133
		}
134
135
		// we cache all member lookup, even the false results
136 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...
137
			self::$_cache_members[$memberID] = \Member::get()->byId($memberID);
138
		}
139
		if(!self::$_cache_members[$memberID]) {
140
			return null;
141
		}
142
143
		$role = null;
144
		foreach (self::$_cache_project_members[$project->ID] as $stackMember) {
145
			if ($stackMember['MemberID'] !== $memberID) {
146
				continue;
147
			}
148
			$role = $stackMember['RoleTitle'];
149
		}
150
151
		// if an administator is approving, they should be shown as one
152
		if ($role === null && \Permission::checkMember(self::$_cache_members[$memberID], 'ADMIN')) {
153
			$role = 'Administrator';
154
		}
155
156
		return [
157
			'id' => $memberID,
158
			'email' => self::$_cache_members[$memberID]->Email,
159
			'role' => $role,
160
			'name' => self::$_cache_members[$memberID]->getName()
161
		];
162
	}
163
164
}
165