WorkflowDefinitionImporter   A
last analyzed

Complexity

Total Complexity 9

Size/Duplication

Total Lines 71
Duplicated Lines 0 %

Coupling/Cohesion

Components 0
Dependencies 4
Metric Value
wmc 9
lcom 0
cbo 4
dl 0
loc 71
rs 10

2 Methods

Rating   Name   Duplication   Size   Complexity  
B getImportedWorkflows() 0 21 5
B parseYAMLImport() 0 32 4
1
<?php
2
/**
3
 * Workflow definition import-specific logic. @see {@link WorkflowDefinitionExporter}.
4
 * 
5
 * @author  [email protected]
6
 * @license BSD License (http://silverstripe.org/bsd-license/)
7
 * @package advancedworkflow
8
 */
9
class WorkflowDefinitionImporter {
0 ignored issues
show
Coding Style Compatibility introduced by
PSR1 recommends that each class must be in a namespace of at least one level to avoid collisions.

You can fix this by adding a namespace to your class:

namespace YourVendor;

class YourClass { }

When choosing a vendor namespace, try to pick something that is not too generic to avoid conflicts with other libraries.

Loading history...
10
	
11
	/**
12
	 * Generates an array of WorkflowTemplate Objects of all uploaded workflows.
13
	 * 
14
	 * @param string $name. If set, a single-value array comprising a WorkflowTemplate object who's first constructor param matches $name
0 ignored issues
show
Bug introduced by
There is no parameter named $name.. Was it maybe removed?

This check looks for PHPDoc comments describing methods or function parameters that do not exist on the corresponding method or function.

Consider the following example. The parameter $italy is not defined by the method finale(...).

/**
 * @param array $germany
 * @param array $island
 * @param array $italy
 */
function finale($germany, $island) {
    return "2:1";
}

The most likely cause is that the parameter was removed, but the annotation was not.

Loading history...
15
	 *						is returned.
16
	 * @return WorkflowTemplate $template | array $importedDefs
17
	 */
18
	public function getImportedWorkflows($name = null) {
19
		$imports = DataObject::get('ImportedWorkflowTemplate');
20
		$importedDefs = array();
21
		foreach($imports as $import) {
22
			if(!$import->Content) {
23
				continue;
24
			}
25
			$structure = unserialize($import->Content);
26
			$struct = $structure['Injector']['ExportedWorkflow'];
27
			$template = Injector::inst()->createWithArgs('WorkflowTemplate', $struct['constructor']);
28
			$template->setStructure($struct['properties']['structure']);
29
			if($name) {
30
				if($struct['constructor'][0] == trim($name)) {
31
					return $template;
32
				}
33
				continue;
34
			}
35
			$importedDefs[] = $template;
36
		}
37
		return $importedDefs;
0 ignored issues
show
Bug Best Practice introduced by
The return type of return $importedDefs; (array) is incompatible with the return type documented by WorkflowDefinitionImporter::getImportedWorkflows of type WorkflowTemplate.

If you return a value from a function or method, it should be a sub-type of the type that is given by the parent type f.e. an interface, or abstract method. This is more formally defined by the Lizkov substitution principle, and guarantees that classes that depend on the parent type can use any instance of a child type interchangably. This principle also belongs to the SOLID principles for object oriented design.

Let’s take a look at an example:

class Author {
    private $name;

    public function __construct($name) {
        $this->name = $name;
    }

    public function getName() {
        return $this->name;
    }
}

abstract class Post {
    public function getAuthor() {
        return 'Johannes';
    }
}

class BlogPost extends Post {
    public function getAuthor() {
        return new Author('Johannes');
    }
}

class ForumPost extends Post { /* ... */ }

function my_function(Post $post) {
    echo strtoupper($post->getAuthor());
}

Our function my_function expects a Post object, and outputs the author of the post. The base class Post returns a simple string and outputting a simple string will work just fine. However, the child class BlogPost which is a sub-type of Post instead decided to return an object, and is therefore violating the SOLID principles. If a BlogPost were passed to my_function, PHP would not complain, but ultimately fail when executing the strtoupper call in its body.

Loading history...
38
	}
39
	
40
	/**
41
	 * Handles finding and parsing YAML input as a string or from the contents of a file.
42
	 * 
43
	 * @see addYAMLConfigFile() on {@link SS_ConfigManifest} from where this logic was taken and adapted.
44
	 * @param string $source YAML as a string or a filename
45
	 * @return array
46
	 */
47
	public function parseYAMLImport($source) {
48
		if(is_file($source)) {
49
			$source = file_get_contents($source);
50
		}
51
52
		require_once('thirdparty/zend_translate_railsyaml/library/Translate/Adapter/thirdparty/sfYaml/lib/sfYamlParser.php');
53
		$parser = new sfYamlParser();
54
		
55
		// Make sure the linefeeds are all converted to \n, PCRE '$' will not match anything else.
56
		$convertLF = str_replace(array("\r\n", "\r"), "\n", $source);
57
		/*
58
		 * Remove illegal colons from Transition/Action titles, otherwise sfYamlParser will barf on them
59
		 * Note: The regex relies on there being single quotes wrapped around these in the export .ss template
60
		 */
61
		$converted = preg_replace("#('[^:\n][^']+)(:)([^']+')#", "$1;$3", $convertLF);
62
		$parts = preg_split('#^---$#m', $converted, -1, PREG_SPLIT_NO_EMPTY);
63
64
		// If we got an odd number of parts the config, file doesn't have a header.
65
		// We know in advance the number of blocks imported content will have so we settle for a count()==2 check.
66
		if(count($parts) != 2) {
67
			$msg = _t('WorkflowDefinitionImporter.INVALID_YML_FORMAT_NO_HEADER', 'Invalid YAML format.');
68
			throw new ValidationException($msg);
69
		}
70
		
71
		try {
72
			$parsed = $parser->parse($parts[1]);
73
			return $parsed;
74
		} catch (Exception $e) {
75
			$msg = _t('WorkflowDefinitionImporter.INVALID_YML_FORMAT_NO_PARSE', 'Invalid YAML format. Unable to parse.');
76
			throw new ValidationException($msg);
77
		}
78
	}		
79
}
80