-
Notifications
You must be signed in to change notification settings - Fork 1
/
cob.theme
766 lines (679 loc) · 26.6 KB
/
cob.theme
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
<?php
/**
* @copyright 2017-2024 City of Bloomington, Indiana
* @license http://www.gnu.org/licenses/agpl.txt GNU/AGPL, see LICENSE
*/
use Drupal\image\Entity\ImageStyle;
use Drupal\node\Entity\Node;
use Drupal\Core\Entity\FieldableEntityInterface;
use Drupal\core\Site\Settings;
use Drupal\core\Url;
use Drupal\calendar\GoogleGateway;
use Drupal\directory\DirectoryService;
use Drupal\interactivemap\MapGateway;
use Drupal\onboard\OnBoardService;
// Some node_ids for pages in the site
const DEPARTMENT_COUNCIL = 2796;
const BOARD_COUNCIL = 47;
/**
* Prepare contact information for various modules
*
* This hook will get called multiple times for a single page render.
* We rely on the fact that module hooks get called before the general page
* hook. During the module hook call, we load a location node. Then, during the
* page hook call, we set inject that node into $vars. Once injected, we
* let the normal cob_preprocess_page() handle rendering contact information
* for that node.
*
* PROMT
* The promt module will be rendering promt programs. When we are displaying
* a single program that has a location, we need to use the contact information
* from the Drupal node that has that location_id. We are storing the
* location_id as the field_promt_id for Drupal's content type: location.
*
* Animal Shelter
* All animal shelter routes are for the same location: 204
*
* @implements module_preprocess()
* @see https://api.drupal.org/api/drupal/core%21lib%21Drupal%21Core%21Render%21theme.api.php/group/themeable/8.2.x
*/
function cob_preprocess(&$vars, $hook)
{
static $location = null;
static $route = null;
switch ($hook) {
case 'promt_program':
$route = 'promt_program';
if (!empty($vars['program']['location_id'])) {
$location_id = $vars['program']['location_id'];
$query = \Drupal::entityQuery('node')
->accessCheck(true)
->condition('status', 1)
->condition('type', 'location')
->condition('field_promt_id', $location_id);
$nids = $query->execute();
if ($nids) {
$location = \Drupal::entityTypeManager()->getStorage('node')->load(current($nids));
$vars['location'] = $location;
}
}
break;
case 'asm_adoptable_animal':
case 'asm_adoptable_animals':
case 'asm_held_animals':
case 'asm_lf_animal':
case 'asm_lf_animals':
$route = $hook;
$location = \Drupal::entityTypeManager()->getStorage('node')->load(204);
$vars['base_path'] = base_path();
break;
case 'page':
if ($location && empty($vars['node'])) {
$vars['node'] = $location;
}
break;
}
}
/**
* @param int $numdays The number of days into the future to gather events
* @param int $maxevents Maximum number of events to return
* @return array The themed render array for the events
*/
function _cob_events($calendarId, int $numdays, int $maxevents): array
{
$start = new \DateTime();
$end = new \DateTime();
$end->add(new \DateInterval("P{$numdays}D"));
$events = null;
try { $events = GoogleGateway::events($calendarId, $start, $end, $maxevents); }
catch (\Exception $e) { }
if ($events) {
return [
'#theme' => 'calendar_events',
'#calendarId' => $calendarId,
'#events' => GoogleGateway::limitEvents($events, $maxevents)
];
}
return [];
}
function cob_preprocess_page__front(&$vars)
{
$id = Settings::get('cob_front_calendar');
if ($id) {
$vars['events'] = _cob_events($id, 7, 4);
}
$vars['available_messages'] = !empty(\Drupal::messenger()->all());
$query = \Drupal::entityQuery('node')
->accessCheck(true)
->condition('type', 'news')
->condition('status', 1)
->sort('created', 'desc')
->range(0, 5);
$vars['news' ] = _cob_renderNodesByQuery($query, 'teaser');
$vars['about'] = _cob_renderNodeById(223, 'promo');
$vars['mayor'] = _cob_renderNodeById(608, 'promo');
// Pothole dataset query
#$vars['pothole_count'] = __cob_latestPotholeCount();
}
function cob_preprocess_page(&$vars)
{
if (isset($vars['node']) && $vars['node'] instanceof \Drupal\node\Entity\Node) {
$vars['page']['title'] = $vars['node']->title->value;
$urls = _cob_coverImageForEntity($vars['node']);
if ($urls) { $vars['cover_image'] = $urls; }
$contactInfo = _cob_contactInfoFromNode($vars['node']);
if ($contactInfo) {
$vars['contactInfo'] = $contactInfo;
}
$vars['available_messages'] = !empty(\Drupal::messenger()->all());
// Custom content for the Parks and Rec landing page
if ((int)$vars['node']->get('nid')->value === 250) {
$vars['program_search_form'] = \Drupal::formBuilder()->getForm('Drupal\promt\Form\ProgramSearchForm');
$vars['events' ] = $vars['node']->field_calendar ->view('full');
$vars['related' ] = $vars['node']->field_department->view('full');
$vars['tlrc' ] = _cob_renderNodeById(502, 'promo');
$vars['rentals' ] = _cob_renderNodeById(368, 'promo');
$vars['cascades' ] = _cob_renderNodeById(553, 'promo');
}
// Don't display committee members on pages rendered by the onboard module
$m = \Drupal::routeMatch()->getRouteName();
if (substr($m, 0, 7) == 'onboard') {
if (isset($vars['page']['content']['committeemembers'])) {
unset($vars['page']['content']['committeemembers']);
}
}
// Boards and Commissions contact info should override any other contact info
if ($vars['node']->getType() == 'board_commission') {
$committee_id = $vars['node']->get('field_committee')->value;
if ($committee_id) {
$committee = OnBoardService::committee_info($committee_id);
if ($committee['info']['phone' ]) { $vars['contactInfo']['phone' ] = $committee['info']['phone' ]; }
if ($committee['info']['email' ]) { $vars['contactInfo']['email' ] = $committee['info']['email' ]; }
if ($committee['info']['address']) { $vars['contactInfo']['address'] = $committee['info']['address']; }
if ($committee['info']['city' ]) { $vars['contactInfo']['city' ] = $committee['info']['city' ]; }
if ($committee['info']['state' ]) { $vars['contactInfo']['state' ] = $committee['info']['state' ]; }
if ($committee['info']['zip' ]) { $vars['contactInfo']['zip' ] = $committee['info']['zip' ]; }
}
}
}
else {
$route = \Drupal::routeMatch()->getRouteName();
if ($route == 'entity.taxonomy_term.canonical') {
$tid = \Drupal::routeMatch()->getRawParameter( 'taxonomy_term');
$term = \Drupal::entityTypeManager()->getStorage('taxonomy_term')->load($tid);
$urls = _cob_coverImageForEntity($term);
if ($urls) { $vars['cover_image'] = $urls; }
}
}
$query = \Drupal::entityQuery('node')
->accessCheck(true)
->condition('type', 'alert')
->condition('status', 1)
->sort('created', 'desc')
->range(0, 5);
$alerts = _cob_renderNodesByQuery($query, 'teaser');
if ($alerts) {
$vars['alerts'] = $alerts;
}
}
/**
* Returns URL's to all the styles for a cover image.
*
* The indexes for the return array will be the names of the image styles.
* $urls[
* 'cover_small' =>'https://host/sites/default/files/styles/small/image.png',
* 'cover_medium'=>'https://host/sites/default/files/styles/medium/image.png',
* 'cover_large' =>'https://host/sites/default/files/styles/large/image.png'
* ]
*
* @return array An array of url strings
*/
function _cob_coverImageForEntity(FieldableEntityInterface $entity): array
{
$urls = [];
if ($entity->hasField('field_cover_image')) {
$img = $entity->get('field_cover_image')->first();
if ($img) {
$styles = ['cover_small', 'cover_medium', 'cover_large'];
$target = $img->get('entity')->getTarget();
if ($target) {
$ent = $target->getValue()->field_media_image->entity;
if ($ent) {
foreach ($styles as $s) {
$urls[$s] = ImageStyle::load($s)->buildUrl($ent->getFileUri());
}
}
}
}
}
return $urls;
}
function cob_preprocess_node(&$vars)
{
if ($vars['view_mode'] == 'full') {
$nid = (int)$vars['node']->get('nid' )->value;
switch ($nid) {
// Engineering Projects
case 573:
$query = \Drupal::entityQuery('node')
->accessCheck(true)
->condition('type', 'project_page')
->condition('field_active', true)
->sort('created', 'desc');
$vars['projects'] = _cob_renderNodesByQuery($query, 'info_card');
break;
// Utilities Projects
case 5519:
$query = \Drupal::entityQuery('node')
->accessCheck(true)
->condition('type', 'utilities_project_page')
->condition('field_active', true)
->sort('created', 'desc');
$vars['utilities_projects'] = _cob_renderNodesByQuery($query, 'info_card');
break;
// Boards
case 217:
$committees = [];
foreach (OnBoardService::committee_list() as $c) {
$committees[$c['id']] = $c;
}
$manager = \Drupal::entityTypeManager();
$storage = $manager->getStorage('node');
$builder = $manager->getViewBuilder('node');
// Active Boards that are not part of the City Council
$query = \Drupal::entityQuery('node')
->accessCheck(true)
->condition('type', 'board_commission' )
->condition('field_active', true )
->condition('field_department', DEPARTMENT_COUNCIL, '<>')
->sort('title');
$nodes = $storage->loadMultiple($query->execute());
__cob_add_onboard_flags_to_nodes($nodes, $committees);
$vars['boards_active'] = $builder->viewMultiple($nodes, 'info_card');
// City Council boards that are active
$query = \Drupal::entityQuery('node')
->accessCheck(true)
->condition('type', 'board_commission')
->condition('field_active', true)
->condition('field_department', DEPARTMENT_COUNCIL)
->sort('title');
// move the city council to the first item in the list
$nodes = $storage->loadMultiple($query->execute());
$ci = null;
$council = null;
foreach ($nodes as $i=>$n) { if ($n->id() == BOARD_COUNCIL) { $ci = $i; } }
if ($ci) {
$council = $nodes[$ci];
unset($nodes[$ci]);
$nodes = array_merge([$council], $nodes);
}
__cob_add_onboard_flags_to_nodes($nodes, $committees);
$vars['boards_council'] = $builder->viewMultiple($nodes, 'info_card');
// All Inactivate boards
$committees = [];
foreach (OnBoardService::committee_list(['current' => 0]) as $c) {
$committees[$c['id']] = $c;
}
$query = \Drupal::entityQuery('node')
->accessCheck(true)
->condition('type', 'board_commission')
->condition('field_active', false)
->sort('title');
$nodes = $storage->loadMultiple($query->execute());
__cob_add_onboard_flags_to_nodes($nodes, $committees);
$vars['boards_inactive'] = $builder->viewMultiple($nodes, 'info_card');
// Load the Google Calendar
$vars['events'] = _cob_events('bloomington.in.gov_r7b1mkrme1r8uhl3b5amhb50bc@group.calendar.google.com', 30, 24);
break;
}
if ($vars['node']->getType() == 'board_commission') {
$start = new \DateTime();
$end = new \DateTime();
$end->add(new \DateInterval("P60D"));
switch ($nid) {
case BOARD_COUNCIL:
$calendar_id = 'bloomington.in.gov_7rki30ccsun4vk4stoq2n4nreg@group.calendar.google.com';
$events = GoogleGateway::events($calendar_id, $start, $end, true, 4);
$vars['meetings'] = [
'#theme' => 'calendar_events',
'#events' => $events,
'#calendarId' => $calendar_id
];
break;
default:
$committee_id = $vars['node']->get('field_committee')->value;
if ($committee_id) {
$committee = OnBoardService::committee_info($committee_id);
$meetings = OnBoardService::meetings($committee_id, null, $start, $end, 4);
$vars['meetings'] = [
'#theme' => 'onboard_upcoming_meetings',
'#meetings' => $meetings,
'#committee' => $committee,
'#nid' => $nid
];
}
}
}
$vars['regions']['secondary_menu'] = _cob_renderRegion('secondary_menu');
}
}
function __cob_add_onboard_flags_to_nodes(array &$nodes, array $committees)
{
foreach ($nodes as $i=>$n) {
$cid = (int)$n->field_committee->getString();
if ($cid && array_key_exists($cid, $committees)) {
$nodes[$i]->committeeType = $committees[$cid]['type'];
$nodes[$i]->vacancies = $committees[$cid]['vacancies'];
$nodes[$i]->takesApplications = $committees[$cid]['takesApplications'];
}
}
}
/**
* Load events calendar when rendering the news archive
*
* @param $vars array Theme variables set by the Archive Controller
* @see drupal-module-archive/src/Controller/ArchiveController
*/
function cob_preprocess_archive_results(&$vars)
{
if ($vars['type'] == 'news') {
$id = Settings::get('cob_front_calendar');
if ($id) {
$vars['events'] = _cob_events($id, 7, 4);
}
}
}
function cob_preprocess_paragraph__info_card(&$vars)
{
$vars['title'] = !empty($vars['elements']['field_info_title']['#items'])
? $vars['elements']['field_info_title']['#items'][0]->value
: null;
$vars['text' ] = !empty($vars['elements']['field_info_text' ]['#items'])
? $vars['elements']['field_info_text' ]['#items'][0]->value
: null;
if ((!$vars['title'] || !$vars['text'])
&& !empty($vars['content']['field_info_link']['#items'][0])
&& preg_match('|entity:([a-z]+)/(\d+)|',
$vars['content']['field_info_link']['#items'][0]->getString(),
$matches)) {
$type = $matches[1];
$id = $matches[2];
$node = \Drupal::entityTypeManager()->getStorage($type)->load($id);
if ($node) {
if (!$vars['title']) { $vars['title'] = $node->title->value; }
if (!$vars['text' ]) { $vars['text' ] = $node->body->summary; }
}
}
}
function cob_preprocess_field__entity_reference(&$vars)
{
foreach ($vars['items'] as $i=>$item) {
if (!empty($item['content']['#type']) && $item['content']['#type'] == 'link') {
$vars['items'][$i]['content']['#title'] = "{$vars['element']['#title']}: {$item['content']['#title']}";
$vars['items'][$i]['content']['#options']['attributes']['class'][] = 'button';
}
}
}
/**
* Link promo titles to their nodes
*/
function cob_preprocess_field__field_promo_title(&$vars)
{
$url = Url::fromRoute('entity.node.canonical', ['node'=>$vars['element']['#object']->nid->value])->toString();
foreach ($vars['items'] as $i=>$item) {
$vars['items'][$i]['content'] = [
'#markup' => "<a href=\"$url\" class=\"btn more\">{$item['content']['#context']['value']}</a>"
];
}
}
/**
* Add titles to internal links
*
* User should not type titles into links, if they're to internal pages.
* Rather, the title should be pulled dynamically from the page they're
* linking to. Title on pages change over time, and we hate going back
* and trying to update all the links with the new title.
*/
function cob_preprocess_field__link(&$vars)
{
foreach ($vars['element']['#items'] as $i=>$item) {
$title = $item->get('title')->getString();
if (!$title) {
$uri = $item->get('uri')->getString();
if (substr($uri, 0, 6) == 'entity') {
$params = Url::fromUri($uri)->getRouteParameters();
$type = key($params);
$entity = \Drupal::entityTypeManager()->getStorage($type)->load($params[$type]);
if ($entity) {
$vars['items'][$i]['content']['#title'] = $entity->title->value;
}
}
}
}
// All link fields are going to be styled as some type of button
foreach ($vars['items'] as $i=>$item) {
$vars['items'][$i]['content']['#options']['attributes']['class'][] = 'button';
}
}
function cob_preprocess_field__node__body__news(&$vars)
{
$vars['label'] = $vars['element']['#object']->getTitle();
}
function cob_preprocess_image(&$vars)
{
unset($vars['attributes']['width'], $vars['attributes']['height']);
}
/**
* Pretty prints military time
*
* Takes a four digit, military time and returns a short version, using am/pm
*/
function _cob_ftime($time)
{
$time = trim($time);
$h = (int)substr($time, 0, 2);
$m = (int)substr($time, -2);
$a = $h >= 12 ? 'pm' : 'am';
$h = $h > 12 ? $h-12 : $h;
// Leave off the minutes, if it's the top of the hour
$m = $m ? ":$m" : '';
return "$h$m$a\n";
}
function cob_preprocess_field__field_hours(&$vars)
{
$days = [
'Sunday',
'Monday',
'Tuesday',
'Wednesday',
'Thursday',
'Friday',
'Saturday'
];
$hours = [];
$temp = [];
foreach ($vars['items'] as $i=>$item) {
foreach (explode("\n", $item['content']['#context']['value']) as $line) {
$hour = explode(',', $line);
if (count($hour) === 3) {
$day = ucfirst(trim($hour[0]));
$start = _cob_ftime($hour[1]);
$end = _cob_ftime($hour[2]);
$temp[$day] = "$start-$end";
}
}
foreach ($days as $d) {
$hours[$d] = isset($temp[$d]) ? $temp[$d] : 'Closed';
}
$vars['items'][$i]['hours'] = $hours;
}
}
function cob_form_search_block_form_alter(&$form, &$form_state)
{
$form['keys']['#attributes']['placeholder'][] = 'Search...';
}
/**
* Populates contact information from various sources for a given node
*
* This function will cache the results by NodeID. The contactInfo
* queries are extensive, and can be slow. We don't want to do this
* more than once.
*
* @param Node $node
* @return array
*/
function _cob_contactInfoFromNode(Node $node)
{
static $info = [];
$nid = $node->nid->value;
// If the NID has been set, then we've already attempted a lookup.
// If it's there, and it is empty, then the lookup returned no results.
// Don't waste time doing another lengthy lookup, just to get empty
// results again.
if (isset($info[$nid])) { return $info[$nid]; }
$info[$nid] = [];
if (empty($info[$nid]['facebook']) && $node->hasField('field_facebook_page')) {
$v = $node->get('field_facebook_page')->getValue();
if (!empty($v[0]['uri'])) {
$info[$nid]['links']['facebook'] = $v[0]['uri'];
}
}
if (empty($info[$nid]['twitter' ]) && $node->hasField('field_twitter_account')) {
$v = $node->get('field_twitter_account')->getValue();
if (!empty($v[0]['uri'])) {
$info[$nid]['links']['twitter'] = $v[0]['uri'];
}
}
$map = [
'email' => 'field_email',
'phone' => 'field_phone',
'fax' => 'field_fax',
'address' => 'field_street_address',
'zip' => 'field_zipcode'
];
foreach ($map as $i=>$f) {
if (empty($info[$nid][$i]) && $node->hasField($f)) {
$value = $node->get($f)->value;
if ($value) { $info[$nid][$i] = $value; }
}
}
if (!empty($info[$nid]['zip'])) {
if (empty($info[$nid]['city' ])) { $info[$nid]['city' ] = 'Bloomington'; }
if (empty($info[$nid]['state'])) { $info[$nid]['state'] = 'IN'; }
}
if ($node->hasField( 'field_directory_dn')) {
$dn = $node->get('field_directory_dn')->value;
if ($dn) { _cob_contactInfoForDn($dn, $info[$nid]); }
}
if ($node->hasField('field_location')) {
$l = $node->get('field_location')->entity;
if ($l) {
$info[$nid]['location_nid'] = $l->get('nid')->value;
$li = _cob_contactInfoFromNode($l);
foreach ($li as $k=>$v) {
if (empty($info[$nid][$k])) { $info[$nid][$k] = $v; }
}
}
}
if ($node->hasField('field_department')) {
$d = $node->get('field_department')->entity;
if ($d) {
$info[$nid]['department_nid'] = $d->get('nid')->value;
$di = _cob_contactInfoFromNode($d);
foreach ($di as $k=>$v) {
if (empty($info[$nid][$k])) { $info[$nid][$k] = $v; }
}
}
}
return $info[$nid];
}
/**
* Populates contactInfo array with data from Directory webservice
*
* @param string $dn
* @param array $contactInfo Reference to the array to populate
*/
function _cob_contactInfoForDn($dn, array &$info)
{
if (\Drupal::moduleHandler()->moduleExists('directory')) {
$json = DirectoryService::department_info($dn);
if ($json) {
_cob_mapContactInfoFields($info, $json, [
'name' => 'name',
'email' => 'email',
'phone' => 'office',
'fax' => 'fax',
'address' => 'address',
'city' => 'city',
'state' => 'state',
'zip' => 'zip'
]);
}
}
}
/**
* Populates empty $info fields with data according to a map.
*
* Does NOT replace existing values in $info.
*
* Map array must specify info fields as keys and data fields as values.
* $map[ $infoField => $dataField ]
*
* @param array $info Reference to contactInfo array to populate
* @param array $data Array of data to copy
* @param array $map Associative array of data fields to info fields
*/
function _cob_mapContactInfoFields(array &$info, array $data, array $map)
{
foreach ($map as $infoField => $dataField) {
if (empty($info[$infoField])) { $info[$infoField] = $data[$dataField]; }
}
}
/**
* @param QueryInterface $query
* @param string $viewMode
* @return array The themed render array
*/
function _cob_renderNodesByQuery(\Drupal\Core\Entity\Query\QueryInterface $query, string $viewMode): array
{
static $manager;
static $builder;
static $storage;
if (!$manager) {
$manager = \Drupal::entityTypeManager();
$builder = $manager->getViewBuilder('node');
$storage = $manager->getStorage('node');
}
return $builder->viewMultiple($storage->loadMultiple($query->execute()), $viewMode);
}
/**
* @param int|array $nid A node ID or array of node IDs
* @param string $viewMode
* @return array The themed render array
*/
function _cob_renderNodeById($nid, string $viewMode): array
{
static $manager;
static $builder;
static $storage;
if (!$manager) {
$manager = \Drupal::entityTypeManager();
$builder = $manager->getViewBuilder('node');
$storage = $manager->getStorage('node');
}
return is_array($nid)
? $builder->viewMultiple($storage->loadMultiple($nid), $viewMode)
: $builder->view ($storage->load ($nid), $viewMode);
}
/**
* @param string $region
* @return array An array of the themed blocks in the region
*/
function _cob_renderRegion(string $region): array
{
static $manager;
static $builder;
static $storage;
if (!$manager) {
$manager = \Drupal::entityTypeManager();
$builder = $manager->getViewBuilder('block');
$storage = $manager->getStorage('block');
}
$blocks = $storage->loadByProperties(['theme'=>'cob', 'region'=>$region]);
uasort($blocks, 'Drupal\block\Entity\Block::sort');
return $builder->viewMultiple($blocks);
}
/**
* Downloads and processes a Google spreadheet for pothole counts
*/
function __cob_latestPotholeCount(): int
{
$csv = '/tmp/potholes.csv';
$url = 'https://docs.google.com/spreadsheets/d/14qN0YTLU4klEhr9H58Eu2zzTMi2bCnjGC4fJ59e-phs/export?format=csv&gid=1274323447';
$year = '2020';
if (is_file($csv)) {
$yesterday = new \DateTime('yesterday');
$lastModified = new \DateTime();
$lastModified->setTimestamp(filemtime($csv));
if ($lastModified < $yesterday) { unlink($csv); }
}
if (!is_file($csv)) {
$client = \Drupal::httpClient(['timeout' => 5]);
$response = $client->get($url);
if ($response) { file_put_contents($csv, $response->getBody()); }
else { return 0; }
}
$data = fopen($csv, 'r');
$count = 0;
$i = 0;
while ($row = fgetcsv($data)) {
if ($i == 0) { $i++; continue; }
if (!empty($row[0]) && !empty($row[1])) {
$date = new \DateTime($row[0]);
if ($date->format('Y') == $year) {
$count += (int)$row[1];
}
}
}
return $count;
}