This repository has been archived by the owner on Jan 31, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 61
/
AbstractHelper.php
903 lines (803 loc) · 25.1 KB
/
AbstractHelper.php
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
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
<?php
/**
* Zend Framework (http://framework.zend.com/)
*
* @link http://github.com/zendframework/zf2 for the canonical source repository
* @copyright Copyright (c) 2005-2015 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
namespace Zend\View\Helper\Navigation;
use Interop\Container\ContainerInterface;
use RecursiveIteratorIterator;
use ReflectionClass;
use ReflectionProperty;
use Zend\EventManager\EventManager;
use Zend\EventManager\EventManagerAwareInterface;
use Zend\EventManager\EventManagerInterface;
use Zend\EventManager\SharedEventManager;
use Zend\Navigation;
use Zend\Navigation\Page\AbstractPage;
use Zend\Permissions\Acl;
use Zend\ServiceManager\AbstractPluginManager;
use Zend\View;
use Zend\View\Exception;
use Zend\View\Helper\TranslatorAwareTrait;
/**
* Base class for navigational helpers.
*
* Duck-types against Zend\I18n\Translator\TranslatorAwareInterface.
*/
abstract class AbstractHelper extends View\Helper\AbstractHtmlElement implements
EventManagerAwareInterface,
HelperInterface
{
use TranslatorAwareTrait;
/**
* @var EventManagerInterface
*/
protected $events;
/**
* AbstractContainer to operate on by default
*
* @var Navigation\AbstractContainer
*/
protected $container;
/**
* The minimum depth a page must have to be included when rendering
*
* @var int
*/
protected $minDepth;
/**
* The maximum depth a page can have to be included when rendering
*
* @var int
*/
protected $maxDepth;
/**
* Indentation string
*
* @var string
*/
protected $indent = '';
/**
* ACL to use when iterating pages
*
* @var Acl\AclInterface
*/
protected $acl;
/**
* Whether invisible items should be rendered by this helper
*
* @var bool
*/
protected $renderInvisible = false;
/**
* ACL role to use when iterating pages
*
* @var string|Acl\Role\RoleInterface
*/
protected $role;
/**
* @var ContainerInterface
*/
protected $serviceLocator;
/**
* Whether ACL should be used for filtering out pages
*
* @var bool
*/
protected $useAcl = true;
/**
* Default ACL to use when iterating pages if not explicitly set in the
* instance by calling {@link setAcl()}
*
* @var Acl\AclInterface
*/
protected static $defaultAcl;
/**
* Default ACL role to use when iterating pages if not explicitly set in the
* instance by calling {@link setRole()}
*
* @var string|Acl\Role\RoleInterface
*/
protected static $defaultRole;
/**
* Magic overload: Proxy calls to the navigation container
*
* @param string $method method name in container
* @param array $arguments rguments to pass
* @return mixed
* @throws Navigation\Exception\ExceptionInterface
*/
public function __call($method, array $arguments = [])
{
return call_user_func_array(
[$this->getContainer(), $method],
$arguments
);
}
/**
* Magic overload: Proxy to {@link render()}.
*
* This method will trigger an E_USER_ERROR if rendering the helper causes
* an exception to be thrown.
*
* Implements {@link HelperInterface::__toString()}.
*
* @return string
*/
public function __toString()
{
try {
return $this->render();
} catch (\Exception $e) {
$msg = get_class($e) . ': ' . $e->getMessage();
trigger_error($msg, E_USER_ERROR);
return '';
}
}
/**
* Finds the deepest active page in the given container
*
* @param Navigation\AbstractContainer $container container to search
* @param int|null $minDepth [optional] minimum depth
* required for page to be
* valid. Default is to use
* {@link getMinDepth()}. A
* null value means no minimum
* depth required.
* @param int|null $maxDepth [optional] maximum depth
* a page can have to be
* valid. Default is to use
* {@link getMaxDepth()}. A
* null value means no maximum
* depth required.
* @return array an associative array with
* the values 'depth' and
* 'page', or an empty array
* if not found
*/
public function findActive($container, $minDepth = null, $maxDepth = -1)
{
$this->parseContainer($container);
if (! is_int($minDepth)) {
$minDepth = $this->getMinDepth();
}
if ((! is_int($maxDepth) || $maxDepth < 0) && null !== $maxDepth) {
$maxDepth = $this->getMaxDepth();
}
$found = null;
$foundDepth = -1;
$iterator = new RecursiveIteratorIterator(
$container,
RecursiveIteratorIterator::CHILD_FIRST
);
/** @var \Zend\Navigation\Page\AbstractPage $page */
foreach ($iterator as $page) {
$currDepth = $iterator->getDepth();
if ($currDepth < $minDepth || ! $this->accept($page)) {
// page is not accepted
continue;
}
if ($page->isActive(false) && $currDepth > $foundDepth) {
// found an active page at a deeper level than before
$found = $page;
$foundDepth = $currDepth;
}
}
if (is_int($maxDepth) && $foundDepth > $maxDepth) {
while ($foundDepth > $maxDepth) {
if (--$foundDepth < $minDepth) {
$found = null;
break;
}
$found = $found->getParent();
if (! $found instanceof AbstractPage) {
$found = null;
break;
}
}
}
if ($found) {
return ['page' => $found, 'depth' => $foundDepth];
}
return [];
}
/**
* Verifies container and eventually fetches it from service locator if it is a string
*
* @param Navigation\AbstractContainer|string|null $container
* @throws Exception\InvalidArgumentException
*/
protected function parseContainer(&$container = null)
{
if (null === $container) {
return;
}
if (is_string($container)) {
$services = $this->getServiceLocator();
if (! $services) {
throw new Exception\InvalidArgumentException(sprintf(
'Attempted to set container with alias "%s" but no ServiceLocator was set',
$container
));
}
// Fallback
if (in_array($container, ['default', 'navigation'], true)) {
// Uses class name
if ($services->has(Navigation\Navigation::class)) {
$container = $services->get(Navigation\Navigation::class);
return;
}
// Uses old service name
if ($services->has('navigation')) {
$container = $services->get('navigation');
return;
}
}
/**
* Load the navigation container from the root service locator
*/
$container = $services->get($container);
return;
}
if (! $container instanceof Navigation\AbstractContainer) {
throw new Exception\InvalidArgumentException(
'Container must be a string alias or an instance of '
. 'Zend\Navigation\AbstractContainer'
);
}
}
// Iterator filter methods:
/**
* Determines whether a page should be accepted when iterating
*
* Default listener may be 'overridden' by attaching listener to 'isAllowed'
* method. Listener must be 'short circuited' if overriding default ACL
* listener.
*
* Rules:
* - If a page is not visible it is not accepted, unless RenderInvisible has
* been set to true
* - If $useAcl is true (default is true):
* - Page is accepted if listener returns true, otherwise false
* - If page is accepted and $recursive is true, the page
* will not be accepted if it is the descendant of a non-accepted page
*
* @param AbstractPage $page page to check
* @param bool $recursive [optional] if true, page will not be
* accepted if it is the descendant of
* a page that is not accepted. Default
* is true
*
* @return bool Whether page should be accepted
*/
public function accept(AbstractPage $page, $recursive = true)
{
$accept = true;
if (! $page->isVisible(false) && ! $this->getRenderInvisible()) {
$accept = false;
} elseif ($this->getUseAcl()) {
$acl = $this->getAcl();
$role = $this->getRole();
$params = ['acl' => $acl, 'page' => $page, 'role' => $role];
$accept = $this->isAllowed($params);
}
if ($accept && $recursive) {
$parent = $page->getParent();
if ($parent instanceof AbstractPage) {
$accept = $this->accept($parent, true);
}
}
return $accept;
}
/**
* Determines whether a page should be allowed given certain parameters
*
* @param array $params
* @return bool
*/
protected function isAllowed($params)
{
$events = $this->getEventManager() ?: $this->createEventManager();
$results = $events->trigger(__FUNCTION__, $this, $params);
return $results->last();
}
// Util methods:
/**
* Retrieve whitespace representation of $indent
*
* @param int|string $indent
* @return string
*/
protected function getWhitespace($indent)
{
if (is_int($indent)) {
$indent = str_repeat(' ', $indent);
}
return (string) $indent;
}
/**
* Converts an associative array to a string of tag attributes.
*
* Overloads {@link View\Helper\AbstractHtmlElement::htmlAttribs()}.
*
* @param array $attribs an array where each key-value pair is converted
* to an attribute name and value
* @return string
*/
protected function htmlAttribs($attribs)
{
// filter out null values and empty string values
foreach ($attribs as $key => $value) {
if ($value === null || (is_string($value) && ! strlen($value))) {
unset($attribs[$key]);
}
}
return parent::htmlAttribs($attribs);
}
/**
* Returns an HTML string containing an 'a' element for the given page
*
* @param AbstractPage $page page to generate HTML for
* @return string HTML string (<a href="…">Label</a>)
*/
public function htmlify(AbstractPage $page)
{
$label = $this->translate($page->getLabel(), $page->getTextDomain());
$title = $this->translate($page->getTitle(), $page->getTextDomain());
// get attribs for anchor element
$attribs = [
'id' => $page->getId(),
'title' => $title,
'class' => $page->getClass(),
'href' => $page->getHref(),
'target' => $page->getTarget()
];
/** @var \Zend\View\Helper\EscapeHtml $escaper */
$escaper = $this->view->plugin('escapeHtml');
$label = $escaper($label);
return '<a' . $this->htmlAttribs($attribs) . '>' . $label . '</a>';
}
/**
* Translate a message (for label, title, …)
*
* @param string $message ID of the message to translate
* @param string $textDomain Text domain (category name for the translations)
* @return string Translated message
*/
protected function translate($message, $textDomain = null)
{
if (! is_string($message) || empty($message)) {
return $message;
}
if (! $this->isTranslatorEnabled() || ! $this->hasTranslator()) {
return $message;
}
$translator = $this->getTranslator();
$textDomain = $textDomain ?: $this->getTranslatorTextDomain();
return $translator->translate($message, $textDomain);
}
/**
* Normalize an ID
*
* Overrides {@link View\Helper\AbstractHtmlElement::normalizeId()}.
*
* @param string $value
* @return string
*/
protected function normalizeId($value)
{
$prefix = get_class($this);
$prefix = strtolower(trim(substr($prefix, strrpos($prefix, '\\')), '\\'));
return $prefix . '-' . $value;
}
/**
* Sets ACL to use when iterating pages
*
* Implements {@link HelperInterface::setAcl()}.
*
* @param Acl\AclInterface $acl ACL object.
* @return AbstractHelper
*/
public function setAcl(Acl\AclInterface $acl = null)
{
$this->acl = $acl;
return $this;
}
/**
* Returns ACL or null if it isn't set using {@link setAcl()} or
* {@link setDefaultAcl()}
*
* Implements {@link HelperInterface::getAcl()}.
*
* @return Acl\AclInterface|null ACL object or null
*/
public function getAcl()
{
if ($this->acl === null && static::$defaultAcl !== null) {
return static::$defaultAcl;
}
return $this->acl;
}
/**
* Checks if the helper has an ACL instance
*
* Implements {@link HelperInterface::hasAcl()}.
*
* @return bool
*/
public function hasAcl()
{
if ($this->acl instanceof Acl\Acl
|| static::$defaultAcl instanceof Acl\Acl
) {
return true;
}
return false;
}
/**
* Set the event manager.
*
* @param EventManagerInterface $events
* @return AbstractHelper
*/
public function setEventManager(EventManagerInterface $events)
{
$events->setIdentifiers([
__CLASS__,
get_called_class(),
]);
$this->events = $events;
if ($events->getSharedManager()) {
$this->setDefaultListeners();
}
return $this;
}
/**
* Get the event manager, if present.
*
* Internally, the helper will lazy-load an EM instance the first time it
* requires one, but ideally it should be injected during instantiation.
*
* @return null|EventManagerInterface
*/
public function getEventManager()
{
return $this->events;
}
/**
* Sets navigation container the helper operates on by default
*
* Implements {@link HelperInterface::setContainer()}.
*
* @param string|Navigation\AbstractContainer $container Default is null, meaning container will be reset.
* @return AbstractHelper
*/
public function setContainer($container = null)
{
$this->parseContainer($container);
$this->container = $container;
return $this;
}
/**
* Returns the navigation container helper operates on by default
*
* Implements {@link HelperInterface::getContainer()}.
*
* If no container is set, a new container will be instantiated and
* stored in the helper.
*
* @return Navigation\AbstractContainer navigation container
*/
public function getContainer()
{
if (null === $this->container) {
$this->container = new Navigation\Navigation();
}
return $this->container;
}
/**
* Checks if the helper has a container
*
* Implements {@link HelperInterface::hasContainer()}.
*
* @return bool
*/
public function hasContainer()
{
return null !== $this->container;
}
/**
* Set the indentation string for using in {@link render()}, optionally a
* number of spaces to indent with
*
* @param string|int $indent
* @return AbstractHelper
*/
public function setIndent($indent)
{
$this->indent = $this->getWhitespace($indent);
return $this;
}
/**
* Returns indentation
*
* @return string
*/
public function getIndent()
{
return $this->indent;
}
/**
* Sets the maximum depth a page can have to be included when rendering
*
* @param int $maxDepth Default is null, which sets no maximum depth.
* @return AbstractHelper
*/
public function setMaxDepth($maxDepth = null)
{
if (null === $maxDepth || is_int($maxDepth)) {
$this->maxDepth = $maxDepth;
} else {
$this->maxDepth = (int) $maxDepth;
}
return $this;
}
/**
* Returns maximum depth a page can have to be included when rendering
*
* @return int|null
*/
public function getMaxDepth()
{
return $this->maxDepth;
}
/**
* Sets the minimum depth a page must have to be included when rendering
*
* @param int $minDepth Default is null, which sets no minimum depth.
* @return AbstractHelper
*/
public function setMinDepth($minDepth = null)
{
if (null === $minDepth || is_int($minDepth)) {
$this->minDepth = $minDepth;
} else {
$this->minDepth = (int) $minDepth;
}
return $this;
}
/**
* Returns minimum depth a page must have to be included when rendering
*
* @return int|null
*/
public function getMinDepth()
{
if (! is_int($this->minDepth) || $this->minDepth < 0) {
return 0;
}
return $this->minDepth;
}
/**
* Render invisible items?
*
* @param bool $renderInvisible
* @return AbstractHelper
*/
public function setRenderInvisible($renderInvisible = true)
{
$this->renderInvisible = (bool) $renderInvisible;
return $this;
}
/**
* Return renderInvisible flag
*
* @return bool
*/
public function getRenderInvisible()
{
return $this->renderInvisible;
}
/**
* Sets ACL role(s) to use when iterating pages
*
* Implements {@link HelperInterface::setRole()}.
*
* @param mixed $role [optional] role to set. Expects a string, an
* instance of type {@link Acl\Role\RoleInterface}, or null. Default
* is null, which will set no role.
* @return AbstractHelper
* @throws Exception\InvalidArgumentException
*/
public function setRole($role = null)
{
if (null === $role || is_string($role) ||
$role instanceof Acl\Role\RoleInterface
) {
$this->role = $role;
} else {
throw new Exception\InvalidArgumentException(sprintf(
'$role must be a string, null, or an instance of '
. 'Zend\Permissions\Role\RoleInterface; %s given',
(is_object($role) ? get_class($role) : gettype($role))
));
}
return $this;
}
/**
* Returns ACL role to use when iterating pages, or null if it isn't set
* using {@link setRole()} or {@link setDefaultRole()}
*
* Implements {@link HelperInterface::getRole()}.
*
* @return string|Acl\Role\RoleInterface|null
*/
public function getRole()
{
if ($this->role === null && static::$defaultRole !== null) {
return static::$defaultRole;
}
return $this->role;
}
/**
* Checks if the helper has an ACL role
*
* Implements {@link HelperInterface::hasRole()}.
*
* @return bool
*/
public function hasRole()
{
if ($this->role instanceof Acl\Role\RoleInterface
|| is_string($this->role)
|| static::$defaultRole instanceof Acl\Role\RoleInterface
|| is_string(static::$defaultRole)
) {
return true;
}
return false;
}
/**
* Set the service locator.
*
* Used internally to pull named navigation containers to render.
*
* @param ContainerInterface $serviceLocator
* @return AbstractHelper
*/
public function setServiceLocator(ContainerInterface $serviceLocator)
{
// If we are provided a plugin manager, we should pull the parent
// context from it.
// @todo We should update tests and code to ensure that this situation
// doesn't happen in the future.
if ($serviceLocator instanceof AbstractPluginManager
&& ! method_exists($serviceLocator, 'configure')
&& $serviceLocator->getServiceLocator()
) {
$serviceLocator = $serviceLocator->getServiceLocator();
}
// v3 variant; likely won't be needed.
if ($serviceLocator instanceof AbstractPluginManager
&& method_exists($serviceLocator, 'configure')
) {
$r = new ReflectionProperty($serviceLocator, 'creationContext');
$r->setAccessible(true);
$serviceLocator = $r->getValue($serviceLocator);
}
$this->serviceLocator = $serviceLocator;
return $this;
}
/**
* Get the service locator.
*
* Used internally to pull named navigation containers to render.
*
* @return ContainerInterface
*/
public function getServiceLocator()
{
return $this->serviceLocator;
}
/**
* Sets whether ACL should be used
*
* Implements {@link HelperInterface::setUseAcl()}.
*
* @param bool $useAcl
* @return AbstractHelper
*/
public function setUseAcl($useAcl = true)
{
$this->useAcl = (bool) $useAcl;
return $this;
}
/**
* Returns whether ACL should be used
*
* Implements {@link HelperInterface::getUseAcl()}.
*
* @return bool
*/
public function getUseAcl()
{
return $this->useAcl;
}
// Static methods:
/**
* Sets default ACL to use if another ACL is not explicitly set
*
* @param Acl\AclInterface $acl [optional] ACL object. Default is null, which
* sets no ACL object.
* @return void
*/
public static function setDefaultAcl(Acl\AclInterface $acl = null)
{
static::$defaultAcl = $acl;
}
/**
* Sets default ACL role(s) to use when iterating pages if not explicitly
* set later with {@link setRole()}
*
* @param mixed $role [optional] role to set. Expects null, string, or an
* instance of {@link Acl\Role\RoleInterface}. Default is null, which
* sets no default role.
* @return void
* @throws Exception\InvalidArgumentException if role is invalid
*/
public static function setDefaultRole($role = null)
{
if (null === $role
|| is_string($role)
|| $role instanceof Acl\Role\RoleInterface
) {
static::$defaultRole = $role;
} else {
throw new Exception\InvalidArgumentException(sprintf(
'$role must be null|string|Zend\Permissions\Role\RoleInterface; received "%s"',
(is_object($role) ? get_class($role) : gettype($role))
));
}
}
/**
* Attaches default ACL listeners, if ACLs are in use
*/
protected function setDefaultListeners()
{
if (! $this->getUseAcl()) {
return;
}
$events = $this->getEventManager() ?: $this->createEventManager();
if (! $events->getSharedManager()) {
return;
}
$events->getSharedManager()->attach(
'Zend\View\Helper\Navigation\AbstractHelper',
'isAllowed',
['Zend\View\Helper\Navigation\Listener\AclListener', 'accept']
);
}
/**
* Create and return an event manager instance.
*
* Ensures that the returned event manager has a shared manager
* composed.
*
* @return EventManager
*/
private function createEventManager()
{
$r = new ReflectionClass(EventManager::class);
if ($r->hasMethod('setSharedManager')) {
$events = new EventManager();
$events->setSharedManager(new SharedEventManager());
} else {
$events = new EventManager(new SharedEventManager());
}
$this->setEventManager($events);
return $events;
}
}