Completed
Push — master ( fbcc1b...090f54 )
by Sean
04:14 queued 26s
created

DNEnvironment::Backend()   B

Complexity

Conditions 4
Paths 4

Size

Total Lines 23
Code Lines 14

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 23
rs 8.7972
c 0
b 0
f 0
cc 4
eloc 14
nc 4
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 {
37
38
	/**
39
	 * If this is set to a full pathfile, it will be used as template
40
	 * file when creating a new capistrano environment config file.
41
	 *
42
	 * If not set, the default 'environment.template' from the module
43
	 * root is used
44
	 *
45
	 * @config
46
	 * @var string
47
	 */
48
	private static $template_file = '';
49
50
	/**
51
	 * Set this to true to allow editing of the environment files via the web admin
52
	 *
53
	 * @var bool
54
	 */
55
	private static $allow_web_editing = false;
56
57
	/**
58
	 * @var array
59
	 */
60
	private static $casting = array(
61
		'DeployHistory' => 'Text'
62
	);
63
64
	/**
65
	 * Allowed backends. A map of Injector identifier to human-readable label.
66
	 *
67
	 * @config
68
	 * @var array
69
	 */
70
	private static $allowed_backends = array();
71
72
	/**
73
	 * @var array
74
	 */
75
	public static $db = array(
76
		"Filename" => "Varchar(255)",
77
		"Name" => "Varchar(255)",
78
		"URL" => "Varchar(255)",
79
		"BackendIdentifier" => "Varchar(255)", // Injector identifier of the DeploymentBackend
80
		"Usage" => "Enum('Production, UAT, Test, Unspecified', 'Unspecified')"
81
	);
82
83
	/**
84
	 * @var array
85
	 */
86
	public static $has_one = array(
87
		"Project" => "DNProject",
88
		"CreateEnvironment" => "DNCreateEnvironment"
89
	);
90
91
	/**
92
	 * @var array
93
	 */
94
	public static $has_many = array(
95
		"Deployments" => "DNDeployment",
96
		"DataArchives" => "DNDataArchive",
97
	);
98
99
	/**
100
	 * @var array
101
	 */
102
	public static $many_many = array(
103
		"Viewers"            => "Member", // Who can view this environment
104
		"ViewerGroups"       => "Group",
105
		"Deployers"          => "Member", // Who can deploy to this environment
106
		"DeployerGroups" => "Group",
107
		"CanRestoreMembers"  => "Member", // Who can restore archive files to this environment
108
		"CanRestoreGroups"  => "Group",
109
		"CanBackupMembers"   => "Member", // Who can backup archive files from this environment
110
		"CanBackupGroups"   => "Group",
111
		"ArchiveUploaders"   => "Member", // Who can upload archive files linked to this environment
112
		"ArchiveUploaderGroups" => "Group",
113
		"ArchiveDownloaders" => "Member", // Who can download archive files from this environment
114
		"ArchiveDownloaderGroups" => "Group",
115
		"ArchiveDeleters"    => "Member", // Who can delete archive files from this environment,
116
		"ArchiveDeleterGroups" => "Group",
117
	);
118
119
	/**
120
	 * @var array
121
	 */
122
	public static $summary_fields = array(
123
		"Name" => "Environment Name",
124
		"Usage" => "Usage",
125
		"URL" => "URL",
126
		"DeployersList" => "Can Deploy List",
127
		"CanRestoreMembersList" => "Can Restore List",
128
		"CanBackupMembersList" => "Can Backup List",
129
		"ArchiveUploadersList" => "Can Upload List",
130
		"ArchiveDownloadersList" => "Can Download List",
131
		"ArchiveDeletersList"  => "Can Delete List",
132
	);
133
134
	private static $singular_name = 'Capistrano Environment';
135
136
	private static $plural_name = 'Capistrano Environments';
137
138
	/**
139
	 * @var array
140
	 */
141
	public static $searchable_fields = array(
142
		"Name",
143
	);
144
145
	/**
146
	 * @var string
147
	 */
148
	private static $default_sort = 'Name';
149
150
	const UAT = 'UAT';
151
152
	const PRODUCTION = 'Production';
153
154
	const UNSPECIFIED = 'Unspecified';
155
156
	/**
157
	 * Used by the sync task
158
	 *
159
	 * @param string $path
160
	 * @return \DNEnvironment
161
	 */
162
	public static function create_from_path($path) {
163
		$e = DNEnvironment::create();
164
		$e->Filename = $path;
165
		$e->Name = basename($e->Filename, '.rb');
166
167
		// add each administrator member as a deployer of the new environment
168
		$adminGroup = Group::get()->filter('Code', 'administrators')->first();
169
		$e->DeployerGroups()->add($adminGroup);
170
		return $e;
171
	}
172
173
	/**
174
	 * Get the deployment backend used for this environment.
175
	 *
176
	 * Enforces compliance with the allowed_backends setting; if the DNEnvironment.BackendIdentifier value is
177
	 * illegal then that value is ignored.
178
	 *
179
	 * @return DeploymentBackend
180
	 */
181
	public function Backend() {
182
		$backends = array_keys($this->config()->get('allowed_backends', Config::FIRST_SET));
183
		switch(sizeof($backends)) {
184
		// Nothing allowed, use the default value "DeploymentBackend"
185
			case 0:
186
				$backend = "DeploymentBackend";
187
				break;
188
189
			// Only 1 thing allowed, use that
190
			case 1:
191
				$backend = $backends[0];
192
				break;
193
194
			// Multiple choices, use our choice if it's legal, otherwise default to the first item on the list
195
			default:
196
				$backend = $this->BackendIdentifier;
197
				if(!in_array($backend, $backends)) {
198
					$backend = $backends[0];
199
				}
200
		}
201
202
		return Injector::inst()->get($backend);
203
	}
204
205
	/**
206
	 * @param SS_HTTPRequest $request
207
	 *
208
	 * @return DeploymentStrategy
209
	 */
210
	public function getDeployStrategy(\SS_HTTPRequest $request) {
211
		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...
212
	}
213
214
	public function Menu() {
215
		$list = new ArrayList();
216
217
		$controller = Controller::curr();
218
		$actionType = $controller->getField('CurrentActionType');
219
220
		$list->push(new ArrayData(array(
221
			'Link' => sprintf('naut/project/%s/environment/%s', $this->Project()->Name, $this->Name),
222
			'Title' => 'Deployments',
223
			'IsCurrent' => $this->isCurrent(),
224
			'IsSection' => $this->isSection() && $actionType == DNRoot::ACTION_DEPLOY
225
		)));
226
227
		$this->extend('updateMenu', $list);
228
229
		return $list;
230
	}
231
232
	/**
233
	 * Return the current object from $this->Menu()
234
	 * Good for making titles and things
235
	 */
236
	public function CurrentMenu() {
237
		return $this->Menu()->filter('IsSection', true)->First();
238
	}
239
240
	/**
241
	 * Return a name for this environment.
242
	 *
243
	 * @param string $separator The string used when concatenating project with env name
244
	 * @return string
245
	 */
246
	public function getFullName($separator = ':') {
247
		return sprintf('%s%s%s', $this->Project()->Name, $separator, $this->Name);
248
	}
249
250
	/**
251
	 * URL for the environment that can be used if no explicit URL is set.
252
	 */
253
	public function getDefaultURL() {
254
		return null;
255
	}
256
257
	public function getBareURL() {
258
		$url = parse_url($this->URL);
259
		if(isset($url['host'])) {
260
			return strtolower($url['host']);
261
		}
262
	}
263
264
	public function getBareDefaultURL() {
265
		$url = parse_url($this->getDefaultURL());
266
		if(isset($url['host'])) {
267
			return strtolower($url['host']);
268
		}
269
	}
270
271
	/**
272
	 * Environments are only viewable by people that can view the environment.
273
	 *
274
	 * @param Member|null $member
275
	 * @return boolean
276
	 */
277
	public function canView($member = null) {
278
		if(!$member) {
279
			$member = Member::currentUser();
280
		}
281
		if(!$member) {
282
			return false;
283
		}
284
		// Must be logged in to check permissions
285
286
		if(Permission::checkMember($member, 'ADMIN')) {
287
			return true;
288
		}
289
290
		// if no Viewers or ViewerGroups defined, fallback to DNProject::canView permissions
291
		if($this->Viewers()->exists() || $this->ViewerGroups()->exists()) {
292
			return $this->Viewers()->byID($member->ID)
293
				|| $member->inGroups($this->ViewerGroups());
294
		}
295
296
		return $this->Project()->canView($member);
297
	}
298
299
	/**
300
	 * Allow deploy only to some people.
301
	 *
302
	 * @param Member|null $member
303
	 * @return boolean
304
	 */
305 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...
306
		if(!$member) {
307
			$member = Member::currentUser();
308
		}
309
		if(!$member) {
310
			return false;
311
		}
312
		// Must be logged in to check permissions
313
314
		if ($this->Usage === self::PRODUCTION || $this->Usage === self::UNSPECIFIED) {
315
			if ($this->Project()->allowed(DNRoot::ALLOW_PROD_DEPLOYMENT, $member)) return true;
316
		} else {
317
			if ($this->Project()->allowed(DNRoot::ALLOW_NON_PROD_DEPLOYMENT, $member)) return true;
318
		}
319
320
		return $this->Deployers()->byID($member->ID)
321
			|| $member->inGroups($this->DeployerGroups());
322
	}
