fantasia /core/classes/framework/route/route.php

Language PHP Lines 779
MD5 Hash f98070b18d604e8d4e2ad0ccfdce5a76
Repository https://github.com/GinoPane/fantasia.git View Raw File
  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
<?php
/**
 *
 * Instant part of routing system
 *
 * @version 1.0
 *
 * @author Sergey Karavay <sergey.karavay@gmail.com>
 */

class Route
{
    /**
     *
     * Route keyname
     * 
     * @var string 
     */
    private $_key = "";
    /**
     * Pattern string for route as it is in configuration
     *
     * @var string
     */
    private $_fullPattern = "";
    
    /**
     * Pattern string for route without parameters
     *
     * @var string
     */
    private $_clearPattern = "";
    
    /**
     *
     * @var array 
     */
    private $_clearPatternArray = array();
    
    /**
     *
     * Packet to link with
     * 
     * @var string 
     */
    private $_packName = "";

    /**
     *
     * Component name for this route
     * 
     * @var string 
     */
    private $_componentName = "";
    
    /**
     *
     * Manager class name to link with
     *
     * @var string
     */
    private $_controllerName = "";
    
    /**
     * 
     * Action to execute within the page. May be empty if page 
     * decides everything about actions internally
     * 
     * @var string
     */
    private $_action = "";

    /**
     *
     * Array of page parameter names to be passed
     *
     * @var array
     */
    private $_parameters = array();
    
    
    /**
     *
     * Array of parameters that passed through validator
     * 
     * @var array 
     */
    private $_parametersMatchedValidator = array();
    
    /**
     * Array of validation patterns for variables
     * 
     * @var array
     */
    private $_validator = array();
    
    
    /**
     * Array of default variable values
     * 
     *@var array 
     */
    private $_defaults = array();

    /**
     *
     * HTTP method used to access the page. 
     * If not set then it's "GET"
     *
     * @var string
     */
    private $_httpMethod = "";
    
    /**
     *
     * If this route is for ajax calls
     * 
     * @var boolean 
     */
    private $_ajaxRoute = false;

    /**
     *
     * Defines whether page is in secured area
     *
     * @var bool
     */
    private $_secured = false;

    /**
     * Creates the Route class instance
     *
     * @param string $pattern pattern that matches route
     * @param string $packComponent pack:component pair     
     *
     * @example 
     * 
     * <pre><code>
     * 
     * $route = new Route("some name", "page/nested-page/{param1}/{param2}", "main:index", "view");
     * 
     * $route->setValidation(array("param1" => 
     *                      array(Validator::IS_PATTERN_STRING =>
     *                              array('pattern' => "[abc]+")),
     *                   "param2" =>
     *                      array(Validator::IS_NUMERIC =>
     *                              array(true))));
     * 
     * $route->setDefaults(array( "param1" => "abcabc",
     *                     "param2" => 13));
     * 
     * </code></pre>
     * 
     * @throws Exception
     *
     * @return Route
     */
    public function  __construct($key, $pattern, $packComponent = "")
    {
        $this->_key = strval($key);
        
        $routeParts = array();
        
        $pattern = self::transliterate($pattern);

        if (!is_string($pattern) 
                || !is_string($packComponent) 
                || (((false == preg_match_all("/{([a-z0-9]+)}|([a-z0-9]+)/i", $pattern, $routeParts))) && ("" !== $pattern)))
        {
            throw new Exception("Wrong variables passed");
        }

        /**
         * 
         * for root_part_1/root_part_2/root_part_3/param_1/param_2
         * 
         * $routeParts should be:
         *  
         * array(3) {
            [0]=>
            array(5) {
              [0]=>
              string(5) "root_part_1"
              [1]=>
              string(5) "root_part_2"
              [2]=>
              string(5) "root_part_3"
              [3]=>
              string(6) "{param_1}"
              [4]=>
              string(6) "{param_2}"
            }
            [1]=>
            array(5) {
              [0]=>
              string(0) ""
              [1]=>
              string(0) ""
              [2]=>
              string(0) ""
              [3]=>
              string(4) "param_1"
              [4]=>
              string(4) "param_2"
            }
            [2]=>
            array(5) {
              [0]=>
              string(5) "root_part_1"
              [1]=>
              string(5) "root_part_2"
              [2]=>
              string(5) "root_part_3"
              [3]=>
              string(0) ""
              [4]=>
              string(0) ""
            }
          }
         */
        if (isset($routeParts[0]))
            $this->_fullPattern = implode("/", array_filter($routeParts[0])) . "/";
        else
            $this->_fullPattern = "/";
        
        if (isset($routeParts[2]))
            $this->_clearPattern = implode("/", array_filter($routeParts[2])) . "/";
        else
            $this->_clearPattern  = "/";

        if (strstr($packComponent, Cfg_App::PACK_COMPONENT_SEPARATOR))
        {
            $pageParts = explode(Cfg_App::PACK_COMPONENT_SEPARATOR, $packComponent);
            $this->_packName = $pageParts[0];
            $this->_componentName = $pageParts[1];
        }
        else
        {
            $this->_packName = App::getCurrentPackName();
            $this->_componentName = $packComponent;
        }

        $parameters = array();

        if (preg_match_all("/{([a-z0-9]+)}/i", $pattern, $parameters))
        {
            $this->_parameters = array_values($parameters[1]);
            
//            foreach($this->_parameters as $param)
//            {
//                $this->_defaults[$param] = "";
//            }
        }

        return $this;
    }
    
