Completed
Pull Request — master (#722)
by Sean
08:27 queued 04:14
created

DNEnvironment::getSupportedOptions()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 3
rs 10
c 0
b 0
f 0
cc 1
eloc 2
nc 1
nop 0
1
<?php
2
3
/**
4
 * DNEnvironment
5
 *
6
 * This dataobject represents a target environment that source code can be deployed to.
7
 * Permissions are controlled by environment, see the various many-many relationships.
8
 *
9
 * @property string $Filename
10
 * @property string $Name
11
 * @property string $URL
12
 * @property string $BackendIdentifier
13
 * @property bool $Usage
14
 *
15
 * @method DNProject Project()
16
 * @property int $ProjectID
17
 *
18
 * @method HasManyList Deployments()
19
 * @method HasManyList DataArchives()
20
 *
21
 * @method ManyManyList Viewers()
22
 * @method ManyManyList ViewerGroups()
23
 * @method ManyManyList Deployers()
24
 * @method ManyManyList DeployerGroups()
25
 * @method ManyManyList CanRestoreMembers()
26
 * @method ManyManyList CanRestoreGroups()
27
 * @method ManyManyList CanBackupMembers()
28
 * @method ManyManyList CanBackupGroups()
29
 * @method ManyManyList ArchiveUploaders()
30
 * @method ManyManyList ArchiveUploaderGroups()
31
 * @method ManyManyList ArchiveDownloaders()
32
 * @method ManyManyList ArchiveDownloaderGroups()
33
 * @method ManyManyList ArchiveDeleters()
34
 * @method ManyManyList ArchiveDeleterGroups()
35
 */
36
class DNEnvironment extends DataObject {
0 ignored issues
show
Coding Style introduced by
The property $template_file 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 $allow_web_editing 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 $allowed_backends 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 $has_one 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 $has_many 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 $many_many 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 $summary_fields 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 $singular_name 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 $plural_name 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 $searchable_fields 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 $default_sort 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...
37
38
	const UAT = 'UAT';
39
40
	const PRODUCTION = 'Production';
41
42
	const UNSPECIFIED = 'Unspecified';
43
44
	/**
45
	 * @var array
46
	 */
47
	public static $db = [
48
		"Filename" => "Varchar(255)",
49
		"Name" => "Varchar(255)",
50
		"URL" => "Varchar(255)",
51
		"BackendIdentifier" => "Varchar(255)", // Injector identifier of the DeploymentBackend
52
		"Usage" => "Enum('Production, UAT, Test, Unspecified', 'Unspecified')",
53
	];
54
55
	/**
56
	 * @var array
57
	 */
58
	public static $has_many = [
59
		"Deployments" => "DNDeployment",
60
		"DataArchives" => "DNDataArchive",
61
		"DataTransfers" => "DNDataTransfer",
62
		"Pings" => "DNPing"
63
	];
64
65
	/**
66
	 * @var array
67
	 */
68
	public static $many_many = [
69
		"Viewers" => "Member", // Who can view this environment
70
		"ViewerGroups" => "Group",
71
		"Deployers" => "Member", // Who can deploy to this environment
72
		"DeployerGroups" => "Group",
73
		"CanRestoreMembers" => "Member", // Who can restore archive files to this environment
74
		"CanRestoreGroups" => "Group",
75
		"CanBackupMembers" => "Member", // Who can backup archive files from this environment
76
		"CanBackupGroups" => "Group",
77
		"ArchiveUploaders" => "Member", // Who can upload archive files linked to this environment
78
		"ArchiveUploaderGroups" => "Group",
79
		"ArchiveDownloaders" => "Member", // Who can download archive files from this environment
80
		"ArchiveDownloaderGroups" => "Group",
81
		"ArchiveDeleters" => "Member", // Who can delete archive files from this environment,
82
		"ArchiveDeleterGroups" => "Group",
83
	];
84
85
	/**
86
	 * @var array
87
	 */
88
	public static $summary_fields = [
89
		"Name" => "Environment Name",
90
		"Usage" => "Usage",
91
		"URL" => "URL",
92
		"DeployersList" => "Can Deploy List",
93
		"CanRestoreMembersList" => "Can Restore List",
94
		"CanBackupMembersList" => "Can Backup List",
95
		"ArchiveUploadersList" => "Can Upload List",
96
		"ArchiveDownloadersList" => "Can Download List",
97
		"ArchiveDeletersList" => "Can Delete List",
98
	];
99
100
	/**
101
	 * @var array
102
	 */
103
	public static $searchable_fields = [
104
		"Name",
105
	];
106
107
	private static $singular_name = 'Capistrano Environment';
0 ignored issues
show
Unused Code introduced by
The property $singular_name is not used and could be removed.

This check marks private properties in classes that are never used. Those properties can be removed.

Loading history...
108
109
	private static $plural_name = 'Capistrano Environments';
110
111
	/**
112
	 * @var string
113
	 */
114
	private static $default_sort = 'Name';
115
116
	/**
117
	 * @var array
118
	 */
119
	public static $has_one = [
120
		"Project" => "DNProject",
121
		"CreateEnvironment" => "DNCreateEnvironment"
122
	];
123
124
	/**
125
	 * If this is set to a full pathfile, it will be used as template
126
	 * file when creating a new capistrano environment config file.
127
	 *
128
	 * If not set, the default 'environment.template' from the module
129
	 * root is used
130
	 *
131
	 * @config
132
	 * @var string
133
	 */
134
	private static $template_file = '';
0 ignored issues
show
Unused Code introduced by
The property $template_file is not used and could be removed.

This check marks private properties in classes that are never used. Those properties can be removed.

Loading history...
135
136
	/**
137
	 * Set this to true to allow editing of the environment files via the web admin
138
	 *
139
	 * @var bool
140
	 */
141
	private static $allow_web_editing = false;
0 ignored issues
show
Unused Code introduced by
The property $allow_web_editing is not used and could be removed.

This check marks private properties in classes that are never used. Those properties can be removed.

Loading history...
142
143
	/**
144
	 * @var array
145
	 */
146
	private static $casting = [
0 ignored issues
show
Unused Code introduced by
The property $casting is not used and could be removed.

This check marks private properties in classes that are never used. Those properties can be removed.

Loading history...
147
		'DeployHistory' => 'Text'
148
	];
149
150
	/**
151
	 * Allowed backends. A map of Injector identifier to human-readable label.
152
	 *
153
	 * @config
154
	 * @var array
155
	 */
156
	private static $allowed_backends = [];
0 ignored issues
show
Unused Code introduced by
The property $allowed_backends is not used and could be removed.

This check marks private properties in classes that are never used. Those properties can be removed.

Loading history...
157
158
	/**
159
	 * Used by the sync task
160
	 *
161
	 * @param string $path
162
	 * @return \DNEnvironment
163
	 */
164
	public static function create_from_path($path) {
165
		$e = DNEnvironment::create();
0 ignored issues
show
Coding Style introduced by
As per coding style, self should be used for accessing local static members.

This check looks for accesses to local static members using the fully qualified name instead of self::.

<?php

class Certificate {
    const TRIPLEDES_CBC = 'ASDFGHJKL';

    private $key;

    public function __construct()
    {
        $this->key = Certificate::TRIPLEDES_CBC;
    }
}

While this is perfectly valid, the fully qualified name of Certificate::TRIPLEDES_CBC could just as well be replaced by self::TRIPLEDES_CBC. Referencing local members with self:: assured the access will still work when the class is renamed, makes it perfectly clear that the member is in fact local and will usually be shorter.

Loading history...
166
		$e->Filename = $path;
167
		$e->Name = basename($e->Filename, '.rb');
168
169
		// add each administrator member as a deployer of the new environment
170
		$adminGroup = Group::get()->filter('Code', 'administrators')->first();
171
		$e->DeployerGroups()->add($adminGroup);
0 ignored issues
show
Bug introduced by
It seems like $adminGroup defined by \Group::get()->filter('C...ministrators')->first() on line 170 can be null; however, ManyManyList::add() 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...
172
		return $e;
173
	}
174
175
	/**
176
	 * Get the deployment backend used for this environment.
177
	 *
178
	 * Enforces compliance with the allowed_backends setting; if the DNEnvironment.BackendIdentifier value is
179
	 * illegal then that value is ignored.
180
	 *
181
	 * @return DeploymentBackend
182
	 */
183
	public function Backend() {
184
		$backends = array_keys($this->config()->get('allowed_backends', Config::FIRST_SET));
185
		switch (sizeof($backends)) {
186
			// Nothing allowed, use the default value "DeploymentBackend"
187
			case 0:
188
				$backend = "DeploymentBackend";
189
				break;
190
191
			// Only 1 thing allowed, use that
192
			case 1:
193
				$backend = $backends[0];
194
				break;
195
196
			// Multiple choices, use our choice if it's legal, otherwise default to the first item on the list
197
			default:
198
				$backend = $this->BackendIdentifier;
199
				if (!in_array($backend, $backends)) {
200
					$backend = $backends[0];
201
				}
202
		}
203
204
		return Injector::inst()->get($backend);
205
	}
206
207
	/**
208
	 * @param SS_HTTPRequest $request
209
	 *
210
	 * @return DeploymentStrategy
211
	 */
212
	public function getDeployStrategy(\SS_HTTPRequest $request) {
213
		return $this->Backend()->planDeploy($this, $request->requestVars());
0 ignored issues
show
Bug introduced by
It seems like $request->requestVars() targeting SS_HTTPRequest::requestVars() can also be of type null; however, DeploymentBackend::planDeploy() does only seem to accept array, maybe add an additional type check?

This check looks at variables that are passed out again to other methods.

If the outgoing method call has stricter type requirements than the method itself, an issue is raised.

An additional type check may prevent trouble.

Loading history...
214
	}
215
216
	/**
217
	 * Return the supported options for this environment.
218
	 * @return ArrayList
219
	 */
220
	public function getSupportedOptions() {
221
		return $this->Backend()->getDeployOptions($this);
222
	}
223
224
	public function Menu() {
225
		$list = new ArrayList();
226
227
		$controller = Controller::curr();
228
		$actionType = $controller->getField('CurrentActionType');
229
230
		$list->push(new ArrayData([
231
			'Link' => sprintf('naut/project/%s/environment/%s', $this->Project()->Name, $this->Name),
232
			'Title' => 'Deployments',
233
			'IsCurrent' => $this->isCurrent(),
234
			'IsSection' => $this->isSection() && $actionType == DNRoot::ACTION_DEPLOY
235
		]));
236
237
		$this->extend('updateMenu', $list);
238
239
		return $list;
240
	}
241
242
	/**
243
	 * Return the current object from $this->Menu()
244
	 * Good for making titles and things
245
	 */
246
	public function CurrentMenu() {
247
		return $this->Menu()->filter('IsSection', true)->First();
248
	}
249
250
	/**
251
	 * Return a name for this environment.
252
	 *
253
	 * @param string $separator The string used when concatenating project with env name
254
	 * @return string
255
	 */
256
	public function getFullName($separator = ':') {
257
		return sprintf('%s%s%s', $this->Project()->Name, $separator, $this->Name);
258
	}
259
260
	/**
261
	 * URL for the environment that can be used if no explicit URL is set.
262
	 */
263
	public function getDefaultURL() {
264
		return null;
265
	}
266
267
	public function getBareURL() {
268
		$url = parse_url($this->URL);
269
		if (isset($url['host'])) {
270
			return strtolower($url['host']);
271
		}
272
	}
273
274
	public function getBareDefaultURL() {
275
		$url = parse_url($this->getDefaultURL());
276
		if (isset($url['host'])) {
277
			return strtolower($url['host']);
278
		}
279
	}
280
281
	/**
282
	 * Environments are only viewable by people that can view the environment.
283
	 *
284
	 * @param Member|null $member
285
	 * @return boolean
286
	 */
287
	public function canView($member = null) {
288
		if (!$member) {
289
			$member = Member::currentUser();
290
		}
291
		if (!$member) {
292
			return false;
293
		}
294
		// Must be logged in to check permissions
295
296
		if (Permission::checkMember($member, 'ADMIN')) {
297
			return true;
298
		}
299
300
		// if no Viewers or ViewerGroups defined, fallback to DNProject::canView permissions
301
		if ($this->Viewers()->exists() || $this->ViewerGroups()->exists()) {
302
			return $this->Viewers()->byID($member->ID)
303
			|| $member->inGroups($this->ViewerGroups());
304
		}
305
306
		return $this->Project()->canView($member);
307
	}
308
309
	/**
310
	 * Allow deploy only to some people.
311
	 *
312
	 * @param Member|null $member
313
	 * @return boolean
314
	 */
315 View Code Duplication
	public function canDeploy($member = null) {
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in 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...
316
		if (!$member) {
317
			$member = Member::currentUser();
318
		}
319
		if (!$member) {
320
			return false;
321
		}
322
		// Must be logged in to check permissions
323
324
		if ($this->Usage === self::PRODUCTION || $this->Usage === self::UNSPECIFIED) {
325
			if ($this->Project()->allowed(DNRoot::ALLOW_PROD_DEPLOYMENT, $member)) {
0 ignored issues
show
Documentation introduced by
$member is of type object<DataObject>, but the function expects a object<Member>|null.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
326
				return true;
327
			}
328
		} else {
329
			if ($this->Project()->allowed(DNRoot::ALLOW_NON_PROD_DEPLOYMENT, $member)) {
330
				return true;
331
			}
332
		}
333
334
		return $this->Deployers()->byID($member->ID)
335
		|| $member->inGroups($this->DeployerGroups());
336
	}
337
338
	/**
339
	 * Provide reason why the user cannot deploy.
340
	 *
341
	 * @return string
342
	 */
343
	public function getCannotDeployMessage() {
344
		return 'You cannot deploy to this environment.';
345
	}
346
347
	/**
348
	 * Allows only selected {@link Member} objects to restore {@link DNDataArchive} objects into this
349
	 * {@link DNEnvironment}.
350
	 *
351
	 * @param Member|null $member The {@link Member} object to test against. If null, uses Member::currentMember();
352
	 * @return boolean true if $member can restore, and false if they can't.
353
	 */
354 View Code Duplication
	public function canRestore($member = null) {
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in 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...
355
		if (!$member) {
356
			$member = Member::currentUser();
357
		}
358
		if (!$member) {
359
			return false;
360
		}
361
		// Must be logged in to check permissions
362
363
		if ($this->Usage === self::PRODUCTION || $this->Usage === self::UNSPECIFIED) {
364
			if ($this->Project()->allowed(DNRoot::ALLOW_PROD_SNAPSHOT, $member)) {
0 ignored issues
show
Documentation introduced by
$member is of type object<DataObject>, but the function expects a object<Member>|null.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
365
				return true;
366
			}
367
		} else {
368
			if ($this->Project()->allowed(DNRoot::ALLOW_NON_PROD_SNAPSHOT, $member)) {
0 ignored issues
show
Documentation introduced by
$member is of type object<DataObject>, but the function expects a object<Member>|null.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
369
				return true;
370
			}
371
		}
372
373
		return $this->CanRestoreMembers()->byID($member->ID)
374
		|| $member->inGroups($this->CanRestoreGroups());
375
	}
376
377
	/**
378
	 * Allows only selected {@link Member} objects to backup this {@link DNEnvironment} to a {@link DNDataArchive}
379
	 * file.
380
	 *
381
	 * @param Member|null $member The {@link Member} object to test against. If null, uses Member::currentMember();
382
	 * @return boolean true if $member can backup, and false if they can't.
383
	 */
384 View Code Duplication
	public function canBackup($member = null) {
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in 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...
385
		$project = $this->Project();
386
		if ($project->HasDiskQuota() && $project->HasExceededDiskQuota()) {
387
			return false;
388
		}
389
390
		if (!$member) {
391
			$member = Member::currentUser();
392
		}
393
		// Must be logged in to check permissions
394
		if (!$member) {
395
			return false;
396
		}
397
398
		if ($this->Usage === self::PRODUCTION || $this->Usage === self::UNSPECIFIED) {
399
			if ($this->Project()->allowed(DNRoot::ALLOW_PROD_SNAPSHOT, $member)) {
0 ignored issues
show
Documentation introduced by
$member is of type object<DataObject>, but the function expects a object<Member>|null.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
400
				return true;
401
			}
402
		} else {
403
			if ($this->Project()->allowed(DNRoot::ALLOW_NON_PROD_SNAPSHOT, $member)) {
0 ignored issues
show
Documentation introduced by
$member is of type object<DataObject>, but the function expects a object<Member>|null.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
404
				return true;
405
			}
406
		}
407
408
		return $this->CanBackupMembers()->byID($member->ID)
409
		|| $member->inGroups($this->CanBackupGroups());
410
	}
411
412
	/**
413
	 * Allows only selected {@link Member} objects to upload {@link DNDataArchive} objects linked to this
414
	 * {@link DNEnvironment}.
415
	 *
416
	 * Note: This is not uploading them to the actual environment itself (e.g. uploading to the live site) - it is the
417
	 * process of uploading a *.sspak file into Deploynaut for later 'restoring' to an environment. See
418
	 * {@link self::canRestore()}.
419
	 *
420
	 * @param Member|null $member The {@link Member} object to test against. If null, uses Member::currentMember();
421
	 * @return boolean true if $member can upload archives linked to this environment, false if they can't.
422
	 */
423 View Code Duplication
	public function canUploadArchive($member = null) {
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in 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...
424
		$project = $this->Project();
425
		if ($project->HasDiskQuota() && $project->HasExceededDiskQuota()) {
426
			return false;
427
		}
428
429
		if (!$member) {
430
			$member = Member::currentUser();
431
		}
432
		if (!$member) {
433
			return false;
434
		}
435
		// Must be logged in to check permissions
436
437
		if ($this->Usage === self::PRODUCTION || $this->Usage === self::UNSPECIFIED) {
438
			if ($this->Project()->allowed(DNRoot::ALLOW_PROD_SNAPSHOT, $member)) {
0 ignored issues
show
Documentation introduced by
$member is of type object<DataObject>, but the function expects a object<Member>|null.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
439
				return true;
440
			}
441
		} else {
442
			if ($this->Project()->allowed(DNRoot::ALLOW_NON_PROD_SNAPSHOT, $member)) {
0 ignored issues
show
Documentation introduced by
$member is of type object<DataObject>, but the function expects a object<Member>|null.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
443
				return true;
444
			}
445
		}
446
447
		return $this->ArchiveUploaders()->byID($member->ID)
448
		|| $member->inGroups($this->ArchiveUploaderGroups());
449
	}
450
451
	/**
452
	 * Allows only selected {@link Member} objects to download {@link DNDataArchive} objects from this
453
	 * {@link DNEnvironment}.
454
	 *
455
	 * @param Member|null $member The {@link Member} object to test against. If null, uses Member::currentMember();
456
	 * @return boolean true if $member can download archives from this environment, false if they can't.
457
	 */
458 View Code Duplication
	public function canDownloadArchive($member = null) {
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in 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...
459
		if (!$member) {
460
			$member = Member::currentUser();
461
		}
462
		if (!$member) {
463
			return false;
464
		}
465
		// Must be logged in to check permissions
466
467
		if ($this->Usage === self::PRODUCTION || $this->Usage === self::UNSPECIFIED) {
468
			if ($this->Project()->allowed(DNRoot::ALLOW_PROD_SNAPSHOT, $member)) {
0 ignored issues
show
Documentation introduced by
$member is of type object<DataObject>, but the function expects a object<Member>|null.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
469
				return true;
470
			}
471
		} else {
472
			if ($this->Project()->allowed(DNRoot::ALLOW_NON_PROD_SNAPSHOT, $member)) {
0 ignored issues
show
Documentation introduced by
$member is of type object<DataObject>, but the function expects a object<Member>|null.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
473
				return true;
474
			}
475
		}
476
477
		return $this->ArchiveDownloaders()->byID($member->ID)
478
		|| $member->inGroups($this->ArchiveDownloaderGroups());
479
	}
480
481
	/**
482
	 * Allows only selected {@link Member} objects to delete {@link DNDataArchive} objects from this
483
	 * {@link DNEnvironment}.
484
	 *
485
	 * @param Member|null $member The {@link Member} object to test against. If null, uses Member::currentMember();
486
	 * @return boolean true if $member can delete archives from this environment, false if they can't.
487
	 */
488 View Code Duplication
	public function canDeleteArchive($member = null) {
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in 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...
489
		if (!$member) {
490
			$member = Member::currentUser();
491
		}
492
		if (!$member) {
493
			return false;
494
		}
495
		// Must be logged in to check permissions
496
497
		if ($this->Usage === self::PRODUCTION || $this->Usage === self::UNSPECIFIED) {
498
			if ($this->Project()->allowed(DNRoot::ALLOW_PROD_SNAPSHOT, $member)) {
0 ignored issues
show
Documentation introduced by
$member is of type object<DataObject>, but the function expects a object<Member>|null.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
499
				return true;
500
			}
501
		} else {
502
			if ($this->Project()->allowed(DNRoot::ALLOW_NON_PROD_SNAPSHOT, $member)) {
0 ignored issues
show
Documentation introduced by
$member is of type object<DataObject>, but the function expects a object<Member>|null.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
503
				return true;
504
			}
505
		}
506
507
		return $this->ArchiveDeleters()->byID($member->ID)
508
		|| $member->inGroups($this->ArchiveDeleterGroups());
509
	}
510
511
	/**
512
	 * Get a string of groups/people that are allowed to deploy to this environment.
513
	 * Used in DNRoot_project.ss to list {@link Member}s who have permission to perform this action.
514
	 *
515
	 * @return string
516
	 */
517
	public function getDeployersList() {
518
		return implode(
519
			", ",
520
			array_merge(
521
				$this->DeployerGroups()->column("Title"),
522
				$this->Deployers()->column("FirstName")
523
			)
524
		);
525
	}
526
527
	/**
528
	 * Get a string of groups/people that are allowed to restore {@link DNDataArchive} objects into this environment.
529
	 *
530
	 * @return string
531
	 */
532
	public function getCanRestoreMembersList() {
533
		return implode(
534
			", ",
535
			array_merge(
536
				$this->CanRestoreGroups()->column("Title"),
537
				$this->CanRestoreMembers()->column("FirstName")
538
			)
539
		);
540
	}
541
542
	/**
543
	 * Get a string of groups/people that are allowed to backup {@link DNDataArchive} objects from this environment.
544
	 *
545
	 * @return string
546
	 */
547
	public function getCanBackupMembersList() {
548
		return implode(
549
			", ",
550
			array_merge(
551
				$this->CanBackupGroups()->column("Title"),
552
				$this->CanBackupMembers()->column("FirstName")
553
			)
554
		);
555
	}
556
557
	/**
558
	 * Get a string of groups/people that are allowed to upload {@link DNDataArchive}
559
	 *  objects linked to this environment.
560
	 *
561
	 * @return string
562
	 */
563
	public function getArchiveUploadersList() {
564
		return implode(
565
			", ",
566
			array_merge(
567
				$this->ArchiveUploaderGroups()->column("Title"),
568
				$this->ArchiveUploaders()->column("FirstName")
569
			)
570
		);
571
	}
572
573
	/**
574
	 * Get a string of groups/people that are allowed to download {@link DNDataArchive} objects from this environment.
575
	 *
576
	 * @return string
577
	 */
578
	public function getArchiveDownloadersList() {
579
		return implode(
580
			", ",
581
			array_merge(
582
				$this->ArchiveDownloaderGroups()->column("Title"),
583
				$this->ArchiveDownloaders()->column("FirstName")
584
			)
585
		);
586
	}
587
588
	/**
589
	 * Get a string of groups/people that are allowed to delete {@link DNDataArchive} objects from this environment.
590
	 *
591
	 * @return string
592
	 */
593
	public function getArchiveDeletersList() {
594
		return implode(
595
			", ",
596
			array_merge(
597
				$this->ArchiveDeleterGroups()->column("Title"),
598
				$this->ArchiveDeleters()->column("FirstName")
599
			)
600
		);
601
	}
602
603
	/**
604
	 * @return DNData
605
	 */
606
	public function DNData() {
607
		return DNData::inst();
608
	}
609
610
	/**
611
	 * Get the current deployed build for this environment
612
	 *
613
	 * Dear people of the future: If you are looking to optimize this, simply create a CurrentBuildSHA(), which can be
614
	 * a lot faster. I presume you came here because of the Project display template, which only needs a SHA.
615
	 *
616
	 * @return false|DNDeployment
617
	 */
618
	public function CurrentBuild() {
619
		// The DeployHistory function is far too slow to use for this
620
621
		/** @var DNDeployment $deploy */
622
		$deploy = DNDeployment::get()->filter([
623
			'EnvironmentID' => $this->ID,
624
			'State' => DNDeployment::STATE_COMPLETED
625
		])->sort('LastEdited DESC')->first();
626
627
		if (!$deploy || (!$deploy->SHA)) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $deploy->SHA of type string|null is loosely compared to false; this is ambiguous if the string can be empty. You might want to explicitly use === null instead.

In PHP, under loose comparison (like ==, or !=, or switch conditions), values of different types might be equal.

For string values, the empty string '' is a special case, in particular the following results might be unexpected:

''   == false // true
''   == null  // true
'ab' == false // false
'ab' == null  // false

// It is often better to use strict comparison
'' === false // false
'' === null  // false
Loading history...
628
			return false;
629
		}
630
631
		$repo = $this->Project()->getRepository();
632
		if (!$repo) {
633
			return $deploy;
634
		}
635
636
		try {
637
			$commit = $this->getCommit($deploy->SHA);
638
			if ($commit) {
639
				$deploy->Message = Convert::raw2xml($this->getCommitMessage($commit));
0 ignored issues
show
Documentation introduced by
The property Message does not exist on object<DNDeployment>. Since you implemented __set, maybe consider adding a @property annotation.

Since your code implements the magic setter _set, this function will be called for any write 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.");
        }
    }

}

Since the property has write access only, you can use the @property-write 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...
640
				$deploy->Committer = Convert::raw2xml($commit->getCommitterName());
0 ignored issues
show
Documentation introduced by
The property Committer does not exist on object<DNDeployment>. Since you implemented __set, maybe consider adding a @property annotation.

Since your code implements the magic setter _set, this function will be called for any write 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.");
        }
    }

}

