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.
Completed
Pull Request — master (#336)
by
unknown
02:01
created

WorkflowDefinitionExporter::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 5
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 5
rs 9.4285
c 0
b 0
f 0
cc 1
eloc 3
nc 1
nop 1
1
<?php
2
3
namespace Symbiote\AdvancedWorkflow\Admin;
4
5
use SilverStripe\Admin\LeftAndMain;
6
use SilverStripe\Control\Director;
7
use SilverStripe\Control\HTTPResponse;
8
use SilverStripe\Core\Config\Configurable;
9
use SilverStripe\Dev\SapphireInfo;
10
use SilverStripe\ORM\DataObject;
11
use SilverStripe\Security\Member;
12
use SilverStripe\Security\Permission;
13
use SilverStripe\Security\Security;
14
use SilverStripe\View\ArrayData;
15
use SilverStripe\View\SSViewer;
16
use Symbiote\AdvancedWorkflow\DataObjects\WorkflowDefinition;
17
18
/**
19
 * Allows workflow definitions to be exported from one SilverStripe install, ready for import into another.
20
 *
21
 * YAML is used for export as it's native to SilverStripe's config system and we're using {@link WorkflowTemplate}
22
 * for some of the import-specific heavy lifting, which is already heavily predicated on YAML.
23
 *
24
 * @todo
25
 *  - If workflow-def is created badly, the "update template definition" logic, sometimes doesn't work
26
 *
27
 * @author  [email protected]
28
 * @license BSD License (http://silverstripe.org/bsd-license/)
29
 * @package advancedworkflow
30
 */
31
class WorkflowDefinitionExporter
32
{
33
    use Configurable;
34
35
    /**
36
     * The base filename of the file to the exported
37
     *
38
     * @config
39
     * @var string
40
     */
41
    private static $export_filename_prefix = 'workflow-definition-export';
0 ignored issues
show
Unused Code introduced by
The property $export_filename_prefix is not used and could be removed.

This check marks private properties in classes that are never used. Those properties can be removed.

Loading history...
42
    /**
43
     *
44
     * @var Member
45
     */
46
    protected $member;
47
    /**
48
     *
49
     * @var WorkflowDefinition
50
     */
51
    protected $workflowDefinition;
52
53
    /**
54
     *
55
     * @param number $definitionID
56
     * @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...
57
     */
58
    public function __construct($definitionID)
59
    {
60
        $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...
61
        $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...
62
    }
63
64
    /**
65
     *
66
     * @param Member $member
67
     */
68
    public function setMember($member)
69
    {
70
        $this->member = $member;
71
    }
72
73
    /**
74
     * @return WorkflowDefinition
75
     */
76
    public function getDefinition()
77
    {
78
        return $this->workflowDefinition;
79
    }
80
81
    /**
82
     * Runs the export
83
     *
84
     * @return string $template
85
     */
86
    public function export()
87
    {
88
        // Disable any access to use of WorkflowExport if user has no SecurityAdmin access
89
        if (!Permission::check('CMS_ACCESS_SecurityAdmin')) {
90
            throw Exception(_t('SilverStripe\\ErrorPage\\ErrorPage.CODE_403', '403 - Forbidden'), 403);
91
        }
92
        $def = $this->getDefinition();
93
        $templateData = new ArrayData(array(
94
            'ExportMetaData' => $this->ExportMetaData(),
95
            '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...
96
            '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...
97
            '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...
98
        ));
99
        return $this->format($templateData);
100
    }
101
102
    /**
103
     * Format the exported data as YAML.
104
     *
105
     * @param ArrayData $templateData
106
     * @return void
107
     */
108
    public function format($templateData)
109
    {
110
        $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...
111
        // Temporary until we find the source of the replacement in SSViewer
112
        $processed = str_replace('&amp;', '&', $viewer);
113
        // Clean-up newline "gaps" that SSViewer leaves behind from the placement of template control structures
114
        return preg_replace("#^\R+|^[\t\s]*\R+#m", '', $processed);
115
    }
116
117
    /**
118
     * Returns the size of the current export in bytes.
119
     * Used for pushing data to the browser to prompt for download
120
     *
121
     * @param string $str
122
     * @return number $bytes
123
     */
124
    public function getExportSize($str)
125
    {
126
        return mb_strlen($str, 'UTF-8');
127
    }
128
129
    /**
130
     * Generate template vars for metadata
131
     *
132
     * @return ArrayData
133
     */
134
    public function ExportMetaData()
135
    {
136
        $def = $this->getDefinition();
137
        return new ArrayData(array(
138
            'ExportHost' => preg_replace("#http(s)?://#", '', Director::protocolAndHost()),
139
            'ExportDate' => date('d/m/Y H-i-s'),
140
            'ExportUser' => $this->member->FirstName . ' ' . $this->member->Surname,
141
            'ExportVersionFramework' => $this->ssVersion(),
142
            '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...
143
            '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...
144
            '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...
145
        ));
146
    }
147
148
    /**
149
     * Try different ways of obtaining the current SilverStripe version for YAML output.
150
     *
151
     * @return string
152
     */
153
    private function ssVersion()
154
    {
155
        // Remove colons so they don't screw with YAML parsing
156
        $versionSapphire = str_replace(':', '', singleton(SapphireInfo::class)->Version());
157
        $versionLeftMain = str_replace(':', '', singleton(LeftAndMain::class)->CMSVersion());
158
        if ($versionSapphire != _t('SilverStripe\\Admin\\LeftAndMain.VersionUnknown', 'Unknown')) {
159
            return $versionSapphire;
160
        }
161
        return $versionLeftMain;
162
    }
163
164
    private function processTitle($title)
165
    {
166
        // If an import is exported and re-imported, the new export date is appended to Title,
167
        // making for a very long title
168
        return preg_replace("#\s[\d]+\/[\d]+\/[\d]+\s[\d]+-[\d]+-[\d]+(\s[\d]+)?#", '', $title);
169
    }
170
171
    /**
172
     * Prompt the client for file download.
173
     * We're "overriding" SS_HTTPRequest::send_file() for more robust cross-browser support
174
     *
175
     * @param array $filedata
176
     * @return HTTPResponse $response
177
     */
178
    public function sendFile($filedata)
0 ignored issues
show
Coding Style introduced by
sendFile uses the super-global variable $_SERVER which is generally not recommended.

Instead of super-globals, we recommend to explicitly inject the dependencies of your class. This makes your code less dependent on global state and it becomes generally more testable:

// Bad
class Router
{
    public function generate($path)
    {
        return $_SERVER['HOST'].$path;
    }
}

// Better
class Router
{
    private $host;

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

    public function generate($path)
    {
        return $this->host.$path;
    }
}

class Controller
{
    public function myAction(Request $request)
    {
        // Instead of
        $page = isset($_GET['page']) ? intval($_GET['page']) : 1;

        // Better (assuming you use the Symfony2 request)
        $page = $request->query->get('page', 1);
    }
}
Loading history...
179
    {
180
        $response = new HTTPResponse($filedata['body']);
181
        if (preg_match("#MSIE\s(6|7|8)?\.0#", $_SERVER['HTTP_USER_AGENT'])) {
182
            // IE headers
183
            $response->addHeader("Cache-Control", "public");
184
            $response->addHeader("Content-Disposition", "attachment; filename=\"" . basename($filedata['name']) . "\"");
185
            $response->addHeader("Content-Type", "application/force-download");
186
            $response->addHeader("Content-Type", "application/octet-stream");
187
            $response->addHeader("Content-Type", "application/download");
188
            $response->addHeader("Content-Type", $filedata['mime']);
189
            $response->addHeader("Content-Description", "File Transfer");
190
            $response->addHeader("Content-Length", $filedata['size']);
191
        } else {
192
            // Everyone else
193
            $response->addHeader(
194
                "Content-Type",
195
                $filedata['mime'] . "; name=\"" . addslashes($filedata['name']) . "\""
196
            );
197
            $response->addHeader("Content-disposition", "attachment; filename=" . addslashes($filedata['name']));
198
            $response->addHeader("Content-Length", $filedata['size']);
199
        }
200
        return $response;
201
    }
202
}
203