public static function preProcess($value, $settings, $model) { if (is_array($value)) { if (!empty($model)) { $model->changed = true; } if (isset($value['href']) && is_numeric($value['href'])) { $url = \CMF\Model\URL::find(intval($value['href'])); if (!empty($url)) { $value = new \CMF\Model\URL(); $value->populate(array('alias' => $url)); } } else { if (isset($value['external']) && intval($value['external'])) { $url = $model->get($settings['mapping']['fieldName']); if (empty($url)) { $url = new \CMF\Model\URL(); } $url->populate(array('url' => @$value['href'], 'slug' => '', 'prefix' => '', 'item_id' => null, 'type' => \CMF\Model\URL::TYPE_EXTERNAL, 'alias' => null)); return $url; } } } return $value; }
/** * Adds a URL that will redirect to another by ID */ public static function addRedirectUrl($url, $parentId, $type = 301, $limit = 2) { if (empty($url)) { return; } if (empty($parentId)) { return; } // Don't bother if the parent doesn't exist $parentCount = intval(\CMF\Model\URL::select("count(item.id)")->where('item.id = :parentid')->setParameter('parentid', intval($parentId))->getQuery()->getSingleScalarResult()); if ($parentCount === 0) { return; } // Standardise the passed URL $url = trim($url, '/'); if (stripos($url, 'http') === 0 && ($urlInfo = parse_url($url))) { $url = trim($url['path'], '/'); } $parts = explode('/', $url); if (empty($parts)) { return; } // Get existing redirects $existing = \CMF\Model\URL::select('item')->where('item.parent_id = :parentid')->setParameter('parentid', intval($parentId))->orderBy('item.updated_at', 'ASC')->getQuery()->getResult(); // Check for redirects with the same URL foreach ($existing as $existingUrl) { if ($existingUrl->url == '/' . $url) { $existingUrl->set('updated_at', new \DateTime()); $existingUrl->set('type', strval($type)); \D::manager()->persist($existingUrl); \D::manager()->flush($existingUrl); return $existingUrl; } } // Create the url unless the limit has been reached if (count($existing) >= $limit) { $redirect = $existing[0]; } else { $redirect = new \CMF\Model\URL(); } // Populate, save and return the new url object $redirect->populate(array('parent_id' => intval($parentId), 'item_id' => null, 'url' => '/' . $url, 'slug' => array_pop($parts), 'prefix' => '/' . implode('/', $parts) . (count($parts) ? '/' : ''), 'type' => strval($type))); \D::manager()->persist($redirect); \D::manager()->flush($redirect); return $redirect; }