View difference between Paste ID: gqRzsr7G and u6tUVgN3
SHOW: | | - or go back to the newest paste.
1
/*
2
How to handle an IF statement for every field in a table?
3
4
5
Because every client I've used this code for over the years wanted to play fast and loose with the values in most DB fields I've had to allow all kinds of values in most fields. For example there are a number of fields where you'd assume you can only enter an integer. But most clients want to enter short phrases or whole paragraphs.
6
7
So on many fields I have to test if the value is numeric or a string. 
8
Display strings as-is but run numbers through number_format and add a dollar sign.
9
Some numbers just need to be run through number_format without the dollar sign.
10
Or run it through a square foot to acre converter and add 'acres' or "sq ft" suffix. 
11
Or test if the value is a csv of strings and put a space between each comma. 
12
Or if it's a csv of id numbers pull the related records from the database. 
13
Or if it's a multi-line string convert it to an unordered list on some pages and a comma-space separated list on other pages. 
14
If the value is zero, don't show a zero. 
15
Some values are a zero or one and should be shown as yes or no. 
16
Some values are y or n and should be shown as yes or no.
17
18
So what I've had to do is set up a bunch of IF statements for each field. The next problem was that there are many sections on the site where many of these fields would be displayed. So what I did next was to turn each field-specific IF statement into its own function. Later I grouped all those functions into a helper class.
19
20
Below is that helper class and an example of its usage. 
21
Does this seem like a good idea? Is there a better way I could be handling this?
22
*/
23
24
Usage:
25
[code]
26
<?
27
$model = new ListingsModel(15671);
28
$ldh = new ListingDisplayHelper( $model );
29
$F = $ldh;
30
?>
31
<tr><td>Property Name</td><td><?=$F->property_name?></td></tr>
32
<tr><td>Categories</td><td><?=$F->category?></td></tr>
33
<tr><td>Sale Price</td><td><?=$F->price?></td></tr>
34
<tr><td>Rent Price</td><td><?=$F->rent_price?></td></tr>
35
<tr><td>List Date</td><td><?=$F->list_date?></td></tr>
36
<tr><td>Island</td><td><?=$F->island?></td></tr>
37
<tr><td>Location</td><td><?=$F->location;?></td></tr>
38
<tr><td>District</td><td><?=$F->district?></td></tr>
39
<tr><td>Property Types</td><td><?=$F->property_types?></td></tr>
40
<tr><td>Key Features</td><td><?=$F->key_features?></td></tr>
41
<tr><td>Building_style</td><td><?=$F->building_style?></td></tr>
42
<tr><td>Bedrooms</td><td><?=$F->bedrooms?></td></tr>
43
<tr><td>Bathrooms</td><td><?=$F->bathrooms?></td></tr>
44
<tr><td>Half Baths</td><td><?=$F->halfbaths?></td></tr>
45
<tr><td>Lot Size</td><td><?=$F->lot_size?></td></tr>
46
<tr><td>Living Area</td><td><?=$F->living_area?></td></tr>
47
<tr><td>NRA</td><td><?=$F->net_rentable?></td></tr>
48
<tr><td>GRA</td><td><?=$F->gross_rentable_area?></td></tr>
49
<tr><td>Land Price/Sq.Ft.</td><td><?=$F->price_sq_ft?></td></tr>
50
<tr><td>Building Rental Rate/Sq.Ft.</td><td><?=$F->sq_ft_rate?></td></tr>
51
<tr><td>Total Expenses</td><td><?=$F->total_expenses?></td></tr>
52
<tr><td>Vacancy Rate</td><td><?=$F->vacancy_rate?></td></tr>
53
[/code]
54
55
56
Helper Class:
57
[code=php]
58
<?
59
## This class should only be concerned with massaging
60
## the main listing values into preferred usable text values 
61
## most useful in most common situations!
62
63
## ListingDisplayHelper requires a listing model object or stdclass or array of db record fields be passed into it.
64
65
## MAGIC METHODS:
66
### 1. Any property requested that exists on the root of the object itself is immediately returned.
67
### 2. The end result of any value tweaking methods is saved in ->cooked. So already cooked values are returned if found.
68
### 3. If a method matching the requested property is found that method cooks the raw value and caches it in ->cooked.
69
###    It is also up to that method to decide what to do if the value is zero.
70
### 4. Any property requested that doesn't have an associated method will be pulled from ->raw.
71
###
72
### Any value that roughly equates to zero 0 will be converted to empty string.
73
### Things that don't actually exist in the db table will also go into ->cooked.
74
75
76
class ListingDisplayHelper 
77
{
78
79
public $_cooked; // adjusted values go in here
80
public $_raw; // original values
81
public $_log;
82
public $_logging = false;
83
84
// Some fields should never show zero even if that's their value.
85
// But for debugging you can have them show another value (like - or !) 
86
// to make them easier to spot
87
public $_zero_placeholder = '';
88
89
90
91
92
function __construct( $listing )
93
{
94
	$this->cooked = new stdclass; 
95
	
96
	if( is_a( $listing, 'ListingsModel') ) 
97
	{
98
		$this->raw = (object) $listing->rowdata;  
99
		$this->model = $listing;
100
	}
101
	elseif( is_array($listing) ) 
102
	{
103
	 $this->raw = (object) $listing;
104
	}
105
	elseif( is_object($listing) )
106
	{
107
		$this->raw = $listing;
108
	}
109
}
110
111
112
# See MAGIC METHODS comment at top.
113
public function __get($name)
114
{
115
	if( false )
116
	{ $nothing; }
117
	
118
	// check for top level class vars
119
	elseif(  property_exists( $this, $name) )
120
	{
121
		$this->_log("found on obj   `$name`");
122
		$to_return = $this->$name;
123
	}
124
	
125
	// check for vars that were already cooked (cached)
126
	elseif (  property_exists($this->cooked, $name) ) 
127
	{
128
		$this->_log("found in cooked `$name`" );
129
		$to_return = $this->cooked->$name;
130
	}
131
	
132
	// check for a matching method that would cook the vars value and cache it in ->cooked.
133
	elseif( method_exists($this, 'get_'.$name) )
134
	{
135
		$method = 'get_'.$name;
136
		$this->_log("method exists   `$name`");
137
		$to_return = $this->$method( $name );
138
	}
139
140
	// check for the raw value
141
	elseif (  property_exists($this->raw, $name) ) 
142
	{
143
		$this->_log("found in raw     `$name`" );
144
		$to_return = $this->raw->$name;
145
	}
146
	else {
147
		$this->_log("!!!!!! $name not found anywhere !!!!!!!");
148
		$to_return = "!!!!!! $name not found anywhere !!!!!!!";
149
		//$to_return = null;
150
	}
151
	
152
	if( (string) $to_return == '0' || $to_return == '0000-00-00' )
153
	{ $to_return = $this->_zero_placeholder; }
154
155
	return $to_return;
156
	
157
}
158
159
private function _log($msg)
160
{
161
	if($this->_logging) {
162
	$this->_log[] = $msg; }
163
}
164
165
166
167
public function get_island( $name )
168
{
169
	return $this->cooked->island = $this->model->island();
170
}
171
172
173
public function get_location( $name )
174
{
175
	return $this->cooked->location = $this->model->location();
176
}
177
178
public function get_district( $name )
179
{
180
	return $this->cooked->district = $this->model->district();
181
}
182
183
184
public function get_property_types( $name )
185
{
186
	$typeArray = $this->model->propertyTypes();
187
	return $this->cooked->property_types = implode(', ', $typeArray);
188
}
189
190
public function get_view_types( $name )
191
{
192
	$typeArray = $this->model->viewTypes();
193
	return $this->cooked->view_types = implode(', ', $typeArray);
194
}
195
196
public function get_key_features( $name )
197
{
198
	return $this->get_view_types ($name);
199
}
200
201
public function get_amenities( $name )
202
{
203
	$typeArray = $this->model->amenities();
204
	return $this->cooked->amenities = implode(', ', $typeArray);
205
}
206
207
208
public function get_visible_on_site()
209
{
210
	return $this->cooked->visible_on_site = ($this->raw->hide === 'no') ? 'yes' : 'no';
211
}
212
213
public function get_under_mls_control()
214
{
215
	return $this->cooked->under_mls_control = ($this->raw->mls_imported === 'y') ? 'yes' : 'no';
216
}
217
218
219
220
221
222
function get_youtube_ids()
223
{
224
	if(!empty( $this->raw->youtube_ids ))
225
	{ 
226
		$ytstring = $this->raw->youtube_ids;
227
		$ytstring = str_replace("\r\n", "\n", $ytstring);
228
		$ytstring = str_replace("\r", "\n", $ytstring);
229
		return $this->cooked->youtube_ids = $ytstring;
230
	}
231
}
232
233
function get_youtube_ids_array()
234
{
235
	return $this->cooked->youtube_ids_array = explode("\n", $this->get_youtube_ids() );
236
}
237
238
function get_youtube_ids_linked()
239
{
240
	$array = $this->get_youtube_ids_array();
241
	if(!empty($array))
242
	{
243
		$url = '<a href="https://www.youtube.com/watch?v=%s">%s</a>';
244
		foreach($array as $ytid)
245
		{
246
			$out[] = sprintf($url, $ytid, $ytid);
247
		}
248
		return $this->cooked->youtube_ids_linked = implode(', ', $out);
249
	}
250
}
251
252
253
// number of photos for this listing on local server
254
public function get_local_photo_count()
255
{
256
	$sql = "SELECT COUNT(*) AS `count` FROM media WHERE parent={$this->raw->listing_id} AND section='listings' 
257
	AND (type='photo' OR type='cropA' OR type='cropB') GROUP BY parent";
258
	$result = sqlQuery($sql);
259
	if(!empty($result)) {
260
	return $this->cooked->local_photo_count = $result[0]['count']; }
261
}
262
263
264
public function get_category()
265
{
266
	return $this->cooked->category =  ucwords(str_replace(',' , ', ', $this->raw->category));
267
}
268
269
270
function get_price( $name )
271
{
272
	return $this->get_sale_price( $name );
273
}
274
275
276
function get_sale_price( $name )
277
{
278
	return $this->_cashmoney( $name );
279
}
280
281
282
function get_rent_price( $name )
283
{
284
	return $this->_cashmoney( $name );
285
}
286
287
288
289
function get_land_price_sq_ft( $name )
290
{ return $this->get_price_sq_ft( $name ); }
291
292
function get_price_sq_ft( $name )
293
{
294
	return $this->_cashmoney( $name );
295
}
296
297
298
function get_building_sq_ft_rate( $name )
299
{
300
	return $this->get_sq_ft_rate( $name );
301
}
302
303
function get_sq_ft_rate( $name )
304
{
305
	return $this->_cashmoney( $name );
306
}
307
308
309
function get_total_expenses( $name )
310
{
311
	return $this->_cashmoney( $name );
312
}
313
314
function get_vacancy_rate( $name )
315
{
316
	return $this->_cashmoney( $name );
317
}
318
319
320
function get_goi( $name )
321
{
322
	return $this->_numeric( $name );
323
}
324
325
function get_noi( $name )
326
{
327
	return $this->_numeric( $name );
328
}
329
330
function get_insurance( $name )
331
{
332
	return $this->_numeric( $name );
333
}
334
335
336
function get_assoc_fees( $name )
337
{
338
	return $this->_numeric( $name );
339
}
340
341
function get_maint_fees( $name )
342
{
343
	return $this->_numeric( $name );
344
}
345
346
function get_rent_deposit( $name )
347
{
348
	return $this->_numeric( $name );
349
}
350
351
function get_security_deposit( $name )
352
{
353
	return $this->_numeric( $name );
354
}
355
356
function get_phone_deposit( $name )
357
{
358
	return $this->_numeric( $name );
359
}
360
361
function get_water_deposit( $name )
362
{
363
	return $this->_numeric( $name );
364
}
365
366
function get_power_deposit( $name )
367
{
368
	return $this->_numeric( 'bec_deposit' );
369
}
370
371
function get_bec_deposit( $name )
372
{
373
	return $this->_numeric( $name );
374
}
375
376
377
/**
378
* For things that are probably a number but might not be. 
379
* In the negative case return the original string.
380
*/
381
private function _numeric( $name ) 
382
{
383
	if(is_numeric($this->raw->$name)){ return $this->_cashmoney( $name ); }
384
	else { return $this->cooked->$name = $this->raw->$name; }
385
}
386
387
388
// Damned `RPTax` is the only camel cased table field.
389
function get_rptax( $name )
390
{
391
	$name = 'rptax'; // normalize the name
392
	$value = $this->raw->rptax = $this->raw->RPTax; // the lower case name needs to exist in raw for _cashmoney to work
393
	$this->cooked->$name = $value;
394
	if(is_numeric( $value )){ return $this->_cashmoney( $name ); }
395
	else { return $this->cooked->$name; }
396
}
397
398
399
400
401
function get_land_sq_ft()
402
{
403
	return $this->get_lot_size();
404
}
405
406
function get_lot_size()
407
{
408
	$size = $this->_sqftacre($this->raw->lot_size);
409
	$this->cooked->land_sq_ft = $size;
410
	$this->cooked->lot_size = $size;
411
	return $size;
412
}
413
414
415
function _sqftacre( $input )
416
{
417
	if(empty($input)){ return ''; }
418
	$out = strtolower(sqftacre( $input ));
419
	$out = explode(' ', $out);
420
	if( $out[1] == 'acres' || $out[1] == 'acre'){ return implode(' ', $out); }
421
	else {return $out[0].' sq.ft.';}
422
}
423
424
function get_living_area()
425
{
426
	return $this->_squarefeet('living_area');
427
	# Sizes of building internals should never be represented in acres.
428
}
429
430
function get_gross_building()
431
{
432
	return $this->_squarefeet('gross_building');
433
	# Sizes of building internals should never be represented in acres.
434
}
435
436
function get_building_area()
437
{
438
	return $this->get_gross_building();
439
}
440
441
442
function get_net_rentable()
443
{
444
	return $this->_squarefeet('net_rentable');
445
	# Sizes of building internals should never be represented in acres.
446
}
447
448
function get_nra()
449
{
450
	return $this->get_net_rentable();
451
}
452
453
454
function get_gross_rentable_area()
455
{
456
	return $this->_squarefeet('gross_rentable_area');
457
	// anything building related should always be in square feet.
458
}
459
460
function get_gra()
461
{
462
	return $this->get_gross_rentable_area();
463
}
464
465
private function _squarefeet( $var )
466
{
467
	if( empty($this->raw->$var) ){ return ''; }
468
	return $this->cooked->$var = number_format($this->raw->$var).' sq.ft.';
469
}
470
471
// For when you're sure something is money and should show a $ and commas.
472
// In the negative case show nothing.
473
private function _cashmoney( $var )
474
{
475
	if( 0 == (int) $this->raw->$var ) { $this->cooked->$var = ''; }
476
	else { $this->cooked->$var = '$'. number_format($this->raw->$var); }
477
478
	return $this->cooked->$var;
479
}
480
481
482
public function get_view_count()
483
{
484
	$sql = "SELECT totalhits FROM listings_hits WHERE listing_id = {$this->raw->listing_id}";
485
	$count = sqlQuery($sql);
486
	if( !empty($count) ) { return $this->cooked->view_count = $count[0]['totalhits']; }
487
}
488
489
490
public function get_bedrooms()
491
{
492
	if($this->raw->bedrooms  == 0) { return $this->cooked->bedrooms = null; }
493
	else { return $this->cooked->bedrooms = $this->raw->bedrooms; }
494
}
495
496
public function get_bathrooms()
497
{
498
	$bathrooms = (float) $this->raw->bathrooms;
499
500
	if($bathrooms == 0)	{ $bathrooms = null; }
501
502
	if(strpos($bathrooms, '.5') !== false)
503
	{ 
504
		$bathrooms = str_replace('.5', "&frac12;", $bathrooms); 
505
	}
506
	elseif( (int)$this->raw->halfbaths > 0 && $bathrooms > 0)
507
	{
508
		$bathrooms .= "&frac12;";
509
	}
510
	return $this->cooked->bathrooms = $bathrooms;
511
}
512
513
514
}
515
?>
516
[/code]