    /**
     * 
     * Returns route as array of it's parts without parameters
     * 
     * @return array
     */
    public function getRouteArray()
    {
        if (!$this->_clearPatternArray)
        {
            $this->_clearPatternArray = self::getUrlArray($this->_clearPattern);
        }
   
        return $this->_clearPatternArray;
    }
    
    /**
     * 
     * Returns route array depth
     * 
     * @return int
     */
    public function getRouteArrayDepth()
    {
        if (!$this->_clearPatternArray)
        {
            $this->getRouteArray();
        }
        
        return count($this->_clearPatternArray);
    }
    
    /**
     * 
     * Returns route key
     * 
     * @return string
     */
    public function getKey()
    {
        return $this->_key;
    }
    
    /**
     * 
     * Returns route pattern without parameters
     * 
     * @return string
     */
    public function getClearPattern()
    {
        return $this->_clearPattern;
    }
    
    /**
     * 
     * Returns http method, that should be used for route
     * 
     * @return string GET | POST
     */
    public function getHttpMethod()
    {
        return $this->_httpMethod ? $this->_httpMethod : "GET";
    }
    
    /**
     * 
     * Sets http method to access this route
     * 
     */
    public function setHttpMethod($method)
    {
        if (in_array($method, Cfg_App::$HTTP_METHODS))
        {
            $this->_httpMethod = $method;
        }
        else
        {
            trigger_error("\{$method}\ is not within supported http methods", E_USER_NOTICE);
        }
    }
    
    /**
     * 
     * Sets the ajaxRoute flag, if $isAjax parameter presents,
     * gets the ajaxRoute flag otherwise
     * 
     * @param boolean $isAjax
     * @return boolean
     */
    public function isAjax($isAjax = null)
    {
        if (is_null($isAjax))
        {
            return $this->_ajaxRoute;
        }
        else
        {
            $this->_ajaxRoute = (bool)$isAjax;
        }
    }
    
    /**
     * Sets the secured flag, if $isSecured parameter presents,
     * gets the secured flag otherwise
     * 
     * @param boolean $isSecured
     * @return boolean
     */
    public function isSecured($isSecured = null)
    {
        if (is_null($isSecured))
        {
            return $this->_secured;
        }
        else
        {
            $this->_secured = (bool)$isSecured;
        }
    }
    
    /**
     * 
     * Returns count of parameters for route
     * 
     * @return int
     */
    public function getParametersCount()
    {
        return count($this->_parameters);
    }
    
    /**
     * 
     * Returns controller class name
     * 
     * @return string
     */
    public function getControllerName()
    {
        if (!$this->_controllerName){
            $this->setControllerName(Cfg_App::getPackOption(Cfg_App::KEY_DEFAULT_CONTROLLER_NAME, $this->getPackName()));
        }

        return $this->_controllerName;
    }
    
    /**
     * 
     * @param type $controllerName
     * @return \Route
     */
    public function setControllerName($controllerName)
    {
        if (!preg_match('/controller$/i', $controllerName))
        {
            $controllerName .= 'Controller';
        }
        
        $this->_controllerName = $controllerName;
        
        return $this;
    }
    