323
324
	/**
325
	 * Provide reason why the user cannot deploy.
326
	 *
327
	 * @return string
328
	 */
329
	public function getCannotDeployMessage() {
330
		return 'You cannot deploy to this environment.';
331
	}
332
333
	/**
334
	 * Allows only selected {@link Member} objects to restore {@link DNDataArchive} objects into this
335
	 * {@link DNEnvironment}.
336
	 *
337
	 * @param Member|null $member The {@link Member} object to test against. If null, uses Member::currentMember();
338
	 * @return boolean true if $member can restore, and false if they can't.
339
	 */
340 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...
341
		if(!$member) {
342
			$member = Member::currentUser();
343
		}
344
		if(!$member) {
345
			return false;
346
		}
347
		// Must be logged in to check permissions
348
349
		if ($this->Usage === self::PRODUCTION || $this->Usage === self::UNSPECIFIED) {
350
			if ($this->Project()->allowed(DNRoot::ALLOW_PROD_SNAPSHOT, $member)) return true;
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...
351
		} else {
352
			if ($this->Project()->allowed(DNRoot::ALLOW_NON_PROD_SNAPSHOT, $member)) return true;
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...
353
		}
354
355
		return $this->CanRestoreMembers()->byID($member->ID)
356
			|| $member->inGroups($this->CanRestoreGroups());
