BulkLoader_Result   A
last analyzed

Complexity

Total Complexity 15

Size/Duplication

Total Lines 169
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 1

Importance

Changes 0
Metric Value
wmc 15
lcom 1
cbo 1
dl 0
loc 169
rs 10
c 0
b 0
f 0

11 Methods

Rating   Name   Duplication   Size   Complexity  
A ErrorCount() 0 4 1
A addError() 0 12 1
A merge() 0 7 1
A getTotal() 0 4 1
A getCreated() 0 4 1
A getUpdated() 0 4 1
A getDeleted() 0 4 1
A getErrors() 0 4 1
A getMessagesArray() 0 31 4
A getMessagesString() 0 4 1
A getMessageType() 0 10 2
1
<?php
2
3
namespace ilateral\SilverStripe\SlightlyBetterBulkLoader;
4
5
use SilverStripe\ORM\ValidationResult;
6
use SilverStripe\Dev\BulkLoader_Result as SS_BulkLoader_Result;
7
8
/**
9
 * Custom bulk loader result that also tracks errors in submission
10
 */
11
class BulkLoader_Result extends SS_BulkLoader_Result
12
{
13
14
    /**
15
     * List of errors tracked, each error should be an error message
16
     * (as a string).
17
     *
18
     * @var array (see {@link $created})
19
     */
20
    protected $errors = [];
21
22
    /**
23
     * Return the number of errors
24
     *
25
     * @return int
26
     */
27
    public function ErrorCount()
28
    {
29
        return count($this->errors);
30
    }
31
32
    /**
33
     * Add an error message to the stack
34
     *
35
     * @param string $message The error message
36
     *
37
     * @return self
38
     */
39
    public function addError($message, $id = null)
40
    {
41
        $this->lastChange = [
42
            'Message' => $message,
43
            'ID' => $id,
44
            '_BulkLoaderMessage' => $message
45
        ];
46
        $this->errors[] = $message;
47
        $this->lastChange['ChangeType'] = 'error';
48
49
        return $this;
50
    }
51
52
    /**
53
     * Merges another BulkLoader_Result into this one.
54
     *
55
     * @param BulkLoader_Result $other
0 ignored issues
show
Documentation introduced by
Should the type for parameter $other not be SS_BulkLoader_Result?

This check looks for @param annotations where the type inferred by our type inference engine differs from the declared type.

It makes a suggestion as to what type it considers more descriptive.

Most often this is a case of a parameter that can be null in addition to its declared types.

Loading history...
56
     */
57
    public function merge(SS_BulkLoader_Result $other)
58
    {
59
        $this->created = array_merge($this->created, $other->getCreated());
0 ignored issues
show
Bug introduced by
The method getCreated() does not exist on SilverStripe\Dev\BulkLoader_Result. Did you maybe mean create()?

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...
60
        $this->updated = array_merge($this->updated, $other->getUpdated());
0 ignored issues
show
Bug introduced by
The method getUpdated() does not exist on SilverStripe\Dev\BulkLoader_Result. Did you maybe mean Updated()?

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...
61
        $this->deleted = array_merge($this->deleted, $other->getDeleted());
0 ignored issues
show
Bug introduced by
The method getDeleted() does not exist on SilverStripe\Dev\BulkLoader_Result. Did you maybe mean Deleted()?

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...
62
        $this->errors = array_merge($this->errors, $other->getErrors());
0 ignored issues
show
Bug introduced by
It seems like you code against a specific sub-type and not the parent class SilverStripe\Dev\BulkLoader_Result as the method getErrors() does only exist in the following sub-classes of SilverStripe\Dev\BulkLoader_Result: ilateral\SilverStripe\Sl...oader\BulkLoader_Result. Maybe you want to instanceof check for one of these explicitly?

Let’s take a look at an example:

abstract class User
{
    /** @return string */
    abstract public function getPassword();
}

class MyUser extends User
{
    public function getPassword()
    {
        // return something
    }

    public function getDisplayName()
    {
        // return some name.
    }
}

class AuthSystem
{
    public function authenticate(User $user)
    {
        $this->logger->info(sprintf('Authenticating %s.', $user->getDisplayName()));
        // do something.
    }
}

In the above example, the authenticate() method works fine as long as you just pass instances of MyUser. However, if you now also want to pass a different sub-classes of User which does not have a getDisplayName() method, the code will break.

Available Fixes

  1. Change the type-hint for the parameter:

    class AuthSystem
    {
        public function authenticate(MyUser $user) { /* ... */ }
    }
    
  2. Add an additional type-check:

    class AuthSystem
    {
        public function authenticate(User $user)
        {
            if ($user instanceof MyUser) {
                $this->logger->info(/** ... */);
            }
    
            // or alternatively
            if ( ! $user instanceof MyUser) {
                throw new \LogicException(
                    '$user must be an instance of MyUser, '
                   .'other instances are not supported.'
                );
            }
    
        }
    }
    
Note: PHP Analyzer uses reverse abstract interpretation to narrow down the types inside the if block in such a case.
  1. Add the method to the parent class:

    abstract class User
    {
        /** @return string */
        abstract public function getPassword();
    
        /** @return string */
        abstract public function getDisplayName();
    }
    
Loading history...
63
    }
64
65
    /**
66
     * Get he total number of results tracked
67
     *
68
     * @return int
69
     */
70
    public function getTotal()
71
    {
72
        return $this->CreatedCount() + $this->UpdatedCount() + $this->DeletedCount() + $this->ErrorCount();
73
    }
74
75
    /**
76
     * Get created array
77
     *
78
     * @return array
79
     */
80
    public function getCreated()
81
    {
82
        return $this->created;
83
    }
84
85
    /**
86
     * Get updated array
87
     *
88
     * @return array
89
     */
90
    public function getUpdated()
91
    {
92
        return $this->updated;
93
    }
94
95
    /**
96
     * Get updated array
97
     *
98
     * @return array
99
     */
100
    public function getDeleted()
101
    {
102
        return $this->deleted;
103
    }
104
105
    /**
106
     * Get errors array
107
     *
108
     * @return array
109
     */
110
    public function getErrors()
111
    {
112
        return $this->errors;
113
    }
114
115
    /**
116
     * Get an array of all messages stored
117
     *
118
     * @return array
119
     */
120
    public function getMessagesArray()
121
    {
122
        $messages = [];
123
124
        if ($this->CreatedCount() > 0) {
125
            $messages[] = _t(
126
                'SilverStripe\\Admin\\ModelAdmin.IMPORTEDRECORDS',
127
                "Imported {count} records.",
128
                ['count' => $this->CreatedCount()]
129
            );
130
        }
131
132
        if ($this->UpdatedCount() > 0) {
133
            $messages[] = _t(
134
                'SilverStripe\\Admin\\ModelAdmin.UPDATEDRECORDS',
135
                "Updated {count} records.",
136
                ['count' => $this->UpdatedCount()]
137
            );
138
        }
139
140
        if ($this->DeletedCount() > 0) {
141
            $messages[] = _t(
142
                'SilverStripe\\Admin\\ModelAdmin.DELETEDRECORDS',
143
                "Deleted {count} records.",
144
                ['count' => $this->DeletedCount()]
145
            );
146
        }
147
        
148
        // Finally include any errors
149
        return array_merge($messages, $this->getErrors());
150
    }
151
152
    /**
153
     * Return a string of all messages (that can be rendered into a message window)
154
     *
155
     * @param bool $html Add the newline as a HTML "<br/>"
0 ignored issues
show
Bug introduced by
There is no parameter named $html. 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...
156
     *
157
     * @return string
158
     */
159
    public function getMessagesString($delimiter = ";")
160
    {
161
        return implode($delimiter, $this->getMessagesArray());
162
    }
163
164
    /**
165
     * Get the "type" of message (using SilverStripe's Validation result)
166
     *
167
     * @return string
168
     */
169
    public function getMessageType()
170
    {
171
        $type = ValidationResult::TYPE_GOOD;
172
173
        if (count($this->getErrors()) > 0) {
174
            $type = ValidationResult::TYPE_ERROR;
175
        }
176
177
        return $type;
178
    }
179
}
180