GitHub Access Token became invalid

It seems like the GitHub access token used for retrieving details about this repository from GitHub became invalid. This might prevent certain types of inspections from being run (in particular, everything related to pull requests).
Please ask an admin of your repository to re-new the access token on this website.

WorkflowDefinitionExporter   A
last analyzed

Complexity

Total Complexity 13

Size/Duplication

Total Lines 170
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 9

Importance

Changes 0
Metric Value
wmc 13
lcom 1
cbo 9
dl 0
loc 170
rs 10
c 0
b 0
f 0

10 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 5 1
A setMember() 0 4 1
A getDefinition() 0 4 1
A export() 0 15 2
A format() 0 8 1
A getExportSize() 0 4 1
A ExportMetaData() 0 13 1
A ssVersion() 0 10 2
A processTitle() 0 6 1
A sendFile() 0 21 2
1
<?php
2
3
namespace Symbiote\AdvancedWorkflow\Admin;
4
5
use Exception;
6
use SilverStripe\Admin\LeftAndMain;
7
use SilverStripe\Control\Director;
8
use SilverStripe\Control\HTTPResponse;
9
use SilverStripe\Core\Config\Configurable;
10
use SilverStripe\Dev\SapphireInfo;
11
use SilverStripe\ORM\DataObject;
12
use SilverStripe\Security\Member;
13
use SilverStripe\Security\Permission;
14
use SilverStripe\Security\Security;
15
use SilverStripe\View\ArrayData;
16
use SilverStripe\View\SSViewer;
17
use Symbiote\AdvancedWorkflow\DataObjects\WorkflowDefinition;
18
19
/**
20
 * Allows workflow definitions to be exported from one SilverStripe install, ready for import into another.
21
 *
22
 * YAML is used for export as it's native to SilverStripe's config system and we're using {@link WorkflowTemplate}
23
 * for some of the import-specific heavy lifting, which is already heavily predicated on YAML.
24
 *
25
 * @todo
26
 *  - If workflow-def is created badly, the "update template definition" logic, sometimes doesn't work
27
 *
28
 * @author  [email protected]
29
 * @license BSD License (http://silverstripe.org/bsd-license/)
30
 * @package advancedworkflow
31
 */
32
class WorkflowDefinitionExporter
33
{
34
    use Configurable;
35
36
    /**
37
     * The base filename of the file to the exported
38
     *
39
     * @config
40
     * @var string
41
     */
42
    private static $export_filename_prefix = 'workflow-definition-export';
43
    /**
44
     *
45
     * @var Member
46
     */
47
    protected $member;
48
    /**
49
     *
50
     * @var WorkflowDefinition
51
     */
52
    protected $workflowDefinition;
53
54
    /**
55
     *
56
     * @param number $definitionID
57
     * @return void
0 ignored issues
show
Comprehensibility Best Practice introduced by
Adding a @return annotation to constructors is generally not recommended as a constructor does not have a meaningful return value.

Adding a @return annotation to a constructor is not recommended, since a constructor does not have a meaningful return value.

Please refer to the PHP core documentation on constructors.

Loading history...
58
     */
59
    public function __construct($definitionID)
60
    {
61
        $this->setMember(Security::getCurrentUser());
0 ignored issues
show
Bug introduced by
It seems like \SilverStripe\Security\Security::getCurrentUser() can be null; however, setMember() does not accept null, maybe add an additional type check?

Unless you are absolutely sure that the expression can never be null because of other conditions, we strongly recommend to add an additional type check to your code:

/** @return stdClass|null */
function mayReturnNull() { }

function doesNotAcceptNull(stdClass $x) { }

// With potential error.
function withoutCheck() {
    $x = mayReturnNull();
    doesNotAcceptNull($x); // Potential error here.
}

// Safe - Alternative 1
function withCheck1() {
    $x = mayReturnNull();
    if ( ! $x instanceof stdClass) {
        throw new \LogicException('$x must be defined.');
    }
    doesNotAcceptNull($x);
}

// Safe - Alternative 2
function withCheck2() {
    $x = mayReturnNull();
    if ($x instanceof stdClass) {
        doesNotAcceptNull($x);
    }
}
Loading history...
62
        $this->workflowDefinition = DataObject::get_by_id(WorkflowDefinition::class, $definitionID);
0 ignored issues
show
Documentation Bug introduced by
It seems like \SilverStripe\ORM\DataOb...::class, $definitionID) can also be of type object<SilverStripe\ORM\DataObject>. However, the property $workflowDefinition is declared as type object<Symbiote\Advanced...cts\WorkflowDefinition>. Maybe add an additional type check?

Our type inference engine has found a suspicous assignment of a value to a property. This check raises an issue when a value that can be of a mixed type is assigned to a property that is type hinted more strictly.

For example, imagine you have a variable $accountId that can either hold an Id object or false (if there is no account id yet). Your code now assigns that value to the id property of an instance of the Account class. This class holds a proper account, so the id value must no longer be false.

Either this assignment is in error or a type check should be added for that assignment.

class Id
{
    public $id;

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

}

class Account
{
    /** @var  Id $id */
    public $id;
}

$account_id = false;

if (starsAreRight()) {
    $account_id = new Id(42);
}

$account = new Account();
if ($account instanceof Id)
{
    $account->id = $account_id;
}
Loading history...
63
    }