357
	}
358
359
	/**
360
	 * Allows only selected {@link Member} objects to backup this {@link DNEnvironment} to a {@link DNDataArchive}
361
	 * file.
362
	 *
363
	 * @param Member|null $member The {@link Member} object to test against. If null, uses Member::currentMember();
364
	 * @return boolean true if $member can backup, and false if they can't.
365
	 */
366 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...
367
		$project = $this->Project();
368
		if($project->HasDiskQuota() && $project->HasExceededDiskQuota()) {
369
			return false;
370
		}
371
372
		if(!$member) {
373
			$member = Member::currentUser();
374
		}
375
		// Must be logged in to check permissions
376
		if(!$member) {
377
			return false;
378
		}
379
380
		if ($this->Usage === self::PRODUCTION || $this->Usage === self::UNSPECIFIED) {
381
			if ($this->Project()->allowed(DNRoot::ALLOW_PROD_SNAPSHOT, $member)) return true;
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...
382
		} else {
383
			if ($this->Project()->allowed(DNRoot::ALLOW_NON_PROD_SNAPSHOT, $member)) return true;
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...
384
		}
385
386
		return $this->CanBackupMembers()->byID($member->ID)
387
			|| $member->inGroups($this->CanBackupGroups());
388
	}
389
390
	/**
391
	 * Allows only selected {@link Member} objects to upload {@link DNDataArchive} objects linked to this
392
	 * {@link DNEnvironment}.
393
	 *
394
	 * Note: This is not uploading them to the actual environment itself (e.g. uploading to the live site) - it is the
395
	 * process of uploading a *.sspak file into Deploynaut for later 'restoring' to an environment. See
396
	 * {@link self::canRestore()}.
397
	 *
398
	 * @param Member|null $member The {@link Member} object to test against. If null, uses Member::currentMember();
399
	 * @return boolean true if $member can upload archives linked to this environment, false if they can't.
400
	 */
401 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...
402
		$project = $this->Project();
403
		if($project->HasDiskQuota() && $project->HasExceededDiskQuota()) {
404
			return false;
405
		}
406
407
		if(!$member) {
408
			$member = Member::currentUser();
409
		}
410
		if(!$member) {
411
			return false;
412
		}
413
		// Must be logged in to check permissions
414
415
		if ($this->Usage === self::PRODUCTION || $this->Usage === self::UNSPECIFIED) {
416
			if ($this->Project()->allowed(DNRoot::ALLOW_PROD_SNAPSHOT, $member)) return true;
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...
417
		} else {
418
			if ($this->Project()->allowed(DNRoot::ALLOW_NON_PROD_SNAPSHOT, $member)) return true;
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...
419
		}