    /**
     * 
     * Returns component name
     * 
     * @return string
     */
    public function getComponentName()
    {
        return $this->_componentName;
    }
    
    /**
     * 
     * Sets route's component name
     * 
     * @param type $componentName
     * @return \Route
     */
    public function setComponentName($componentName)
    {
        $this->_componentName = $componentName;
        
        return $this;
    }
    
    /**
     * 
     * Returns pack name for this route
     * 
     * @return string
     */
    public function getPackName()
    {
        return $this->_packName;
    }

    /**
     *
     * Sets the validators for parameter patterns
     *
     * @param array $validators
     *
     * @example 
     * 
     * <pre><code>
     * 
     * $route->setValidation(array( 
     *                   "param1" => 
     *                      array(Validator::IS_PATTERN_STRING =>
     *                              array('pattern' => "[abc]+")),
     *                   "param2" =>
     *                      array(Validator::IS_NUMERIC =>
     *                              array(true)))
     *                   );
     * 
     * </code></pre>
     * 
     * @throws Exception
     *
     * @return Route
     */
    public function setValidation(array $validators = array())
    {
        foreach($validators as $var => $validatorPattern)
        {
            if (in_array($var, $this->_parameters))
            {
                $this->_validator[$var] = $validatorPattern;
            }
        }

        return $this->_checkConsistency();
    }
    
    /**
     * 
     * Return true, if validation enabled
     * 
     * @return bool
     */
    public function validationEnabled()
    {
        return (bool)$this->_filter;
    }
    
    /**
     * 
     * Returns count of parameters that passed through validation
     * 
     * @return int
     */
    public function getParametersMatchedCount()
    {
        return count($this->_parametersMatchedValidator);
    }
    
    /**
     * 
     * Returns parameter value associated with passed $key. If wrong parameter passed
     * default value will be returned. If parameter not passed or not filled by defaults null value will be returned then
     * 
     * @param type $key
     * 
     * @return mixed|null
     */
    public function getParameter($key)
    {
        if (in_array($key, $this->_parameters)){
            if (isset($this->_parametersMatchedValidator[$key])){
                return $this->_parametersMatchedValidator[$key];
            } elseif (isset($this->_defaults[$key])) {
                return $this->_defaults[$key];
            } else {
                return null;
            }
        } else {
            return null;
        }
    }
    
    public function getParameters()
    {
        
    }
    
    /**
     * 
     * Returns count of parameters that are not covered by default values
     * 
     * @return int count of parameters without defaults
     */
    public function getDefaultsCoverage()
    {
       return count(array_diff($this->_parameters, array_keys($this->_defaults))); 
    }
    
    /**
     * 
     * Returns count of parameters that have validators
     * 
     * @return int count of parameters under validation  
     */
    public function getValidationCoverage()
    {
        return count($this->_validator);
    }

    /**
     * 
     * Sets the default values for page parameters
     *
     * @param array $defaults
     *
     * @throws Exception
     * 
     * @return Route
     */
    public function setDefaults(array $defaults = array())
    {
        foreach($defaults as $var => $defaultValue)
        {
            if (in_array($var, $this->_parameters))
            {
                $this->_defaults[$var] = $defaultValue;
            }
        }

        return $this->_checkConsistency();
    }
    
    /**
     * 
     * Sets route controller action
     * 
     * @param string $action
     * @return Route
     */
    public function setActionName($action)
    {
       $this->_action = $action;
       
       return $this; 
    }
    
    /**
     * 
     * Returns action name to be called
     * 
     * @return string Action name
     */
    public function getActionName()
    {
        if ($this->_action && is_string($this->_action))
        {
            return $this->_action;
        }
        else
        {
            return Cfg_App::getPackOption(Cfg_App::KEY_DEFAULT_ACTION_NAME, $this->getPackName());
        }
    }
    
    /**
     * 
     * Returns calculated difficulty of ValidatorS
     * 
     * @return int calculated difficulty of all Validators for this route
     */
    public function getValidationDifficulty()
    {
        return Validator::getValidationDifficulty($this->_validator);
    }

