Completed
Pull Request — master (#489)
by Helpful
03:51
created
code/api/DeploynautAPI.php 1 patch
Indentation   +137 added lines, -137 removed lines patch added patch discarded remove patch
@@ -16,141 +16,141 @@
 block discarded – undo
16 16
 class DeploynautAPI extends APINoun
17 17
 {
18 18
 
19
-    /**
20
-     * Default URL handlers - (Action)/(ID)//(OtherID)
21
-     *
22
-     * @var array
23
-     */
24
-    private static $url_handlers = array(
25
-        '' => 'listProjects',
26
-        '$Project//fetch' => 'project',
27
-        '$Project/$Environment!' => 'environment',
28
-        '$Project/' => 'project',
29
-    );
30
-
31
-    /**
32
-     * @var array
33
-     */
34
-    public static $allowed_actions = array(
35
-        'project',
36
-        'environment',
37
-        'listProjects'
38
-    );
39
-
40
-    /**
41
-     * @var string
42
-     */
43
-    protected $link = 'deploynaut/api';
44
-
45
-    /**
46
-     * @param SS_HTTPRequest $request
47
-     * @return SS_HTTPResponse
48
-     */
49
-    public function listProjects(SS_HTTPRequest $request)
50
-    {
51
-        $response = array(
52
-            'href' => Director::absoluteURL($this->Link()),
53
-            'projects' => array(),
54
-        );
55
-
56
-        if ($request->httpMethod() != 'GET') {
57
-            return $this->message('API not found', 404);
58
-        }
59
-
60
-        foreach (DNProject::get() as $item) {
61
-            if ($item->canView($this->getMember())) {
62
-                $response['projects'][] = array(
63
-                    "name" => $item->Name,
64
-                    "href" => Director::absoluteURL($item->APILink("")),
65
-                );
66
-            }
67
-        }
68
-
69
-        return $this->getAPIResponse($response);
70
-    }
71
-
72
-    /**
73
-     * Controller Action
74
-     *
75
-     * @param SS_HTTPRequest $request
76
-     * @return APIProject
77
-     */
78
-    public function project(SS_HTTPRequest $request)
79
-    {
80
-        $project = $this->getProject();
81
-        if (!$project) {
82
-            return $this->project404Response();
83
-        }
84
-        return new APIProject($this, $project);
85
-    }
86
-
87
-    /**
88
-     * Controller Action
89
-     *
90
-     * @param SS_HTTPRequest $request
91
-     * @return APIEnvironment
92
-     */
93
-    public function environment(SS_HTTPRequest $request)
94
-    {
95
-        $project = $this->getProject();
96
-        if (!$project) {
97
-            return $this->project404Response();
98
-        }
99
-
100
-        $environment = $this->getEnvironment();
101
-        if (!$environment) {
102
-            return $this->environment404Response();
103
-        }
104
-        return new APIEnvironment($this, $environment);
105
-    }
106
-
107
-    /**
108
-     * @return SS_HTTPResponse
109
-     */
110
-    protected function project404Response()
111
-    {
112
-        $projectName = Convert::raw2xml($this->getRequest()->latestParam('Project'));
113
-        return new SS_HTTPResponse('Project "' . $projectName . '" not found.', 404);
114
-    }
115
-
116
-    /**
117
-     * @return SS_HTTPResponse
118
-     */
119
-    protected function environment404Response()
120
-    {
121
-        $envName = Convert::raw2xml($this->getRequest()->latestParam('Environment'));
122
-        return new SS_HTTPResponse('Environment "' . $envName . '" not found.', 404);
123
-    }
124
-
125
-    /**
126
-     * Get project from URL
127
-     *
128
-     * @return DNProject
129
-     */
130
-    protected function getProject()
131
-    {
132
-        $projectName = $this->getRequest()->param('Project');
133
-        return DNProject::get()->filter('Name', $projectName)->first();
134
-    }
135
-
136
-    /**
137
-     * Get environment from URL
138
-     *
139
-     * @return DNEnvironment
140
-     */
141
-    protected function getEnvironment()
142
-    {
143
-        $projectName = $this->getRequest()->param('Project');
144
-        $project = DNProject::get()->filter('Name', $projectName)->first();
145
-        $environmentName = $this->getRequest()->param('Environment');
146
-        return $project->Environments()->filter('Name', $environmentName)->first();
147
-    }
148
-
149
-    /**
150
-     * @return string
151
-     */
152
-    public function Link()
153
-    {
154
-        return 'naut/api';
155
-    }
19
+	/**
20
+	 * Default URL handlers - (Action)/(ID)//(OtherID)
21
+	 *
22
+	 * @var array
23
+	 */
24
+	private static $url_handlers = array(
25
+		'' => 'listProjects',
26
+		'$Project//fetch' => 'project',
27
+		'$Project/$Environment!' => 'environment',
28
+		'$Project/' => 'project',
29
+	);
30
+
31
+	/**
32
+	 * @var array
33
+	 */
34
+	public static $allowed_actions = array(
35
+		'project',
36
+		'environment',
37
+		'listProjects'
38
+	);
39
+
40
+	/**
41
+	 * @var string
42
+	 */
43
+	protected $link = 'deploynaut/api';
44
+
45
+	/**
46
+	 * @param SS_HTTPRequest $request
47
+	 * @return SS_HTTPResponse
48
+	 */
49
+	public function listProjects(SS_HTTPRequest $request)
50
+	{
51
+		$response = array(
52
+			'href' => Director::absoluteURL($this->Link()),
53
+			'projects' => array(),
54
+		);
55
+
56
+		if ($request->httpMethod() != 'GET') {
57
+			return $this->message('API not found', 404);
58
+		}
59
+
60
+		foreach (DNProject::get() as $item) {
61
+			if ($item->canView($this->getMember())) {
62
+				$response['projects'][] = array(
63
+					"name" => $item->Name,
64
+					"href" => Director::absoluteURL($item->APILink("")),
65
+				);
66
+			}
67
+		}
68
+
69
+		return $this->getAPIResponse($response);
70
+	}
71
+
72
+	/**
73
+	 * Controller Action
74
+	 *
75
+	 * @param SS_HTTPRequest $request
76
+	 * @return APIProject
77
+	 */
78
+	public function project(SS_HTTPRequest $request)
79
+	{
80
+		$project = $this->getProject();
81
+		if (!$project) {
82
+			return $this->project404Response();
83
+		}
84
+		return new APIProject($this, $project);
85
+	}
86
+
87
+	/**
88
+	 * Controller Action
89
+	 *
90
+	 * @param SS_HTTPRequest $request
91
+	 * @return APIEnvironment
92
+	 */
93
+	public function environment(SS_HTTPRequest $request)
94
+	{
95
+		$project = $this->getProject();
96
+		if (!$project) {
97
+			return $this->project404Response();
98
+		}
99
+
100
+		$environment = $this->getEnvironment();
101
+		if (!$environment) {
102
+			return $this->environment404Response();
103
+		}
104
+		return new APIEnvironment($this, $environment);
105
+	}
106
+
107
+	/**
108
+	 * @return SS_HTTPResponse
109
+	 */
110
+	protected function project404Response()
111
+	{
112
+		$projectName = Convert::raw2xml($this->getRequest()->latestParam('Project'));
113
+		return new SS_HTTPResponse('Project "' . $projectName . '" not found.', 404);
114
+	}
115
+
116
+	/**
117
+	 * @return SS_HTTPResponse
118
+	 */
119
+	protected function environment404Response()
120
+	{
121
+		$envName = Convert::raw2xml($this->getRequest()->latestParam('Environment'));
122
+		return new SS_HTTPResponse('Environment "' . $envName . '" not found.', 404);
123
+	}
124
+
125
+	/**
126
+	 * Get project from URL
127
+	 *
128
+	 * @return DNProject
129
+	 */
130
+	protected function getProject()
131
+	{
132
+		$projectName = $this->getRequest()->param('Project');
133
+		return DNProject::get()->filter('Name', $projectName)->first();
134
+	}
135
+
136
+	/**
137
+	 * Get environment from URL
138
+	 *
139
+	 * @return DNEnvironment
140
+	 */
141
+	protected function getEnvironment()
142
+	{
143
+		$projectName = $this->getRequest()->param('Project');
144
+		$project = DNProject::get()->filter('Name', $projectName)->first();
145
+		$environmentName = $this->getRequest()->param('Environment');
146
+		return $project->Environments()->filter('Name', $environmentName)->first();
147
+	}
148
+
149
+	/**
150
+	 * @return string
151
+	 */
152
+	public function Link()
153
+	{
154
+		return 'naut/api';
155
+	}
156 156
 }
Please login to merge, or discard this patch.
code/api/nouns/APIEnvironment.php 1 patch
Indentation   +198 added lines, -198 removed lines patch added patch discarded remove patch
@@ -3,202 +3,202 @@
 block discarded – undo
3 3
 class APIEnvironment extends APINoun
4 4
 {
5 5
 
6
-    /**
7
-     * @var array
8
-     */
9
-    private static $allowed_actions = array(
10
-        'ping',
11
-        'deploy'
12
-    );
13
-
14
-    /**
15
-     * @param SS_HTTPRequest $request
16
-     * @return SS_HTTPResponse
17
-     */
18
-    public function index(SS_HTTPRequest $request)
19
-    {
20
-        if (!$this->record->canView($this->getMember())) {
21
-            return $this->message('You are not authorized to view this environment', 403);
22
-        }
23
-        switch ($request->httpMethod()) {
24
-            case 'GET':
25
-                $href = Director::absoluteURL($this->record->Project()->APILink($this->record->Name));
26
-                return $this->getAPIResponse(array(
27
-                    "name" => $this->record->Name,
28
-                    "project" => $this->record->Project()->Name,
29
-                    "href" => $href,
30
-                    "created" => $this->record->Created,
31
-                    "last-edited" => $this->record->LastEdited,
32
-
33
-                    // Stolen from https://github.com/kevinswiber/siren spec
34
-                    "actions" => array(
35
-                        array(
36
-                            "name" => "deploy",
37
-                            "method" =>  "POST",
38
-                            "href" => "$href/deploy",
39
-                            "type" => "application/json",
40
-                            "fields" => array(
41
-                                array("name" => "release", "type" => "text"),
42
-                            ),
43
-                        )
44
-                    )
45
-                ));
46
-            default:
47
-                return $this->message('API not found', 404);
48
-        }
49
-    }
50
-
51
-    /**
52
-     * @param SS_HTTPRequest $request
53
-     * @return SS_HTTPResponse
54
-     */
55
-    public function ping(SS_HTTPRequest $request)
56
-    {
57
-        if (!$this->record->canView($this->getMember())) {
58
-            return $this->message('You are not authorized to do that on this environment', 403);
59
-        }
60
-        switch ($request->httpMethod()) {
61
-            case 'GET':
62
-                return $this->getPing($this->getRequest()->param('ID'));
63
-            case 'POST':
64
-                return $this->createPing();
65
-            default:
66
-                return $this->message('API not found', 404);
67
-        }
68
-    }
69
-
70
-    /**
71
-     * @param SS_HTTPRequest $request
72
-     * @return SS_HTTPResponse
73
-     */
74
-    public function deploy(SS_HTTPRequest $request)
75
-    {
76
-        if (!$this->record->canView($this->getMember())) {
77
-            return $this->message('You are not authorized to do that on this environment', 403);
78
-        }
79
-        switch ($request->httpMethod()) {
80
-            case 'GET':
81
-                return $this->getDeploy($this->getRequest()->param('ID'));
82
-            case 'POST':
83
-                return $this->createDeploy();
84
-            default:
85
-                return $this->message('API not found', 404);
86
-        }
87
-    }
88
-
89
-    /**
90
-     * @return string
91
-     */
92
-    public function Link()
93
-    {
94
-        return Controller::join_links(
95
-            $this->parent->Link(),
96
-            $this->record->Project()->Name,
97
-            $this->record->Name
98
-        );
99
-    }
100
-
101
-    /**
102
-     * @return SS_HTTPResponse
103
-     */
104
-    protected function showRecord()
105
-    {
106
-        return $this->getAPIResponse($this->record->toMap());
107
-    }
108
-
109
-    /**
110
-     * @return SS_HTTPResponse
111
-     */
112
-    protected function createPing()
113
-    {
114
-        if (!$this->record->canDeploy($this->getMember())) {
115
-            return $this->message('You are not authorized to do that on this environment', 403);
116
-        }
117
-        $ping = DNPing::create();
118
-        $ping->EnvironmentID = $this->record->ID;
119
-        $ping->write();
120
-        $ping->start();
121
-
122
-        $location = Director::absoluteBaseURL() . $this->Link() . '/ping/' . $ping->ID;
123
-        $output = array(
124
-            'message' => 'Ping queued as job ' . $ping->ResqueToken,
125
-            'href' => $location,
126
-        );
127
-
128
-        $response = $this->getAPIResponse($output);
129
-        $response->setStatusCode(201);
130
-        $response->addHeader('Location', $location);
131
-        return $response;
132
-    }
133
-
134
-    /**
135
-     * @param int $ID
136
-     * @return SS_HTTPResponse
137
-     */
138
-    protected function getPing($ID)
139
-    {
140
-        $ping = DNPing::get()->byID($ID);
141
-        if (!$ping) {
142
-            return $this->message('Ping not found', 404);
143
-        }
144
-        $output = array(
145
-            'status' => $ping->ResqueStatus(),
146
-            'message' => $ping->LogContent()
147
-        );
148
-
149
-        return $this->getAPIResponse($output);
150
-    }
151
-
152
-    /**
153
-     * @return SS_HTTPResponse
154
-     */
155
-    protected function createDeploy()
156
-    {
157
-        if (!$this->record->canDeploy($this->getMember())) {
158
-            return $this->message('You are not authorized to do that on this environment', 403);
159
-        }
160
-
161
-        $reqBody = $this->getRequestBody();
162
-
163
-        if ($reqBody === null) {
164
-            return $this->message('the request body did not contain a valid JSON object.', 400);
165
-        }
166
-
167
-        if (empty($reqBody['release'])) {
168
-            return $this->message('deploy requires a {"release": "sha1"} in the body of the request.', 400);
169
-        }
170
-
171
-        $strategy = new DeploymentStrategy($this->record, array(
172
-            'sha' => $reqBody['release']
173
-        ));
174
-        $deploy = $strategy->createDeployment();
175
-        $deploy->start();
176
-        $location = Director::absoluteBaseURL() . $this->Link() . '/deploy/' . $deploy->ID;
177
-        $output = array(
178
-            'message' => 'Deploy queued as job ' . $deploy->ResqueToken,
179
-            'href' => $location,
180
-        );
181
-        $response = $this->getAPIResponse($output);
182
-        $response->setStatusCode(201);
183
-        $response->addHeader('Location', $location);
184
-        return $response;
185
-    }
186
-
187
-    /**
188
-     * @param int $id
189
-     * @return SS_HTTPResponse
190
-     */
191
-    protected function getDeploy($id)
192
-    {
193
-        $deploy = DNDeployment::get()->byID($id);
194
-        if (!$deploy) {
195
-            return $this->message('Deploy not found', 404);
196
-        }
197
-        $output = array(
198
-            'status' => $deploy->ResqueStatus(),
199
-            'message' => $deploy->LogContent()
200
-        );
201
-
202
-        return $this->getAPIResponse($output);
203
-    }
6
+	/**
7
+	 * @var array
8
+	 */
9
+	private static $allowed_actions = array(
10
+		'ping',
11
+		'deploy'
12
+	);
13
+
14
+	/**
15
+	 * @param SS_HTTPRequest $request
16
+	 * @return SS_HTTPResponse
17
+	 */
18
+	public function index(SS_HTTPRequest $request)
19
+	{
20
+		if (!$this->record->canView($this->getMember())) {
21
+			return $this->message('You are not authorized to view this environment', 403);
22
+		}
23
+		switch ($request->httpMethod()) {
24
+			case 'GET':
25
+				$href = Director::absoluteURL($this->record->Project()->APILink($this->record->Name));
26
+				return $this->getAPIResponse(array(
27
+					"name" => $this->record->Name,
28
+					"project" => $this->record->Project()->Name,
29
+					"href" => $href,
30
+					"created" => $this->record->Created,
31
+					"last-edited" => $this->record->LastEdited,
32
+
33
+					// Stolen from https://github.com/kevinswiber/siren spec
34
+					"actions" => array(
35
+						array(
36
+							"name" => "deploy",
37
+							"method" =>  "POST",
38
+							"href" => "$href/deploy",
39
+							"type" => "application/json",
40
+							"fields" => array(
41
+								array("name" => "release", "type" => "text"),
42
+							),
43
+						)
44
+					)
45
+				));
46
+			default:
47
+				return $this->message('API not found', 404);
48
+		}
49
+	}
50
+
51
+	/**
52
+	 * @param SS_HTTPRequest $request
53
+	 * @return SS_HTTPResponse
54
+	 */
55
+	public function ping(SS_HTTPRequest $request)
56
+	{
57
+		if (!$this->record->canView($this->getMember())) {
58
+			return $this->message('You are not authorized to do that on this environment', 403);
59
+		}
60
+		switch ($request->httpMethod()) {
61
+			case 'GET':
62
+				return $this->getPing($this->getRequest()->param('ID'));
63
+			case 'POST':
64
+				return $this->createPing();
65
+			default:
66
+				return $this->message('API not found', 404);
67
+		}
68
+	}
69
+
70
+	/**
71
+	 * @param SS_HTTPRequest $request
72
+	 * @return SS_HTTPResponse
73
+	 */
74
+	public function deploy(SS_HTTPRequest $request)
75
+	{
76
+		if (!$this->record->canView($this->getMember())) {
77
+			return $this->message('You are not authorized to do that on this environment', 403);
78
+		}
79
+		switch ($request->httpMethod()) {
80
+			case 'GET':
81
+				return $this->getDeploy($this->getRequest()->param('ID'));
82
+			case 'POST':
83
+				return $this->createDeploy();
84
+			default:
85
+				return $this->message('API not found', 404);
86
+		}
87
+	}
88
+
89
+	/**
90
+	 * @return string
91
+	 */
92
+	public function Link()
93
+	{
94
+		return Controller::join_links(
95
+			$this->parent->Link(),
96
+			$this->record->Project()->Name,
97
+			$this->record->Name
98
+		);
99
+	}
100
+
101
+	/**
102
+	 * @return SS_HTTPResponse
103
+	 */
104
+	protected function showRecord()
105
+	{
106
+		return $this->getAPIResponse($this->record->toMap());
107
+	}
108
+
109
+	/**
110
+	 * @return SS_HTTPResponse
111
+	 */
112
+	protected function createPing()
113
+	{
114
+		if (!$this->record->canDeploy($this->getMember())) {
115
+			return $this->message('You are not authorized to do that on this environment', 403);
116
+		}
117
+		$ping = DNPing::create();
118
+		$ping->EnvironmentID = $this->record->ID;
119
+		$ping->write();
120
+		$ping->start();
121
+
122
+		$location = Director::absoluteBaseURL() . $this->Link() . '/ping/' . $ping->ID;
123
+		$output = array(
124
+			'message' => 'Ping queued as job ' . $ping->ResqueToken,
125
+			'href' => $location,
126
+		);
127
+
128
+		$response = $this->getAPIResponse($output);
129
+		$response->setStatusCode(201);
130
+		$response->addHeader('Location', $location);
131
+		return $response;
132
+	}
133
+
134
+	/**
135
+	 * @param int $ID
136
+	 * @return SS_HTTPResponse
137
+	 */
138
+	protected function getPing($ID)
139
+	{
140
+		$ping = DNPing::get()->byID($ID);
141
+		if (!$ping) {
142
+			return $this->message('Ping not found', 404);
143
+		}
144
+		$output = array(
145
+			'status' => $ping->ResqueStatus(),
146
+			'message' => $ping->LogContent()
147
+		);
148
+
149
+		return $this->getAPIResponse($output);
150
+	}
151
+
152
+	/**
153
+	 * @return SS_HTTPResponse
154
+	 */
155
+	protected function createDeploy()
156
+	{
157
+		if (!$this->record->canDeploy($this->getMember())) {
158
+			return $this->message('You are not authorized to do that on this environment', 403);
159
+		}
160
+
161
+		$reqBody = $this->getRequestBody();
162
+
163
+		if ($reqBody === null) {
164
+			return $this->message('the request body did not contain a valid JSON object.', 400);
165
+		}
166
+
167
+		if (empty($reqBody['release'])) {
168
+			return $this->message('deploy requires a {"release": "sha1"} in the body of the request.', 400);
169
+		}
170
+
171
+		$strategy = new DeploymentStrategy($this->record, array(
172
+			'sha' => $reqBody['release']
173
+		));
174
+		$deploy = $strategy->createDeployment();
175
+		$deploy->start();
176
+		$location = Director::absoluteBaseURL() . $this->Link() . '/deploy/' . $deploy->ID;
177
+		$output = array(
178
+			'message' => 'Deploy queued as job ' . $deploy->ResqueToken,
179
+			'href' => $location,
180
+		);
181
+		$response = $this->getAPIResponse($output);
182
+		$response->setStatusCode(201);
183
+		$response->addHeader('Location', $location);
184
+		return $response;
185
+	}
186
+
187
+	/**
188
+	 * @param int $id
189
+	 * @return SS_HTTPResponse
190
+	 */
191
+	protected function getDeploy($id)
192
+	{
193
+		$deploy = DNDeployment::get()->byID($id);
194
+		if (!$deploy) {
195
+			return $this->message('Deploy not found', 404);
196
+		}
197
+		$output = array(
198
+			'status' => $deploy->ResqueStatus(),
199
+			'message' => $deploy->LogContent()
200
+		);
201
+
202
+		return $this->getAPIResponse($output);
203
+	}
204 204
 }
Please login to merge, or discard this patch.
code/api/nouns/APINoun.php 1 patch
Indentation   +114 added lines, -114 removed lines patch added patch discarded remove patch
@@ -1,131 +1,131 @@
 block discarded – undo
1 1
 <?php
2 2
 /**
3
- * Base class for the APINouns
4
- */
3
+	 * Base class for the APINouns
4
+	 */
5 5
 class APINoun extends Controller
6 6
 {
7 7
 
8
-    /**
9
-     * @var controller
10
-     */
11
-    protected $parent = null;
8
+	/**
9
+	 * @var controller
10
+	 */
11
+	protected $parent = null;
12 12
 
13
-    /**
14
-     * @var DataObject
15
-     */
16
-    protected $record = null;
13
+	/**
14
+	 * @var DataObject
15
+	 */
16
+	protected $record = null;
17 17
 
18
-    /**
19
-     * @var Member
20
-     */
21
-    protected $member = null;
18
+	/**
19
+	 * @var Member
20
+	 */
21
+	protected $member = null;
22 22
 
23
-    /**
24
-     * Holds the url segment for this admin
25
-     *
26
-     * @param Controller|null $parent
27
-     * @param DataObject|null $record
28
-     */
29
-    public function __construct(\Controller $parent = null, DataObject $record = null)
30
-    {
31
-        $this->record = $record;
32
-        $this->parent = $parent;
33
-        parent::__construct();
34
-    }
23
+	/**
24
+	 * Holds the url segment for this admin
25
+	 *
26
+	 * @param Controller|null $parent
27
+	 * @param DataObject|null $record
28
+	 */
29
+	public function __construct(\Controller $parent = null, DataObject $record = null)
30
+	{
31
+		$this->record = $record;
32
+		$this->parent = $parent;
33
+		parent::__construct();
34
+	}
35 35
 
36
-    /**
37
-     * Enable basic auth on the API
38
-     */
39
-    public function init()
40
-    {
41
-        $this->member = BasicAuth::requireLogin('Deploynaut API');
42
-        parent::init();
43
-    }
36
+	/**
37
+	 * Enable basic auth on the API
38
+	 */
39
+	public function init()
40
+	{
41
+		$this->member = BasicAuth::requireLogin('Deploynaut API');
42
+		parent::init();
43
+	}
44 44
 
45
-    /**
46
-     * @return DataObject
47
-     */
48
-    public function getRecord()
49
-    {
50
-        return $this->record;
51
-    }
45
+	/**
46
+	 * @return DataObject
47
+	 */
48
+	public function getRecord()
49
+	{
50
+		return $this->record;
51
+	}
52 52
 
53
-    /**
54
-     * @return Member
55
-     */
56
-    public function getMember()
57
-    {
58
-        return $this->member;
59
-    }
53
+	/**
54
+	 * @return Member
55
+	 */
56
+	public function getMember()
57
+	{
58
+		return $this->member;
59
+	}
60 60
 
61
-    /**
62
-     * @param array $output
63
-     * @return SS_HTTPResponse
64
-     */
65
-    protected function getAPIResponse($output)
66
-    {
67
-        $response = $this->getResponse();
68
-        if ($this->respondWithText()) {
69
-            $body = print_r($output, true);
70
-            $response->addHeader('Content-Type', 'text/plain');
71
-        } else {
72
-            $body = Convert::raw2json($output);
73
-            $response->addHeader('Content-Type', 'application/json');
74
-        }
75
-        $response->setBody($body);
76
-        return $response;
77
-    }
61
+	/**
62
+	 * @param array $output
63
+	 * @return SS_HTTPResponse
64
+	 */
65
+	protected function getAPIResponse($output)
66
+	{
67
+		$response = $this->getResponse();
68
+		if ($this->respondWithText()) {
69
+			$body = print_r($output, true);
70
+			$response->addHeader('Content-Type', 'text/plain');
71
+		} else {
72
+			$body = Convert::raw2json($output);
73
+			$response->addHeader('Content-Type', 'application/json');
74
+		}
75
+		$response->setBody($body);
76
+		return $response;
77
+	}
78 78
 
79
-    /**
80
-     * @return boolean
81
-     */
82
-    protected function respondWithJSON()
83
-    {
84
-        if ($this->getRequest()->getExtension() == 'json') {
85
-            return true;
86
-        }
87
-        if (strpos($this->getRequest()->getHeader('Accept'), 'application/json') !== false) {
88
-            return true;
89
-        }
90
-        return false;
91
-    }
79
+	/**
80
+	 * @return boolean
81
+	 */
82
+	protected function respondWithJSON()
83
+	{
84
+		if ($this->getRequest()->getExtension() == 'json') {
85
+			return true;
86
+		}
87
+		if (strpos($this->getRequest()->getHeader('Accept'), 'application/json') !== false) {
88
+			return true;
89
+		}
90
+		return false;
91
+	}
92 92
 
93
-    /**
94
-     * @return boolean
95
-     */
96
-    protected function respondWithText()
97
-    {
98
-        if ($this->getRequest()->getExtension() == 'txt') {
99
-            return true;
100
-        }
101
-        if (strpos($this->getRequest()->getHeader('Accept'), 'text/plain') !== false) {
102
-            return true;
103
-        }
104
-        return false;
105
-    }
93
+	/**
94
+	 * @return boolean
95
+	 */
96
+	protected function respondWithText()
97
+	{
98
+		if ($this->getRequest()->getExtension() == 'txt') {
99
+			return true;
100
+		}
101
+		if (strpos($this->getRequest()->getHeader('Accept'), 'text/plain') !== false) {
102
+			return true;
103
+		}
104
+		return false;
105
+	}
106 106
 
107
-    /**
108
-     * @return array|null
109
-     */
110
-    protected function getRequestBody()
111
-    {
112
-        return Convert::json2array($this->getRequest()->getBody());
113
-    }
107
+	/**
108
+	 * @return array|null
109
+	 */
110
+	protected function getRequestBody()
111
+	{
112
+		return Convert::json2array($this->getRequest()->getBody());
113
+	}
114 114
 
115
-    /**
116
-     * Return a simple response with a message
117
-     *
118
-     * @param string $message
119
-     * @param int $statusCode
120
-     * @return SS_HTTPResponse
121
-     */
122
-    protected function message($message, $statusCode)
123
-    {
124
-        $response = $this->getAPIResponse(array(
125
-            'message' => $message,
126
-            'statusCode' => $statusCode
127
-        ));
128
-        $response->setStatusCode($statusCode);
129
-        return $response;
130
-    }
115
+	/**
116
+	 * Return a simple response with a message
117
+	 *
118
+	 * @param string $message
119
+	 * @param int $statusCode
120
+	 * @return SS_HTTPResponse
121
+	 */
122
+	protected function message($message, $statusCode)
123
+	{
124
+		$response = $this->getAPIResponse(array(
125
+			'message' => $message,
126
+			'statusCode' => $statusCode
127
+		));
128
+		$response->setStatusCode($statusCode);
129
+		return $response;
130
+	}
131 131
 }
Please login to merge, or discard this patch.
code/api/nouns/APIProject.php 1 patch
Indentation   +101 added lines, -101 removed lines patch added patch discarded remove patch
@@ -3,115 +3,115 @@
 block discarded – undo
3 3
 class APIProject extends APINoun
4 4
 {
5 5
 
6
-    /**
7
-     * @var array
8
-     */
9
-    private static $allowed_actions = array(
10
-        'index',
11
-        'fetch'
12
-    );
6
+	/**
7
+	 * @var array
8
+	 */
9
+	private static $allowed_actions = array(
10
+		'index',
11
+		'fetch'
12
+	);
13 13
 
14
-    /**
15
-     * @param SS_HTTPRequest $request
16
-     * @return SS_HTTPResponse
17
-     */
18
-    public function index(SS_HTTPRequest $request)
19
-    {
20
-        if (!$this->record->canView($this->getMember())) {
21
-            return $this->message('You are not authorized to this environment', 403);
22
-        }
14
+	/**
15
+	 * @param SS_HTTPRequest $request
16
+	 * @return SS_HTTPResponse
17
+	 */
18
+	public function index(SS_HTTPRequest $request)
19
+	{
20
+		if (!$this->record->canView($this->getMember())) {
21
+			return $this->message('You are not authorized to this environment', 403);
22
+		}
23 23
 
24
-        switch ($request->httpMethod()) {
25
-            case 'GET':
26
-                $response = array(
27
-                    "name" => $this->record->Name,
28
-                    "href" => Director::absoluteURL($this->record->APILink("")),
29
-                    "created" => $this->record->Created,
30
-                    "last-edited" => $this->record->LastEdited,
31
-                    "disk-quota-mb" => $this->record->DiskQuotaMB,
32
-                    "environments" => array(),
33
-                );
34
-                foreach ($this->record->DNEnvironmentList() as $environment) {
35
-                    $response['environments'][] = array(
36
-                        'name' => $environment->Name,
37
-                        'href' => Director::absoluteURL($this->record->APILink($environment->Name)),
38
-                    );
39
-                }
24
+		switch ($request->httpMethod()) {
25
+			case 'GET':
26
+				$response = array(
27
+					"name" => $this->record->Name,
28
+					"href" => Director::absoluteURL($this->record->APILink("")),
29
+					"created" => $this->record->Created,
30
+					"last-edited" => $this->record->LastEdited,
31
+					"disk-quota-mb" => $this->record->DiskQuotaMB,
32
+					"environments" => array(),
33
+				);
34
+				foreach ($this->record->DNEnvironmentList() as $environment) {
35
+					$response['environments'][] = array(
36
+						'name' => $environment->Name,
37
+						'href' => Director::absoluteURL($this->record->APILink($environment->Name)),
38
+					);
39
+				}
40 40
 
41
-                return $this->getAPIResponse($response);
42
-            default:
43
-                return $this->message('API not found', 404);
44
-        }
45
-    }
41
+				return $this->getAPIResponse($response);
42
+			default:
43
+				return $this->message('API not found', 404);
44
+		}
45
+	}
46 46
 
47
-    /**
48
-     * @param SS_HTTPRequest $request
49
-     * @return SS_HTTPResponse
50
-     */
51
-    public function fetch(SS_HTTPRequest $request)
52
-    {
53
-        if (!$this->record->canView($this->getMember())) {
54
-            return $this->message('You are not authorized to do that on this environment', 403);
55
-        }
56
-        switch ($request->httpMethod()) {
57
-            case 'GET':
58
-                return $this->getFetch($this->getRequest()->param('ID'));
59
-            case 'POST':
60
-                return $this->createFetch();
61
-            default:
62
-                return $this->message('API not found', 404);
63
-        }
64
-    }
47
+	/**
48
+	 * @param SS_HTTPRequest $request
49
+	 * @return SS_HTTPResponse
50
+	 */
51
+	public function fetch(SS_HTTPRequest $request)
52
+	{
53
+		if (!$this->record->canView($this->getMember())) {
54
+			return $this->message('You are not authorized to do that on this environment', 403);
55
+		}
56
+		switch ($request->httpMethod()) {
57
+			case 'GET':
58
+				return $this->getFetch($this->getRequest()->param('ID'));
59
+			case 'POST':
60
+				return $this->createFetch();
61
+			default:
62
+				return $this->message('API not found', 404);
63
+		}
64
+	}
65 65
 
66
-    /**
67
-     * @param int $ID
68
-     * @return SS_HTTPResponse
69
-     */
70
-    protected function getFetch($ID)
71
-    {
72
-        $ping = DNGitFetch::get()->byID($ID);
73
-        if (!$ping) {
74
-            return $this->message('Fetch not found', 404);
75
-        }
76
-        $output = array(
77
-            'status' => $ping->ResqueStatus(),
78
-            'message' => $ping->LogContent()
79
-        );
66
+	/**
67
+	 * @param int $ID
68
+	 * @return SS_HTTPResponse
69
+	 */
70
+	protected function getFetch($ID)
71
+	{
72
+		$ping = DNGitFetch::get()->byID($ID);
73
+		if (!$ping) {
74
+			return $this->message('Fetch not found', 404);
75
+		}
76
+		$output = array(
77
+			'status' => $ping->ResqueStatus(),
78
+			'message' => $ping->LogContent()
79
+		);
80 80
 
81
-        return $this->getAPIResponse($output);
82
-    }
81
+		return $this->getAPIResponse($output);
82
+	}
83 83
 
84
-    /**
85
-     * @return SS_HTTPResponse
86
-     */
87
-    protected function createFetch()
88
-    {
89
-        /** @var DNGitFetch $fetch */
90
-        $fetch = DNGitFetch::create();
91
-        $fetch->ProjectID = $this->record->ID;
92
-        $fetch->write();
93
-        $fetch->start();
84
+	/**
85
+	 * @return SS_HTTPResponse
86
+	 */
87
+	protected function createFetch()
88
+	{
89
+		/** @var DNGitFetch $fetch */
90
+		$fetch = DNGitFetch::create();
91
+		$fetch->ProjectID = $this->record->ID;
92
+		$fetch->write();
93
+		$fetch->start();
94 94
 
95
-        $location = Director::absoluteBaseURL() . $this->Link() . '/fetch/' . $fetch->ID;
96
-        $output = array(
97
-            'message' => 'Fetch queued as job ' . $fetch->ResqueToken,
98
-            'href' => $location,
99
-        );
95
+		$location = Director::absoluteBaseURL() . $this->Link() . '/fetch/' . $fetch->ID;
96
+		$output = array(
97
+			'message' => 'Fetch queued as job ' . $fetch->ResqueToken,
98
+			'href' => $location,
99
+		);
100 100
 
101
-        $response = $this->getAPIResponse($output);
102
-        $response->setStatusCode(201);
103
-        $response->addHeader('Location', $location);
104
-        return $response;
105
-    }
101
+		$response = $this->getAPIResponse($output);
102
+		$response->setStatusCode(201);
103
+		$response->addHeader('Location', $location);
104
+		return $response;
105
+	}
106 106
 
107
-    /**
108
-     * @return string
109
-     */
110
-    public function Link()
111
-    {
112
-        return Controller::join_links(
113
-            $this->parent->Link(),
114
-            $this->record->Name
115
-        );
116
-    }
107
+	/**
108
+	 * @return string
109
+	 */
110
+	public function Link()
111
+	{
112
+		return Controller::join_links(
113
+			$this->parent->Link(),
114
+			$this->record->Name
115
+		);
116
+	}
117 117
 }
Please login to merge, or discard this patch.
code/backends/CapistranoDeploymentBackend.php 1 patch
Indentation   +423 added lines, -423 removed lines patch added patch discarded remove patch
@@ -4,427 +4,427 @@
 block discarded – undo
4 4
 class CapistranoDeploymentBackend extends Object implements DeploymentBackend
5 5
 {
6 6
 
7
-    protected $packageGenerator;
8
-
9
-    public function getPackageGenerator()
10
-    {
11
-        return $this->packageGenerator;
12
-    }
13
-
14
-    public function setPackageGenerator(PackageGenerator $packageGenerator)
15
-    {
16
-        $this->packageGenerator = $packageGenerator;
17
-    }
18
-
19
-    /**
20
-     * Create a deployment strategy.
21
-     *
22
-     * @param DNEnvironment $environment
23
-     * @param array $options
24
-     *
25
-     * @return DeploymentStrategy
26
-     */
27
-    public function planDeploy(DNEnvironment $environment, $options)
28
-    {
29
-        $strategy = new DeploymentStrategy($environment, $options);
30
-
31
-        $currentBuild = $environment->CurrentBuild();
32
-        $currentSha = $currentBuild ? $currentBuild->SHA : '-';
33
-        if ($currentSha !== $options['sha']) {
34
-            $strategy->setChange('Code version', $currentSha, $options['sha']);
35
-        }
36
-        $strategy->setActionTitle('Confirm deployment');
37
-        $strategy->setActionCode('fast');
38
-        $strategy->setEstimatedTime('2');
39
-
40
-        return $strategy;
41
-    }
42
-
43
-    /**
44
-     * Deploy the given build to the given environment.
45
-     *
46
-     * @param DNEnvironment $environment
47
-     * @param DeploynautLogFile $log
48
-     * @param DNProject $project
49
-     * @param array $options
50
-     */
51
-    public function deploy(
52
-        DNEnvironment $environment,
53
-        DeploynautLogFile $log,
54
-        DNProject $project,
55
-        $options
56
-    ) {
57
-        $name = $environment->getFullName();
58
-        $repository = $project->getLocalCVSPath();
59
-        $sha = $options['sha'];
60
-
61
-        $args = array(
62
-            'branch' => $sha,
63
-            'repository' => $repository,
64
-        );
65
-
66
-        $this->extend('deployStart', $environment, $sha, $log, $project);
67
-
68
-        $log->write(sprintf('Deploying "%s" to "%s"', $sha, $name));
69
-
70
-        $this->enableMaintenance($environment, $log, $project);
71
-
72
-        // Use a package generator if specified, otherwise run a direct deploy, which is the default behaviour
73
-        // if build_filename isn't specified
74
-        if ($this->packageGenerator) {
75
-            $log->write(sprintf('Using package generator "%s"', get_class($this->packageGenerator)));
76
-
77
-            try {
78
-                $args['build_filename'] = $this->packageGenerator->getPackageFilename($project->Name, $sha, $repository, $log);
79
-            } catch (Exception $e) {
80
-                $log->write($e->getMessage());
81
-                throw $e;
82
-            }
83
-
84
-            if (empty($args['build_filename'])) {
85
-                throw new RuntimeException('Failed to generate package.');
86
-            }
87
-        }
88
-
89
-        $command = $this->getCommand('deploy', 'web', $environment, $args, $log);
90
-        $command->run(function ($type, $buffer) use ($log) {
91
-            $log->write($buffer);
92
-        });
93
-
94
-        // Deployment cleanup. We assume it is always safe to run this at the end, regardless of the outcome.
95
-        $self = $this;
96
-        $cleanupFn = function () use ($self, $environment, $args, $log) {
97
-            $command = $self->getCommand('deploy:cleanup', 'web', $environment, $args, $log);
98
-            $command->run(function ($type, $buffer) use ($log) {
99
-                $log->write($buffer);
100
-            });
101
-
102
-            if (!$command->isSuccessful()) {
103
-                $this->extend('cleanupFailure', $environment, $sha, $log, $project);
104
-                $log->write('Warning: Cleanup failed, but fine to continue. Needs manual cleanup sometime.');
105
-            }
106
-        };
107
-
108
-        // Once the deployment has run it's necessary to update the maintenance page status
109
-        if (!empty($options['leaveMaintenancePage'])) {
110
-            $this->enableMaintenance($environment, $log, $project);
111
-        }
112
-
113
-        if (!$command->isSuccessful()) {
114
-            $cleanupFn();
115
-            $this->extend('deployFailure', $environment, $sha, $log, $project);
116
-            throw new RuntimeException($command->getErrorOutput());
117
-        }
118
-
119
-        // Check if maintenance page should be removed
120
-        if (empty($options['leaveMaintenancePage'])) {
121
-            $this->disableMaintenance($environment, $log, $project);
122
-        }
123
-
124
-        $cleanupFn();
125
-
126
-        $log->write(sprintf('Deploy of "%s" to "%s" finished', $sha, $name));
127
-
128
-        $this->extend('deployEnd', $environment, $sha, $log, $project);
129
-    }
130
-
131
-    /**
132
-     * Enable a maintenance page for the given environment using the maintenance:enable Capistrano task.
133
-     */
134
-    public function enableMaintenance(DNEnvironment $environment, DeploynautLogFile $log, DNProject $project)
135
-    {
136
-        $name = $environment->getFullName();
137
-        $command = $this->getCommand('maintenance:enable', 'web', $environment, null, $log);
138
-        $command->run(function ($type, $buffer) use ($log) {
139
-            $log->write($buffer);
140
-        });
141
-        if (!$command->isSuccessful()) {
142
-            $this->extend('maintenanceEnableFailure', $environment, $log);
143
-            throw new RuntimeException($command->getErrorOutput());
144
-        }
145
-        $log->write(sprintf('Maintenance page enabled on "%s"', $name));
146
-    }
147
-
148
-    /**
149
-     * Disable the maintenance page for the given environment using the maintenance:disable Capistrano task.
150
-     */
151
-    public function disableMaintenance(DNEnvironment $environment, DeploynautLogFile $log, DNProject $project)
152
-    {
153
-        $name = $environment->getFullName();
154
-        $command = $this->getCommand('maintenance:disable', 'web', $environment, null, $log);
155
-        $command->run(function ($type, $buffer) use ($log) {
156
-            $log->write($buffer);
157
-        });
158
-        if (!$command->isSuccessful()) {
159
-            $this->extend('maintenanceDisableFailure', $environment, $log);
160
-            throw new RuntimeException($command->getErrorOutput());
161
-        }
162
-        $log->write(sprintf('Maintenance page disabled on "%s"', $name));
163
-    }
164
-
165
-    /**
166
-     * Check the status using the deploy:check capistrano method
167
-     */
168
-    public function ping(DNEnvironment $environment, DeploynautLogFile $log, DNProject $project)
169
-    {
170
-        $command = $this->getCommand('deploy:check', 'web', $environment, null, $log);
171
-        $command->run(function ($type, $buffer) use ($log) {
172
-            $log->write($buffer);
173
-            echo $buffer;
174
-        });
175
-    }
176
-
177
-    /**
178
-     * @inheritdoc
179
-     */
180
-    public function dataTransfer(DNDataTransfer $dataTransfer, DeploynautLogFile $log)
181
-    {
182
-        if ($dataTransfer->Direction == 'get') {
183
-            $this->dataTransferBackup($dataTransfer, $log);
184
-        } else {
185
-            $environment = $dataTransfer->Environment();
186
-            $project = $environment->Project();
187
-            $workingDir = TEMP_FOLDER . DIRECTORY_SEPARATOR . 'deploynaut-transfer-' . $dataTransfer->ID;
188
-            $archive = $dataTransfer->DataArchive();
189
-
190
-            // extract the sspak contents, we'll need these so capistrano can restore that content
191
-            try {
192
-                $archive->extractArchive($workingDir);
193
-            } catch (Exception $e) {
194
-                $log->write($e->getMessage());
195
-                throw new RuntimeException($e->getMessage());
196
-            }
197
-
198
-            // validate the contents match the requested transfer mode
199
-            $result = $archive->validateArchiveContents($dataTransfer->Mode);
200
-            if (!$result->valid()) {
201
-                // do some cleaning, get rid of the extracted archive lying around
202
-                $process = new Process(sprintf('rm -rf %s', escapeshellarg($workingDir)));
203
-                $process->run();
204
-
205
-                // log the reason why we can't restore the snapshot and halt the process
206
-                $log->write($result->message());
207
-                throw new RuntimeException($result->message());
208
-            }
209
-
210
-            // Put up a maintenance page during a restore of db or assets.
211
-            $this->enableMaintenance($environment, $log, $project);
212
-            $this->dataTransferRestore($workingDir, $dataTransfer, $log);
213
-            $this->disableMaintenance($environment, $log, $project);
214
-        }
215
-    }
216
-
217
-    /**
218
-     * @param string $action Capistrano action to be executed
219
-     * @param string $roles Defining a server role is required to target only the required servers.
220
-     * @param DNEnvironment $environment
221
-     * @param array<string>|null $args Additional arguments for process
222
-     * @param DeploynautLogFile $log
223
-     * @return \Symfony\Component\Process\Process
224
-     */
225
-    public function getCommand($action, $roles, DNEnvironment $environment, $args = null, DeploynautLogFile $log)
226
-    {
227
-        $name = $environment->getFullName();
228
-        $env = $environment->Project()->getProcessEnv();
229
-
230
-        if (!$args) {
231
-            $args = array();
232
-        }
233
-        $args['history_path'] = realpath(DEPLOYNAUT_LOG_PATH . '/');
234
-
235
-        // Inject env string directly into the command.
236
-        // Capistrano doesn't like the $process->setEnv($env) we'd normally do below.
237
-        $envString = '';
238
-        if (!empty($env)) {
239
-            $envString .= 'env ';
240
-            foreach ($env as $key => $value) {
241
-                $envString .= "$key=\"$value\" ";
242
-            }
243
-        }
244
-
245
-        $data = DNData::inst();
246
-        // Generate a capfile from a template
247
-        $capTemplate = file_get_contents(BASE_PATH . '/deploynaut/Capfile.template');
248
-        $cap = str_replace(
249
-            array('<config root>', '<ssh key>', '<base path>'),
250
-            array($data->getEnvironmentDir(), DEPLOYNAUT_SSH_KEY, BASE_PATH),
251
-            $capTemplate
252
-        );
253
-
254
-        if (defined('DEPLOYNAUT_CAPFILE')) {
255
-            $capFile = DEPLOYNAUT_CAPFILE;
256
-        } else {
257
-            $capFile = ASSETS_PATH . '/Capfile';
258
-        }
259
-        file_put_contents($capFile, $cap);
260
-
261
-        $command = "{$envString}cap -f " . escapeshellarg($capFile) . " -vv $name $action ROLES=$roles";
262
-        foreach ($args as $argName => $argVal) {
263
-            $command .= ' -s ' . escapeshellarg($argName) . '=' . escapeshellarg($argVal);
264
-        }
265
-
266
-        $log->write(sprintf('Running command: %s', $command));
267
-
268
-        $process = new Process($command);
269
-        $process->setTimeout(3600);
270
-        return $process;
271
-    }
272
-
273
-    /**
274
-     * Backs up database and/or assets to a designated folder,
275
-     * and packs up the files into a single sspak.
276
-     *
277
-     * @param DNDataTransfer    $dataTransfer
278
-     * @param DeploynautLogFile $log
279
-     */
280
-    protected function dataTransferBackup(DNDataTransfer $dataTransfer, DeploynautLogFile $log)
281
-    {
282
-        $environment = $dataTransfer->Environment();
283
-        $name = $environment->getFullName();
284
-
285
-        // Associate a new archive with the transfer.
286
-        // Doesn't retrieve a filepath just yet, need to generate the files first.
287
-        $dataArchive = DNDataArchive::create();
288
-        $dataArchive->Mode = $dataTransfer->Mode;
289
-        $dataArchive->AuthorID = $dataTransfer->AuthorID;
290
-        $dataArchive->OriginalEnvironmentID = $environment->ID;
291
-        $dataArchive->EnvironmentID = $environment->ID;
292
-        $dataArchive->IsBackup = $dataTransfer->IsBackupDataTransfer();
293
-
294
-        // Generate directory structure with strict permissions (contains very sensitive data)
295
-        $filepathBase = $dataArchive->generateFilepath($dataTransfer);
296
-        mkdir($filepathBase, 0700, true);
297
-
298
-        $databasePath = $filepathBase . DIRECTORY_SEPARATOR . 'database.sql';
299
-
300
-        // Backup database
301
-        if (in_array($dataTransfer->Mode, array('all', 'db'))) {
302
-            $log->write(sprintf('Backup of database from "%s" started', $name));
303
-            $command = $this->getCommand('data:getdb', 'db', $environment, array('data_path' => $databasePath), $log);
304
-            $command->run(function ($type, $buffer) use ($log) {
305
-                $log->write($buffer);
306
-            });
307
-            if (!$command->isSuccessful()) {
308
-                $this->extend('dataTransferFailure', $environment, $log);
309
-                throw new RuntimeException($command->getErrorOutput());
310
-            }
311
-            $log->write(sprintf('Backup of database from "%s" done', $name));
312
-        }
313
-
314
-        // Backup assets
315
-        if (in_array($dataTransfer->Mode, array('all', 'assets'))) {
316
-            $log->write(sprintf('Backup of assets from "%s" started', $name));
317
-            $command = $this->getCommand('data:getassets', 'web', $environment, array('data_path' => $filepathBase), $log);
318
-            $command->run(function ($type, $buffer) use ($log) {
319
-                $log->write($buffer);
320
-            });
321
-            if (!$command->isSuccessful()) {
322
-                $this->extend('dataTransferFailure', $environment, $log);
323
-                throw new RuntimeException($command->getErrorOutput());
324
-            }
325
-            $log->write(sprintf('Backup of assets from "%s" done', $name));
326
-        }
327
-
328
-        $sspakFilename = sprintf('%s.sspak', $dataArchive->generateFilename($dataTransfer));
329
-        $sspakFilepath = $filepathBase . DIRECTORY_SEPARATOR . $sspakFilename;
330
-
331
-        try {
332
-            $dataArchive->attachFile($sspakFilepath, $dataTransfer);
333
-            $dataArchive->setArchiveFromFiles($filepathBase);
334
-        } catch (Exception $e) {
335
-            $log->write($e->getMessage());
336
-            throw new RuntimeException($e->getMessage());
337
-        }
338
-
339
-        // Remove any assets and db files lying around, they're not longer needed as they're now part
340
-        // of the sspak file we just generated. Use --force to avoid errors when files don't exist,
341
-        // e.g. when just an assets backup has been requested and no database.sql exists.
342
-        $process = new Process(sprintf('rm -rf %s/assets && rm -f %s', $filepathBase, $databasePath));
343
-        $process->run();
344
-        if (!$process->isSuccessful()) {
345
-            $log->write('Could not delete temporary files');
346
-            throw new RuntimeException($process->getErrorOutput());
347
-        }
348
-
349
-        $log->write(sprintf('Creating sspak file done: %s', $dataArchive->ArchiveFile()->getAbsoluteURL()));
350
-    }
351
-
352
-    /**
353
-     * Utility function for triggering the db rebuild and flush.
354
-     * Also cleans up and generates new error pages.
355
-     * @param DeploynautLogFile $log
356
-     */
357
-    public function rebuild(DNEnvironment $environment, $log)
358
-    {
359
-        $name = $environment->getFullName();
360
-        $command = $this->getCommand('deploy:migrate', 'web', $environment, null, $log);
361
-        $command->run(function ($type, $buffer) use ($log) {
362
-            $log->write($buffer);
363
-        });
364
-        if (!$command->isSuccessful()) {
365
-            $log->write(sprintf('Rebuild of "%s" failed: %s', $name, $command->getErrorOutput()));
366
-            throw new RuntimeException($command->getErrorOutput());
367
-        }
368
-        $log->write(sprintf('Rebuild of "%s" done', $name));
369
-    }
370
-
371
-    /**
372
-     * Extracts a *.sspak file referenced through the passed in $dataTransfer
373
-     * and pushes it to the environment referenced in $dataTransfer.
374
-     *
375
-     * @param string $workingDir Directory for the unpacked files.
376
-     * @param DNDataTransfer $dataTransfer
377
-     * @param DeploynautLogFile $log
378
-     */
379
-    protected function dataTransferRestore($workingDir, DNDataTransfer $dataTransfer, DeploynautLogFile $log)
380
-    {
381
-        $environment = $dataTransfer->Environment();
382
-        $name = $environment->getFullName();
383
-
384
-        // Rollback cleanup.
385
-        $self = $this;
386
-        $cleanupFn = function () use ($self, $workingDir, $environment, $log) {
387
-            // Rebuild makes sense even if failed - maybe we can at least partly recover.
388
-            $self->rebuild($environment, $log);
389
-            $process = new Process(sprintf('rm -rf %s', escapeshellarg($workingDir)));
390
-            $process->run();
391
-        };
392
-
393
-        // Restore database into target environment
394
-        if (in_array($dataTransfer->Mode, array('all', 'db'))) {
395
-            $log->write(sprintf('Restore of database to "%s" started', $name));
396
-            $args = array('data_path' => $workingDir . DIRECTORY_SEPARATOR . 'database.sql');
397
-            $command = $this->getCommand('data:pushdb', 'db', $environment, $args, $log);
398
-            $command->run(function ($type, $buffer) use ($log) {
399
-                $log->write($buffer);
400
-            });
401
-            if (!$command->isSuccessful()) {
402
-                $cleanupFn();
403
-                $log->write(sprintf('Restore of database to "%s" failed: %s', $name, $command->getErrorOutput()));
404
-                $this->extend('dataTransferFailure', $environment, $log);
405
-                throw new RuntimeException($command->getErrorOutput());
406
-            }
407
-            $log->write(sprintf('Restore of database to "%s" done', $name));
408
-        }
409
-
410
-        // Restore assets into target environment
411
-        if (in_array($dataTransfer->Mode, array('all', 'assets'))) {
412
-            $log->write(sprintf('Restore of assets to "%s" started', $name));
413
-            $args = array('data_path' => $workingDir . DIRECTORY_SEPARATOR . 'assets');
414
-            $command = $this->getCommand('data:pushassets', 'web', $environment, $args, $log);
415
-            $command->run(function ($type, $buffer) use ($log) {
416
-                $log->write($buffer);
417
-            });
418
-            if (!$command->isSuccessful()) {
419
-                $cleanupFn();
420
-                $log->write(sprintf('Restore of assets to "%s" failed: %s', $name, $command->getErrorOutput()));
421
-                $this->extend('dataTransferFailure', $environment, $log);
422
-                throw new RuntimeException($command->getErrorOutput());
423
-            }
424
-            $log->write(sprintf('Restore of assets to "%s" done', $name));
425
-        }
426
-
427
-        $log->write('Rebuilding and cleaning up');
428
-        $cleanupFn();
429
-    }
7
+	protected $packageGenerator;
8
+
9
+	public function getPackageGenerator()
10
+	{
11
+		return $this->packageGenerator;
12
+	}
13
+
14
+	public function setPackageGenerator(PackageGenerator $packageGenerator)
15
+	{
16
+		$this->packageGenerator = $packageGenerator;
17
+	}
18
+
19
+	/**
20
+	 * Create a deployment strategy.
21
+	 *
22
+	 * @param DNEnvironment $environment
23
+	 * @param array $options
24
+	 *
25
+	 * @return DeploymentStrategy
26
+	 */
27
+	public function planDeploy(DNEnvironment $environment, $options)
28
+	{
29
+		$strategy = new DeploymentStrategy($environment, $options);
30
+
31
+		$currentBuild = $environment->CurrentBuild();
32
+		$currentSha = $currentBuild ? $currentBuild->SHA : '-';
33
+		if ($currentSha !== $options['sha']) {
34
+			$strategy->setChange('Code version', $currentSha, $options['sha']);
35
+		}
36
+		$strategy->setActionTitle('Confirm deployment');
37
+		$strategy->setActionCode('fast');
38
+		$strategy->setEstimatedTime('2');
39
+
40
+		return $strategy;
41
+	}
42
+
43
+	/**
44
+	 * Deploy the given build to the given environment.
45
+	 *
46
+	 * @param DNEnvironment $environment
47
+	 * @param DeploynautLogFile $log
48
+	 * @param DNProject $project
49
+	 * @param array $options
50
+	 */
51
+	public function deploy(
52
+		DNEnvironment $environment,
53
+		DeploynautLogFile $log,
54
+		DNProject $project,
55
+		$options
56
+	) {
57
+		$name = $environment->getFullName();
58
+		$repository = $project->getLocalCVSPath();
59
+		$sha = $options['sha'];
60
+
61
+		$args = array(
62
+			'branch' => $sha,
63
+			'repository' => $repository,
64
+		);
65
+
66
+		$this->extend('deployStart', $environment, $sha, $log, $project);
67
+
68
+		$log->write(sprintf('Deploying "%s" to "%s"', $sha, $name));
69
+
70
+		$this->enableMaintenance($environment, $log, $project);
71
+
72
+		// Use a package generator if specified, otherwise run a direct deploy, which is the default behaviour
73
+		// if build_filename isn't specified
74
+		if ($this->packageGenerator) {
75
+			$log->write(sprintf('Using package generator "%s"', get_class($this->packageGenerator)));
76
+
77
+			try {
78
+				$args['build_filename'] = $this->packageGenerator->getPackageFilename($project->Name, $sha, $repository, $log);
79
+			} catch (Exception $e) {
80
+				$log->write($e->getMessage());
81
+				throw $e;
82
+			}
83
+
84
+			if (empty($args['build_filename'])) {
85
+				throw new RuntimeException('Failed to generate package.');
86
+			}
87
+		}
88
+
89
+		$command = $this->getCommand('deploy', 'web', $environment, $args, $log);
90
+		$command->run(function ($type, $buffer) use ($log) {
91
+			$log->write($buffer);
92
+		});
93
+
94
+		// Deployment cleanup. We assume it is always safe to run this at the end, regardless of the outcome.
95
+		$self = $this;
96
+		$cleanupFn = function () use ($self, $environment, $args, $log) {
97
+			$command = $self->getCommand('deploy:cleanup', 'web', $environment, $args, $log);
98
+			$command->run(function ($type, $buffer) use ($log) {
99
+				$log->write($buffer);
100
+			});
101
+
102
+			if (!$command->isSuccessful()) {
103
+				$this->extend('cleanupFailure', $environment, $sha, $log, $project);
104
+				$log->write('Warning: Cleanup failed, but fine to continue. Needs manual cleanup sometime.');
105
+			}
106
+		};
107
+
108
+		// Once the deployment has run it's necessary to update the maintenance page status
109
+		if (!empty($options['leaveMaintenancePage'])) {
110
+			$this->enableMaintenance($environment, $log, $project);
111
+		}
112
+
113
+		if (!$command->isSuccessful()) {
114
+			$cleanupFn();
115
+			$this->extend('deployFailure', $environment, $sha, $log, $project);
116
+			throw new RuntimeException($command->getErrorOutput());
117
+		}
118
+
119
+		// Check if maintenance page should be removed
120
+		if (empty($options['leaveMaintenancePage'])) {
121
+			$this->disableMaintenance($environment, $log, $project);
122
+		}
123
+
124
+		$cleanupFn();
125
+
126
+		$log->write(sprintf('Deploy of "%s" to "%s" finished', $sha, $name));
127
+
128
+		$this->extend('deployEnd', $environment, $sha, $log, $project);
129
+	}
130
+
131
+	/**
132
+	 * Enable a maintenance page for the given environment using the maintenance:enable Capistrano task.
133
+	 */
134
+	public function enableMaintenance(DNEnvironment $environment, DeploynautLogFile $log, DNProject $project)
135
+	{
136
+		$name = $environment->getFullName();
137
+		$command = $this->getCommand('maintenance:enable', 'web', $environment, null, $log);
138
+		$command->run(function ($type, $buffer) use ($log) {
139
+			$log->write($buffer);
140
+		});
141
+		if (!$command->isSuccessful()) {
142
+			$this->extend('maintenanceEnableFailure', $environment, $log);
143
+			throw new RuntimeException($command->getErrorOutput());
144
+		}
145
+		$log->write(sprintf('Maintenance page enabled on "%s"', $name));
146
+	}
147
+
148
+	/**
149
+	 * Disable the maintenance page for the given environment using the maintenance:disable Capistrano task.
150
+	 */
151
+	public function disableMaintenance(DNEnvironment $environment, DeploynautLogFile $log, DNProject $project)
152
+	{
153
+		$name = $environment->getFullName();
154
+		$command = $this->getCommand('maintenance:disable', 'web', $environment, null, $log);
155
+		$command->run(function ($type, $buffer) use ($log) {
156
+			$log->write($buffer);
157
+		});
158
+		if (!$command->isSuccessful()) {
159
+			$this->extend('maintenanceDisableFailure', $environment, $log);
160
+			throw new RuntimeException($command->getErrorOutput());
161
+		}
162
+		$log->write(sprintf('Maintenance page disabled on "%s"', $name));
163
+	}
164
+
165
+	/**
166
+	 * Check the status using the deploy:check capistrano method
167
+	 */
168
+	public function ping(DNEnvironment $environment, DeploynautLogFile $log, DNProject $project)
169
+	{
170
+		$command = $this->getCommand('deploy:check', 'web', $environment, null, $log);
171
+		$command->run(function ($type, $buffer) use ($log) {
172
+			$log->write($buffer);
173
+			echo $buffer;
174
+		});
175
+	}
176
+
177
+	/**
178
+	 * @inheritdoc
179
+	 */
180
+	public function dataTransfer(DNDataTransfer $dataTransfer, DeploynautLogFile $log)
181
+	{
182
+		if ($dataTransfer->Direction == 'get') {
183
+			$this->dataTransferBackup($dataTransfer, $log);
184
+		} else {
185
+			$environment = $dataTransfer->Environment();
186
+			$project = $environment->Project();
187
+			$workingDir = TEMP_FOLDER . DIRECTORY_SEPARATOR . 'deploynaut-transfer-' . $dataTransfer->ID;
188
+			$archive = $dataTransfer->DataArchive();
189
+
190
+			// extract the sspak contents, we'll need these so capistrano can restore that content
191
+			try {
192
+				$archive->extractArchive($workingDir);
193
+			} catch (Exception $e) {
194
+				$log->write($e->getMessage());
195
+				throw new RuntimeException($e->getMessage());
196
+			}
197
+
198
+			// validate the contents match the requested transfer mode
199
+			$result = $archive->validateArchiveContents($dataTransfer->Mode);
200
+			if (!$result->valid()) {
201
+				// do some cleaning, get rid of the extracted archive lying around
202
+				$process = new Process(sprintf('rm -rf %s', escapeshellarg($workingDir)));
203
+				$process->run();
204
+
205
+				// log the reason why we can't restore the snapshot and halt the process
206
+				$log->write($result->message());
207
+				throw new RuntimeException($result->message());
208
+			}
209
+
210
+			// Put up a maintenance page during a restore of db or assets.
211
+			$this->enableMaintenance($environment, $log, $project);
212
+			$this->dataTransferRestore($workingDir, $dataTransfer, $log);
213
+			$this->disableMaintenance($environment, $log, $project);
214
+		}
215
+	}
216
+
217
+	/**
218
+	 * @param string $action Capistrano action to be executed
219
+	 * @param string $roles Defining a server role is required to target only the required servers.
220
+	 * @param DNEnvironment $environment
221
+	 * @param array<string>|null $args Additional arguments for process
222
+	 * @param DeploynautLogFile $log
223
+	 * @return \Symfony\Component\Process\Process
224
+	 */
225
+	public function getCommand($action, $roles, DNEnvironment $environment, $args = null, DeploynautLogFile $log)
226
+	{
227
+		$name = $environment->getFullName();
228
+		$env = $environment->Project()->getProcessEnv();
229
+
230
+		if (!$args) {
231
+			$args = array();
232
+		}
233
+		$args['history_path'] = realpath(DEPLOYNAUT_LOG_PATH . '/');
234
+
235
+		// Inject env string directly into the command.
236
+		// Capistrano doesn't like the $process->setEnv($env) we'd normally do below.
237
+		$envString = '';
238
+		if (!empty($env)) {
239
+			$envString .= 'env ';
240
+			foreach ($env as $key => $value) {
241
+				$envString .= "$key=\"$value\" ";
242
+			}
243
+		}
244
+
245
+		$data = DNData::inst();
246
+		// Generate a capfile from a template
247
+		$capTemplate = file_get_contents(BASE_PATH . '/deploynaut/Capfile.template');
248
+		$cap = str_replace(
249
+			array('<config root>', '<ssh key>', '<base path>'),
250
+			array($data->getEnvironmentDir(), DEPLOYNAUT_SSH_KEY, BASE_PATH),
251
+			$capTemplate
252
+		);
253
+
254
+		if (defined('DEPLOYNAUT_CAPFILE')) {
255
+			$capFile = DEPLOYNAUT_CAPFILE;
256
+		} else {
257
+			$capFile = ASSETS_PATH . '/Capfile';
258
+		}
259
+		file_put_contents($capFile, $cap);
260
+
261
+		$command = "{$envString}cap -f " . escapeshellarg($capFile) . " -vv $name $action ROLES=$roles";
262
+		foreach ($args as $argName => $argVal) {
263
+			$command .= ' -s ' . escapeshellarg($argName) . '=' . escapeshellarg($argVal);
264
+		}
265
+
266
+		$log->write(sprintf('Running command: %s', $command));
267
+
268
+		$process = new Process($command);
269
+		$process->setTimeout(3600);
270
+		return $process;
271
+	}
272
+
273
+	/**
274
+	 * Backs up database and/or assets to a designated folder,
275
+	 * and packs up the files into a single sspak.
276
+	 *
277
+	 * @param DNDataTransfer    $dataTransfer
278
+	 * @param DeploynautLogFile $log
279
+	 */
280
+	protected function dataTransferBackup(DNDataTransfer $dataTransfer, DeploynautLogFile $log)
281
+	{
282
+		$environment = $dataTransfer->Environment();
283
+		$name = $environment->getFullName();
284
+
285
+		// Associate a new archive with the transfer.
286
+		// Doesn't retrieve a filepath just yet, need to generate the files first.
287
+		$dataArchive = DNDataArchive::create();
288
+		$dataArchive->Mode = $dataTransfer->Mode;
289
+		$dataArchive->AuthorID = $dataTransfer->AuthorID;
290
+		$dataArchive->OriginalEnvironmentID = $environment->ID;
291
+		$dataArchive->EnvironmentID = $environment->ID;
292
+		$dataArchive->IsBackup = $dataTransfer->IsBackupDataTransfer();
293
+
294
+		// Generate directory structure with strict permissions (contains very sensitive data)
295
+		$filepathBase = $dataArchive->generateFilepath($dataTransfer);
296
+		mkdir($filepathBase, 0700, true);
297
+
298
+		$databasePath = $filepathBase . DIRECTORY_SEPARATOR . 'database.sql';
299
+
300
+		// Backup database
301
+		if (in_array($dataTransfer->Mode, array('all', 'db'))) {
302
+			$log->write(sprintf('Backup of database from "%s" started', $name));
303
+			$command = $this->getCommand('data:getdb', 'db', $environment, array('data_path' => $databasePath), $log);
304
+			$command->run(function ($type, $buffer) use ($log) {
305
+				$log->write($buffer);
306
+			});
307
+			if (!$command->isSuccessful()) {
308
+				$this->extend('dataTransferFailure', $environment, $log);
309
+				throw new RuntimeException($command->getErrorOutput());
310
+			}
311
+			$log->write(sprintf('Backup of database from "%s" done', $name));
312
+		}
313
+
314
+		// Backup assets
315
+		if (in_array($dataTransfer->Mode, array('all', 'assets'))) {
316
+			$log->write(sprintf('Backup of assets from "%s" started', $name));
317
+			$command = $this->getCommand('data:getassets', 'web', $environment, array('data_path' => $filepathBase), $log);
318
+			$command->run(function ($type, $buffer) use ($log) {
319
+				$log->write($buffer);
320
+			});
321
+			if (!$command->isSuccessful()) {
322
+				$this->extend('dataTransferFailure', $environment, $log);
323
+				throw new RuntimeException($command->getErrorOutput());
324
+			}
325
+			$log->write(sprintf('Backup of assets from "%s" done', $name));
326
+		}
327
+
328
+		$sspakFilename = sprintf('%s.sspak', $dataArchive->generateFilename($dataTransfer));
329
+		$sspakFilepath = $filepathBase . DIRECTORY_SEPARATOR . $sspakFilename;
330
+
331
+		try {
332
+			$dataArchive->attachFile($sspakFilepath, $dataTransfer);
333
+			$dataArchive->setArchiveFromFiles($filepathBase);
334
+		} catch (Exception $e) {
335
+			$log->write($e->getMessage());
336
+			throw new RuntimeException($e->getMessage());
337
+		}
338
+
339
+		// Remove any assets and db files lying around, they're not longer needed as they're now part
340
+		// of the sspak file we just generated. Use --force to avoid errors when files don't exist,
341
+		// e.g. when just an assets backup has been requested and no database.sql exists.
342
+		$process = new Process(sprintf('rm -rf %s/assets && rm -f %s', $filepathBase, $databasePath));
343
+		$process->run();
344
+		if (!$process->isSuccessful()) {
345
+			$log->write('Could not delete temporary files');
346
+			throw new RuntimeException($process->getErrorOutput());
347
+		}
348
+
349
+		$log->write(sprintf('Creating sspak file done: %s', $dataArchive->ArchiveFile()->getAbsoluteURL()));
350
+	}
351
+
352
+	/**
353
+	 * Utility function for triggering the db rebuild and flush.
354
+	 * Also cleans up and generates new error pages.
355
+	 * @param DeploynautLogFile $log
356
+	 */
357
+	public function rebuild(DNEnvironment $environment, $log)
358
+	{
359
+		$name = $environment->getFullName();
360
+		$command = $this->getCommand('deploy:migrate', 'web', $environment, null, $log);
361
+		$command->run(function ($type, $buffer) use ($log) {
362
+			$log->write($buffer);
363
+		});
364
+		if (!$command->isSuccessful()) {
365
+			$log->write(sprintf('Rebuild of "%s" failed: %s', $name, $command->getErrorOutput()));
366
+			throw new RuntimeException($command->getErrorOutput());
367
+		}
368
+		$log->write(sprintf('Rebuild of "%s" done', $name));
369
+	}
370
+
371
+	/**
372
+	 * Extracts a *.sspak file referenced through the passed in $dataTransfer
373
+	 * and pushes it to the environment referenced in $dataTransfer.
374
+	 *
375
+	 * @param string $workingDir Directory for the unpacked files.
376
+	 * @param DNDataTransfer $dataTransfer
377
+	 * @param DeploynautLogFile $log
378
+	 */
379
+	protected function dataTransferRestore($workingDir, DNDataTransfer $dataTransfer, DeploynautLogFile $log)
380
+	{
381
+		$environment = $dataTransfer->Environment();
382
+		$name = $environment->getFullName();
383
+
384
+		// Rollback cleanup.
385
+		$self = $this;
386
+		$cleanupFn = function () use ($self, $workingDir, $environment, $log) {
387
+			// Rebuild makes sense even if failed - maybe we can at least partly recover.
388
+			$self->rebuild($environment, $log);
389
+			$process = new Process(sprintf('rm -rf %s', escapeshellarg($workingDir)));
390
+			$process->run();
391
+		};
392
+
393
+		// Restore database into target environment
394
+		if (in_array($dataTransfer->Mode, array('all', 'db'))) {
395
+			$log->write(sprintf('Restore of database to "%s" started', $name));
396
+			$args = array('data_path' => $workingDir . DIRECTORY_SEPARATOR . 'database.sql');
397
+			$command = $this->getCommand('data:pushdb', 'db', $environment, $args, $log);
398
+			$command->run(function ($type, $buffer) use ($log) {
399
+				$log->write($buffer);
400
+			});
401
+			if (!$command->isSuccessful()) {
402
+				$cleanupFn();
403
+				$log->write(sprintf('Restore of database to "%s" failed: %s', $name, $command->getErrorOutput()));
404
+				$this->extend('dataTransferFailure', $environment, $log);
405
+				throw new RuntimeException($command->getErrorOutput());
406
+			}
407
+			$log->write(sprintf('Restore of database to "%s" done', $name));
408
+		}
409
+
410
+		// Restore assets into target environment
411
+		if (in_array($dataTransfer->Mode, array('all', 'assets'))) {
412
+			$log->write(sprintf('Restore of assets to "%s" started', $name));
413
+			$args = array('data_path' => $workingDir . DIRECTORY_SEPARATOR . 'assets');
414
+			$command = $this->getCommand('data:pushassets', 'web', $environment, $args, $log);
415
+			$command->run(function ($type, $buffer) use ($log) {
416
+				$log->write($buffer);
417
+			});
418
+			if (!$command->isSuccessful()) {
419
+				$cleanupFn();
420
+				$log->write(sprintf('Restore of assets to "%s" failed: %s', $name, $command->getErrorOutput()));
421
+				$this->extend('dataTransferFailure', $environment, $log);
422
+				throw new RuntimeException($command->getErrorOutput());
423
+			}
424
+			$log->write(sprintf('Restore of assets to "%s" done', $name));
425
+		}
426
+
427
+		$log->write('Rebuilding and cleaning up');
428
+		$cleanupFn();
429
+	}
430 430
 }
Please login to merge, or discard this patch.
code/backends/DemoDeploymentBackend.php 1 patch
Indentation   +67 added lines, -67 removed lines patch added patch discarded remove patch
@@ -10,82 +10,82 @@
 block discarded – undo
10 10
 class DemoDeploymentBackend extends Object implements DeploymentBackend
11 11
 {
12 12
 
13
-    /**
14
-     * Create a deployment strategy.
15
-     *
16
-     * @param DNEnvironment $environment
17
-     * @param array $options
18
-     *
19
-     * @return DeploymentStrategy
20
-     */
21
-    public function planDeploy(DNEnvironment $environment, $options = array())
22
-    {
23
-        return new DeploymentStrategy($environment, $options);
24
-    }
13
+	/**
14
+	 * Create a deployment strategy.
15
+	 *
16
+	 * @param DNEnvironment $environment
17
+	 * @param array $options
18
+	 *
19
+	 * @return DeploymentStrategy
20
+	 */
21
+	public function planDeploy(DNEnvironment $environment, $options = array())
22
+	{
23
+		return new DeploymentStrategy($environment, $options);
24
+	}
25 25
 
26
-    /**
27
-     * Deploy the given build to the given environment
28
-     *
29
-     * @param DNEnvironment $environment
30
-     * @param DeploynautLogFile $log
31
-     * @param DNProject $project
32
-     * @param array $options
33
-     */
34
-    public function deploy(
35
-        DNEnvironment $environment,
36
-        DeploynautLogFile $log,
37
-        DNProject $project,
38
-        $options
39
-    ) {
40
-        $sha = $options['sha'];
26
+	/**
27
+	 * Deploy the given build to the given environment
28
+	 *
29
+	 * @param DNEnvironment $environment
30
+	 * @param DeploynautLogFile $log
31
+	 * @param DNProject $project
32
+	 * @param array $options
33
+	 */
34
+	public function deploy(
35
+		DNEnvironment $environment,
36
+		DeploynautLogFile $log,
37
+		DNProject $project,
38
+		$options
39
+	) {
40
+		$sha = $options['sha'];
41 41
 
42
-        $this->extend('deployStart', $environment, $sha, $log, $project);
42
+		$this->extend('deployStart', $environment, $sha, $log, $project);
43 43
 
44
-        $file = sprintf('%s/%s.deploy-history.txt', DEPLOYNAUT_LOG_PATH, $environment->getFullName());
45
-        $CLI_file = escapeshellarg($file);
46
-        $CLI_line = escapeshellarg(date('Y-m-d H:i:s') . " => $sha");
44
+		$file = sprintf('%s/%s.deploy-history.txt', DEPLOYNAUT_LOG_PATH, $environment->getFullName());
45
+		$CLI_file = escapeshellarg($file);
46
+		$CLI_line = escapeshellarg(date('Y-m-d H:i:s') . " => $sha");
47 47
 
48
-        // Put maintenance page up
49
-        $this->enableMaintenance($environment, $log, $project);
48
+		// Put maintenance page up
49
+		$this->enableMaintenance($environment, $log, $project);
50 50
 
51
-        // Do the deployment
52
-        $log->write("Demo deployment: echo $CLI_line >> $CLI_file");
53
-        `echo $CLI_line >> $CLI_file`;
54
-        $log->write("Arbitrary pause for 10s");
55
-        sleep(10);
56
-        $log->write("Well, that was a waste of time");
51
+		// Do the deployment
52
+		$log->write("Demo deployment: echo $CLI_line >> $CLI_file");
53
+		`echo $CLI_line >> $CLI_file`;
54
+		$log->write("Arbitrary pause for 10s");
55
+		sleep(10);
56
+		$log->write("Well, that was a waste of time");
57 57
 
58
-        // Once the deployment has run it's necessary to update the maintenance page status
59
-        if (!empty($options['leaveMaintenancePage'])) {
60
-            $this->enableMaintenance($environment, $log, $project);
61
-        } else {
62
-            // Remove maintenance page if we want it to
63
-            $this->disableMaintenance($environment, $log, $project);
64
-        }
58
+		// Once the deployment has run it's necessary to update the maintenance page status
59
+		if (!empty($options['leaveMaintenancePage'])) {
60
+			$this->enableMaintenance($environment, $log, $project);
61
+		} else {
62
+			// Remove maintenance page if we want it to
63
+			$this->disableMaintenance($environment, $log, $project);
64
+		}
65 65
 
66
-        $this->extend('deployEnd', $environment, $sha, $log, $project);
67
-    }
66
+		$this->extend('deployEnd', $environment, $sha, $log, $project);
67
+	}
68 68
 
69
-    /**
70
-     * @inheritdoc
71
-     */
72
-    public function dataTransfer(DNDataTransfer $dataTransfer, DeploynautLogFile $log)
73
-    {
74
-        die('Not implemented');
75
-    }
69
+	/**
70
+	 * @inheritdoc
71
+	 */
72
+	public function dataTransfer(DNDataTransfer $dataTransfer, DeploynautLogFile $log)
73
+	{
74
+		die('Not implemented');
75
+	}
76 76
 
77
-    public function enableMaintenance(DNEnvironment $environment, \DeploynautLogFile $log, DNProject $project)
78
-    {
79
-        $log->write(sprintf('Maintenance page enabled on "%s"', $environment->getFullName()));
80
-    }
77
+	public function enableMaintenance(DNEnvironment $environment, \DeploynautLogFile $log, DNProject $project)
78
+	{
79
+		$log->write(sprintf('Maintenance page enabled on "%s"', $environment->getFullName()));
80
+	}
81 81
 
82
-    public function disableMaintenance(DNEnvironment $environment, DeploynautLogFile $log, DNProject $project)
83
-    {
84
-        $log->write(sprintf('Maintenance page disabled on "%s"', $environment->getFullName()));
85
-    }
82
+	public function disableMaintenance(DNEnvironment $environment, DeploynautLogFile $log, DNProject $project)
83
+	{
84
+		$log->write(sprintf('Maintenance page disabled on "%s"', $environment->getFullName()));
85
+	}
86 86
 
87
-    public function ping(\DNEnvironment $environment, DeploynautLogFile $log, DNProject $project)
88
-    {
89
-        $log->write(sprintf('Ping "%s"', $environment->getFullName()));
90
-    }
87
+	public function ping(\DNEnvironment $environment, DeploynautLogFile $log, DNProject $project)
88
+	{
89
+		$log->write(sprintf('Ping "%s"', $environment->getFullName()));
90
+	}
91 91
 }
Please login to merge, or discard this patch.
code/backends/DeploymentBackend.php 1 patch
Indentation   +55 added lines, -55 removed lines patch added patch discarded remove patch
@@ -3,64 +3,64 @@
 block discarded – undo
3 3
 interface DeploymentBackend
4 4
 {
5 5
 
6
-    /**
7
-     * Creates a deployment strategy that can be used to do some pre-flight checks.
8
-     *
9
-     * @param DNEnvironment $environment
10
-     * @param array $options An unsanitised array of request parameters from $request->requestVars.
11
-     *
12
-     * @return DeploymentStrategy
13
-     */
14
-    public function planDeploy(DNEnvironment $environment, $options);
6
+	/**
7
+	 * Creates a deployment strategy that can be used to do some pre-flight checks.
8
+	 *
9
+	 * @param DNEnvironment $environment
10
+	 * @param array $options An unsanitised array of request parameters from $request->requestVars.
11
+	 *
12
+	 * @return DeploymentStrategy
13
+	 */
14
+	public function planDeploy(DNEnvironment $environment, $options);
15 15
 
16
-    /**
17
-     * Deploy the given build to the given environment.
18
-     *
19
-     * @param DNEnvironment $environment
20
-     * @param DeploynautLogFile $log
21
-     * @param DNProject $project
22
-     * @param array $options
23
-     */
24
-    public function deploy(
25
-        DNEnvironment $environment,
26
-        DeploynautLogFile $log,
27
-        DNProject $project,
28
-        $options
29
-    );
16
+	/**
17
+	 * Deploy the given build to the given environment.
18
+	 *
19
+	 * @param DNEnvironment $environment
20
+	 * @param DeploynautLogFile $log
21
+	 * @param DNProject $project
22
+	 * @param array $options
23
+	 */
24
+	public function deploy(
25
+		DNEnvironment $environment,
26
+		DeploynautLogFile $log,
27
+		DNProject $project,
28
+		$options
29
+	);
30 30
 
31
-    /**
32
-     * Transfer data from an environment to a local file, or from a local file
33
-     * back into an environment. See {@link DNDataTransfer} for details.
34
-     *
35
-     * @param DNDataTransfer $dataTransfer
36
-     * @param DeploynautLogFile $log
37
-     */
38
-    public function dataTransfer(DNDataTransfer $dataTransfer, DeploynautLogFile $log);
31
+	/**
32
+	 * Transfer data from an environment to a local file, or from a local file
33
+	 * back into an environment. See {@link DNDataTransfer} for details.
34
+	 *
35
+	 * @param DNDataTransfer $dataTransfer
36
+	 * @param DeploynautLogFile $log
37
+	 */
38
+	public function dataTransfer(DNDataTransfer $dataTransfer, DeploynautLogFile $log);
39 39
 
40
-    /**
41
-     * Put put the maintenance page
42
-     *
43
-     * @param DNEnvironment $environment
44
-     * @param DeploynautLogFile $log
45
-     * @param DNProject $project
46
-     */
47
-    public function enableMaintenance(DNEnvironment $environment, DeploynautLogFile $log, DNProject $project);
40
+	/**
41
+	 * Put put the maintenance page
42
+	 *
43
+	 * @param DNEnvironment $environment
44
+	 * @param DeploynautLogFile $log
45
+	 * @param DNProject $project
46
+	 */
47
+	public function enableMaintenance(DNEnvironment $environment, DeploynautLogFile $log, DNProject $project);
48 48
 
49
-    /**
50
-     * Disable the maintenance page
51
-     *
52
-     * @param DNEnvironment $environment
53
-     * @param DeploynautLogFile $log
54
-     * @param DNProject $project
55
-     */
56
-    public function disableMaintenance(DNEnvironment $environment, DeploynautLogFile $log, DNProject $project);
49
+	/**
50
+	 * Disable the maintenance page
51
+	 *
52
+	 * @param DNEnvironment $environment
53
+	 * @param DeploynautLogFile $log
54
+	 * @param DNProject $project
55
+	 */
56
+	public function disableMaintenance(DNEnvironment $environment, DeploynautLogFile $log, DNProject $project);
57 57
 
58
-    /**
59
-     * Checks the status of the environment
60
-     *
61
-     * @param DNEnvironment $environment
62
-     * @param DeploynautLogFile $log
63
-     * @param DNProject $project
64
-     */
65
-    public function ping(DNEnvironment $environment, DeploynautLogFile $log, DNProject $project);
58
+	/**
59
+	 * Checks the status of the environment
60
+	 *
61
+	 * @param DNEnvironment $environment
62
+	 * @param DeploynautLogFile $log
63
+	 * @param DNProject $project
64
+	 */
65
+	public function ping(DNEnvironment $environment, DeploynautLogFile $log, DNProject $project);
66 66
 }
Please login to merge, or discard this patch.
code/backends/DeploymentStrategy.php 1 patch
Indentation   +336 added lines, -336 removed lines patch added patch discarded remove patch
@@ -3,340 +3,340 @@
 block discarded – undo
3 3
 class DeploymentStrategy extends ViewableData
4 4
 {
5 5
 
6
-    const SUCCESS_CODE = 'success';
7
-
8
-    const WARNING_CODE = 'warning';
9
-
10
-    const ERROR_CODE = 'error';
11
-
12
-    /**
13
-     * @var DNEnvironment
14
-     */
15
-    protected $environment;
16
-
17
-    /**
18
-     * @var string
19
-     */
20
-    protected $actionTitle = 'Deploy';
21
-
22
-    /**
23
-     * @var string
24
-     */
25
-    protected $actionCode = 'default';
26
-
27
-    /**
28
-     * @var int
29
-     */
30
-    protected $estimatedTime = 0;
31
-
32
-    /**
33
-     * @var array
34
-     */
35
-    protected $changes = [];
36
-
37
-    /**
38
-     * @var array
39
-     */
40
-    protected $options;
41
-
42
-    /**
43
-     * Validation code
44
-     *
45
-     * @var string
46
-     */
47
-    protected $validationCode = DeploymentStrategy::SUCCESS_CODE;
48
-
49
-    /**
50
-     * @var array
51
-     */
52
-    protected $messages = [];
53
-
54
-
55
-    /**
56
-     * @param DNEnvironment $environment
57
-     * @param array $options
58
-     */
59
-    public function __construct(DNEnvironment $environment, $options = array())
60
-    {
61
-        $this->environment = $environment;
62
-        $this->options = $options;
63
-    }
64
-
65
-    /**
66
-     * @param string $title
67
-     */
68
-    public function setActionTitle($title)
69
-    {
70
-        $this->actionTitle = $title;
71
-    }
72
-
73
-    /**
74
-     * @return string
75
-     */
76
-    public function getActionTitle()
77
-    {
78
-        return $this->actionTitle;
79
-    }
80
-
81
-    /**
82
-     */
83
-    public function setActionCode($code)
84
-    {
85
-        $this->actionCode = $code;
86
-    }
87
-
88
-    /**
89
-     * @return string
90
-     */
91
-    public function getActionCode()
92
-    {
93
-        return $this->actionCode;
94
-    }
95
-
96
-    /**
97
-     * @param int
98
-     */
99
-    public function setEstimatedTime($seconds)
100
-    {
101
-        $this->estimatedTime = $seconds;
102
-    }
103
-
104
-    /**
105
-     * @return int Time in minutes
106
-     */
107
-    public function getEstimatedTime()
108
-    {
109
-        return $this->estimatedTime;
110
-    }
111
-
112
-    /**
113
-     * @param string $title
114
-     * @param string $from
115
-     * @param string $to
116
-     */
117
-    public function setChange($title, $from, $to)
118
-    {
119
-        return $this->changes[$title] = array(
120
-            'from' => $from,
121
-            'to' => $to
122
-        );
123
-    }
124
-
125
-    /**
126
-     * @param string $title
127
-     * @param string $desc
128
-     */
129
-    public function setChangeDescriptionOnly($title, $desc)
130
-    {
131
-        return $this->changes[$title] = array(
132
-            'description' => $desc
133
-        );
134
-    }
135
-
136
-    /**
137
-     * Filter the changeset where modification was not required.
138
-     *
139
-     * @return array
140
-     */
141
-    public function getChangesModificationNeeded()
142
-    {
143
-        $filtered = [];
144
-        foreach ($this->changes as $change => $details) {
145
-            if (array_key_exists('description', $details)) {
146
-                $filtered[$change] = $details;
147
-            } elseif (
148
-                (array_key_exists('from', $details) || array_key_exists('to', $details))
149
-                && $details['from'] !== $details['to']
150
-            ) {
151
-                $filtered[$change] = $details;
152
-            }
153
-        }
154
-
155
-        return $filtered;
156
-    }
157
-
158
-    /**
159
-     * @return array Associative array of changes, e.g.
160
-     *	array(
161
-     *		'SHA' => array(
162
-     *			'from' => 'abc',
163
-     *			'to' => 'def'
164
-     *		)
165
-     *	)
166
-     */
167
-    public function getChanges()
168
-    {
169
-        return $this->changes;
170
-    }
171
-
172
-    /**
173
-     * Returns a change or a given key.
174
-     *
175
-     * @return ArrayData|null
176
-     */
177
-    public function getChange($key)
178
-    {
179
-        $changes = $this->getChanges();
180
-        if (array_key_exists($key, $changes)) {
181
-            return new ArrayData($changes[$key]);
182
-        }
183
-        return null;
184
-    }
185
-
186
-    /**
187
-     * @param string $option
188
-     * @param string $value
189
-     */
190
-    public function setOption($option, $value)
191
-    {
192
-        $this->options[$option] = $value;
193
-    }
194
-
195
-    /**
196
-     * @param string $option
197
-     * @return string|null
198
-     */
199
-    public function getOption($option)
200
-    {
201
-        if (!empty($this->options[$option])) {
202
-            return $this->options[$option];
203
-        }
204
-    }
205
-
206
-    /**
207
-     * @return string
208
-     */
209
-    public function getOptions()
210
-    {
211
-        return $this->options;
212
-    }
213
-
214
-    /**
215
-     * @param string $code
216
-     */
217
-    public function setValidationCode($code)
218
-    {
219
-        $this->validationCode = $code;
220
-    }
221
-
222
-    /**
223
-     * @return string
224
-     */
225
-    public function getValidationCode()
226
-    {
227
-        return $this->validationCode;
228
-    }
229
-
230
-    /**
231
-     * @param string $msg
232
-     */
233
-    public function setMessage($msg, $code = self::ERROR_CODE)
234
-    {
235
-        $this->messages[] = [
236
-            'text' => $msg,
237
-            'code' => $code
238
-        ];
239
-
240
-        $current = $this->getValidationCode();
241
-        $map = [
242
-            DeploymentStrategy::SUCCESS_CODE => 0,
243
-            DeploymentStrategy::WARNING_CODE => 1,
244
-            DeploymentStrategy::ERROR_CODE => 2
245
-        ];
246
-        if ($map[$current] < $map[$code]) {
247
-            $this->setValidationCode($code);
248
-        }
249
-    }
250
-
251
-    /**
252
-     * @return array
253
-     */
254
-    public function getMessages()
255
-    {
256
-        return $this->messages;
257
-    }
258
-
259
-    /**
260
-     * Transform the deployment strategy to an array.
261
-     *
262
-     * @return array
263
-     */
264
-    public function toArray()
265
-    {
266
-        $fields = array(
267
-            'actionTitle',
268
-            'actionCode',
269
-            'estimatedTime',
270
-            'changes',
271
-            'options',
272
-            'validationCode',
273
-            'messages'
274
-        );
275
-
276
-        $output = array();
277
-        foreach ($fields as $field) {
278
-            $output[$field] = $this->$field;
279
-        }
280
-        return $output;
281
-    }
282
-
283
-    /**
284
-     * @return string
285
-     */
286
-    public function toJSON()
287
-    {
288
-        return json_encode($this->toArray(), JSON_PRETTY_PRINT);
289
-    }
290
-
291
-    /**
292
-     * Load from JSON associative array.
293
-     * Environment must be set by the callee when creating this object.
294
-     *
295
-     * @param string $json
296
-     */
297
-    public function fromJSON($json)
298
-    {
299
-        $decoded = json_decode($json, true);
300
-        return $this->fromArray($decoded);
301
-    }
302
-
303
-    /**
304
-     * Load from array.
305
-     * Environment must be set by the callee when creating this object.
306
-     *
307
-     * @param string $data
308
-     */
309
-    public function fromArray($data)
310
-    {
311
-        $fields = array(
312
-            'actionTitle',
313
-            'actionCode',
314
-            'estimatedTime',
315
-            'changes',
316
-            'options',
317
-            'validationCode',
318
-            'messages'
319
-        );
320
-
321
-        foreach ($fields as $field) {
322
-            if (!empty($data[$field])) {
323
-                $this->$field = $data[$field];
324
-            }
325
-        }
326
-    }
327
-
328
-    /**
329
-     * @return DNDeployment
330
-     */
331
-    public function createDeployment()
332
-    {
333
-        $deployment = DNDeployment::create();
334
-        $deployment->EnvironmentID = $this->environment->ID;
335
-        // Pull out the SHA from the options so we can make it queryable.
336
-        $deployment->SHA = $this->getOption('sha');
337
-        $deployment->Strategy = $this->toJSON();
338
-        $deployment->write();
339
-
340
-        return $deployment;
341
-    }
6
+	const SUCCESS_CODE = 'success';
7
+
8
+	const WARNING_CODE = 'warning';
9
+
10
+	const ERROR_CODE = 'error';
11
+
12
+	/**
13
+	 * @var DNEnvironment
14
+	 */
15
+	protected $environment;
16
+
17
+	/**
18
+	 * @var string
19
+	 */
20
+	protected $actionTitle = 'Deploy';
21
+
22
+	/**
23
+	 * @var string
24
+	 */
25
+	protected $actionCode = 'default';
26
+
27
+	/**
28
+	 * @var int
29
+	 */
30
+	protected $estimatedTime = 0;
31
+
32
+	/**
33
+	 * @var array
34
+	 */
35
+	protected $changes = [];
36
+
37
+	/**
38
+	 * @var array
39
+	 */
40
+	protected $options;
41
+
42
+	/**
43
+	 * Validation code
44
+	 *
45
+	 * @var string
46
+	 */
47
+	protected $validationCode = DeploymentStrategy::SUCCESS_CODE;
48
+
49
+	/**
50
+	 * @var array
51
+	 */
52
+	protected $messages = [];
53
+
54
+
55
+	/**
56
+	 * @param DNEnvironment $environment
57
+	 * @param array $options
58
+	 */
59
+	public function __construct(DNEnvironment $environment, $options = array())
60
+	{
61
+		$this->environment = $environment;
62
+		$this->options = $options;
63
+	}
64
+
65
+	/**
66
+	 * @param string $title
67
+	 */
68
+	public function setActionTitle($title)
69
+	{
70
+		$this->actionTitle = $title;
71
+	}
72
+
73
+	/**
74
+	 * @return string
75
+	 */
76
+	public function getActionTitle()
77
+	{
78
+		return $this->actionTitle;
79
+	}
80
+
81
+	/**
82
+	 */
83
+	public function setActionCode($code)
84
+	{
85
+		$this->actionCode = $code;
86
+	}
87
+
88
+	/**
89
+	 * @return string
90
+	 */
91
+	public function getActionCode()
92
+	{
93
+		return $this->actionCode;
94
+	}
95
+
96
+	/**
97
+	 * @param int
98
+	 */
99
+	public function setEstimatedTime($seconds)
100
+	{
101
+		$this->estimatedTime = $seconds;
102
+	}
103
+
104
+	/**
105
+	 * @return int Time in minutes
106
+	 */
107
+	public function getEstimatedTime()
108
+	{
109
+		return $this->estimatedTime;
110
+	}
111
+
112
+	/**
113
+	 * @param string $title
114
+	 * @param string $from
115
+	 * @param string $to
116
+	 */
117
+	public function setChange($title, $from, $to)
118
+	{
119
+		return $this->changes[$title] = array(
120
+			'from' => $from,
121
+			'to' => $to
122
+		);
123
+	}
124
+
125
+	/**
126
+	 * @param string $title
127
+	 * @param string $desc
128
+	 */
129
+	public function setChangeDescriptionOnly($title, $desc)
130
+	{
131
+		return $this->changes[$title] = array(
132
+			'description' => $desc
133
+		);
134
+	}
135
+
136
+	/**
137
+	 * Filter the changeset where modification was not required.
138
+	 *
139
+	 * @return array
140
+	 */
141
+	public function getChangesModificationNeeded()
142
+	{
143
+		$filtered = [];
144
+		foreach ($this->changes as $change => $details) {
145
+			if (array_key_exists('description', $details)) {
146
+				$filtered[$change] = $details;
147
+			} elseif (
148
+				(array_key_exists('from', $details) || array_key_exists('to', $details))
149
+				&& $details['from'] !== $details['to']
150
+			) {
151
+				$filtered[$change] = $details;
152
+			}
153
+		}
154
+
155
+		return $filtered;
156
+	}
157
+
158
+	/**
159
+	 * @return array Associative array of changes, e.g.
160
+	 *	array(
161
+	 *		'SHA' => array(
162
+	 *			'from' => 'abc',
163
+	 *			'to' => 'def'
164
+	 *		)
165
+	 *	)
166
+	 */
167
+	public function getChanges()
168
+	{
169
+		return $this->changes;
170
+	}
171
+
172
+	/**
173
+	 * Returns a change or a given key.
174
+	 *
175
+	 * @return ArrayData|null
176
+	 */
177
+	public function getChange($key)
178
+	{
179
+		$changes = $this->getChanges();
180
+		if (array_key_exists($key, $changes)) {
181
+			return new ArrayData($changes[$key]);
182
+		}
183
+		return null;
184
+	}
185
+
186
+	/**
187
+	 * @param string $option
188
+	 * @param string $value
189
+	 */
190
+	public function setOption($option, $value)
191
+	{
192
+		$this->options[$option] = $value;
193
+	}
194
+
195
+	/**
196
+	 * @param string $option
197
+	 * @return string|null
198
+	 */
199
+	public function getOption($option)
200
+	{
201
+		if (!empty($this->options[$option])) {
202
+			return $this->options[$option];
203
+		}
204
+	}
205
+
206
+	/**
207
+	 * @return string
208
+	 */
209
+	public function getOptions()
210
+	{
211
+		return $this->options;
212
+	}
213
+
214
+	/**
215
+	 * @param string $code
216
+	 */
217
+	public function setValidationCode($code)
218
+	{
219
+		$this->validationCode = $code;
220
+	}
221
+
222
+	/**
223
+	 * @return string
224
+	 */
225
+	public function getValidationCode()
226
+	{
227
+		return $this->validationCode;
228
+	}
229
+
230
+	/**
231
+	 * @param string $msg
232
+	 */
233
+	public function setMessage($msg, $code = self::ERROR_CODE)
234
+	{
235
+		$this->messages[] = [
236
+			'text' => $msg,
237
+			'code' => $code
238
+		];
239
+
240
+		$current = $this->getValidationCode();
241
+		$map = [
242
+			DeploymentStrategy::SUCCESS_CODE => 0,
243
+			DeploymentStrategy::WARNING_CODE => 1,
244
+			DeploymentStrategy::ERROR_CODE => 2
245
+		];
246
+		if ($map[$current] < $map[$code]) {
247
+			$this->setValidationCode($code);
248
+		}
249
+	}
250
+
251
+	/**
252
+	 * @return array
253
+	 */
254
+	public function getMessages()
255
+	{
256
+		return $this->messages;
257
+	}
258
+
259
+	/**
260
+	 * Transform the deployment strategy to an array.
261
+	 *
262
+	 * @return array
263
+	 */
264
+	public function toArray()
265
+	{
266
+		$fields = array(
267
+			'actionTitle',
268
+			'actionCode',
269
+			'estimatedTime',
270
+			'changes',
271
+			'options',
272
+			'validationCode',
273
+			'messages'
274
+		);
275
+
276
+		$output = array();
277
+		foreach ($fields as $field) {
278
+			$output[$field] = $this->$field;
279
+		}
280
+		return $output;
281
+	}
282
+
283
+	/**
284
+	 * @return string
285
+	 */
286
+	public function toJSON()
287
+	{
288
+		return json_encode($this->toArray(), JSON_PRETTY_PRINT);
289
+	}
290
+
291
+	/**
292
+	 * Load from JSON associative array.
293
+	 * Environment must be set by the callee when creating this object.
294
+	 *
295
+	 * @param string $json
296
+	 */
297
+	public function fromJSON($json)
298
+	{
299
+		$decoded = json_decode($json, true);
300
+		return $this->fromArray($decoded);
301
+	}
302
+
303
+	/**
304
+	 * Load from array.
305
+	 * Environment must be set by the callee when creating this object.
306
+	 *
307
+	 * @param string $data
308
+	 */
309
+	public function fromArray($data)
310
+	{
311
+		$fields = array(
312
+			'actionTitle',
313
+			'actionCode',
314
+			'estimatedTime',
315
+			'changes',
316
+			'options',
317
+			'validationCode',
318
+			'messages'
319
+		);
320
+
321
+		foreach ($fields as $field) {
322
+			if (!empty($data[$field])) {
323
+				$this->$field = $data[$field];
324
+			}
325
+		}
326
+	}
327
+
328
+	/**
329
+	 * @return DNDeployment
330
+	 */
331
+	public function createDeployment()
332
+	{
333
+		$deployment = DNDeployment::create();
334
+		$deployment->EnvironmentID = $this->environment->ID;
335
+		// Pull out the SHA from the options so we can make it queryable.
336
+		$deployment->SHA = $this->getOption('sha');
337
+		$deployment->Strategy = $this->toJSON();
338
+		$deployment->write();
339
+
340
+		return $deployment;
341
+	}
342 342
 }
Please login to merge, or discard this patch.
code/backends/EnvironmentCreateBackend.php 1 patch
Indentation   +20 added lines, -20 removed lines patch added patch discarded remove patch
@@ -3,26 +3,26 @@
 block discarded – undo
3 3
 interface EnvironmentCreateBackend
4 4
 {
5 5
 
6
-    /**
7
-     * @param DNCreateEnvironment $job
8
-     *
9
-     * @return true
10
-     * @throws Exception
11
-     */
12
-    public function createEnvironment(DNCreateEnvironment $job);
6
+	/**
7
+	 * @param DNCreateEnvironment $job
8
+	 *
9
+	 * @return true
10
+	 * @throws Exception
11
+	 */
12
+	public function createEnvironment(DNCreateEnvironment $job);
13 13
 
14
-    /**
15
-     * Returns form fields for the create form.
16
-     *
17
-     * @param DNProject $project
18
-     * @return FieldList
19
-     */
20
-    public function getCreateEnvironmentFields(DNProject $project);
14
+	/**
15
+	 * Returns form fields for the create form.
16
+	 *
17
+	 * @param DNProject $project
18
+	 * @return FieldList
19
+	 */
20
+	public function getCreateEnvironmentFields(DNProject $project);
21 21
 
22
-    /**
23
-     * Returns validator for the create form.
24
-     *
25
-     * @return Validator
26
-     */
27
-    public function getCreateEnvironmentValidator();
22
+	/**
23
+	 * Returns validator for the create form.
24
+	 *
25
+	 * @return Validator
26
+	 */
27
+	public function getCreateEnvironmentValidator();
28 28
 }
Please login to merge, or discard this patch.