Completed
Push — master ( fd23d8...b5c256 )
by Will
28:53
created

Address::toString()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 15
Code Lines 12

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 12
CRAP Score 1

Importance

Changes 0
Metric Value
dl 0
loc 15
ccs 12
cts 12
cp 1
rs 9.4285
c 0
b 0
f 0
cc 1
eloc 12
nc 1
nop 1
crap 1
1
<?php
2
3
/**
4
 * Address model using a generic format for storing international addresses.
5
 *
6
 * Typical Address Hierarcy:
7
 *    Continent
8
 *    Country
9
 *    State / Province / Territory (Island?)
10
 *    District / Suburb / County / City
11
 *        Code / Zip (may cross over the above)
12
 *    Street / Road - name + type: eg Gandalf Cresent
13
 *    (Premises/Building/Unit/Suite)
14
 *        (Floor/Level/Side/Wing)
15
 *    Number / Entrance / Room
16
 *    Person(s), Company, Department
17
 *
18
 * Collection of international address formats:
19
 *
20
 * @see http://bitboost.com/ref/international-address-formats.html
21
 *      xAL address standard:
22
 * @see https://www.oasis-open.org/committees/ciq/ciq.html#6
23
 *      Universal Postal Union addressing standards:
24
 * @see http://www.upu.int/nc/en/activities/addressing/standards.html
25
 */
