Test Failed
Push — develop ( ff58ad...b8f9b2 )
by steve
13:44 queued 12s
created

CmsUrl::findByUrl()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 6
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 5
CRAP Score 1

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 1
eloc 4
nc 1
nop 1
dl 0
loc 6
ccs 5
cts 5
cp 1
crap 1
rs 10
c 1
b 0
f 0
1
<?php
2
/**
3
 * @link http://www.newicon.net/neon
4
 * @copyright Copyright (c) 2008 Newicon Ltd
5
 * @license http://www.newicon.net/neon/license/
6
 */
7
8
9
10
namespace neon\cms\models;
11
12
use neon\core\db\ActiveRecord;
13
use yii\caching\CacheInterface;
14
15
/**
16
 * CmsPage model
17
 *
18
 * The idea is that each url has a dedicated page.  A page then has content attached to it.
19
 * For example a page might show a an ecommerce product, a blog post and an author, each of these
20
 * items needs to be attached to the page.
21
 *
22
 * You could imagine a product manager for example would have to add a product and under the hood
23
 * configure a page record that shows the product.  This allows you to set custom page type things
24
 * and I think gives maximum flexibility, for example different templates for each page if you really
25
 * want.   However another approach could be to make a generic routes lookup table that defers everything
26
 * to the routing.
27
 *
28
 * @property string $nice_id - the nice_id of the page this url points to
29
 * @property string $url - the relative url on the site
30
 * @property string $redirect - a url to redirect to
31
 * @property int $hits - a number representing the number of times this url has been followed
32
 */
33
class CmsUrl extends ActiveRecord
34
{
35
	/**
36
	 * @inheritdoc
37
	 */
38 28
	public static function tableName()
39
	{
40 28
		return '{{%cms_url}}';
41
	}
42
43
	/**
44
	 * @inheritdoc
45
	 */
46 28
	public function rules()
47
	{
48
		return [
49 28
			['url', 'required'],
50
			['url', 'unique'],
51
			[['nice_id', 'url', 'redirect'], 'safe'],
52
			[['nice_id', 'url', 'redirect'], 'check'],
53
		];
54
	}
55
56
	public function check($attribute, $params)
0 ignored issues
show
Unused Code introduced by
The parameter $attribute is not used and could be removed. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-unused  annotation

56
	public function check(/** @scrutinizer ignore-unused */ $attribute, $params)

This check looks for parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
Unused Code introduced by
The parameter $params is not used and could be removed. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-unused  annotation

56
	public function check($attribute, /** @scrutinizer ignore-unused */ $params)

This check looks for parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
57
	{
58
		if (empty($this->redirect) && empty($this->nice_id)) {
59
			$this->addError('url', 'A page id or a redirect must be specified');
60
		}
61
	}
62
63
	/**
64
	 * Update a url
65
	 * Specify whether a 301 redirect should be created for the old url by setting $createRedirect to true
66
	 *
67
	 * @param string $newUrl - the new url value
68
	 * @param boolean $createRedirect - whether to create a redirect
69
	 * @throws \yii\web\HttpException - if $newUrl already exists
70
	 * @return boolean whether new url was saved
71
	 */
72
	public function updateUrl($newUrl, $createRedirect)
73
	{
74
		if ($newUrl !== $this->url) {
75
			$oldUrl = $this->url;
76
			// lets sanity check here - make sure the new url does not already exist:
77
			abort_if(CmsUrl::find()->where(['url' => $newUrl])->exists(), 400, 'The new url must not already exist');
78
			$this->url = $newUrl;
79
			$saved = $this->save();
80
			// do the redirect:
81
			if ($createRedirect) {
82
				static::createRedirect($oldUrl, $newUrl);
83
			}
84
			return $saved;
85
		}
86
		return false;
87
	}
88
89
	/**
90
	 * Create a redirect
91
	 *
92
	 * @param string $fromUrl
93
	 * @param string $toUrl
94
	 * @return CmsUrl - the new CmsUrl record created
95
	 */
96
	public static function createRedirect($fromUrl, $toUrl)
97
	{
98
		$r = new CmsUrl();
99
		$r->url = $fromUrl;
100
		// this must be null to prevent page link lookups (on nice_id) returning redirects
101
		$r->nice_id = null;
102
		$r->redirect = $toUrl;
103
		$r->save();
104
		return $r;
105
	}
106 2
107
	/**
108 2
	 * Returns the url for this niceId or false if not found
109 2
	 *
110
	 * @param string $niceId
111 2
	 * @return bool|string
112
	 */
113
	public static function getUrlByNiceId($niceId)
114
	{
115
		$urls = static::getAllUrlsByNiceId();
116 2
		$url = $urls[$niceId]['url'] ?? false;
117
		// if we can not find the url we try the $niceId as the page $id parameter of the pages table
118
		if ($url === false) {
119
			$pages = static::getPagesIndex();
120
			$pageNiceId = $pages[$niceId] ?? false;
121
			$url = $urls[$pageNiceId]['url'] ?? false;
122
		}
123
		return $url;
124
	}
125
126 2
	public static function findByUrl($url)
127 2
	{
128 2
		return CmsUrl::find()
129 2
			->where(['url'=>$url])
130 2
			->asArray()
131
			->one();
132
	}
133
134
	/**
135
	 * Gets all urls indexed by nice_id
136
	 *
137
	 * @return array
138
	 */
139
	public static function getAllUrlsByNiceId()
140
	{
141
		return static::cache()->getOrSet('cms_url', function() {
142
			return collect(CmsUrl::find()->asArray()->all())
143
				->indexBy('nice_id')
144
				->all();
145 28
		});
146
	}
147 28
148 28
	public static function getPagesIndex()
149 28
	{
150
		return static::cache()->getOrSet('cms_url_pages', function() {
151
			return collect(CmsPage::find()->select('id, nice_id')->asArray()->all())
152
				->flatMap(function($i){ return [$i['id'] => $i['nice_id']]; })
153
				->all();
154
		});
155
	}
156 28
157
	/**
158 28
	 * @inheritDoc
159
	 */
160
	public function afterSave($insert, $changedAttributes)
161
	{
162
		parent::afterSave($insert, $changedAttributes);
163
		static::cache()->delete('cms_url');
164
	}
165
166
	/**
167
	 * Get the cache component to use for url caching
168
	 *
169
	 * @return \yii\caching\CacheInterface
170
	 */
171
	public static function cache()
172
	{
173
		return neon()->isDevMode() ? neon()->cacheArray : neon()->cache;
174
	}
175
}
176