420
421
		return $this->ArchiveUploaders()->byID($member->ID)
422
			|| $member->inGroups($this->ArchiveUploaderGroups());
423
	}
424
425
	/**
426
	 * Allows only selected {@link Member} objects to download {@link DNDataArchive} objects from this
427
	 * {@link DNEnvironment}.
428
	 *
429
	 * @param Member|null $member The {@link Member} object to test against. If null, uses Member::currentMember();
430
	 * @return boolean true if $member can download archives from this environment, false if they can't.
431
	 */
432 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...
433
		if(!$member) {
434
			$member = Member::currentUser();
435
		}
436
		if(!$member) {
437
			return false;
438
		}
439
		// Must be logged in to check permissions
440
441
		if ($this->Usage === self::PRODUCTION || $this->Usage === self::UNSPECIFIED) {
442
			if ($this->Project()->allowed(DNRoot::ALLOW_PROD_SNAPSHOT, $member)) return true;
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
		} else {
444
			if ($this->Project()->allowed(DNRoot::ALLOW_NON_PROD_SNAPSHOT, $member)) return true;
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...
445
		}
446
447
		return $this->ArchiveDownloaders()->byID($member->ID)
448
			|| $member->inGroups($this->ArchiveDownloaderGroups());
449
	}
450
451
	/**
452
	 * Allows only selected {@link Member} objects to delete {@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 delete archives from this environment, false if they can't.
457
	 */
458 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...
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)) return true;
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
		} else {
470
			if ($this->Project()->allowed(DNRoot::ALLOW_NON_PROD_SNAPSHOT, $member)) return true;
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...
471
		}
472
473
		return $this->ArchiveDeleters()->byID($member->ID)
474
			|| $member->inGroups($this->ArchiveDeleterGroups());
475
	}
476
	/**
477
	 * Get a string of groups/people that are allowed to deploy to this environment.
478
	 * Used in DNRoot_project.ss to list {@link Member}s who have permission to perform this action.
479
	 *
480
	 * @return string
481
	 */
482
	public function getDeployersList() {
483
		return implode(
484
			", ",
485
			array_merge(
486
				$this->DeployerGroups()->column("Title"),
487
				$this->Deployers()->column("FirstName")
488
			)
489
		);
490
	}
491
492
	/**
493
	 * Get a string of groups/people that are allowed to restore {@link DNDataArchive} objects into this environment.
494
	 *
495
	 * @return string
496
	 */
497
	public function getCanRestoreMembersList() {
498
		return implode(
499
			", ",
500
			array_merge(
501
				$this->CanRestoreGroups()->column("Title"),
502
				$this->CanRestoreMembers()->column("FirstName")
503
			)
504
		);
505
	}
506
507
	/**
508
	 * Get a string of groups/people that are allowed to backup {@link DNDataArchive} objects from this environment.
509
	 *
510
	 * @return string
511
	 */
512
	public function getCanBackupMembersList() {
513
		return implode(
514
			", ",
515
			array_merge(
516
				$this->CanBackupGroups()->column("Title"),
517
				$this->CanBackupMembers()->column("FirstName")
518
			)
519
		);
520
	}
521
522
	/**
523
	 * Get a string of groups/people that are allowed to upload {@link DNDataArchive}
524
	 *  objects linked to this environment.
525
	 *
526
	 * @return string
527
	 */
528
	public function getArchiveUploadersList() {
529
		return implode(
530
			", ",
531
			array_merge(
532
				$this->ArchiveUploaderGroups()->column("Title"),
533
				$this->ArchiveUploaders()->column("FirstName")
534
			)
535
		);
536
	}
537
538
	/**
539
	 * Get a string of groups/people that are allowed to download {@link DNDataArchive} objects from this environment.
540
	 *
541
	 * @return string
542
	 */
543
	public function getArchiveDownloadersList() {
544
		return implode(
545
			", ",
546
			array_merge(
547
				$this->ArchiveDownloaderGroups()->column("Title"),
548
				$this->ArchiveDownloaders()->column("FirstName")
549
			)
550
		);
551
	}
552
553
	/**
554
	 * Get a string of groups/people that are allowed to delete {@link DNDataArchive} objects from this environment.
555
	 *
556
	 * @return string
557
	 */
558
	public function getArchiveDeletersList() {
559
		return implode(
560
			", ",
561
			array_merge(
562
				$this->ArchiveDeleterGroups()->column("Title"),
563
				$this->ArchiveDeleters()->column("FirstName")
564
			)
565
		);
566
	}