Since the property has write access only, you can use the @property-write 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...
641
				$deploy->CommitDate = $commit->getCommitterDate()->Format('d/m/Y g:ia');
0 ignored issues
show
Documentation introduced by
The property CommitDate does not exist on object<DNDeployment>. Since you implemented __set, maybe consider adding a @property annotation.

Since your code implements the magic setter _set, this function will be called for any write 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.");
        }
    }

}

Since the property has write access only, you can use the @property-write 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...
642
				$deploy->Author = Convert::raw2xml($commit->getAuthorName());
0 ignored issues
show
Documentation introduced by
The property Author does not exist on object<DNDeployment>. Since you implemented __set, maybe consider adding a @property annotation.

Since your code implements the magic setter _set, this function will be called for any write 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.");
        }
    }

}

Since the property has write access only, you can use the @property-write 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...
643
				$deploy->AuthorDate = $commit->getAuthorDate()->Format('d/m/Y g:ia');
0 ignored issues
show
Documentation introduced by
The property AuthorDate does not exist on object<DNDeployment>. Since you implemented __set, maybe consider adding a @property annotation.

Since your code implements the magic setter _set, this function will be called for any write 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.");
        }
    }

}

Since the property has write access only, you can use the @property-write 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...
644
			}
645
			// We can't find this SHA, so we ignore adding a commit message to the deployment
