ProjectCommitController::abortMergeAction()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 6
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 1
c 0
b 0
f 0
nc 1
nop 1
dl 0
loc 6
rs 10
1
<?php
2
/*
3
 * This file is part of the GitControlBundle package.
4
 *
5
 * (c) Paul Schweppe <[email protected]>
6
 *
7
 * For the full copyright and license information, please view the LICENSE
8
 * file that was distributed with this source code.
9
 */
10
11
namespace VersionControl\GitControlBundle\Controller;
12
13
use VersionControl\GitControlBundle\Controller\Base\BaseProjectController;
14
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;
15
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
16
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
17
use VersionControl\GitControlBundle\Entity\Project;
18
use Symfony\Component\HttpFoundation\Request;
19
use VersionControl\GitControlBundle\Form\CommitType;
20
use VersionControl\GitControlBundle\Entity\Commit;
21
use VersionControl\GitControlBundle\Annotation\ProjectAccess;
22
use Symfony\Component\Form\Extension\Core\Type\SubmitType;
23
24
/** ///Route("/example", service="example_bundle.controller.example_controller") */
25
26
/**
27
 * Project Commit controller.
28
 *
29
 * @Route("/project/{id}/commit")
30
 */
31
class ProjectCommitController extends BaseProjectController
32
{
33
    /**
34
     * @var GitCommand
0 ignored issues
show
Bug introduced by
The type VersionControl\GitContro...e\Controller\GitCommand was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
35
     */
36
    protected $gitCommitCommand;
37
38
    /**
39
     * @var GitCommand
40
     */
41
    protected $gitSyncCommands;
42
43
    /**
44
     * The current Project.
45
     *
46
     * @var Project
47
     */
48
    protected $project;
49
50
    /**
51
     * Number of issues for this project.
52
     *
53
     * @var int
54
     */
55
    protected $issuesCount;
56
57
    /**
58
     * Issue Respository.
59
     *
60
     * @var VersionControl\GitControlBundle\Repository\Issues\IssueRepositoryInterface
0 ignored issues
show
Bug introduced by
The type VersionControl\GitContro...ssueRepositoryInterface was not found. Did you mean VersionControl\GitContro...ssueRepositoryInterface? If so, make sure to prefix the type with \.
Loading history...
61
     */
62
    protected $issueRepository;
63
64
    /**
65
     * List files to be commited.
66
     *
67
     * @Route("/", name="project_commitlist")
68
     * @Method("GET")
69
     * @Template()
70
     * @ProjectAccess(grantType="EDIT")
71
     */
72
    public function listAction($id)
0 ignored issues
show
Unused Code introduced by
The parameter $id is not used and could be removed. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-unused  annotation

72
    public function listAction(/** @scrutinizer ignore-unused */ $id)

This check looks for parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
73
    {
74
        $files = $this->gitCommitCommand->getFilesToCommit();
75
        
76
        //Get merge conflicts
77
        $conflictFileNames = $this->gitCommands->command('diff')->getConflictFileNames();
78
        
79
        $files = $this->filterConflicts($files,$conflictFileNames);
80
81
        $commitEntity = new Commit();
82
        $commitEntity->setProject($this->project);
83
        $commitEntity->setStatusHash($this->gitCommitCommand->getStatusHash());
84
85
        $issueNumber = $this->issueNumberfromBranch($this->branchName);
86
        if ($issueNumber !== false) {
87
            $commitEntity->setIssue($issueNumber);
88
        }
89
90
        $commitForm = $this->createCommitForm($commitEntity, $files);
91
92
        return array_merge($this->viewVariables, array(
93
            'files' => $files,
94
            'conflictFileNames' => $conflictFileNames,
95
            'commit_form' => $commitForm->createView(),
96
            'issueCount' => $this->issuesCount,
97
        ));
98
    }
99
100
    /**
101
     * Handles the commit form.
102
     *
103
     * @Route("/", name="project_commit")
104
     * @Method("POST")
105
     * @Template("VersionControlGitControlBundle:ProjectCommit:list.html.twig")
106
     * @ProjectAccess(grantType="EDIT")
107
     */
108
    public function commitAction(Request $request)
109
    {
110
        $files = $this->gitCommitCommand->getFilesToCommit();
111
        
112
        //Get merge conflicts
113
        $conflictFileNames = $this->gitCommands->command('diff')->getConflictFileNames();
114
        $files = $this->filterConflicts($files,$conflictFileNames);
115
116
        $commitEntity = new Commit();
117
        $commitEntity->setProject($this->project);
118
        $commitForm = $this->createCommitForm($commitEntity, $files);
119
        $commitForm->handleRequest($request);
120
121
        if ($commitForm->isValid()) {
122
            $selectedGitFiles = $commitEntity->getFiles();
123
124
            try {
125
                $selectedFiles = array();
126
                $filesCommited = 0;
127
128
                if (is_array($selectedGitFiles)) {
0 ignored issues
show
introduced by
The condition is_array($selectedGitFiles) is always true.
Loading history...
129
                    foreach ($selectedGitFiles as $gitFile) {
130
                        $selectedFiles[] = $gitFile->getPath1();
131
                    }
132
133
                    $filesCommited = count($selectedFiles);
134
                    //Git Stage selected files
135
                    $this->gitCommitCommand->stageFiles($selectedFiles);
136
                } else {
137
                    //To many files
138
                    if ($selectedGitFiles === true) {
139
                        $this->gitCommitCommand->stageAll();
140
141
                        $filesCommited = count($files);
142
                    }
143
                }
144
145
                //Handle Issue Action eg Close issue. Update Commit message
146
                $this->handleIssue($commitEntity);
147
148
                $user = $this->get('security.token_storage')->getToken()->getUser();
149
                $author = $user->getName().' <'.$user->getEmail().'>';
150
                //Git Commit
151
                $this->gitCommitCommand->commit($commitEntity->getComment(), $author);
152
153
                //Set notice of successfull commit
154
                $this->get('session')->getFlashBag()->add('notice', $filesCommited.' files have been committed');
155
156
                $this->get('session')->getFlashBag()->add('status-refresh', 'true');
157
158
                //Git Push to remote repository
159
                $this->pushToRemote($commitEntity);
160
161
                return $this->redirect($this->generateUrl('project_commitlist'));
162
            } catch (\Exception $e) {
163
                $this->get('session')->getFlashBag()->add('error', $e->getMessage());
164
            }
165
        }
166
167
        return array_merge($this->viewVariables, array(
168
            'files' => $files,
169
            'conflictFileNames' => $conflictFileNames,
170
            'commit_form' => $commitForm->createView(),
171
            'issueCount' => $this->issuesCount,
172
        ));
173
    }
174
175
    /**
176
     * @param int $id
177
     */
178
    public function initAction($id, $grantType = 'EDIT')
179
    {
180
        $redirectUrl = parent::initAction($id, $grantType);
181
        if ($redirectUrl) {
182
            return $redirectUrl;
183
        }
184
        $this->gitCommitCommand = $this->gitCommands->command('commit');
185
        $this->gitSyncCommands = $this->gitCommands->command('sync');
186
187
        $em = $this->getDoctrine()->getManager();
188
189
        $issueIntegrator = $em->getRepository('VersionControlGitControlBundle:ProjectIssueIntegrator')->findOneByProject($this->project);
190
        $this->issueManager = $this->get('version_control.issue_repository_manager');
0 ignored issues
show
Bug Best Practice introduced by
The property issueManager does not exist. Although not strictly required by PHP, it is generally a best practice to declare properties explicitly.
Loading history...
191
        if ($issueIntegrator) {
192
            $this->issueManager->setIssueIntegrator($issueIntegrator);
193
        } else {
194
            $this->issueManager->setProject($this->project);
195
        }
196
        $this->issueRepository = $this->issueManager->getIssueRepository();
197
        $this->issuesCount = $this->issueRepository->countFindIssues('', 'open');
198
    }
199
200
    private function createCommitForm($commitEntity, $fileChoices)
201
    {
202
        $includeIssues = ($this->issuesCount > 0) ? true : false;
203
        //$fileChoices = $this->gitCommitCommand->getFilesToCommit();
204
        $gitRemoteVersions = $this->gitSyncCommands->getRemoteVersions();
205
206
        $form = $this->createForm(CommitType::class, $commitEntity, array(
207
            'action' => $this->generateUrl('project_commit'),
208
            'method' => 'POST',
209
            'includeIssues' => $includeIssues,
210
            'gitRemoteVersions' => $gitRemoteVersions,
211
            'fileChoices' => $fileChoices,
212
        ));
213
214
        $form->add('submit', SubmitType::class, array('label' => 'Commit'));
215
216
        return $form;
217
    }
218
219
    /**
220
     * Aborts a merge action. Should only be called after a merge.
221
     *
222
     * @Route("/about-merge/", name="project_commit_abortmerge")
223
     * @Method("GET")
224
     * @ProjectAccess(grantType="EDIT")
225
     */
226
    public function abortMergeAction($id)
0 ignored issues
show
Unused Code introduced by
The parameter $id is not used and could be removed. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-unused  annotation

226
    public function abortMergeAction(/** @scrutinizer ignore-unused */ $id)

This check looks for parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
227
    {
228
229
        //$this->gitCommitCommand = $this->get('version_control.git_command')->setProject($this->project);
230
231
        return $this->redirect($this->generateUrl('project_commitlist'));
232
    }
233
234
    /**
235
     * Check if issue options have been set and updates git message
236
     * and closes issue if certain issue actions are set.
237
     *
238
     * @param Commit $commitEntity]
239
     */
240
    protected function handleIssue(\VersionControl\GitControlBundle\Entity\Commit &$commitEntity)
241
    {
242
        $issueId = $commitEntity->getIssue();
243
        $commitMessage = $commitEntity->getComment();
244
        $issueCloseStatus = array('Fixed', 'Closed', 'Resolved');
245
246
        if ($issueId) {
247
            $issueEntity = $this->issueRepository->findIssueById($issueId);
248
            if ($issueEntity) {
249
                $issueAction = $commitEntity->getIssueAction();
250
                $commitMessage = $issueAction.' #'.$issueEntity->getId().':'.$commitMessage;
251
                $commitEntity->setComment($commitMessage);
252
                if (in_array($issueAction, $issueCloseStatus)) {
253
                    //Close Issue
254
                    $this->issueRepository->closeIssue($issueEntity->getId());
255
                }
256
            }
257
        }
258
    }
259
260
    /**
261
     * Push to remote repositories. Supports mulitple pushes.
262
     *
263
     * @param Commit $commitEntity
264
     */
265
    protected function pushToRemote(\VersionControl\GitControlBundle\Entity\Commit $commitEntity)
266
    {
267
        $branch = $this->gitCommands->command('branch')->getCurrentBranch();
268
269
        $gitRemotes = $commitEntity->getPushRemote();
270
        if (count($gitRemotes) > 0) {
271
            foreach ($gitRemotes as $gitRemote) {
272
                try {
273
                    $response = $this->gitSyncCommands->push($gitRemote, $branch);
274
                    $this->get('session')->getFlashBag()->add('notice', $response);
275
                } catch (\Exception $e) {
276
                    $this->get('session')->getFlashBag()->add('error', $e->getMessage());
277
                }
278
            }
279
        }
280
    }
281
282
    /**
283
     * Show Git commit diff.
284
     *
285
     * @Route("/filediff/{difffile}", name="project_filediff")
286
     * @Method("GET")
287
     * @Template()
288
     * @ProjectAccess(grantType="EDIT")
289
     */
290
    public function fileDiffAction($id, $difffile)
0 ignored issues
show
Unused Code introduced by
The parameter $id is not used and could be removed. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-unused  annotation

290
    public function fileDiffAction(/** @scrutinizer ignore-unused */ $id, $difffile)

This check looks for parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
291
    {
292
        $gitDiffCommand = $this->gitCommands->command('diff');
293
294
        $difffile = urldecode($difffile);
295
296
        $gitDiffs = $gitDiffCommand->getDiffFile($difffile);
297
298
        return array_merge($this->viewVariables, array(
299
            'diffs' => $gitDiffs,
300
        ));
301
    }
302
    
303
    /**
304
     * Filter conflicted files. Following is list of conflicted states
305
     * -------------------------------------------------
306
     * D           D    unmerged, both deleted
307
     * A           U    unmerged, added by us
308
     * U           D    unmerged, deleted by them
309
     * U           A    unmerged, added by them
310
     * D           U    unmerged, deleted by us
311
     * A           A    unmerged, both added
312
     * U           U    unmerged, both modified
313
     * -------------------------------------------------
314
     * 
315
     * @param array $files
316
     * @param array $conflictedFiles
317
     * @return type
0 ignored issues
show
Bug introduced by
The type VersionControl\GitControlBundle\Controller\type was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
318
     */
319
    public function filterConflicts($files,$conflictedFiles){
0 ignored issues
show
Unused Code introduced by
The parameter $conflictedFiles is not used and could be removed. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-unused  annotation

319
    public function filterConflicts($files,/** @scrutinizer ignore-unused */ $conflictedFiles){

This check looks for parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
320
        
321
        //Get merge conflicts
322
        $conflictFileNames = $this->gitCommands->command('diff')->getConflictFileNames();
323
        if(count($conflictFileNames) > 0){
324
            $conflictedFiles = array();
325
            foreach($files as $file){
326
                if(($file->getIndexStatus() == 'U' || $file->getWorkTreeStatus() == 'U')
327
                        || ($file->getIndexStatus() == 'D' && $file->getWorkTreeStatus() == 'D')
328
                        || ($file->getIndexStatus() == 'A' && $file->getWorkTreeStatus() == 'A')
329
                        ){
330
                    $conflictedFiles[] = $file;
331
                }
332
            } 
333
            $files = $conflictedFiles;
334
        }
335
        
336
        return $files;
0 ignored issues
show
Bug Best Practice introduced by
The expression return $files returns the type array which is incompatible with the documented return type VersionControl\GitControlBundle\Controller\type.
Loading history...
337
    }
338
339
    /**
340
     * Reset a File back to head.
341
     *
342
     * @Route("/reset-file/{filePath}", name="project_reset_file")
343
     * @Method("GET")
344
     * @ProjectAccess(grantType="EDIT")
345
     */
346
    public function resetFileAction($filePath)
347
    {
348
        try {
349
            $gitUndoCommand = $this->gitCommands->command('undo');
350
            $file = urldecode($filePath);
351
            $response = $gitUndoCommand->checkoutFile($file, 'HEAD', false);
352
            $this->get('session')->getFlashBag()->add('notice', $response);
353
            $this->get('session')->getFlashBag()->add('status-refresh', 'true');
354
        } catch (\Exception $e) {
355
            $this->get('session')->getFlashBag()->add('error', $e->getMessage());
356
        }
357
358
        return $this->redirect($this->generateUrl('project_commitlist'));
359
    }
360
361
    protected function issueNumberfromBranch($branch)
362
    {
363
        $issueNumber = false;
364
        $matches = array();
365
        if (preg_match('/(issue|iss|issu)(\d+)/i', $branch, $matches)) {
366
            foreach ($matches as $issueId) {
367
                if (is_numeric($issueId)) {
368
                    $issueNumber = $issueId;
369
                }
370
            }
371
        }
372
373
        return $issueNumber;
374
    }
375
    
376
    /**
377
     * Fix git conflict files
378
     *
379
     * @Route("/fix-conflict/{filePath}", name="project_fix_conflict")
380
     * @Method("GET")
381
     * @ProjectAccess(grantType="EDIT")
382
     * @Template()
383
     */
384
    public function fixConflictAction($filePath)
385
    {
386
        $file = urldecode($filePath);
0 ignored issues
show
Unused Code introduced by
The assignment to $file is dead and can be removed.
Loading history...
387
        
388
        return array_merge($this->viewVariables, array(
389
            'filePath' => $filePath,
390
        ));
391
    }
392
    
393
    /**
394
     * Reset a File back to head.
395
     *
396
     * @Route("/fixed-conflict/{filePath}/{option}", name="project_fixed_conflict")
397
     * @Method("GET")
398
     * @ProjectAccess(grantType="EDIT")
399
     * @Template()
400
     */
401
    public function fixedConflictAction($filePath,$option)
402
    {
403
        $file = urldecode($filePath);
404
        try {
405
            $gitUndoCommand = $this->gitCommands->command('undo');
406
            if($option === 'theirs'){
407
                $response = $gitUndoCommand->checkoutTheirFile($file);
408
            }elseif($option === 'ours'){
409
                $response = $gitUndoCommand->checkoutOurFile($file);
410
            }elseif($option === 'delete'){
411
                $response = $gitUndoCommand->deleteFile($file);
412
            }else{
413
                $response = $gitUndoCommand->addFile($file);
414
            }
415
            
416
            $this->get('session')->getFlashBag()->add('notice', $response);
417
            $this->get('session')->getFlashBag()->add('status-refresh', 'true');
418
        } catch (\Exception $e) {
419
            $this->get('session')->getFlashBag()->add('error', $e->getMessage());
420
        }
421
        
422
        return $this->redirect($this->generateUrl('project_commitlist'));
423
    }
424
    
425
    /**
426
     * Fix deleted conflict e.g. (D U)
427
     *
428
     * @Route("/fix-delete-conflict/{filePath}", name="project_fix_delete_conflict")
429
     * @Method("GET")
430
     * @ProjectAccess(grantType="EDIT")
431
     * @Template()
432
     */
433
    public function fixDeleteConflictAction($filePath)
434
    {
435
        $file = urldecode($filePath);
0 ignored issues
show
Unused Code introduced by
The assignment to $file is dead and can be removed.
Loading history...
436
        
437
        return array_merge($this->viewVariables, array(
438
            'filePath' => $filePath,
439
        ));
440
    }
441
    
442
    /**
443
     * Fix file that has been added in both branches e.g. (A A)
444
     *
445
     * @Route("/fix-add-conflict/{filePath}", name="project_fix_add_conflict")
446
     * @Method("GET")
447
     * @ProjectAccess(grantType="EDIT")
448
     * @Template()
449
     */
450
    public function fixAddConflictAction($filePath)
451
    {
452
        $file = urldecode($filePath);
0 ignored issues
show
Unused Code introduced by
The assignment to $file is dead and can be removed.
Loading history...
453
        
454
        return array_merge($this->viewVariables, array(
455
            'filePath' => $filePath,
456
        ));
457
    }
458
}
459