Completed
Push — master ( 39204a...32cc9c )
by Russell
03:14
created

JSONTextExtension::onBeforeWrite()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 18
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 18
rs 9.4285
c 0
b 0
f 0
cc 3
eloc 10
nc 3
nop 0
1
<?php
2
3
/**
4
 * Add this DataExtension to your models if you wish to have specific DB fields
5
 * receive JSON data POSTed from particular input fields in the CMS. 
6
 * 
7
 * You'll need to declare declare a `$jsontext_field_map` config static on the desired
8
 * model(s) as follows:
9
 * 
10
 * <code>
11
 * private static $jsontext_field_map = [
12
 *  'MyDBField1' => [
13
 *      'MyInputField1',
14
 *      'MyInputField2'
15
 *  ],
16
 *  'MyDBField2' => [
17
 *       'MyInputField3',
18
         'MyInputField4'
19
 *  ]
20
 * ];
21
 * <code>
22
 * 
23
 * @package silverstripe-jsontext
24
 * @subpackage extensions
25
 * @author Russell Michell <[email protected]>
26
 */
27
         
28
class JSONTextExtension extends \DataExtension
0 ignored issues
show
Coding Style Compatibility introduced by
PSR1 recommends that each class must be in a namespace of at least one level to avoid collisions.

You can fix this by adding a namespace to your class:

namespace YourVendor;

class YourClass { }

When choosing a vendor namespace, try to pick something that is not too generic to avoid conflicts with other libraries.

Loading history...
29
{
30
    /**
31
     * Manipulate POSTed data from pre-specified CMS fields and write their data
32
     * as JSON.
33
     * 
34
     * @return void
35
     */
36
    public function onBeforeWrite()
37
    {
38
        // Fields are declared in a config static on decorated models
39
        $fieldMap = $this->getOwner()->config()->get('jsontext_field_map');
40
        $postVars = Controller::curr()->getRequest()->postVars();
41
        $data = [];
42
        
43
        foreach ($fieldMap as $dbFieldName => $inputFields) {
44
            foreach ($inputFields as $inputField) {
45
                $data[$dbFieldName][] = [$inputField => $postVars[$inputField]];
46
            }
47
            
48
            $jsonTextField = $this->getOwner()->dbObject($dbFieldName);
49
            $this->getOwner()->setField($dbFieldName, $jsonTextField->toJSON($data[$dbFieldName]));
50
        }
51
        
52
        parent::onBeforeWrite();
53
    }
54
    
55
}
56