646
		} catch (Exception $ex) {
647
		}
648
649
		return $deploy;
650
	}
651
652
	/**
653
	 * This is a proxy call to gitonmy that caches the information per project and sha
654
	 *
655
	 * @param string $sha
656
	 * @return \Gitonomy\Git\Commit
657
	 */
658
	public function getCommit($sha) {
659
		return $this->Project()->getCommit($sha);
660
	}
661
662
	public function getCommitMessage(\Gitonomy\Git\Commit $commit) {
663
		return $this->Project()->getCommitMessage($commit);
664
	}
665
666
	public function getCommitTags(\Gitonomy\Git\Commit $commit) {
667
		return $this->Project()->getCommitTags($commit);
668
	}
669
670
	/**
671
	 * A list of past deployments.
672
	 * @param string $orderBy - the name of a DB column to sort in descending order
673
	 * @return \ArrayList
674
	 */
675
	public function DeployHistory($orderBy = '') {
676
		$sort = [];
677
		if ($orderBy != '') {
678
			$sort[$orderBy] = 'DESC';
679
		}
680
		// default / fallback sort order
681
		$sort['LastEdited'] = 'DESC';
682
683
		return $this->Deployments()
684
			->where('"SHA" IS NOT NULL')
685
			->filter('State', [
686
				DNDeployment::STATE_COMPLETED,
687
				DNDeployment::STATE_FAILED,
688
				DNDeployment::STATE_INVALID
689
			])
690
			->sort($sort);
691
	}