567
568
	/**
569
	 * @return DNData
570
	 */
571
	public function DNData() {
572
		return DNData::inst();
573
	}
574
575
	/**
576
	 * Get the current deployed build for this environment
577
	 *
578
	 * Dear people of the future: If you are looking to optimize this, simply create a CurrentBuildSHA(), which can be
579
	 * a lot faster. I presume you came here because of the Project display template, which only needs a SHA.
580
	 *
581
	 * @return false|DNDeployment
582
	 */
583
	public function CurrentBuild() {
584
		// The DeployHistory function is far too slow to use for this
585
586
		/** @var DNDeployment $deploy */
587
		$deploy = DNDeployment::get()->filter(array(
588
			'EnvironmentID' => $this->ID,
589
			'State' => 'Completed'
590
		))->sort('LastEdited DESC')->first();
591
592
		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...
593
			return false;
594
		}
595
596
		$repo = $this->Project()->getRepository();
597
		if(!$repo) {
598
			return $deploy;
599
		}
600
601
		try {
602
			$commit = $repo->getCommit($deploy->SHA);
603
			if($commit) {
604
				$deploy->Message = Convert::raw2xml($commit->getMessage());
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...
605
				$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...
606
				$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...
607
				$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...
608
				$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...
609
			}
610
			// We can't find this SHA, so we ignore adding a commit message to the deployment
611
		} catch(Exception $ex) { }
612
613
		return $deploy;
614
	}
615
616
	/**
617
	 * A history of all builds deployed to this environment
618
	 *
619
	 * @return ArrayList
620
	 */
621
	public function DeployHistory() {
622
		return $this->Deployments()
623
			->where('SHA IS NOT NULL')
624
			->sort('LastEdited DESC');
625
	}
626
627
	/**
628
	 * @param string $sha
629
	 * @return array
630
	 */
631
	protected function getCommitData($sha) {
632
		try {
633
			$repo = $this->Project()->getRepository();
634
			if($repo !== false) {
635
				$commit = new \Gitonomy\Git\Commit($repo, $sha);
636
				return [
637
					'AuthorName' => (string)Convert::raw2xml($commit->getAuthorName()),
638
					'AuthorEmail' => (string)Convert::raw2xml($commit->getAuthorEmail()),
639
					'Message' => (string)Convert::raw2xml($commit->getMessage()),
640
					'ShortHash' => Convert::raw2xml($commit->getFixedShortHash(8)),
641
					'Hash' => Convert::raw2xml($commit->getHash())
642
				];
643
			}
644
		} catch(\Gitonomy\Git\Exception\ReferenceNotFoundException $exc) {
645
			SS_Log::log($exc, SS_Log::WARN);
646
		}
647
		return array(
648
			'AuthorName' => '(unknown)',
649
			'AuthorEmail' => '(unknown)',
650
			'Message' => '(unknown)',
651
			'ShortHash' => $sha,
652
			'Hash' => '(unknown)',
653
		);
654
	}
655
656
	/**
657
	 * @return string
658
	 */
659
	public function Link() {
660
		return $this->Project()->Link() . "/environment/" . $this->Name;
661
	}
662
663
	/**
664
	 * Is this environment currently at the root level of the controller that handles it?
665
	 * @return bool
666
	 */
667
	public function isCurrent() {
668
		return $this->isSection() && Controller::curr()->getAction() == 'environment';
669
	}
670
671
	/**
672
	 * Is this environment currently in a controller that is handling it or performing a sub-task?
673
	 * @return bool
674
	 */
675
	public function isSection() {
676
		$controller = Controller::curr();
677
		$environment = $controller->getField('CurrentEnvironment');
678
		return $environment && $environment->ID == $this->ID;
679
	}
680
681
682
	/**
683
	 * Build a set of multi-select fields for assigning permissions to a pair of group and member many_many relations
684
	 *
685
	 * @param string $groupField Group field name
686
	 * @param string $memberField Member field name
687
	 * @param array $groups List of groups
688
	 * @param array $members List of members
689
	 * @return FieldGroup
690
	 */
691
	protected function buildPermissionField($groupField, $memberField, $groups, $members) {
692
		return FieldGroup::create(
693
			ListboxField::create($groupField, false, $groups)
694
				->setMultiple(true)
695
				->setAttribute('data-placeholder', 'Groups')
696
				->setAttribute('placeholder', 'Groups')
697
				->setAttribute('style', 'width: 400px;'),
698
699
			ListboxField::create($memberField, false, $members)
700
				->setMultiple(true)
701
				->setAttribute('data-placeholder', 'Members')
702
				->setAttribute('placeholder', 'Members')
703
				->setAttribute('style', 'width: 400px;')
704
		);
705
	}