26
class Address extends DataObject
27
{
28
    private static $db              = array(
29
        'Country'    => 'ShopCountry',
30
        //level1: Country = ISO 2-character country code
31
        'State'      => 'Varchar(100)',
32
        //level2: Locality, Administrative Area, State, Province, Region, Territory, Island
33
        'City'       => 'Varchar(100)',
34
        //level3: Dependent Locality, City, Suburb, County, District
35
        'PostalCode' => 'Varchar(20)',
36
        //code: ZipCode, PostCode (could cross above levels within a country)
37
38
        'Address'      => 'Varchar(255)',
39
        //Number + type of thoroughfare/street. P.O. box
40
        'AddressLine2' => 'Varchar(255)',
41
        //Premises, Apartment, Building. Suite, Unit, Floor, Level, Side, Wing.
42
43
        'Company' => 'Varchar(100)',
44
        //Business, Organisation, Group, Institution.
45
46
        'FirstName' => 'Varchar(100)',
47
        //Individual, Person, Contact, Attention
48
        'Surname'   => 'Varchar(100)',
49
        'Phone'     => 'Varchar(100)',
50
    );
51
52
    private static $has_one         = array(
53
        'Member' => 'Member',
54
    );
55
56
    private static $has_many = array(
57
        'ShippingAddressOrders' => 'Order.ShippingAddress',
58
        'BillingAddressOrders' => 'Order.BillingAddress'
59
    ];
0 ignored issues
show
Bug introduced by
This code did not parse for me. Apparently, there is an error somewhere around this line:

Syntax error, unexpected ']', expecting ')'
Loading history...
60
61
    private static $casting         = array(
62
        'Country' => 'ShopCountry',
63
    );
64
65
    private static $required_fields = array(
66
        'Country',
67
        'State',
68
        'City',
69
        'Address',
70
    );
71
72
    private static $summary_fields  = array(
73
        'toString' => 'Address',
74
    );
75
76
    public function getCMSFields()
77
    {
78
        $fields = parent::getCMSFields();
79
        $fields->addFieldToTab(
80
            "Root.Main",
81
            $this->getCountryField(),
82
            'State'
83
        );
84 5
        $fields->removeByName("MemberID");
85
86 5
        return $fields;
87 5
    }
88 5
89
    public function getFrontEndFields($params = null)
90 5
    {
91 5
        $fields = new FieldList(
92 5
            $this->getCountryField(),
93 5
            $addressfield = TextField::create('Address', _t('Address.db_Address', 'Address')),
94 5
            $address2field =
95 5
                TextField::create('AddressLine2', _t('Address.db_AddressLine2', 'Address Line 2 (optional)')),
96 5
            $cityfield = TextField::create('City', _t('Address.db_City', 'City')),
97 2
            $statefield = TextField::create('State', _t('Address.db_State', 'State')),
98 2
            $postcodefield = TextField::create('PostalCode', _t('Address.db_PostalCode', 'Postal Code')),
99 2
            $phonefield = TextField::create('Phone', _t('Address.db_Phone', 'Phone Number'))
100 2
        );
101 2
        if (isset($params['addfielddescriptions']) && !empty($params['addfielddescriptions'])) {
102 2
            $addressfield->setDescription(
103 2
                _t("Address.AddressHint", "street / thoroughfare number, name, and type or P.O. Box")
104 2
            );
105 2
            $address2field->setDescription(
106
                _t("Address.AddressLine2Hint", "premises, building, apartment, unit, floor")
107 5
            );
108 5
            $cityfield->setDescription(_t("Address.CityHint", "or suburb, county, district"));
109
            $statefield->setDescription(_t("Address.StateHint", "or province, territory, island"));
110
        }
111 5
112
        $this->extend('updateFormFields', $fields);
113 5
        return $fields;
114 5
    }
115
116 3
    public function getCountryField()
117 3
    {
118 3
        $countries = SiteConfig::current_site_config()->getCountriesList();
119 3
        if (count($countries) == 1) {
120 3
            //field name is Country_readonly so it's value doesn't get updated
121
            return ReadonlyField::create(
122 2
                "Country_readonly",
123 2
                _t('Address.db_Country', 'Country'),
124 2
                array_pop($countries)
125
            );
126 2
        }
127
        $field = DropdownField::create(
128 2
            "Country",
129
            _t('Address.db_Country', 'Country'),
130 2
            $countries
131
        )->setHasEmptyDefault(true);
132
133
        $this->extend('updateCountryField', $field);
134
135
        return $field;
136
    }
137 16
138
    /**
139 16
     * Get an array of data fields that must be populated for model to be valid.
140
     * Required fields can be customised via self::$required_fields
141 16
     */
142
    public function getRequiredFields()
143
    {
144
        $fields = self::config()->required_fields;
145
        //hack to allow overriding arrays in ss config
146
        if (self::$required_fields != $fields) {
147
            foreach (self::$required_fields as $requirement) {
148
                if (($key = array_search($requirement, $fields)) !== false) {
149 16
                    unset($fields[$key]);
150 16
                }
151
            }
152 16
        }
153 3
        //set nicer keys for easier processing
154 3
        $fields = array_combine($fields, $fields);
155
        $this->extend('updateRequiredFields', $fields);
156 16
        //don't require country if shop config only specifies a single country
157
        if (isset($fields['Country']) && SiteConfig::current_site_config()->getSingleCountry()) {
158
            unset($fields['Country']);
159
        }
160
161
        return $fields;
162 11
    }
163
164 11
    /**
165 11
     * Get full name associated with this Address
166 11
     */
167
    public function getName()
168 11
    {
169 11
        return implode(
170
            ' ',
171 11
            array_filter(
172 11
                array(
173
                    $this->FirstName,
174
                    $this->Surname,
175
                )
176
            )
177
        );
178 4
    }
179
180
    /**
181 4
     * Convert address to a single string.
182 4
     */
183 4
    public function toString($separator = ", ")
184 4
    {
185 4
        $fields = array(
186 4
            $this->Company,
187 4
            $this->getName(),
188 4
            $this->Address,
189 4
            $this->AddressLine2,
190 4
            $this->City,
191 4
            $this->State,
192
            $this->PostalCode,
193
            $this->Country
194
        );
195
        $this->extend('updateToString', $fields);
196
        return implode($separator, array_filter($fields));
197
    }
198
199 7
    public function getTitle()
200
    {
201 7
        return $this->toString();
202
    }
203
204
    public function forTemplate()
205
    {
206
        return $this->renderWith('Address');
207 17
    }
208
209 17
    /**
210 17
     * Add alias setters for fields which are synonymous
211
     */
212 17
    public function setProvince($val)
213
    {
214 17
        $this->State = $val;
215 17
    }
216
217
    public function setTerritory($val)
218
    {
219
        $this->State = $val;
220
    }
221
222 26
    public function setIsland($val)
223
    {
224 26
        $this->State = $val;
225 26
    }
226
227 17
    public function setPostCode($val)
228
    {
229 17
        $this->PostalCode = $val;
230 17
    }
231
232
    public function setZipCode($val)
233
    {
234
        $this->PostalCode = $val;
235
    }
236
237
    public function setStreet($val)
238
    {
239
        $this->Address = $val;
240
    }
241
242 26
    public function setStreet2($val)
243
    {
244 26
        $this->AddressLine2 = $val;
245 26
    }
246
247
    public function setAddress2($val)
248
    {
249
        $this->AddressLine2 = $val;
250
    }
251
252
    public function setInstitution($val)
253
    {
254
        $this->Company = $val;
255
    }
256
257
    public function setBusiness($val)
258
    {
259
        $this->Company = $val;
260
    }
261
262
    public function setOrganisation($val)
263
    {
264
        $this->Company = $val;
265
    }
266
267 15
    public function setOrganization($val)
268
    {
269 15
        $this->Company = $val;
270
    }
271 15
272 15
    function validate()
0 ignored issues
show
Best Practice introduced by
It is generally recommended to explicitly declare the visibility for methods.

Adding explicit visibility (private, protected, or public) is generally recommend to communicate to other developers how, and from where this method is intended to be used.

Loading history...
273 1
    {
274 1
        $result = parent::validate();
275 15
276
        foreach ($this->getRequiredFields() as $requirement) {
277 15
            if (empty($this->$requirement)) {
278
                $result->error("Address Model validate function - missing required field: $requirement");
279
            }
280 2
        }
281
282
        return $result;
283
    }
284
}
285