692
693
	/**
694
	 * A list of upcoming or current deployments.
695
	 * @return ArrayList
696
	 */
697
	public function UpcomingDeployments() {
698
		return $this->Deployments()
699
			->where('"SHA" IS NOT NULL')
700
			->filter('State', [
701
				DNDeployment::STATE_NEW,
702
				DNDeployment::STATE_SUBMITTED,
703
				DNDeployment::STATE_APPROVED,
704
				DNDeployment::STATE_REJECTED,
705
				DNDeployment::STATE_ABORTING,
706
				DNDeployment::STATE_QUEUED,
707
				DNDeployment::STATE_DEPLOYING,
708
			])
709
			->sort('LastEdited DESC');
710
	}
711
712
	/**
713
	 * @param string $action
714
	 *
715
	 * @return string
716
	 */
717
	public function Link($action = '') {
718
		return \Controller::join_links($this->Project()->Link(), "environment", $this->Name, $action);
719
	}
720
721
	/**
722
	 * Is this environment currently at the root level of the controller that handles it?
723
	 * @return bool
724
	 */
725
	public function isCurrent() {
726
		return $this->isSection() && Controller::curr()->getAction() == 'environment';
727
	}
728
729
	/**
730
	 * Is this environment currently in a controller that is handling it or performing a sub-task?
731
	 * @return bool
732
	 */