706
707
	/**
708
	 * @return FieldList
709
	 */
710
	public function getCMSFields() {
711
		$fields = new FieldList(new TabSet('Root'));
712
713
		$project = $this->Project();
714
		if($project && $project->exists()) {
715
			$viewerGroups = $project->Viewers();
716
			$groups = $viewerGroups->sort('Title')->map()->toArray();
717
			$members = array();
718
			foreach($viewerGroups as $group) {
719
				foreach($group->Members()->map() as $k => $v) {
720
					$members[$k] = $v;
721
				}
722
			}
723
			asort($members);
724
		} else {
725
			$groups = array();
726
			$members = array();
727
		}
728
729
		// Main tab
730
		$fields->addFieldsToTab('Root.Main', array(
731
			// The Main.ProjectID
732
			TextField::create('ProjectName', 'Project')
733
				->setValue(($project = $this->Project()) ? $project->Name : null)
734
				->performReadonlyTransformation(),
735
736
			// The Main.Name
737
			TextField::create('Name', 'Environment name')
738
				->setDescription('A descriptive name for this environment, e.g. staging, uat, production'),
739
740
741
			$this->obj('Usage')->scaffoldFormField('Environment usage'),
742
743
			// The Main.URL field
744
			TextField::create('URL', 'Server URL')
745
				->setDescription('This url will be used to provide the front-end with a link to this environment'),
746
747
			// The Main.Filename
748
			TextField::create('Filename')
749
				->setDescription('The capistrano environment file name')
750
				->performReadonlyTransformation(),
751
		));
752
753
		// Backend identifier - pick from a named list of configurations specified in YML config
754
		$backends = $this->config()->get('allowed_backends', Config::FIRST_SET);
755
		// If there's only 1 backend, then user selection isn't needed
756
		if(sizeof($backends) > 1) {
757
			$fields->addFieldToTab('Root.Main', DropdownField::create('BackendIdentifier', 'Deployment backend')
758
				->setSource($backends)
759
				->setDescription('What kind of deployment system should be used to deploy to this environment'));
760
		}
761
762
		$fields->addFieldsToTab('Root.UserPermissions', array(
763
			// The viewers of the environment
764
			$this
765
				->buildPermissionField('ViewerGroups', 'Viewers', $groups, $members)
766
				->setTitle('Who can view this environment?')
767
				->setDescription('Groups or Users who can view this environment'),
768
769
			// The Main.Deployers
770
			$this
771
				->buildPermissionField('DeployerGroups', 'Deployers', $groups, $members)
772
				->setTitle('Who can deploy?')
773
				->setDescription('Groups or Users who can deploy to this environment'),
774
775
			// A box to select all snapshot options.
776
			$this
777
				->buildPermissionField('TickAllSnapshotGroups', 'TickAllSnapshot', $groups, $members)
778
				->setTitle("<em>All snapshot permissions</em>")
779
				->addExtraClass('tickall')
780
				->setDescription('UI shortcut to select all snapshot-related options - not written to the database.'),
781
782
			// The Main.CanRestoreMembers
783
			$this
784
				->buildPermissionField('CanRestoreGroups', 'CanRestoreMembers', $groups, $members)
785
				->setTitle('Who can restore?')
786
				->setDescription('Groups or Users who can restore archives from Deploynaut into this environment'),
787
788
			// The Main.CanBackupMembers
789
			$this
790
				->buildPermissionField('CanBackupGroups', 'CanBackupMembers', $groups, $members)
791
				->setTitle('Who can backup?')
792
				->setDescription('Groups or Users who can backup archives from this environment into Deploynaut'),
793
794
			// The Main.ArchiveDeleters
795
			$this
796
				->buildPermissionField('ArchiveDeleterGroups', 'ArchiveDeleters', $groups, $members)
797
				->setTitle('Who can delete?')
798
				->setDescription("Groups or Users who can delete archives from this environment's staging area."),
799
800
			// The Main.ArchiveUploaders
801
			$this
802
				->buildPermissionField('ArchiveUploaderGroups', 'ArchiveUploaders', $groups, $members)
803
				->setTitle('Who can upload?')
804
				->setDescription(
805
					'Users who can upload archives linked to this environment into Deploynaut.<br />' .
806
					'Linking them to an environment allows limiting download permissions (see below).'
807
				),
808
809
			// The Main.ArchiveDownloaders
810
			$this
811
				->buildPermissionField('ArchiveDownloaderGroups', 'ArchiveDownloaders', $groups, $members)
812
				->setTitle('Who can download?')
813
				->setDescription(<<<PHP
814
Users who can download archives from this environment to their computer.<br />
815
Since this implies access to the snapshot, it is also a prerequisite for restores
816
to other environments, alongside the "Who can restore" permission.<br>
817
Should include all users with upload permissions, otherwise they can't download
818
their own uploads.
819
PHP
820
				)
821
822
		));
823
824
		// The Main.DeployConfig
825
		if($this->Project()->exists()) {
826
			$this->setDeployConfigurationFields($fields);
827
		}
828
829
		// The DataArchives
830
		$dataArchiveConfig = GridFieldConfig_RecordViewer::create();
831
		$dataArchiveConfig->removeComponentsByType('GridFieldAddNewButton');
832
		if(class_exists('GridFieldBulkManager')) {
833
			$dataArchiveConfig->addComponent(new GridFieldBulkManager());
834
		}
835
		$dataArchive = GridField::create('DataArchives', 'Data Archives', $this->DataArchives(), $dataArchiveConfig);
836
		$fields->addFieldToTab('Root.DataArchive', $dataArchive);
837
838
		// Deployments
839
		$deploymentsConfig = GridFieldConfig_RecordEditor::create();
840
		$deploymentsConfig->removeComponentsByType('GridFieldAddNewButton');
841
		if(class_exists('GridFieldBulkManager')) {
842
			$deploymentsConfig->addComponent(new GridFieldBulkManager());
843
		}
844
		$deployments = GridField::create('Deployments', 'Deployments', $this->Deployments(), $deploymentsConfig);
845
		$fields->addFieldToTab('Root.Deployments', $deployments);
846
847
		Requirements::javascript('deploynaut/javascript/environment.js');
848
849
		// Add actions
850
		$action = new FormAction('check', 'Check Connection');
851
		$action->setUseButtonTag(true);
852
		$dataURL = Director::absoluteBaseURL() . 'naut/api/' . $this->Project()->Name . '/' . $this->Name . '/ping';
853
		$action->setAttribute('data-url', $dataURL);
854
		$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...
855
856
		// Allow extensions
857
		$this->extend('updateCMSFields', $fields);
858
		return $fields;
859
	}
