public static function handleRewritesRequest(Endpoint $Endpoint)
 {
     switch ($_SERVER['REQUEST_METHOD']) {
         case 'GET':
             return static::respond('endpointRewrites', ['data' => $Endpoint->Rewrites]);
         case 'POST':
             if (!is_array($_POST['rewrites'])) {
                 return static::throwInvalidRequestError('POST method expects "rewrites" array');
             }
             $saved = [];
             $deleted = [];
             $invalid = [];
             foreach ($_POST['rewrites'] as $key => $data) {
                 $nonEmptyData = array_filter($data);
                 if ($key == 'new') {
                     if (!count($nonEmptyData)) {
                         continue;
                     }
                     $Rewrite = EndpointRewrite::create(['Endpoint' => $Endpoint]);
                 } else {
                     $Rewrite = EndpointRewrite::getByID($key);
                     if ($Rewrite->EndpointID != $Endpoint->ID) {
                         return static::throwInvalidRequestError('Supplied rewrite ID does not belong to this endpoint');
                     }
                     if (!count($nonEmptyData)) {
                         $Rewrite->destroy();
                         $deleted[] = $Rewrite;
                         continue;
                     }
                 }
                 if (empty($data['Priority'])) {
                     $data['Priority'] = EndpointRewrite::getFieldOptions('Priority', 'default');
                 }
                 $Rewrite->setFields($data);
                 if ($Rewrite->isDirty) {
                     if ($Rewrite->validate()) {
                         $Rewrite->save();
                         $saved[] = $Rewrite;
                     } else {
                         $invalid[] = $Rewrite;
                     }
                 }
             }
             return static::respond('endpointRewritesSaved', ['success' => count($saved) > 0, 'saved' => $saved, 'invalid' => $invalid, 'deleted' => $deleted, 'Endpoint' => $Endpoint]);
         default:
             return static::throwInvalidRequestError('Only GET/POST methods are supported');
     }
 }
Esempio n. 2
0
 public function applyRewrites($url)
 {
     $cacheKey = "endpoints/{$this->ID}/rewrites";
     // get ordered list of rewrites
     if (false == ($rewriteIDs = Cache::fetch($cacheKey))) {
         $rewriteIDs = array_map(function ($Rewrite) {
             return $Rewrite->ID;
         }, $this->Rewrites);
         Cache::store($cacheKey, $rewriteIDs);
     }
     // apply each rewrite
     foreach ($rewriteIDs as $rewriteID) {
         $Rewrite = EndpointRewrite::getByID($rewriteID);
         if (preg_match($Rewrite->Pattern, $url)) {
             $url = preg_replace($Rewrite->Pattern, $Rewrite->Replace, $url);
             if ($Rewrite->Last) {
                 break;
             }
         }
     }
     return $url;
 }