733
	public function isSection() {
734
		$controller = Controller::curr();
735
		$environment = $controller->getField('CurrentEnvironment');
736
		return $environment && $environment->ID == $this->ID;
737
	}
738
739
	/**
740
	 * @return FieldList
741
	 */
742
	public function getCMSFields() {
743
		$fields = new FieldList(new TabSet('Root'));
744
745
		$project = $this->Project();
746
		if ($project && $project->exists()) {
747
			$viewerGroups = $project->Viewers();
748
			$groups = $viewerGroups->sort('Title')->map()->toArray();
749
			$members = [];
750
			foreach ($viewerGroups as $group) {
751
				foreach ($group->Members()->map() as $k => $v) {
752
					$members[$k] = $v;
753
				}
754
			}
755
			asort($members);
756
		} else {
757
			$groups = [];
758
			$members = [];
759
		}
760
761
		// Main tab
762
		$fields->addFieldsToTab('Root.Main', [
763
			// The Main.ProjectID
764
			TextField::create('ProjectName', 'Project')
765
				->setValue(($project = $this->Project()) ? $project->Name : null)
766
				->performReadonlyTransformation(),
767
768
			// The Main.Name
769
			TextField::create('Name', 'Environment name')
770
				->setDescription('A descriptive name for this environment, e.g. staging, uat, production'),
771
772
			$this->obj('Usage')->scaffoldFormField('Environment usage'),
773
774
			// The Main.URL field
775
			TextField::create('URL', 'Server URL')
776
				->setDescription('This url will be used to provide the front-end with a link to this environment'),
777
778
			// The Main.Filename
779
			TextField::create('Filename')
780
				->setDescription('The capistrano environment file name')
781
				->performReadonlyTransformation(),
782
		]);
783
784
		// Backend identifier - pick from a named list of configurations specified in YML config
785
		$backends = $this->config()->get('allowed_backends', Config::FIRST_SET);
786
		// If there's only 1 backend, then user selection isn't needed
787
		if (sizeof($backends) > 1) {
788
			$fields->addFieldToTab('Root.Main', DropdownField::create('BackendIdentifier', 'Deployment backend')
789
				->setSource($backends)
790
				->setDescription('What kind of deployment system should be used to deploy to this environment'));
791
		}
792
793
		$fields->addFieldsToTab('Root.UserPermissions', [
794
			// The viewers of the environment
795
			$this
796
				->buildPermissionField('ViewerGroups', 'Viewers', $groups, $members)
797
				->setTitle('Who can view this environment?')
798
				->setDescription('Groups or Users who can view this environment'),
799
800
			// The Main.Deployers
801
			$this
802
				->buildPermissionField('DeployerGroups', 'Deployers', $groups, $members)
803
				->setTitle('Who can deploy?')
804
				->setDescription('Groups or Users who can deploy to this environment'),
805
806
			// A box to select all snapshot options.
807
			$this
808
				->buildPermissionField('TickAllSnapshotGroups', 'TickAllSnapshot', $groups, $members)
809
				->setTitle("<em>All snapshot permissions</em>")
810
				->addExtraClass('tickall')
811
				->setDescription('UI shortcut to select all snapshot-related options - not written to the database.'),
812
813
			// The Main.CanRestoreMembers
814
			$this
815
				->buildPermissionField('CanRestoreGroups', 'CanRestoreMembers', $groups, $members)
816
				->setTitle('Who can restore?')
817
				->setDescription('Groups or Users who can restore archives from Deploynaut into this environment'),
818
819
			// The Main.CanBackupMembers
820
			$this
821
				->buildPermissionField('CanBackupGroups', 'CanBackupMembers', $groups, $members)
822
				->setTitle('Who can backup?')
823
				->setDescription('Groups or Users who can backup archives from this environment into Deploynaut'),
824
825
			// The Main.ArchiveDeleters
826
			$this
827
				->buildPermissionField('ArchiveDeleterGroups', 'ArchiveDeleters', $groups, $members)
828
				->setTitle('Who can delete?')
829
				->setDescription("Groups or Users who can delete archives from this environment's staging area."),
830
831
			// The Main.ArchiveUploaders
832
			$this
833
				->buildPermissionField('ArchiveUploaderGroups', 'ArchiveUploaders', $groups, $members)
834
				->setTitle('Who can upload?')
835
				->setDescription(
836
					'Users who can upload archives linked to this environment into Deploynaut.<br />' .
837
					'Linking them to an environment allows limiting download permissions (see below).'
838
				),
839
840
			// The Main.ArchiveDownloaders
841
			$this
842
				->buildPermissionField('ArchiveDownloaderGroups', 'ArchiveDownloaders', $groups, $members)
843
				->setTitle('Who can download?')
844
				->setDescription(<<<PHP
845
Users who can download archives from this environment to their computer.<br />
846
Since this implies access to the snapshot, it is also a prerequisite for restores
847
to other environments, alongside the "Who can restore" permission.<br>
848
Should include all users with upload permissions, otherwise they can't download
849
their own uploads.
850
PHP
851
				)
852
853
		]);
854
855
		// The Main.DeployConfig
856
		if ($this->Project()->exists()) {
857
			$this->setDeployConfigurationFields($fields);
858
		}
859
860
		// The DataArchives
861
		$dataArchiveConfig = GridFieldConfig_RecordViewer::create();
862
		$dataArchiveConfig->removeComponentsByType('GridFieldAddNewButton');
863
		if (class_exists('GridFieldBulkManager')) {
864
			$dataArchiveConfig->addComponent(new GridFieldBulkManager());
865
		}
866
		$dataArchive = GridField::create('DataArchives', 'Data Archives', $this->DataArchives(), $dataArchiveConfig);
867
		$fields->addFieldToTab('Root.DataArchive', $dataArchive);
868
869
		// Deployments
870
		$deploymentsConfig = GridFieldConfig_RecordEditor::create();
871
		$deploymentsConfig->removeComponentsByType('GridFieldAddNewButton');
872
		if (class_exists('GridFieldBulkManager')) {
873
			$deploymentsConfig->addComponent(new GridFieldBulkManager());
874
		}
875
		$deployments = GridField::create('Deployments', 'Deployments', $this->Deployments(), $deploymentsConfig);
876
		$fields->addFieldToTab('Root.Deployments', $deployments);
877
878
		Requirements::javascript('deploynaut/javascript/environment.js');
879
880
		// Add actions
881
		$action = new FormAction('check', 'Check Connection');
882
		$action->setUseButtonTag(true);
883
		$dataURL = Director::absoluteBaseURL() . 'naut/api/' . $this->Project()->Name . '/' . $this->Name . '/ping';
884
		$action->setAttribute('data-url', $dataURL);
885
		$fields->insertBefore($action, 'Name');
0 ignored issues
show
Documentation introduced by
'Name' is of type string, but the function expects a object<FormField>.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
886
887
		// Allow extensions
888
		$this->extend('updateCMSFields', $fields);
889
		return $fields;
890
	}