860
861
	/**
862
	 * @param FieldList $fields
863
	 */
864
	protected function setDeployConfigurationFields(&$fields) {
865
		if(!$this->config()->get('allow_web_editing')) {
866
			return;
867
		}
868
869
		if($this->envFileExists()) {
870
			$deployConfig = new TextareaField('DeployConfig', 'Deploy config', $this->getEnvironmentConfig());
871
			$deployConfig->setRows(40);
872
			$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...
873
			return;
874
		}
875
876
		$warning = 'Warning: This environment doesn\'t have deployment configuration.';
877
		$noDeployConfig = new LabelField('noDeployConfig', $warning);
878
		$noDeployConfig->addExtraClass('message warning');
879
		$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...
880
		$createConfigField = new CheckboxField('CreateEnvConfig', 'Create Config');
881
		$createConfigField->setDescription('Would you like to create the capistrano deploy configuration?');
882
		$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...
883
	}
884
885
	/**
886
	 */
887
	public function onBeforeWrite() {
888
		parent::onBeforeWrite();
889
		if($this->Name && $this->Name . '.rb' != $this->Filename) {
890
			$this->Filename = $this->Name . '.rb';
891
		}
892
		$this->checkEnvironmentPath();
893
		$this->writeConfigFile();
894
	}
895
896
	public function onAfterWrite() {
897
		parent::onAfterWrite();
898
899
		if($this->Usage === self::PRODUCTION || $this->Usage === self::UAT) {
900
			$conflicting = DNEnvironment::get()
901
				->filter('ProjectID', $this->ProjectID)
902
				->filter('Usage', $this->Usage)
903
				->exclude('ID', $this->ID);
904
905
			foreach($conflicting as $otherEnvironment) {
906
				$otherEnvironment->Usage = self::UNSPECIFIED;
907
				$otherEnvironment->write();
908
			}
909
		}
910
	}
911
912
913
	/**
914
	 * Ensure that environment paths are setup on the local filesystem
915
	 */