    /**
     *
     * @return Route 
     */
    private function _checkConsistency()
    {
        if ($this->_parameters && $this->_validator && $this->_defaults)
        {
            foreach($this->_parameters as $parameter)
            {
                if (isset($this->_defaults[$parameter]) && $this->_defaults[$parameter] &&
                    isset($this->_validator[$parameter]))
                {
                    if (!Validator::passMultiValidatorValue($this->_defaults[$parameter],
                                    $this->_validator[$parameter]))
                    {
                        throw new Exception("Wrong default parameters passed");
                    }
                }
            }
        }

        return $this;
    }
    
    /**
     * 
     * Validates parameters passed to the route
     * 
     * @param array $urlArray
     * 
     * @return array    [0] => count of parameters passed to script, 
     *                  [1] => count of parameters that passed the validator, 
     *                  [2] => count of parameters that were not filled from defaults array
     */
    public function validateParameters($urlArray)
    {
        $freeParameters = array_values(array_diff($urlArray, $this->getRouteArray()));
        //echo "<br /> free params " .var_dump($urlArray).var_dump($this->getRouteArray()). var_dump($freeParameters) . "<br />";
        $notFilledByDefaultsCount = 0;
        $this->_parametersMatchedValidator = array();

        //parameters passed to script
        $count = $this->getParametersCount() > count($freeParameters) ? count($freeParameters) : $this->getParametersCount();
        $result = true;

        for($i = 0; $i < $count; $i++)
        {
            if (isset($this->_validator[$this->_parameters[$i]]))
            {
                $result &= Validator::passMultiValidatorValue($freeParameters[$i],
                                    $this->_validator[$this->_parameters[$i]]);
            }

            if ($result)
            {
                $this->_parametersMatchedValidator[$this->_parameters[$i]] = $freeParameters[$i];
            }
            else
            {
                break;
            }
        }

        if ($result && ($count < $this->getParametersCount()))
        {
            $notPassedParameters = array_diff($this->_parameters, array_keys($this->_parametersMatchedValidator));
            $notFilledByDefaultsCount = count(array_diff($notPassedParameters, array_keys($this->_defaults)));
        }
//var_dump($freeParameters,count($freeParameters),count($this->_parametersMatchedFilter), $notFilledByDefaultsCount);
        return array(count($freeParameters), count($this->_parametersMatchedValidator), $notFilledByDefaultsCount);
    }
    
    /**
     * 
     * "Compares" routes; longer routes
     * are more preferable, but route with less parameters 
     * is more likely to be used,
     * so it should be closer to the top; 
     * 
     * @param Route $a 
     * @param Route $b
     * @return int
     */
    public static function compare(Route $a, Route $b)
    {
        if ($a->getClearPattern() == $b->getClearPattern())
        {
            return ($a->getParametersCount() < $b->getParametersCount()) ? -1 : 1;
        }
        else
        {
            return ($a->getClearPattern() > $b->getClearPattern()) ? -1 : 1;
        }
    }
    
    /**
     * 
     * Returns an array of url parts
     * 
     * @example
     * /path1/path2/path3/ => array('path1', 'path2', 'path3')
     * 
     * @param string $url url string to be converted to array
     * @return array
     * 
     * @throws Exception
     */
    public static function getUrlArray($url)
    {
        if (!is_string($url))
        {
            throw new Exception("Url must be a string");
        }
        
        $url = self::transliterate($url);
        
        $urlParts = array_map('trim', array_filter(explode("/", $url)));

        array_unshift($urlParts, "/");

        return $urlParts;
    }
    
    /**
     * 
     * One-way transliteration function for cyrrilic support
     * 
     * @param string $text Cyrillic text
     * @return string Transliterated text
     */
    public static function transliterate($text) {
        
        $cyrrilic = array(
            'а', 'б', 'в', 'г', 'д', 'e', 'ё', 'ж', 'з', 'и', 'й', 'к', 'л', 'м', 'н', 'о', 'п', 'р', 'с', 'т', 'у', 'ф', 'х', 'ц', 'ч', 'ш', 'щ', 'ъ', 'ы', 'ь', 'э', 'ю', 'я',
        );
        $latin = array(
            'a', 'b', 'v', 'g', 'd', 'e', 'yo', 'zh', 'z', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'r', 's', 't', 'u', 'f', 'h', 'c', 'ch', 'sh', 'sht', '', 'y', '', 'e', 'yu', 'ya',
        );
       
        return str_ireplace($cyrrilic, $latin, $text);
    }
}
?>
Back to Top