891
892
	/**
893
	 */
894
	public function onBeforeWrite() {
895
		parent::onBeforeWrite();
896
		if ($this->Name && $this->Name . '.rb' != $this->Filename) {
897
			$this->Filename = $this->Name . '.rb';
898
		}
899
		$this->checkEnvironmentPath();
900
		$this->writeConfigFile();
901
	}
902
903
	public function onAfterWrite() {
904
		parent::onAfterWrite();
905
906
		if ($this->Usage === self::PRODUCTION || $this->Usage === self::UAT) {
907
			$conflicting = DNEnvironment::get()
0 ignored issues
show
Coding Style introduced by
As per coding style, self should be used for accessing local static members.

This check looks for accesses to local static members using the fully qualified name instead of self::.

<?php

class Certificate {
    const TRIPLEDES_CBC = 'ASDFGHJKL';

    private $key;

    public function __construct()
    {
        $this->key = Certificate::TRIPLEDES_CBC;
    }
}

While this is perfectly valid, the fully qualified name of Certificate::TRIPLEDES_CBC could just as well be replaced by self::TRIPLEDES_CBC. Referencing local members with self:: assured the access will still work when the class is renamed, makes it perfectly clear that the member is in fact local and will usually be shorter.

Loading history...
908
				->filter('ProjectID', $this->ProjectID)
909
				->filter('Usage', $this->Usage)
910
				->exclude('ID', $this->ID);
911
912
			foreach ($conflicting as $otherEnvironment) {
913
				$otherEnvironment->Usage = self::UNSPECIFIED;
914
				$otherEnvironment->write();
915
			}
916
		}
917
	}
