Completed
Push — master ( 87fbd5...f3b6bb )
by Daniel
11:18
created

GridFieldPaginatorTest   A

Complexity

Total Complexity 5

Size/Duplication

Total Lines 109
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 13

Importance

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

5 Methods

Rating   Name   Duplication   Size   Complexity  
A setUp() 0 12 1
A testThereIsPaginatorWhenMoreThanOnePage() 0 10 1
A testThereIsNoPaginatorWhenOnlyOnePage() 0 15 1
A testUnlimitedRowCount() 0 20 1
A testPaginationAvoidsIllegalOffsets() 0 17 1
1
<?php
2
3
namespace SilverStripe\Forms\Tests\GridField;
4
5
use SilverStripe\Control\Controller;
6
use SilverStripe\Dev\CSSContentParser;
7
use SilverStripe\Dev\FunctionalTest;
8
use SilverStripe\Forms\FieldList;
9
use SilverStripe\Forms\Form;
10
use SilverStripe\Forms\GridField\GridField;
11
use SilverStripe\Forms\GridField\GridFieldConfig;
12
use SilverStripe\Forms\GridField\GridFieldPageCount;
13
use SilverStripe\Forms\GridField\GridFieldPaginator;
14
use SilverStripe\Forms\GridField\GridFieldToolbarHeader;
15
use SilverStripe\Forms\Tests\GridField\GridFieldTest\Player;
16
use SilverStripe\Forms\Tests\GridField\GridFieldTest\Team;
17
use SilverStripe\ORM\ArrayList;
18
use SilverStripe\ORM\DataList;
19
20
class GridFieldPaginatorTest extends FunctionalTest
21
{
22
    /**
23
     * @var ArrayList
24
     */
25
    protected $list;
26
27
    /**
28
     * @var GridField
29
     */
30
    protected $gridField;
31
32
    /**
33
     * @var string
34
     */
35
    protected static $fixture_file = 'GridFieldTest.yml';
36
37
    /**
38
     * @var Form
39
     */
40
    protected $form;
41
42
    /**
43
     * @var array
44
     */
45
    protected $extraDataObjects = array(
46
        Team::class,
47
        Player::class
48
    );
49
50
    public function setUp()
51
    {
52
        parent::setUp();
53
        $this->list = new DataList(Team::class);
0 ignored issues
show
Documentation Bug introduced by
It seems like new \SilverStripe\ORM\Da...dFieldTest\Team::class) of type object<SilverStripe\ORM\DataList> is incompatible with the declared type object<SilverStripe\ORM\ArrayList> of property $list.

Our type inference engine has found an assignment to a property that is incompatible with the declared type of that property.

Either this assignment is in error or the assigned type should be added to the documentation/type hint for that property..

Loading history...
54
        $config = GridFieldConfig::create()->addComponents(
55
            new GridFieldToolbarHeader(), // Required to support pagecount
56
            new GridFieldPaginator(2),
57
            new GridFieldPageCount('toolbar-header-right')
58
        );
59
        $this->gridField = new GridField('testfield', 'testfield', $this->list, $config);
60
        $this->form = new Form(new Controller(), 'mockform', new FieldList(array($this->gridField)), new FieldList());
61
    }
62
63
    public function testThereIsPaginatorWhenMoreThanOnePage()
64
    {
65
        $fieldHolder = $this->gridField->FieldHolder();
66
        $content = new CSSContentParser($fieldHolder);
67
        // Check that there is paginator render into the footer
68
        $this->assertEquals(1, count($content->getBySelector('.datagrid-pagination')));
69
70
        // Check that the header and footer both contains a page count
71
        $this->assertEquals(2, count($content->getBySelector('.pagination-records-number')));
72
    }
73
74
    public function testThereIsNoPaginatorWhenOnlyOnePage()
75
    {
76
        // We set the itemsPerPage to an reasonably big number so as to avoid test broke from small changes
77
        // on the fixture YML file
78
        $total = $this->list->count();
79
        $this->gridField->getConfig()->getComponentByType(GridFieldPaginator::class)->setItemsPerPage($total);
0 ignored issues
show
Bug introduced by
It seems like you code against a concrete implementation and not the interface SilverStripe\Forms\GridField\GridFieldComponent as the method setItemsPerPage() does only exist in the following implementations of said interface: SilverStripe\Forms\GridField\GridFieldPaginator.

Let’s take a look at an example:

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

class MyUser implements 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 implementation 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 interface:

    interface User
    {
        /** @return string */
        public function getPassword();
    
        /** @return string */
        public function getDisplayName();
    }
    
Loading history...
80
        $fieldHolder = $this->gridField->FieldHolder();
81
        $content = new CSSContentParser($fieldHolder);
82
83
        // Check that there is no paginator render into the footer
84
        $this->assertEquals(0, count($content->getBySelector('.datagrid-pagination')));
85
86
        // Check that there is still 'View 1 - 4 of 4' part on the left of the paginator
87
        $this->assertEquals(2, count($content->getBySelector('.pagination-records-number')));
88
    }
89
90
    public function testUnlimitedRowCount()
91
    {
92
        $total = $this->list->count();
93
        // set up the paginator
94
        /** @var GridFieldPaginator $paginator */
95
        $paginator = $this->gridField->getConfig()->getComponentByType(GridFieldPaginator::class);
96
        $paginator->setThrowExceptionOnBadDataType(true);
97
        $paginator->setItemsPerPage(1);
98
        $paginator->getManipulatedData($this->gridField, $this->list);
99
100
101
        $params = $paginator->getTemplateParameters($this->gridField)->toMap();
102
        $this->assertFalse($params['OnlyOnePage']);
103
        $this->assertEquals($total, $params['NumRecords']);
104
105
        $paginator->setItemsPerPage(0);
106
        $params = $paginator->getTemplateParameters($this->gridField)->toMap();
107
        $this->assertTrue($params['OnlyOnePage']);
108
        $this->assertEquals($total, $params['NumRecords']);
109
    }
110
111
    public function testPaginationAvoidsIllegalOffsets()
112
    {
113
        $grid = $this->gridField;
114
        $total = $this->list->count();
115
        $perPage = $grid->getConfig()->getComponentByType(GridFieldPaginator::class)->getItemsPerPage();
0 ignored issues
show
Bug introduced by
It seems like you code against a concrete implementation and not the interface SilverStripe\Forms\GridField\GridFieldComponent as the method getItemsPerPage() does only exist in the following implementations of said interface: SilverStripe\Forms\GridField\GridFieldPaginator.

Let’s take a look at an example:

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

class MyUser implements 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 implementation 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 interface:

    interface User
    {
        /** @return string */
        public function getPassword();
    
        /** @return string */
        public function getDisplayName();
    }
    
Loading history...
116
        // Get the last page that will contain results
117
        $lastPage = ceil($total / $perPage);
118
        // Set the paginator state to point to an 'invalid' page
119
        $grid->State->GridFieldPaginator->currentPage = $lastPage + 1;
120
121
        // Get the paginated list
122
        $list = $grid->getManipulatedList();
123
124
        // Assert that the paginator state has been corrected and the list contains items
125
        $this->assertEquals(1, $grid->State->GridFieldPaginator->currentPage);
126
        $this->assertEquals($perPage, $list->count());
127
    }
128
}
129