64
65
    /**
66
     *
67
     * @param Member $member
68
     */
69
    public function setMember($member)
70
    {
71
        $this->member = $member;
72
    }
73
74
    /**
75
     * @return WorkflowDefinition
76
     */
77
    public function getDefinition()
78
    {
79
        return $this->workflowDefinition;
80
    }
81
82
    /**
83
     * Runs the export
84
     *
85
     * @return string $template
86
     * @throws Exception if the current user doesn't have permission to access export functionality
87
     */
88
    public function export()
89
    {
90
        // Disable any access to use of WorkflowExport if user has no SecurityAdmin access
91
        if (!Permission::check('CMS_ACCESS_SecurityAdmin')) {
92
            throw new Exception(_t('SilverStripe\\ErrorPage\\ErrorPage.CODE_403', '403 - Forbidden'), 403);
93
        }
94
        $def = $this->getDefinition();
95
        $templateData = new ArrayData(array(
96
            'ExportMetaData' => $this->ExportMetaData(),
97
            'ExportActions' => $def->Actions(),
0 ignored issues
show
Bug introduced by
The method Actions() does not exist on Symbiote\AdvancedWorkflo...ects\WorkflowDefinition. Did you maybe mean updateAdminActions()?

This check marks calls to methods that do not seem to exist on an object.

This is most likely the result of a method being renamed without all references to it being renamed likewise.

Loading history...
98
            'ExportUsers' => $def->Users(),
0 ignored issues
show
Documentation Bug introduced by
The method Users does not exist on object<Symbiote\Advanced...cts\WorkflowDefinition>? Since you implemented __call, maybe consider adding a @method annotation.

If you implement __call and you know which methods are available, you can improve IDE auto-completion and static analysis by adding a @method annotation to the class.

This is often the case, when __call is implemented by a parent class and only the child class knows which methods exist:

class ParentClass {
    private $data = array();

    public function __call($method, array $args) {
        if (0 === strpos($method, 'get')) {
            return $this->data[strtolower(substr($method, 3))];
        }

        throw new \LogicException(sprintf('Unsupported method: %s', $method));
    }
}

/**
 * If this class knows which fields exist, you can specify the methods here:
 *
 * @method string getName()
 */
class SomeClass extends ParentClass { }
Loading history...
99
            'ExportGroups' => $def->Groups()
0 ignored issues
show
Documentation Bug introduced by
The method Groups does not exist on object<Symbiote\Advanced...cts\WorkflowDefinition>? Since you implemented __call, maybe consider adding a @method annotation.

If you implement __call and you know which methods are available, you can improve IDE auto-completion and static analysis by adding a @method annotation to the class.

This is often the case, when __call is implemented by a parent class and only the child class knows which methods exist:

class ParentClass {
    private $data = array();

    public function __call($method, array $args) {
        if (0 === strpos($method, 'get')) {
            return $this->data[strtolower(substr($method, 3))];
        }

        throw new \LogicException(sprintf('Unsupported method: %s', $method));
    }
}

/**
 * If this class knows which fields exist, you can specify the methods here:
 *
 * @method string getName()
 */
class SomeClass extends ParentClass { }
Loading history...
100
        ));
101
        return $this->format($templateData);
102
    }
