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.

MemoryWorkflowStoreTest   D
last analyzed

Complexity

Total Complexity 44

Size/Duplication

Total Lines 1047
Duplicated Lines 6.49 %

Coupling/Cohesion

Components 2
Dependencies 8

Importance

Changes 7
Bugs 0 Features 0
Metric Value
wmc 44
c 7
b 0
f 0
lcom 2
cbo 8
dl 68
loc 1047
rs 4.6097

35 Methods

Rating   Name   Duplication   Size   Complexity  
A setUp() 0 4 1
A testInit() 0 6 1
A testInitCorrect() 0 6 1
A testGetPropertySetWithCachedEntry() 10 10 1
A testGetPropertySetWithIncorrectEntryId() 0 5 1
A testGetPropertySet() 0 18 1
A testSetEntryState() 0 20 1
A testFindNotIntEntry() 0 5 1
A testFindNotExistsEntry() 0 5 1
A testFindNotEntryInterfaceEntry() 0 8 1
A testFindCorrectEntry() 10 10 1
A testCreateEntry() 11 11 1
A testCreateCurrentStep() 0 16 1
A testFindCurrentStepWithIncorrectId() 0 5 1
A testFindCurrectStep() 0 6 1
A testMarkFinishedForEmptyCurrentSteps() 0 16 1
A testMarkFinished() 0 57 1
B testReset() 0 27 1
A testMoveNotExistsInCurrentStepsStepToHistory() 0 15 1
A testMoveToHistory() 0 64 1
A testFindHistoryStepWithEmptyHistory() 0 7 1
A testFindHistoryStep() 0 19 1
A testQueryWithEmptyEntryCache() 0 9 1
A testQueryEntryName() 0 69 1
A testQueryEntryNameWithIncorrectOperator() 13 13 1
A testEntryStateWithIncorrectValue() 12 12 1
A testEntryState() 0 49 1
A testEntryStateWithIncorrectOperator() 0 17 1
A testEntryWithIncorrectField() 12 12 1
C testQueryActionInCurrentSteps() 0 147 7
B testQueryActionInHistorySteps() 0 103 4
A testQueryStepsWithUnknownContext() 0 22 1
B testSuccessNestedExpression() 0 31 1
B testNestedExpressionWithoutResult() 0 41 1
A testNestedExpressionWithIncorrectOperator() 0 22 1

How to fix   Duplicated Code    Complexity   

Duplicated Code

Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.

Common duplication problems, and corresponding solutions are:

Complex Class

 Tip:   Before tackling complexity, make sure that you eliminate any duplication first. This often can reduce the size of classes significantly.

Complex classes like MemoryWorkflowStoreTest often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes. You can also have a look at the cohesion graph to spot any un-connected, or weakly-connected components.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

While breaking up the class, it is a good idea to analyze how other classes use MemoryWorkflowStoreTest, and based on these observations, apply Extract Interface, too.

1
<?php
2
/**
3
 * Created by PhpStorm.
4
 * User: keanor
5
 * Date: 26.10.15
6
 * Time: 20:28
7
 */
8
namespace OldTown\Workflow\PhpUnitTest\Spi\Memory;
9
10
use DateTime;
11
use OldTown\Workflow\Exception\InvalidArgumentException;
12
use OldTown\Workflow\Query\FieldExpression;
13
use OldTown\Workflow\Query\NestedExpression;
14
use OldTown\Workflow\Query\WorkflowExpressionQuery;
15
use OldTown\Workflow\Spi\Memory\MemoryWorkflowStore;
16
use OldTown\Workflow\Spi\SimpleStep;
17
use OldTown\Workflow\Spi\SimpleWorkflowEntry;
18
use OldTown\Workflow\Spi\StepInterface;
19
use OldTown\Workflow\Spi\WorkflowEntryInterface;
20
use PHPUnit_Framework_TestCase as TestCase;
21
use ReflectionProperty;
22
use SplObjectStorage;
23
24
/**
25
 * Class MemoryWorkflowStoreTest
26
 * @package OldTown\Workflow\PhpUnitTest\Spi\Memory
27
 */