918
919
	/**
920
	 * Delete any related config files
921
	 */
922
	public function onAfterDelete() {
923
		parent::onAfterDelete();
924
925
		// Create a basic new environment config from a template
926
		if ($this->config()->get('allow_web_editing') && $this->envFileExists()) {
927
			unlink($this->getConfigFilename());
928
		}
929
930
		$deployments = $this->Deployments();
931
		if ($deployments && $deployments->exists()) {
932
			foreach ($deployments as $deployment) {
933
				$deployment->delete();
934
			}
935
		}
936
937
		$archives = $this->DataArchives();
938
		if ($archives && $archives->exists()) {
939
			foreach ($archives as $archive) {
940
				$archive->delete();
941
			}
942
		}
943
944
		$transfers = $this->DataTransfers();
0 ignored issues
show
Documentation Bug introduced by
The method DataTransfers does not exist on object<DNEnvironment>? 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...
945
		if ($transfers && $transfers->exists()) {
946
			foreach ($transfers as $transfer) {
947
				$transfer->delete();
948
			}
949
		}
950
951
		$pings = $this->Pings();
0 ignored issues
show
Documentation Bug introduced by
The method Pings does not exist on object<DNEnvironment>? 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...
952
		if ($pings && $pings->exists()) {
953
			foreach ($pings as $ping) {
954
				$ping->delete();
955
			}
956
		}
957
958
		$create = $this->CreateEnvironment();
0 ignored issues
show
Documentation Bug introduced by
The method CreateEnvironment does not exist on object<DNEnvironment>? 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...
959
		if ($create && $create->exists()) {
960
			$create->delete();
961
		}
962
	}
963
964
	/**
965
	 * Returns the path to the ruby config file
966
	 *
967
	 * @return string
968
	 */
969
	public function getConfigFilename() {
970
		if (!$this->Project()->exists()) {
971
			return '';
972
		}
973
		if (!$this->Filename) {
974
			return '';
975
		}
976
		return $this->DNData()->getEnvironmentDir() . '/' . $this->Project()->Name . '/' . $this->Filename;
977
	}
978
979
	/**
980
	 * Helper function to convert a multi-dimensional array (associative or indexed) to an {@link ArrayList} or
981
	 * {@link ArrayData} object structure, so that values can be used in templates.
982
	 *
983
	 * @param array $array The (single- or multi-dimensional) array to convert
984
	 * @return object Either an {@link ArrayList} or {@link ArrayData} object, or the original item ($array) if $array
985
	 * isn't an array.
986
	 */
987
	public static function array_to_viewabledata($array) {
988
		// Don't transform non-arrays
989
		if (!is_array($array)) {
990
			return $array;
991
		}
992
993
		// Figure out whether this is indexed or associative
994
		$keys = array_keys($array);
995
		$assoc = ($keys != array_keys($keys));
996
		if ($assoc) {
997
			// Treat as viewable data
998
			$data = new ArrayData([]);
999
			foreach ($array as $key => $value) {
1000
				$data->setField($key, self::array_to_viewabledata($value));
1001
			}
1002
			return $data;
1003
		} else {
1004
			// Treat this as basic non-associative list
1005
			$list = new ArrayList();
1006
			foreach ($array as $value) {
1007
				$list->push(self::array_to_viewabledata($value));
1008
			}
1009
			return $list;
1010
		}
1011
	}
1012
1013
	/**
1014
	 * Fetchs all deployments in progress. Limits to 1 hour to prevent deployments
1015
	 * if an old deployment is stuck.
1016
	 *
1017
	 * @return DataList
1018
	 */
1019
	public function runningDeployments() {
1020
		return DNDeployment::get()
1021
			->filter([
1022
				'EnvironmentID' => $this->ID,
1023
				'State' => [
1024
					DNDeployment::STATE_QUEUED,
1025
					DNDeployment::STATE_DEPLOYING,
1026
					DNDeployment::STATE_ABORTING
1027
				],
1028
				'Created:GreaterThan' => strtotime('-1 hour')
1029
			]);
1030
	}
1031
1032
	/**
1033
	 * @param string $sha
1034
	 * @return array
1035
	 */