103
104
    /**
105
     * Format the exported data as YAML.
106
     *
107
     * @param ArrayData $templateData
108
     * @return void
109
     */
110
    public function format($templateData)
111
    {
112
        $viewer = SSViewer::execute_template(['type' => 'Includes', 'WorkflowDefinitionExport'], $templateData);
0 ignored issues
show
Documentation introduced by
array('type' => 'Include...kflowDefinitionExport') is of type array<string|integer,str..."string","0":"string"}>, but the function expects a string.

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

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

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

function acceptsInteger($int) { }

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

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
113
        // Temporary until we find the source of the replacement in SSViewer
114
        $processed = str_replace('&amp;', '&', $viewer);
115
        // Clean-up newline "gaps" that SSViewer leaves behind from the placement of template control structures
116
        return preg_replace("#^\R+|^[\t\s]*\R+#m", '', $processed);
117
    }
118
119
    /**
120
     * Returns the size of the current export in bytes.
121
     * Used for pushing data to the browser to prompt for download
122
     *
123
     * @param string $str
124
     * @return number $bytes
125
     */
126
    public function getExportSize($str)
127
    {
128
        return mb_strlen($str, 'UTF-8');
129
    }
130
131
    /**
132
     * Generate template vars for metadata
133
     *
134
     * @return ArrayData
135
     */
136
    public function ExportMetaData()
137
    {
138
        $def = $this->getDefinition();
139
        return new ArrayData(array(
140
            'ExportHost' => preg_replace("#http(s)?://#", '', Director::protocolAndHost()),
141
            'ExportDate' => date('d/m/Y H-i-s'),
142
            'ExportUser' => $this->member->FirstName.' '.$this->member->Surname,
143
            'ExportVersionFramework' => $this->ssVersion(),
144
            'ExportWorkflowDefName' => $this->processTitle($def->Title),
0 ignored issues
show
Documentation introduced by
The property Title does not exist on object<Symbiote\Advanced...cts\WorkflowDefinition>. Since you implemented __get, maybe consider adding a @property annotation.

Since your code implements the magic getter _get, this function will be called for any read access on an undefined variable. You can add the @property annotation to your class or interface to document the existence of this variable.

<?php

/**
 * @property int $x
 * @property int $y
 * @property string $text
 */
class MyLabel
{
    private $properties;

    private $allowedProperties = array('x', 'y', 'text');

    public function __get($name)
    {
        if (isset($properties[$name]) && in_array($name, $this->allowedProperties)) {
            return $properties[$name];
        } else {
            return null;
        }
    }

    public function __set($name, $value)
    {
        if (in_array($name, $this->allowedProperties)) {
            $properties[$name] = $value;
        } else {
            throw new \LogicException("Property $name is not defined.");
        }
    }

}

If the property has read access only, you can use the @property-read annotation instead.

Of course, you may also just have mistyped another name, in which case you should fix the error.

See also the PhpDoc documentation for @property.

Loading history...
145
            'ExportRemindDays' => $def->RemindDays,
0 ignored issues
show
Documentation introduced by
The property RemindDays does not exist on object<Symbiote\Advanced...cts\WorkflowDefinition>. Since you implemented __get, maybe consider adding a @property annotation.

Since your code implements the magic getter _get, this function will be called for any read access on an undefined variable. You can add the @property annotation to your class or interface to document the existence of this variable.

<?php

/**
 * @property int $x
 * @property int $y
 * @property string $text
 */
class MyLabel
{
    private $properties;

    private $allowedProperties = array('x', 'y', 'text');

    public function __get($name)
    {
        if (isset($properties[$name]) && in_array($name, $this->allowedProperties)) {
            return $properties[$name];
        } else {
            return null;
        }
    }

    public function __set($name, $value)
    {
        if (in_array($name, $this->allowedProperties)) {
            $properties[$name] = $value;
        } else {
            throw new \LogicException("Property $name is not defined.");
        }
    }

}

If the property has read access only, you can use the @property-read annotation instead.

Of course, you may also just have mistyped another name, in which case you should fix the error.

See also the PhpDoc documentation for @property.

Loading history...
146
            'ExportSort' => $def->Sort
0 ignored issues
show
Documentation introduced by
The property Sort does not exist on object<Symbiote\Advanced...cts\WorkflowDefinition>. Since you implemented __get, maybe consider adding a @property annotation.

Since your code implements the magic getter _get, this function will be called for any read access on an undefined variable. You can add the @property annotation to your class or interface to document the existence of this variable.

<?php

/**
 * @property int $x
 * @property int $y
 * @property string $text
 */
class MyLabel
{
    private $properties;

    private $allowedProperties = array('x', 'y', 'text');

    public function __get($name)
    {
        if (isset($properties[$name]) && in_array($name, $this->allowedProperties)) {
            return $properties[$name];
        } else {
            return null;
        }
    }

    public function __set($name, $value)
    {
        if (in_array($name, $this->allowedProperties)) {
            $properties[$name] = $value;
        } else {
            throw new \LogicException("Property $name is not defined.");
        }
    }

}

If the property has read access only, you can use the @property-read annotation instead.

Of course, you may also just have mistyped another name, in which case you should fix the error.

See also the PhpDoc documentation for @property.

Loading history...
147
        ));
148
    }