28
class MemoryWorkflowStoreTest extends TestCase
29
{
30
    /**
31
     * Из-за того что методы статичные, при создании через new они не всегда пустые
32
     */
33
    protected function setUp()
34
    {
35
        MemoryWorkflowStore::reset();
36
    }
37
38
    /**
39
     * Поскольку init пустой то тестим только type hinting
40
     */
41
    public function testInit()
42
    {
43
        $memory = new MemoryWorkflowStore();
44
        $this->setExpectedException('PHPUnit_Framework_Error');
45
        $memory->init('this is not array');
0 ignored issues
show
Documentation introduced by
'this is not array' is of type string, but the function expects a array.

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...
46
    }
47
48
    /**
49
     * Проверяем что init ничего не возвращает
50
     */
51
    public function testInitCorrect()
52
    {
53
        $memory = new MemoryWorkflowStore();
54
        $result = $memory->init([]);
0 ignored issues
show
Bug introduced by
Are you sure the assignment to $result is correct as $memory->init(array()) (which targets OldTown\Workflow\Spi\Mem...ryWorkflowStore::init()) seems to always return null.

This check looks for function or method calls that always return null and whose return value is assigned to a variable.

class A
{
    function getObject()
    {
        return null;
    }

}

$a = new A();
$object = $a->getObject();

The method getObject() can return nothing but null, so it makes no sense to assign that value to a variable.

The reason is most likely that a function or method is imcomplete or has been reduced for debug purposes.

Loading history...
55
        $this->assertNull($result);
56
    }
57
58
    /**
59
     * Тестируем корректное возвращение WorkflowEntryInterface из кэша
60
     */
61 View Code Duplication
    public function testGetPropertySetWithCachedEntry()
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
62
    {
63
        $memory = new MemoryWorkflowStore();
64
        $refStaticProp = new ReflectionProperty(MemoryWorkflowStore::class, 'propertySetCache');
65
        $refStaticProp->setAccessible(true);
66
        $entryMock = $this->getMockBuilder(WorkflowEntryInterface::class)->getMock();
67
        $refStaticProp->setValue([123 => $entryMock]);
68
69
        $this->assertEquals($entryMock, $memory->getPropertySet(123));
70
    }
71
72
    /**
73
     * Проверяем наличие exception при некорректном entryId
74
     *
75
     * @expectedException \OldTown\Workflow\Exception\ArgumentNotNumericException
76
     */
77
    public function testGetPropertySetWithIncorrectEntryId()
78
    {
79
        $memory = new MemoryWorkflowStore();
80
        $memory->getPropertySet('not int');
81
    }
82
83
    /**
84
     * Тестируем корректное получение и сохранение WorkflowEntryInterface в кэш
85
     */
86
    public function testGetPropertySet()
87
    {
88
        /** @var MemoryWorkflowStore|\PHPUnit_Framework_MockObject_MockObject $mockMemoryStore */
89
        $mockMemoryStore = $this->getMockBuilder(MemoryWorkflowStore::class)
90
            ->setMethods(['createPropertySet'])
91
            ->getMock();
92
93
        $entryMock = $this->getMockBuilder(WorkflowEntryInterface::class)->getMock();
94
        $mockMemoryStore->expects($this->once())
0 ignored issues
show
Bug introduced by
The method expects does only exist in PHPUnit_Framework_MockObject_MockObject, but not in OldTown\Workflow\Spi\Memory\MemoryWorkflowStore.

It seems like the method you are trying to call exists only in some of the possible types.

Let’s take a look at an example:

class A
{
    public function foo() { }
}

class B extends A
{
    public function bar() { }
}

/**
 * @param A|B $x
 */
function someFunction($x)
{
    $x->foo(); // This call is fine as the method exists in A and B.
    $x->bar(); // This method only exists in B and might cause an error.
}

Available Fixes

  1. Add an additional type-check:

    /**
     * @param A|B $x
     */
    function someFunction($x)
    {
        $x->foo();
    
        if ($x instanceof B) {
            $x->bar();
        }
    }
    
  2. Only allow a single type to be passed if the variable comes from a parameter:

    function someFunction(B $x) { /** ... */ }
    
Loading history...
95
            ->method('createPropertySet')
96
            ->will($this->returnValue($entryMock));
97
98
        $this->assertEquals($entryMock, $mockMemoryStore->getPropertySet(123));
0 ignored issues
show
Bug introduced by
The method getPropertySet does only exist in OldTown\Workflow\Spi\Memory\MemoryWorkflowStore, but not in PHPUnit_Framework_MockObject_MockObject.

It seems like the method you are trying to call exists only in some of the possible types.

Let’s take a look at an example:

class A
{
    public function foo() { }
}

class B extends A
{
    public function bar() { }
}

/**
 * @param A|B $x
 */
function someFunction($x)
{
    $x->foo(); // This call is fine as the method exists in A and B.
    $x->bar(); // This method only exists in B and might cause an error.
}

Available Fixes

  1. Add an additional type-check:

    /**
     * @param A|B $x
     */
    function someFunction($x)
    {
        $x->foo();
    
        if ($x instanceof B) {
            $x->bar();
        }
    }
    
  2. Only allow a single type to be passed if the variable comes from a parameter:

    function someFunction(B $x) { /** ... */ }
    
Loading history...
99
100
        $refProperty = new ReflectionProperty(MemoryWorkflowStore::class, 'propertySetCache');
101
        $refProperty->setAccessible(true);
102
        $this->assertEquals([123 => $entryMock], $refProperty->getValue($mockMemoryStore));
103
    }
104
105
    /**
106
     * Проверяем что для сохраненного entry устанавливается статус
107
     *
108
     * findEntry мы тут не тестируем
109
     */
110
    public function testSetEntryState()
111
    {
112
        $entryMock = $this->getMockBuilder(SimpleWorkflowEntry::class)
113
            ->setMethods(['setState'])
114
            ->disableOriginalConstructor()
115
            ->getMock();
116
117
        $entryMock->expects($this->once())
118
            ->method('setState')
119
            ->with($this->equalTo(456));
120
121
        /** @var MemoryWorkflowStore|\PHPUnit_Framework_MockObject_MockObject $memoryMock */
122
        $memoryMock = $this->getMock(MemoryWorkflowStore::class, ['findEntry']);
123
        $memoryMock->expects($this->once())
0 ignored issues
show
Bug introduced by
The method expects does only exist in PHPUnit_Framework_MockObject_MockObject, but not in OldTown\Workflow\Spi\Memory\MemoryWorkflowStore.

It seems like the method you are trying to call exists only in some of the possible types.

Let’s take a look at an example:

class A
{
    public function foo() { }
}

class B extends A
{
    public function bar() { }
}

/**
 * @param A|B $x
 */
function someFunction($x)
{
    $x->foo(); // This call is fine as the method exists in A and B.
    $x->bar(); // This method only exists in B and might cause an error.
}

Available Fixes

  1. Add an additional type-check:

    /**
     * @param A|B $x
     */
    function someFunction($x)
    {
        $x->foo();
    
        if ($x instanceof B) {
            $x->bar();
        }
    }
    
  2. Only allow a single type to be passed if the variable comes from a parameter:

    function someFunction(B $x) { /** ... */ }
    
Loading history...
124
            ->method('findEntry')
125
            ->with($this->equalTo(123))
126
            ->will($this->returnValue($entryMock));
127
128
        $memoryMock->setEntryState(123, 456);
0 ignored issues
show
Bug introduced by
The method setEntryState does only exist in OldTown\Workflow\Spi\Memory\MemoryWorkflowStore, but not in PHPUnit_Framework_MockObject_MockObject.

It seems like the method you are trying to call exists only in some of the possible types.

Let’s take a look at an example:

class A
{
    public function foo() { }
}

class B extends A
{
    public function bar() { }
}

/**
 * @param A|B $x
 */
function someFunction($x)
{
    $x->foo(); // This call is fine as the method exists in A and B.
    $x->bar(); // This method only exists in B and might cause an error.
}

Available Fixes

  1. Add an additional type-check:

    /**
     * @param A|B $x
     */
    function someFunction($x)
    {
        $x->foo();
    
        if ($x instanceof B) {
            $x->bar();
        }
    }
    
  2. Only allow a single type to be passed if the variable comes from a parameter:

    function someFunction(B $x) { /** ... */ }
    
Loading history...
129
    }
130
131
    /**
132
     * Поиск entry с некорректным id
133
     *
134
     * @expectedException \OldTown\Workflow\Exception\ArgumentNotNumericException
135
     */
136
    public function testFindNotIntEntry()
137
    {
138
        $memory = new MemoryWorkflowStore();
139
        $memory->findEntry('not int');
140
    }
141
142
    /**
143
     * Поиск несуществующего entry
144
     *
145
     * @expectedException \OldTown\Workflow\Exception\NotFoundWorkflowEntryException
146
     */
147
    public function testFindNotExistsEntry()
148
    {
149
        $memory = new MemoryWorkflowStore();
150
        $memory->findEntry(123);
151
    }
152
153
    /**
154
     * Проверка, что при некорректно сохраненном entry метод findEntry ругнется
155
     *
156
     * @expectedException \OldTown\Workflow\Exception\InvalidWorkflowEntryException
157
     */
158
    public function testFindNotEntryInterfaceEntry()
159
    {
160
        $memory = new MemoryWorkflowStore();
161
        $refProp = new \ReflectionProperty(MemoryWorkflowStore::class, 'entryCache');
162
        $refProp->setAccessible(true);
163
        $refProp->setValue($memory, [123 => 'asd']);
164
        $memory->findEntry(123);
165
    }
166
167
    /**
168
     * Проверяем что при корректно сохраненном entry метод findEntry его вернет
169
     */
170 View Code Duplication
    public function testFindCorrectEntry()
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
171
    {
172
        $memory = new MemoryWorkflowStore();
173
        $refProp = new ReflectionProperty(MemoryWorkflowStore::class, 'entryCache');
174
        $refProp->setAccessible(true);
175
        $entryMock = $this->getMockBuilder(WorkflowEntryInterface::class)->getMock();
176
        $refProp->setValue($memory, [123 => $entryMock]);
177
178
        $this->assertEquals($entryMock, $memory->findEntry(123));
179
    }
180
181
    /**
182
     * Тестируем создание + добавление в кэш
183
     */
184 View Code Duplication
    public function testCreateEntry()
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
185
    {
186
        $memory = new MemoryWorkflowStore();
187
        $entry = $memory->createEntry('wokflow_name');
188
189
        $this->assertInstanceOf(WorkflowEntryInterface::class, $entry);
190
191
        $refProp = new ReflectionProperty(MemoryWorkflowStore::class, 'entryCache');
192
        $refProp->setAccessible(true);
193
        $this->assertEquals([1 => $entry], $refProp->getValue($memory));
194
    }
195
196
    /**
197
     * Тестируем создание текущего шага
198
     */
199
    public function testCreateCurrentStep()
200
    {
201
        $memory = new MemoryWorkflowStore();
202
        $d = new DateTime();
203
        $step = $memory->createCurrentStep(123, 2, 'ow', $d, $d, 'stat', [1, 2, 3]);
204
205
        $refProp = new ReflectionProperty(MemoryWorkflowStore::class, 'currentStepsCache');
206
        $refProp->setAccessible(true);
207
        $stepsCache = $refProp->getValue($memory);
208
209
        $this->assertTrue(array_key_exists(123, $stepsCache));
210
        /** @var SplObjectStorage $objectStorage */
211
        $objectStorage = $stepsCache[123];
212
        $this->assertInstanceOf(SplObjectStorage::class, $objectStorage);
213
        $this->assertTrue($objectStorage->contains($step));
214
    }
215
216
    /**
217
     * Поиск текущего шага с некорректным id
218
     *
219
     * @expectedException \OldTown\Workflow\Exception\ArgumentNotNumericException
220
     */
221
    public function testFindCurrentStepWithIncorrectId()
222
    {
223
        $memory = new MemoryWorkflowStore();
224
        $memory->findCurrentSteps('asdasd');
225
    }
226
227
    /**
228
     * Тестируем создание пустого контейнера шага
229
     */
230
    public function testFindCurrectStep()
231
    {
232
        $memory = new MemoryWorkflowStore();
233
        $step = $memory->findCurrentSteps(123);
234
        $this->assertInstanceOf(SplObjectStorage::class, $step);
235
    }
236
237
    /**
238
     * Тестируем корректную работу метода при пустом currentSteps
239
     */
240
    public function testMarkFinishedForEmptyCurrentSteps()
241
    {
242
        $memory = new MemoryWorkflowStore();
243
        /** @var StepInterface|\PHPUnit_Framework_MockObject_MockObject $step */
244
        $step = $this->getMockBuilder(SimpleStep::class)
245
            ->setMethods(['getEntryId'])
246
            ->disableOriginalConstructor()
247
            ->getMock();
248
249
        $step->expects($this->once())
0 ignored issues
show
Bug introduced by
The method expects does only exist in PHPUnit_Framework_MockObject_MockObject, but not in OldTown\Workflow\Spi\StepInterface.

It seems like the method you are trying to call exists only in some of the possible types.

Let’s take a look at an example:

class A
{
    public function foo() { }
}

class B extends A
{
    public function bar() { }
}

/**
 * @param A|B $x
 */
function someFunction($x)
{
    $x->foo(); // This call is fine as the method exists in A and B.
    $x->bar(); // This method only exists in B and might cause an error.
}

Available Fixes

  1. Add an additional type-check:

    /**
     * @param A|B $x
     */
    function someFunction($x)
    {
        $x->foo();
    
        if ($x instanceof B) {
            $x->bar();
        }
    }
    
  2. Only allow a single type to be passed if the variable comes from a parameter:

    function someFunction(B $x) { /** ... */ }
    
Loading history...
250
            ->method('getEntryId')
251
            ->will($this->returnValue(123));
252
253
        $result = $memory->markFinished($step, 1, new DateTime(), 'done', 'petrov');
254
        $this->assertNull($result);
255
    }
256
257
    /**
258
     * Тестируем корректную работу
259
     */
260
    public function testMarkFinished()
261
    {
262
        // Данные для проверки
263
        $id = 2;
264
        $entryId = 123;
265
        $actionId = 1;
266
        $finishDate = new DateTime();
267
        $status = 'done';
268
        $caller = 'Petrov';
269
270
        $savedStep = $this->getMockBuilder(SimpleStep::class)
271
            ->setMethods(['getId', 'setStatus', 'setActionId', 'setFinishDate', 'setCaller'])
272
            ->disableOriginalConstructor()
273
            ->getMock();
274
275
        $savedStep->expects($this->once())
276
            ->method('getId')
277
            ->will($this->returnValue($id));
278
        $savedStep->expects($this->once())
279
            ->method('setStatus')
280
            ->with($this->equalTo($status));
281
        $savedStep->expects($this->once())
282
            ->method('setActionId')
283
            ->with($this->equalTo($actionId));
284
        $savedStep->expects($this->once())
285
            ->method('setFinishDate')
286
            ->with($this->equalTo($finishDate));
287
        $savedStep->expects($this->once())
288
            ->method('setCaller')
289
            ->with($this->equalTo($caller));
290
291
        $currentSteps = new SplObjectStorage();
292
        $currentSteps->attach($savedStep);
293
294
        /** @var MemoryWorkflowStore|\PHPUnit_Framework_MockObject_MockObject $storage */
295
        $storage = $this->getMockBuilder(MemoryWorkflowStore::class)
296
            ->setMethods(['findCurrentSteps'])
297
            ->getMock();
298
        $storage->expects($this->once())
0 ignored issues
show
Bug introduced by
The method expects does only exist in PHPUnit_Framework_MockObject_MockObject, but not in OldTown\Workflow\Spi\Memory\MemoryWorkflowStore.

It seems like the method you are trying to call exists only in some of the possible types.

Let’s take a look at an example:

class A
{
    public function foo() { }
}

class B extends A
{
    public function bar() { }
}

/**
 * @param A|B $x
 */
function someFunction($x)
{
    $x->foo(); // This call is fine as the method exists in A and B.
    $x->bar(); // This method only exists in B and might cause an error.
}

Available Fixes

  1. Add an additional type-check:

    /**
     * @param A|B $x
     */
    function someFunction($x)
    {
        $x->foo();
    
        if ($x instanceof B) {
            $x->bar();
        }
    }
    
  2. Only allow a single type to be passed if the variable comes from a parameter:

    function someFunction(B $x) { /** ... */ }
    
Loading history...
299
            ->method('findCurrentSteps')
300
            ->with($this->equalTo($entryId))
301
            ->will($this->returnValue($currentSteps));
302
303
        $step = $this->getMockBuilder(SimpleStep::class)
304
            ->setMethods(['getId', 'getEntryId'])
305
            ->disableOriginalConstructor()
306
            ->getMock();
307
        $step->expects($this->once())
308
            ->method('getEntryId')
309
            ->will($this->returnValue($entryId));
310
        $step->expects($this->once())
311
            ->method('getId')
312
            ->will($this->returnValue($id));
313
314
        $markedStep = $storage->markFinished($step, $actionId, $finishDate, $status, $caller);
0 ignored issues
show
Bug introduced by
The method markFinished does only exist in OldTown\Workflow\Spi\Memory\MemoryWorkflowStore, but not in PHPUnit_Framework_MockObject_MockObject.

It seems like the method you are trying to call exists only in some of the possible types.

Let’s take a look at an example:

class A
{
    public function foo() { }
}

class B extends A
{
    public function bar() { }
}

/**
 * @param A|B $x
 */
function someFunction($x)
{
    $x->foo(); // This call is fine as the method exists in A and B.
    $x->bar(); // This method only exists in B and might cause an error.
}

Available Fixes

  1. Add an additional type-check:

    /**
     * @param A|B $x
     */
    function someFunction($x)
    {
        $x->foo();
    
        if ($x instanceof B) {
            $x->bar();
        }
    }
    
  2. Only allow a single type to be passed if the variable comes from a parameter:

    function someFunction(B $x) { /** ... */ }
    
Loading history...
315
        $this->assertEquals($savedStep, $markedStep);
316
    }
317
318
    /**
319
     * Проверяем что reset очищает все нужные св-ва
320
     */
321
    public function testReset()
322
    {
323
        $memory = new MemoryWorkflowStore();
324
325
        $refEntryProp = new ReflectionProperty(MemoryWorkflowStore::class, 'entryCache');
326
        $refEntryProp->setAccessible(true);
327
        $refEntryProp->setValue($memory, [123 => 'not empty array']);
328
329
        $refCurStepsProp = new ReflectionProperty(MemoryWorkflowStore::class, 'currentStepsCache');
330
        $refCurStepsProp->setAccessible(true);
331
        $refCurStepsProp->setValue($memory, [123 => 'not empty array']);
332
333
        $refHisStepsProp = new ReflectionProperty(MemoryWorkflowStore::class, 'historyStepsCache');
334
        $refHisStepsProp->setAccessible(true);
335
        $refHisStepsProp->setValue($memory, [123 => 'not empty array']);
336
337
        $refPropSetStepsProp = new ReflectionProperty(MemoryWorkflowStore::class, 'propertySetCache');
338
        $refPropSetStepsProp->setAccessible(true);
339
        $refPropSetStepsProp->setValue($memory, [123 => 'not empty array']);
340
341
        $memory->reset();
342
343
        $this->assertEquals($refEntryProp->getValue($memory), []);
344
        $this->assertEquals($refCurStepsProp->getValue($memory), []);
345
        $this->assertEquals($refHisStepsProp->getValue($memory), []);
346
        $this->assertEquals($refPropSetStepsProp->getValue($memory), []);
347
    }
348
349
    /**
350
     * Проверяем отсутствие ошибок при перемещении отсутствующего шага в историю
351
     */
352
    public function testMoveNotExistsInCurrentStepsStepToHistory()
353
    {
354
        // Мок для шага который будем перемещать в историю
355
        $step = $this->getMockBuilder(SimpleStep::class)
356
            ->disableOriginalConstructor()
357
            ->setMethods(['getEntryId', 'getId'])
358
            ->getMock();
359
360
        $step->expects($this->once())
361
            ->method('getEntryId')
362
            ->will($this->returnValue(123));
363
364
        $memory = new MemoryWorkflowStore();
365
        $memory->moveToHistory($step);
366
    }
367
368
    /**
369
     * Проверяем корректное перемещение шага в историю
370
     */
371
    public function testMoveToHistory()
372
    {
373
        // Мок который будет лежать в currentSteps
374
        $currentStep = $this->getMockBuilder(SimpleStep::class)
375
            ->disableOriginalConstructor()
376
            ->setMethods(['getId'])
377
            ->getMock();
378
379
        $currentStep->expects($this->once())
380
            ->method('getId')
381
            ->will($this->returnValue(2));
382
383
        $currentSteps = new SplObjectStorage();
384
        $currentSteps->attach($currentStep);
385
386
        // Мок который будет лежать в истории
387
        $historyStep = $this->getMockBuilder(SimpleStep::class)
388
            ->disableOriginalConstructor()
389
            ->setMethods(['getId'])
390
            ->getMock();
391
392
        $historyStep->expects($this->once())
393
            ->method('getId')
394
            ->will($this->returnValue(2));
395
396
        $historySteps = new SplObjectStorage();
397
        $historySteps->attach($historyStep);
398
399
        // Мок для шага который будем перемещать в историю
400
        $step = $this->getMockBuilder(SimpleStep::class)
401
            ->disableOriginalConstructor()
402
            ->setMethods(['getEntryId', 'getId'])
403
            ->getMock();
404
405
        $step->expects($this->once())
406
            ->method('getEntryId')
407
            ->will($this->returnValue(123));
408
409
        $step->expects($this->exactly(2))
410
            ->method('getId')
411
            ->will($this->returnValue(2));
412
413
        $memory = $this->getMockBuilder(MemoryWorkflowStore::class)
414
            ->setMethods(['findCurrentSteps'])
415
            ->getMock();
416
417
        $memory->expects($this->once())
418
            ->method('findCurrentSteps')
419
            ->with($this->equalTo(123))
420
            ->will($this->returnValue($currentSteps));
421
422
        $refHistory = new ReflectionProperty(MemoryWorkflowStore::class, 'historyStepsCache');
423
        $refHistory->setAccessible(true);
424
        $refHistory->setValue($memory, [123 => $historySteps]);
425
426
        $memory->moveToHistory($step);
427
428
        // Проверяем что шаг исчез из currentSteps
429
        $this->assertEquals($currentSteps->count(), 0);
430
431
        // Проверяем что шаг появился в historySteps
432
        $historyArray = $refHistory->getValue($memory);
433
        $this->assertTrue(array_key_exists(123, $historyArray));
434
    }
435
436
    /**
437
     * Проверяем что при отсутствии шага в истории, будет возвращен пустой SplObjectStorage
438
     */
439
    public function testFindHistoryStepWithEmptyHistory()
440
    {
441
        $memory = new MemoryWorkflowStore();
442
        $historySteps = $memory->findHistorySteps(123);
443
        $this->assertInstanceOf(SplObjectStorage::class, $historySteps);
444
        $this->assertEquals(0, $historySteps->count());
0 ignored issues
show
Bug introduced by
The method count does only exist in SplObjectStorage, but not in OldTown\Workflow\Spi\SimpleStep.

It seems like the method you are trying to call exists only in some of the possible types.

Let’s take a look at an example:

class A
{
    public function foo() { }
}

class B extends A
{
    public function bar() { }
}

/**
 * @param A|B $x
 */
function someFunction($x)
{
    $x->foo(); // This call is fine as the method exists in A and B.
    $x->bar(); // This method only exists in B and might cause an error.
}

Available Fixes

  1. Add an additional type-check:

    /**
     * @param A|B $x
     */
    function someFunction($x)
    {
        $x->foo();
    
        if ($x instanceof B) {
            $x->bar();
        }
    }
    
  2. Only allow a single type to be passed if the variable comes from a parameter:

    function someFunction(B $x) { /** ... */ }
    
Loading history...
445
    }
446
447
    /**
448
     * Проверяем шаг из истории возвращается корректно
449
     */
450
    public function testFindHistoryStep()
451
    {
452
        // Мок который будет лежать в истории
453
        $historyStep = $this->getMockBuilder(SimpleStep::class)
454
            ->disableOriginalConstructor()
455
            ->getMock();
456
457
        $historySteps = new SplObjectStorage();
458
        $historySteps->attach($historyStep);
459
460
        $memory = new MemoryWorkflowStore();
461
462
        $refHistory = new ReflectionProperty(MemoryWorkflowStore::class, 'historyStepsCache');
463
        $refHistory->setAccessible(true);
464
        $refHistory->setValue($memory, [123 => $historySteps]);
465
466
        $stepsFromHistory = $memory->findHistorySteps(123);
467
        $this->assertEquals($historySteps, $stepsFromHistory);
468
    }
469
470
    /**
471
     * Проверяем query с пустым кэшем entry
472
     */
473
    public function testQueryWithEmptyEntryCache()
474
    {
475
        $query = new WorkflowExpressionQuery();
476
        $query->setExpression(new FieldExpression(1, 2, 3, 'value'));
477
478
        $memory = new MemoryWorkflowStore();
479
        $results = $memory->query($query);
480
        $this->assertEquals([], $results);
481
    }
482
483
    /**
484
     * Проверяем имя entry
485
     */
486
    public function testQueryEntryName()
487
    {
488
        $memory = new MemoryWorkflowStore();
489
        $memory->createEntry('entryName');
490
491
        // Проверяем равно, ожидаем правду
492
        $this->assertCount(1, $memory->query(new WorkflowExpressionQuery(new FieldExpression(
493
            FieldExpression::NAME,
494
            FieldExpression::ENTRY,
495
            FieldExpression::EQUALS,
496
            'entryName'
497
        ))));
498
499
        // Проверяем равно, ожидаем неправду
500
        $this->assertCount(0, $memory->query(new WorkflowExpressionQuery(new FieldExpression(
501
            FieldExpression::NAME,
502
            FieldExpression::ENTRY,
503
            FieldExpression::EQUALS,
504
            'incorrectName'
505
        ))));
506
507
        // Проверяем "не равно", ожидаем правду
508
        $this->assertCount(0, $memory->query(new WorkflowExpressionQuery(new FieldExpression(
509
            FieldExpression::NAME,
510
            FieldExpression::ENTRY,
511
            FieldExpression::NOT_EQUALS,
512
            'entryName'
513
        ))));
514
515
        // Проверяем "не равно", ожидаем неправду
516
        $this->assertCount(1, $memory->query(new WorkflowExpressionQuery(new FieldExpression(
517
            FieldExpression::NAME,
518
            FieldExpression::ENTRY,
519
            FieldExpression::NOT_EQUALS,
520
            'incorrectName'
521
        ))));
522
523
        // Проверяем "больше", ожидаем правду
524
        $this->assertCount(1, $memory->query(new WorkflowExpressionQuery(new FieldExpression(
525
            FieldExpression::NAME,
526
            FieldExpression::ENTRY,
527
            FieldExpression::GT,
528
            'enshrt'
529
        ))));
530
531
        // Проверяем "больше", ожидаем неправду
532
        $this->assertCount(0, $memory->query(new WorkflowExpressionQuery(new FieldExpression(
533
            FieldExpression::NAME,
534
            FieldExpression::ENTRY,
535
            FieldExpression::GT,
536
            'entryNameLooooooooong'
537
        ))));
538
539
        // Проверяем "Меньше", ожидаем правду
540
        $this->assertCount(1, $memory->query(new WorkflowExpressionQuery(new FieldExpression(
541
            FieldExpression::NAME,
542
            FieldExpression::ENTRY,
543
            FieldExpression::LT,
544
            'entryNameLooooooooong'
545
        ))));
546
547
        // Проверяем "Меньше", ожидаем неправду
548
        $this->assertCount(0, $memory->query(new WorkflowExpressionQuery(new FieldExpression(
549
            FieldExpression::NAME,
550
            FieldExpression::ENTRY,
551
            FieldExpression::LT,
552
            'enshrt'
553
        ))));
554
    }
555
556
    /**
557
     * Проверяем имя entry с некорректным условием
558
     *
559
     * @expectedException InvalidArgumentException
560
     */
561 View Code Duplication
    public function testQueryEntryNameWithIncorrectOperator()
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
562
    {
563
        $memory = new MemoryWorkflowStore();
564
        $memory->createEntry('entryName');
565
566
        // Проверяем "Меньше", ожидаем неправду
567
        $this->assertCount(0, $memory->query(new WorkflowExpressionQuery(new FieldExpression(
568
            FieldExpression::NAME,
569
            FieldExpression::ENTRY,
570
            123,
571
            'entryName'
572
        ))));
573
    }
574
575
    /**
576
     * Проверяем поиск экземпляра по состоянию
577
     *
578
     * @expectedException InvalidArgumentException
579
     */
580 View Code Duplication
    public function testEntryStateWithIncorrectValue()
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
581
    {
582
        $memory = new MemoryWorkflowStore();
583
        $memory->createEntry('entryName');
584
585
        $memory->query(new WorkflowExpressionQuery(new FieldExpression(
586
            FieldExpression::STATE,
587
            FieldExpression::ENTRY,
588
            FieldExpression::EQUALS,
589
            'not string'
590
        )));
591
    }
592
593
    /**
594
     * Тестируем поиск по состоянию
595
     */
596
    public function testEntryState()
597
    {
598
        $memory = new MemoryWorkflowStore();
599
600
        // Создаем entry с состоянием CREATED
601
        $created = $memory->createEntry('entry1');
602
603
        // Создаем второе entry и через рефлекию меняем его состояние
604
        $active = $memory->createEntry('entry2');
605
        $refPropState = new ReflectionProperty(SimpleWorkflowEntry::class, 'state');
606
        $refPropState->setAccessible(true);
607
        $refPropState->setValue($active, WorkflowEntryInterface::SUSPENDED);
608
609
        $results = $memory->query(new WorkflowExpressionQuery(new FieldExpression(
610
            FieldExpression::STATE,
611
            FieldExpression::ENTRY,
612
            FieldExpression::EQUALS,
613
            WorkflowEntryInterface::CREATED
614
        )));
615
        $this->assertArrayHasKey($created->getId(), $results);
616
        $this->assertArrayNotHasKey($active->getId(), $results);
617
618
        $results = $memory->query(new WorkflowExpressionQuery(new FieldExpression(
619
            FieldExpression::STATE,
620
            FieldExpression::ENTRY,
621
            FieldExpression::NOT_EQUALS,
622
            WorkflowEntryInterface::CREATED
623
        )));
624
        $this->assertArrayNotHasKey($created->getId(), $results);
625
        $this->assertArrayHasKey($active->getId(), $results);
626
627
        $results = $memory->query(new WorkflowExpressionQuery(new FieldExpression(
628
            FieldExpression::STATE,
629
            FieldExpression::ENTRY,
630
            FieldExpression::GT,
631
            WorkflowEntryInterface::SUSPENDED
632
        )));
633
        $this->assertArrayHasKey($created->getId(), $results);
634
        $this->assertArrayNotHasKey($active->getId(), $results);
635
636
        $results = $memory->query(new WorkflowExpressionQuery(new FieldExpression(
637
            FieldExpression::STATE,
638
            FieldExpression::ENTRY,
639
            FieldExpression::LT,
640
            WorkflowEntryInterface::CREATED
641
        )));
642
        $this->assertArrayNotHasKey($created->getId(), $results);
643
        $this->assertArrayHasKey($active->getId(), $results);
644
    }
645
646
    /**
647
     * @expectedException InvalidArgumentException
648
     */
649
    public function testEntryStateWithIncorrectOperator()
650
    {
651
        $memory = new MemoryWorkflowStore();
652
        $memory->createEntry('entry1');
653
654
        $expression = new FieldExpression(
655
            FieldExpression::STATE,
656
            FieldExpression::ENTRY,
657
            1,
658
            WorkflowEntryInterface::CREATED
659
        );
660
        $refProp = new ReflectionProperty(FieldExpression::class, 'operator');
661
        $refProp->setAccessible(true);
662
        $refProp->setValue($expression, 'not int operator');
663
664
        $memory->query(new WorkflowExpressionQuery($expression));
665
    }
666
667
    /**
668
     * @expectedException InvalidArgumentException
669
     */
670 View Code Duplication
    public function testEntryWithIncorrectField()
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
671
    {
672
        $memory = new MemoryWorkflowStore();
673
        $memory->createEntry('entry1');
674
675
        $memory->query(new WorkflowExpressionQuery(new FieldExpression(
676
            99999,
677
            FieldExpression::ENTRY,
678
            1,
679
            WorkflowEntryInterface::CREATED
680
        )));
681
    }
682
683
    /**
684
     * Тестируем наличие действия в текущем шаге
685
     */
686
    public function testQueryActionInCurrentSteps()
687
    {
688
        $memory = new MemoryWorkflowStore();
689
        $entry = $memory->createEntry('entryId');
690
691
        // Проверяем что не найдет
692
        $this->assertCount(0, $memory->query(new WorkflowExpressionQuery(new FieldExpression(
693
            FieldExpression::ACTION,
694
            FieldExpression::CURRENT_STEPS,
695
            FieldExpression::EQUALS,
696
            1
697
        ))));
698
699
        $step = $memory->createCurrentStep(
700
            $entry->getId(),
701
            1,
702
            'i am',
703
            new DateTime(),
704
            new DateTime('+1 h'),
705
            'status',
706
            []
707
        );
708
709
        try {
710
            $memory->query(new WorkflowExpressionQuery(new FieldExpression(
711
                FieldExpression::ACTION,
712
                FieldExpression::CURRENT_STEPS,
713
                FieldExpression::EQUALS,
714
                'incorrect value'
715
            )));
716
            $this->fail('expect InvalidArgumentException exception');
717
        } catch (InvalidArgumentException $e) {
718
            // nothing
719
        }
720
721
        $this->assertArrayHasKey($step->getId(), $memory->query(new WorkflowExpressionQuery(new FieldExpression(
722
            FieldExpression::ACTION,
723
            FieldExpression::CURRENT_STEPS,
724
            FieldExpression::EQUALS,
725
            $step->getActionId()
726
        ))));
727
728
        $this->assertArrayNotHasKey($step->getId(), $memory->query(new WorkflowExpressionQuery(new FieldExpression(
729
            FieldExpression::ACTION,
730
            FieldExpression::CURRENT_STEPS,
731
            FieldExpression::EQUALS,
732
            $step->getActionId(),
733
            true
734
        ))));
735
736
        $this->assertArrayHasKey($step->getId(), $memory->query(new WorkflowExpressionQuery(new FieldExpression(
737
            FieldExpression::OWNER,
738
            FieldExpression::CURRENT_STEPS,
739
            FieldExpression::EQUALS,
740
            $step->getOwner()
741
        ))));
742
743
        try {
744
            $memory->query(new WorkflowExpressionQuery(new FieldExpression(
745
                FieldExpression::OWNER,
746
                FieldExpression::CURRENT_STEPS,
747
                FieldExpression::EQUALS,
748
                function () {
749
                }// closure не стринг :)
750
            )));
751
            $this->fail('expect InvalidArgumentException exception on owner');
752
        } catch (InvalidArgumentException $e) {
753
            // nothing
754
        }
755
756
        $this->assertArrayHasKey($step->getId(), $memory->query(new WorkflowExpressionQuery(new FieldExpression(
757
            FieldExpression::START_DATE,
758
            FieldExpression::CURRENT_STEPS,
759
            FieldExpression::EQUALS,
760
            $step->getStartDate()
761
        ))));
762
763
        try {
764
            $memory->query(new WorkflowExpressionQuery(new FieldExpression(
765
                FieldExpression::START_DATE,
766
                FieldExpression::CURRENT_STEPS,
767
                FieldExpression::EQUALS,
768
                function () {
769
                }// closure не DateTime :)
770
            )));
771
            $this->fail('expect InvalidArgumentException exception on START_DATE');
772
        } catch (InvalidArgumentException $e) {
773
            // nothing
774
        }
775
776
        $this->assertArrayHasKey($step->getId(), $memory->query(new WorkflowExpressionQuery(new FieldExpression(
777
            FieldExpression::STATUS,
778
            FieldExpression::CURRENT_STEPS,
779
            FieldExpression::EQUALS,
780
            $step->getStatus()
781
        ))));
782
783
        try {
784
            $memory->query(new WorkflowExpressionQuery(new FieldExpression(
785
                FieldExpression::STATUS,
786
                FieldExpression::CURRENT_STEPS,
787
                FieldExpression::EQUALS,
788
                []
789
            )));
790
            $this->fail('expect InvalidArgumentException exception on STATUS');
791
        } catch (InvalidArgumentException $e) {
792
            // nothing
793
        }
794
795
        $this->assertArrayHasKey($step->getId(), $memory->query(new WorkflowExpressionQuery(new FieldExpression(
796
            FieldExpression::STEP,
797
            FieldExpression::CURRENT_STEPS,
798
            FieldExpression::EQUALS,
799
            $step->getStepId()
800
        ))));
801
802
        try {
803
            $memory->query(new WorkflowExpressionQuery(new FieldExpression(
804
                FieldExpression::STEP,
805
                FieldExpression::CURRENT_STEPS,
806
                FieldExpression::EQUALS,
807
                'asd'
808
            )));
809
            $this->fail('expect InvalidArgumentException exception on STEP');
810
        } catch (InvalidArgumentException $e) {
811
            // nothing
812
        }
813
814
        $this->assertArrayHasKey($step->getId(), $memory->query(new WorkflowExpressionQuery(new FieldExpression(
815
            FieldExpression::DUE_DATE,
816
            FieldExpression::CURRENT_STEPS,
817
            FieldExpression::EQUALS,
818
            $step->getDueDate()
819
        ))));
820
821
        try {
822
            $memory->query(new WorkflowExpressionQuery(new FieldExpression(
823
                FieldExpression::DUE_DATE,
824
                FieldExpression::CURRENT_STEPS,
825
                FieldExpression::EQUALS,
826
                'asd'
827
            )));
828
            $this->fail('expect InvalidArgumentException exception on DUE_DATE');
829
        } catch (InvalidArgumentException $e) {
830
            // nothing
831
        }
832
    }
833
834
    /**
835
     * Тестируем наличие действия в текущем шаге
836
     */
837
    public function testQueryActionInHistorySteps()
838
    {
839
        $memory = new MemoryWorkflowStore();
840
        $entry = $memory->createEntry('entryId');
841
842
        // Проверяем что не найдет
843
        $this->assertCount(0, $memory->query(new WorkflowExpressionQuery(new FieldExpression(
844
            FieldExpression::ACTION,
845
            FieldExpression::HISTORY_STEPS,
846
            FieldExpression::EQUALS,
847
            1
848
        ))));
849
850
        $step = $memory->createCurrentStep(
851
            $entry->getId(),
852
            1,
853
            'i am',
854
            new DateTime(),
855
            new DateTime('+1 h'),
856
            'status',
857
            []
858
        );
859
860
        $finishDate = new DateTime();
861
        $memory->markFinished($step, $step->getActionId(), $finishDate, 'f', 'ya');
862
        $memory->moveToHistory($step);
863
864
        $this->assertArrayHasKey($step->getId(), $memory->query(new WorkflowExpressionQuery(new FieldExpression(
865
            FieldExpression::FINISH_DATE,
866
            FieldExpression::HISTORY_STEPS,
867
            FieldExpression::EQUALS,
868
            $finishDate
869
        ))));
870
871
        try {
872
            $memory->query(new WorkflowExpressionQuery(new FieldExpression(
873
                FieldExpression::FINISH_DATE,
874
                FieldExpression::HISTORY_STEPS,
875
                FieldExpression::EQUALS,
876
                'asd'
877
            )));
878
            $this->fail('expect InvalidArgumentException exception on DUE_DATE');
879
        } catch (InvalidArgumentException $e) {
880
            // nothing
881
        }
882
883
        $this->assertArrayHasKey($step->getId(), $memory->query(new WorkflowExpressionQuery(new FieldExpression(
884
            FieldExpression::CALLER,
885
            FieldExpression::HISTORY_STEPS,
886
            FieldExpression::EQUALS,
887
            $step->getCaller()
888
        ))));
889
890
        try {
891
            $memory->query(new WorkflowExpressionQuery(new FieldExpression(
892
                FieldExpression::CALLER,
893
                FieldExpression::HISTORY_STEPS,
894
                FieldExpression::EQUALS,
895
                []
896
            )));
897
            $this->fail('expect InvalidArgumentException exception on DUE_DATE');
898
        } catch (InvalidArgumentException $e) {
899
            // nothing
900
        }
901
902
        // Заодно протестируем сравнение дат...
903
        $testDate = clone $finishDate;
904
        $this->assertArrayHasKey($step->getId(), $memory->query(new WorkflowExpressionQuery(new FieldExpression(
905
            FieldExpression::FINISH_DATE,
906
            FieldExpression::HISTORY_STEPS,
907
            FieldExpression::NOT_EQUALS,
908
            $testDate->modify('+1 hour')
909
        ))));
910
911
        $testDate = clone $finishDate;
912
        $this->assertArrayHasKey($step->getId(), $memory->query(new WorkflowExpressionQuery(new FieldExpression(
913
            FieldExpression::FINISH_DATE,
914
            FieldExpression::HISTORY_STEPS,
915
            FieldExpression::GT,
916
            $testDate->modify('-1 hour')
917
        ))));
918
919
        $testDate = clone $finishDate;
920
        $this->assertArrayHasKey($step->getId(), $memory->query(new WorkflowExpressionQuery(new FieldExpression(
921
            FieldExpression::FINISH_DATE,
922
            FieldExpression::HISTORY_STEPS,
923
            FieldExpression::LT,
924
            $testDate->modify('+1 hour')
925
        ))));
926
927
        try {
928
            $this->assertArrayHasKey($step->getId(), $memory->query(new WorkflowExpressionQuery(new FieldExpression(
929
                FieldExpression::FINISH_DATE,
930
                FieldExpression::HISTORY_STEPS,
931
                99999,
932
                $testDate
933
            ))));
934
935
            $this->fail('expect InvalidArgumentException exception FINISH_DATE');
936
        } catch (InvalidArgumentException $e) {
937
            // nothing
938
        }
939
    }
940
941
    /**
942
     * @expectedException \OldTown\Workflow\Exception\InvalidArgumentException
943
     */
944
    public function testQueryStepsWithUnknownContext()
945
    {
946
        $memory = new MemoryWorkflowStore();
947
        $entry = $memory->createEntry('entryId');
948
949
        $memory->createCurrentStep(
950
            $entry->getId(),
951
            1,
952
            'i am',
953
            new DateTime(),
954
            new DateTime('+1 h'),
955
            'status',
956
            []
957
        );
958
959
        $memory->query(new WorkflowExpressionQuery(new FieldExpression(
960
            FieldExpression::FINISH_DATE,
961
            999,
962
            FieldExpression::EQUALS,
963
            new DateTime()
964
        )));
965
    }
966
967
    /**
968
     * Тестируем вложенные выражения c AND и OR возвращающие результат
969
     */
970
    public function testSuccessNestedExpression()
971
    {
972
        $memory = new MemoryWorkflowStore();
973
        $memory->createEntry('entryName');
974
975
        $expression = new NestedExpression([
976
            new FieldExpression(
977
                FieldExpression::STATE,
978
                FieldExpression::ENTRY,
979
                FieldExpression::EQUALS,
980
                SimpleWorkflowEntry::CREATED
981
            ),
982
            new NestedExpression([
983
                new FieldExpression(
984
                    FieldExpression::NAME,
985
                    FieldExpression::ENTRY,
986
                    FieldExpression::EQUALS,
987
                    'somename'
988
                ),
989
                new FieldExpression(
990
                    FieldExpression::NAME,
991
                    FieldExpression::ENTRY,
992
                    FieldExpression::EQUALS,
993
                    'entryName'
994
                ),
995
            ], NestedExpression::OR_OPERATOR)
996
        ], NestedExpression::AND_OPERATOR);
997
998
        $result = $memory->query(new WorkflowExpressionQuery($expression));
999
        $this->assertCount(1, $result);
1000
    }
1001
1002
    /**
1003
     * Тестируем запросы в которых результат невозможен
1004
     */
1005
    public function testNestedExpressionWithoutResult()
1006
    {
1007
        $memory = new MemoryWorkflowStore();
1008
        $memory->createEntry('entryName');
1009
1010
        $expression = new NestedExpression([
1011
            new FieldExpression(
1012
                FieldExpression::STATE,
1013
                FieldExpression::ENTRY,
1014
                FieldExpression::EQUALS,
1015
                SimpleWorkflowEntry::CREATED
1016
            ),
1017
            new FieldExpression(
1018
                FieldExpression::STATE,
1019
                FieldExpression::ENTRY,
1020
                FieldExpression::EQUALS,
1021
                SimpleWorkflowEntry::ACTIVATED
1022
            ),
1023
        ], NestedExpression::AND_OPERATOR);
1024
1025
        $result = $memory->query(new WorkflowExpressionQuery($expression));
1026
        $this->assertCount(0, $result);
1027
1028
        $expression = new NestedExpression([
1029
            new FieldExpression(
1030
                FieldExpression::STATE,
1031
                FieldExpression::ENTRY,
1032
                FieldExpression::EQUALS,
1033
                SimpleWorkflowEntry::ACTIVATED
1034
            ),
1035
            new FieldExpression(
1036
                FieldExpression::STATE,
1037
                FieldExpression::ENTRY,
1038
                FieldExpression::EQUALS,
1039
                SimpleWorkflowEntry::ACTIVATED
1040
            ),
1041
        ], NestedExpression::OR_OPERATOR);
1042
1043
        $result = $memory->query(new WorkflowExpressionQuery($expression));
1044
        $this->assertCount(0, $result);
1045
    }
1046
1047
    /**
1048
     * Тестируем наличие фатала
1049
     *
1050
     * @expectedException \OldTown\Workflow\Exception\InvalidArgumentException
1051
     */
1052
    public function testNestedExpressionWithIncorrectOperator()
1053
    {
1054
        $memory = new MemoryWorkflowStore();
1055
        $memory->createEntry('entryName');
1056
1057
        $expression = new NestedExpression([
1058
            new FieldExpression(
1059
                FieldExpression::STATE,
1060
                FieldExpression::ENTRY,
1061
                FieldExpression::EQUALS,
1062
                SimpleWorkflowEntry::CREATED
1063
            ),
1064
            new FieldExpression(
1065
                FieldExpression::STATE,
1066
                FieldExpression::ENTRY,
1067
                FieldExpression::EQUALS,
1068
                SimpleWorkflowEntry::ACTIVATED
1069
            ),
1070
        ], 999);
1071
1072
        $memory->query(new WorkflowExpressionQuery($expression));
1073
    }
1074
}
1075