1036
	protected function getCommitData($sha) {
1037
		try {
1038
			$repo = $this->Project()->getRepository();
1039
			if ($repo !== false) {
1040
				$commit = new \Gitonomy\Git\Commit($repo, $sha);
1041
				return [
1042
					'AuthorName' => (string) Convert::raw2xml($commit->getAuthorName()),
1043
					'AuthorEmail' => (string) Convert::raw2xml($commit->getAuthorEmail()),
1044
					'Message' => (string) Convert::raw2xml($this->getCommitMessage($commit)),
1045
					'ShortHash' => Convert::raw2xml($commit->getFixedShortHash(8)),
1046
					'Hash' => Convert::raw2xml($commit->getHash())
1047
				];
1048
			}
1049
		} catch (\Gitonomy\Git\Exception\ReferenceNotFoundException $exc) {
1050
			SS_Log::log($exc, SS_Log::WARN);
1051
		}
1052
		return [
1053
			'AuthorName' => '(unknown)',
1054
			'AuthorEmail' => '(unknown)',
1055
			'Message' => '(unknown)',
1056
			'ShortHash' => $sha,
1057
			'Hash' => '(unknown)',
1058
		];
1059
	}
1060
1061
	/**
1062
	 * Build a set of multi-select fields for assigning permissions to a pair of group and member many_many relations
1063
	 *
1064
	 * @param string $groupField Group field name
1065
	 * @param string $memberField Member field name
1066
	 * @param array $groups List of groups
1067
	 * @param array $members List of members
1068
	 * @return FieldGroup
1069
	 */
1070
	protected function buildPermissionField($groupField, $memberField, $groups, $members) {
1071
		return FieldGroup::create(
1072
			ListboxField::create($groupField, false, $groups)
1073
				->setMultiple(true)
1074
				->setAttribute('data-placeholder', 'Groups')
1075
				->setAttribute('placeholder', 'Groups')
1076
				->setAttribute('style', 'width: 400px;'),
1077
1078
			ListboxField::create($memberField, false, $members)
1079
				->setMultiple(true)
1080
				->setAttribute('data-placeholder', 'Members')
1081
				->setAttribute('placeholder', 'Members')
1082
				->setAttribute('style', 'width: 400px;')
1083
		);
1084
	}
1085
1086
	/**
1087
	 * @param FieldList $fields
1088
	 */
1089
	protected function setDeployConfigurationFields(&$fields) {
1090
		if (!$this->config()->get('allow_web_editing')) {
1091
			return;
1092
		}
1093
1094
		if ($this->envFileExists()) {
1095
			$deployConfig = new TextareaField('DeployConfig', 'Deploy config', $this->getEnvironmentConfig());
1096
			$deployConfig->setRows(40);
1097
			$fields->insertAfter($deployConfig, 'Filename');
0 ignored issues
show
Documentation introduced by
'Filename' is of type string, but the function expects a object<FormField>.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
1098
			return;
1099
		}
1100
1101
		$warning = 'Warning: This environment doesn\'t have deployment configuration.';
1102
		$noDeployConfig = new LabelField('noDeployConfig', $warning);
1103
		$noDeployConfig->addExtraClass('message warning');
1104
		$fields->insertAfter($noDeployConfig, 'Filename');
0 ignored issues
show
Documentation introduced by
'Filename' is of type string, but the function expects a object<FormField>.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
1105
		$createConfigField = new CheckboxField('CreateEnvConfig', 'Create Config');
1106
		$createConfigField->setDescription('Would you like to create the capistrano deploy configuration?');
1107
		$fields->insertAfter($createConfigField, 'noDeployConfig');
0 ignored issues
show
Documentation introduced by
'noDeployConfig' is of type string, but the function expects a object<FormField>.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
1108
	}
1109
1110
	/**
1111
	 * Ensure that environment paths are setup on the local filesystem
1112
	 */
1113
	protected function checkEnvironmentPath() {
1114
		// Create folder if it doesn't exist
1115
		$configDir = dirname($this->getConfigFilename());
1116
		if (!file_exists($configDir) && $configDir) {
1117
			mkdir($configDir, 0777, true);
1118
		}
1119
	}
1120
1121
	/**
1122
	 * Write the deployment config file to filesystem
1123
	 */
1124
	protected function writeConfigFile() {
1125
		if (!$this->config()->get('allow_web_editing')) {
1126
			return;
1127
		}
1128
1129
		// Create a basic new environment config from a template
1130
		if (!$this->envFileExists()
1131
			&& $this->Filename
1132
			&& $this->CreateEnvConfig
0 ignored issues
show
Documentation introduced by
The property CreateEnvConfig does not exist on object<DNEnvironment>. 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...
1133
		) {
1134
			$templateFile = $this->config()->template_file ?: BASE_PATH . '/deploynaut/environment.template';
1135
			file_put_contents($this->getConfigFilename(), file_get_contents($templateFile));
1136
		} else if ($this->envFileExists() && $this->DeployConfig) {
0 ignored issues
show
Documentation introduced by
The property DeployConfig does not exist on object<DNEnvironment>. 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...
1137
			file_put_contents($this->getConfigFilename(), $this->DeployConfig);
0 ignored issues
show
Documentation introduced by
The property DeployConfig does not exist on object<DNEnvironment>. 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...
1138
		}
1139
	}
1140
1141
	/**
1142
	 * @return string
1143
	 */
1144
	protected function getEnvironmentConfig() {
1145
		if (!$this->envFileExists()) {
1146
			return '';
1147
		}
1148
		return file_get_contents($this->getConfigFilename());
1149
	}
1150
1151
	/**
1152
	 * @return boolean
1153
	 */
1154
	protected function envFileExists() {
1155
		if (!$this->getConfigFilename()) {
1156
			return false;
1157
		}
1158
		return file_exists($this->getConfigFilename());
1159
	}
1160
1161
	protected function validate() {
1162
		$result = parent::validate();
1163
		$backend = $this->Backend();
1164
1165
		if (strcasecmp('test', $this->Name) === 0 && get_class($backend) == 'CapistranoDeploymentBackend') {
1166
			$result->error('"test" is not a valid environment name when using Capistrano backend.');
1167
		}
1168
1169
		return $result;
1170
	}
1171
1172
}
1173