149
150
    /**
151
     * Try different ways of obtaining the current SilverStripe version for YAML output.
152
     *
153
     * @return string
154
     */
155
    private function ssVersion()
156
    {
157
        // Remove colons so they don't screw with YAML parsing
158
        $versionSapphire = str_replace(':', '', singleton(SapphireInfo::class)->Version());
159
        $versionLeftMain = str_replace(':', '', singleton(LeftAndMain::class)->CMSVersion());
160
        if ($versionSapphire != _t('SilverStripe\\Admin\\LeftAndMain.VersionUnknown', 'Unknown')) {
161
            return $versionSapphire;
162
        }
163
        return $versionLeftMain;
164
    }
165
166
    private function processTitle($title)
167
    {
168
        // If an import is exported and re-imported, the new export date is appended to Title, making for
169
        // a very long title
170
        return preg_replace("#\s[\d]+\/[\d]+\/[\d]+\s[\d]+-[\d]+-[\d]+(\s[\d]+)?#", '', $title);
171
    }
172
173
    /**
174
     * Prompt the client for file download.
175
     * We're "overriding" SS_HTTPRequest::send_file() for more robust cross-browser support
176
     *
177
     * @param array $filedata
178
     * @return HTTPResponse $response
179
     */
180
    public function sendFile($filedata)
181
    {
182
        $response = new HTTPResponse($filedata['body']);
183
        if (preg_match("#MSIE\s(6|7|8)?\.0#", $_SERVER['HTTP_USER_AGENT'])) {
184
            // IE headers
185
            $response->addHeader("Cache-Control", "public");
186
            $response->addHeader("Content-Disposition", "attachment; filename=\"".basename($filedata['name'])."\"");
187
            $response->addHeader("Content-Type", "application/force-download");
188
            $response->addHeader("Content-Type", "application/octet-stream");
189
            $response->addHeader("Content-Type", "application/download");
190
            $response->addHeader("Content-Type", $filedata['mime']);
191
            $response->addHeader("Content-Description", "File Transfer");
192
            $response->addHeader("Content-Length", $filedata['size']);
193
        } else {
194
            // Everyone else
195
            $response->addHeader("Content-Type", $filedata['mime']."; name=\"".addslashes($filedata['name'])."\"");
196
            $response->addHeader("Content-disposition", "attachment; filename=".addslashes($filedata['name']));
197
            $response->addHeader("Content-Length", $filedata['size']);
198
        }
199
        return $response;
200
    }
201
}
202