916
	protected function checkEnvironmentPath() {
917
		// Create folder if it doesn't exist
918
		$configDir = dirname($this->getConfigFilename());
919
		if(!file_exists($configDir) && $configDir) {
920
			mkdir($configDir, 0777, true);
921
		}
922
	}
923
924
	/**
925
	 * Write the deployment config file to filesystem
926
	 */
927
	protected function writeConfigFile() {
928
		if(!$this->config()->get('allow_web_editing')) {
929
			return;
930
		}
931
932
		// Create a basic new environment config from a template
933
		if(!$this->envFileExists()
934
			&& $this->Filename
935
			&& $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...
936
		) {
937
			$templateFile = $this->config()->template_file ?: BASE_PATH . '/deploynaut/environment.template';
938
			file_put_contents($this->getConfigFilename(), file_get_contents($templateFile));
939
		} 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...
940
			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...
941
		}
942
	}
943
944
	/**
945
	 * Delete any related config files
946
	 */
947
	public function onAfterDelete() {
948
		parent::onAfterDelete();
949
		// Create a basic new environment config from a template
950
		if($this->config()->get('allow_web_editing') && $this->envFileExists()) {
951
			unlink($this->getConfigFilename());
952
		}
953
954
		$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...
955
		if($create && $create->exists()) {
956
			$create->delete();
957
		}
958
	}
959
960
	/**
961
	 * @return string
962
	 */
963
	protected function getEnvironmentConfig() {
964
		if(!$this->envFileExists()) {
965
			return '';
966
		}
967
		return file_get_contents($this->getConfigFilename());
968
	}
969
970
	/**
971
	 * @return boolean
972
	 */
973
	protected function envFileExists() {
974
		if(!$this->getConfigFilename()) {
975
			return false;
976
		}
977
		return file_exists($this->getConfigFilename());
978
	}
979
980
	/**
981
	 * Returns the path to the ruby config file
982
	 *
983
	 * @return string
984
	 */
985
	public function getConfigFilename() {
986
		if(!$this->Project()->exists()) {
987
			return '';
988
		}
989
		if(!$this->Filename) {
990
			return '';
991
		}
992
		return $this->DNData()->getEnvironmentDir() . '/' . $this->Project()->Name . '/' . $this->Filename;
993
	}
994
995
	/**
996
	 * Helper function to convert a multi-dimensional array (associative or indexed) to an {@link ArrayList} or
997
	 * {@link ArrayData} object structure, so that values can be used in templates.
998
	 *
999
	 * @param array $array The (single- or multi-dimensional) array to convert
1000
	 * @return object Either an {@link ArrayList} or {@link ArrayData} object, or the original item ($array) if $array
1001
	 * isn't an array.
1002
	 */
1003
	public static function array_to_viewabledata($array) {
1004
		// Don't transform non-arrays
1005
		if(!is_array($array)) {
1006
			return $array;
1007
		}
1008
1009
		// Figure out whether this is indexed or associative
1010
		$keys = array_keys($array);
1011
		$assoc = ($keys != array_keys($keys));
1012
		if($assoc) {
1013
			// Treat as viewable data
1014
			$data = new ArrayData(array());
1015
			foreach($array as $key => $value) {
1016
				$data->setField($key, self::array_to_viewabledata($value));
1017
			}
1018
			return $data;
1019
		} else {
1020
			// Treat this as basic non-associative list
1021
			$list = new ArrayList();
1022
			foreach($array as $value) {
1023
				$list->push(self::array_to_viewabledata($value));
1024
			}
1025
			return $list;
1026
		}
1027
	}
1028
1029
	protected function validate() {
1030
		$result = parent::validate();
1031
		$backend = $this->Backend();
1032
1033
		if(strcasecmp('test', $this->Name) === 0 && get_class($backend) == 'CapistranoDeploymentBackend') {
1034
			$result->error('"test" is not a valid environment name when using Capistrano backend.');
1035
		}
1036
1037
		return $result;
1038
	}
1039
1040
	/**
1041
	 * Fetchs all deployments in progress. Limits to 1 hour to prevent deployments
1042
	 * if an old deployment is stuck.
1043
	 *
1044
	 * @return DataList
1045
	 */
1046
	public function runningDeployments() {
1047
		return DNDeployment::get()
1048
			->filter([
1049
				'EnvironmentID' => $this->ID,
1050
				'State' => ['Queued', 'Deploying', 'Aborting'],
1051
				'Created:GreaterThan' => strtotime('-1 hour')
1052
			]);
1053
	}
1054
1055
}
1056
1057