Controller::_getPageData()   A
last analyzed

Complexity

Conditions 3
Paths 4

Size

Total Lines 2
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 3
eloc 1
c 1
b 0
f 0
nc 4
nop 1
dl 0
loc 2
rs 10
1
<?php
2
3
namespace Phpsa\Datastore\Http\Controllers\Admin;
4
5
use App\Http\Controllers\Controller as BaseController;
0 ignored issues
show
Bug introduced by
The type App\Http\Controllers\Controller was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
6
use Phpsa\Datastore\Datastore;
7
use Phpsa\Datastore\Asset;
8
use Phpsa\Datastore\Helpers;
9
use Phpsa\Datastore\DatastoreException;
10
use Phpsa\Datastore\Repositories\DatastoreRepository;
11
use Phpsa\Datastore\Models\Datastore as DatastoreModel;
12
use Phpsa\Datastore\Models\DatastorePages;
13
use Phpsa\Datastore\Models\DatastoreDatastore;
14
use App\Exceptions\GeneralException;
0 ignored issues
show
Bug introduced by
The type App\Exceptions\GeneralException was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
15
use Illuminate\Support\Facades\DB;
16
use Illuminate\Support\Str;
17
use Illuminate\Support\Facades\Storage;
18
use Illuminate\Http\Request;
19
use App\Models\Auth\User;
0 ignored issues
show
Bug introduced by
The type App\Models\Auth\User was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
20
21
use Intervention\Image\Facades\Image;
22
23
Class Controller extends BaseController {
24
25
26
	/**
27
	 * @var DatastoreRepository
28
	 */
29
    protected $datastoreRepository;
30
31
    /**
32
     * UserController constructor.
33
     *
34
     * @param DatastoreRepository $datastoreRepository
35
     */
36
    public function __construct(DatastoreRepository $datastoreRepository)
37
    {
38
        $this->datastoreRepository = $datastoreRepository;
39
    }
40
41
42
43
	/**
44
	 * @param Request $request
45
	 *
46
	 * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
47
	 */
48
	public function list($asset,Request $request){
49
50
		$assetData = Helpers::parseAssetType($asset);
0 ignored issues
show
Bug introduced by
Are you sure the assignment to $assetData is correct as Phpsa\Datastore\Helpers::parseAssetType($asset) targeting Phpsa\Datastore\Helpers::parseAssetType() seems to always return null.

This check looks for function or method calls that always return null and whose return value is assigned to a variable.

class A
{
    function getObject()
    {
        return null;
    }

}

$a = new A();
$object = $a->getObject();

The method getObject() can return nothing but null, so it makes no sense to assign that value to a variable.

The reason is most likely that a function or method is imcomplete or has been reduced for debug purposes.

Loading history...
51
52
		return view('phpsa-datastore::backend.ams.list')
53
		->withAsset($assetData)
54
		->withAssetType($asset)
55
		->withContent($this->datastoreRepository->paginateAssets($assetData, 25, 'page' ));
56
57
	}
58
59
	public function inject(Request $request){
60
		$assetData = Helpers::parseAssetType($request->input('asset'), true);
0 ignored issues
show
Bug introduced by
Are you sure the assignment to $assetData is correct as Phpsa\Datastore\Helpers:...->input('asset'), true) targeting Phpsa\Datastore\Helpers::parseAssetType() seems to always return null.

This check looks for function or method calls that always return null and whose return value is assigned to a variable.

class A
{
    function getObject()
    {
        return null;
    }

}

$a = new A();
$object = $a->getObject();

The method getObject() can return nothing but null, so it makes no sense to assign that value to a variable.

The reason is most likely that a function or method is imcomplete or has been reduced for debug purposes.

Loading history...
61
		$newAsset = Datastore::getAsset($assetData);
0 ignored issues
show
Bug introduced by
$assetData of type void is incompatible with the type string expected by parameter $type of Phpsa\Datastore\Datastore::getAsset(). ( Ignorable by Annotation )

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

61
		$newAsset = Datastore::getAsset(/** @scrutinizer ignore-type */ $assetData);
Loading history...
62
		return response($newAsset->injectForm($request->input('idx')));
63
	}
64
65
66
	protected function _getKids($asset){
67
		$children = [];
68
		if ( ! empty($asset->children))
69
		{
70
			$children				 = Helpers::assetInfo($asset->children);
71
			$children['classname']	 = $asset->children;
72
			$children['path']        = Helpers::getPath($asset->children);
0 ignored issues
show
Bug introduced by
Are you sure the assignment to $children['path'] is correct as Phpsa\Datastore\Helpers:...tPath($asset->children) targeting Phpsa\Datastore\Helpers::getPath() seems to always return null.

This check looks for function or method calls that always return null and whose return value is assigned to a variable.

class A
{
    function getObject()
    {
        return null;
    }

}

$a = new A();
$object = $a->getObject();

The method getObject() can return nothing but null, so it makes no sense to assign that value to a variable.

The reason is most likely that a function or method is imcomplete or has been reduced for debug purposes.

Loading history...
73
74
			$kids = $asset->children();
75
76
			if (!$kids)
77
			{
78
				$kids[] = Datastore::getAsset($children['classname']);
79
			}
80
81
			$children['kids'] = $kids;
82
		}
83
		return $children;
84
	}
85
86
	protected function _getParents($asset){
87
88
		$type = str_replace('\\', "\\\\", $asset->type);
89
		$parentAssets = $this->datastoreRepository->where('accept', '%' . $type . '%', 'like')->distinct()->get(['type', 'name', 'accept_limit'])->toArray();
90
91
		if ($parentAssets)
92
		{
93
			// get these parents
94
			foreach ($parentAssets as $k => $parent)
95
			{
96
				$parentAssets[$k]['key'] = Str::slug($parent['type']);
97
				$parents = $this->datastoreRepository->where('type', $parent['type'])->get()->toArray();
98
				if ($parents)
99
				{
100
					foreach ($parents as $key => $p)
101
					{
102
103
						$found = DatastoreDatastore::where('datastore_id', $asset->getId())
104
						->where('datastore2_id', $p['id'])->exists();
105
						if ($found)
106
						{
107
							$parents[$key]['assigned_and_found'] = true;
108
						}
109
					}
110
					$parentAssets[$k]['related'] = $parents;
111
				}
112
				else
113
				{
114
					$parentAssets[$k]['related'] = false;
115
				}
116
			}
117
		}
118
		return $parentAssets;
119
	}
120
121
	protected function _getPageData($asset){
122
		return ($asset->is_child || !$asset->id )? null : DatastorePages::where('asset', $asset->id)->first();
123
	}
124
125
	public function create($assetType, Request $request){
126
127
128
		$assetData = Helpers::parseAssetType($assetType, true);
0 ignored issues
show
Bug introduced by
Are you sure the assignment to $assetData is correct as Phpsa\Datastore\Helpers:...tType($assetType, true) targeting Phpsa\Datastore\Helpers::parseAssetType() seems to always return null.

This check looks for function or method calls that always return null and whose return value is assigned to a variable.

class A
{
    function getObject()
    {
        return null;
    }

}

$a = new A();
$object = $a->getObject();

The method getObject() can return nothing but null, so it makes no sense to assign that value to a variable.

The reason is most likely that a function or method is imcomplete or has been reduced for debug purposes.

Loading history...
129
		$newAsset = Datastore::getAsset($assetData);
0 ignored issues
show
Bug introduced by
$assetData of type void is incompatible with the type string expected by parameter $type of Phpsa\Datastore\Datastore::getAsset(). ( Ignorable by Annotation )

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

129
		$newAsset = Datastore::getAsset(/** @scrutinizer ignore-type */ $assetData);
Loading history...
130
131
		if($newAsset->max_instances > 0){
132
			$count = DatastoreModel::where('type', $assetData)->count();
133
			if($count >= $newAsset->max_instances){
134
				return redirect()->route('admin.ams.content.list', $assetType)->withFlashDanger("You can only create " . $newAsset->max_instances . " instances of this Asset");
135
			}
136
		}
137
138
139
		$children = $this->_getKids($newAsset);
140
		$parentAssets = $this->_getParents($newAsset);
141
		$pageData = $this->_getPageData($newAsset);
142
143
		return view('phpsa-datastore::backend.ams.create')
144
		->withAsset($newAsset)
145
		->withParents($parentAssets)
146
		->withChildren($children)
147
		->withPageData($pageData);
148
	}
149
150
	public function edit($assetType, $id){
151
152
		$asset = Datastore::getAssetById($id);
153
154
155
		$children = $this->_getKids($asset);
156
		$parentAssets = $this->_getParents($asset);
157
		$pageData = $this->_getPageData($asset);
158
159
		return view('phpsa-datastore::backend.ams.create')
160
		->withAsset($asset)
161
		->withParents($parentAssets)
162
		->withChildren($children)
163
		->withPageData($pageData);
164
	}
165
166
	public function save($assetType , Request $request){
167
168
169
		$assetData = Helpers::parseAssetType($assetType, true);
0 ignored issues
show
Bug introduced by
Are you sure the assignment to $assetData is correct as Phpsa\Datastore\Helpers:...tType($assetType, true) targeting Phpsa\Datastore\Helpers::parseAssetType() seems to always return null.

This check looks for function or method calls that always return null and whose return value is assigned to a variable.

class A
{
    function getObject()
    {
        return null;
    }

}

$a = new A();
$object = $a->getObject();

The method getObject() can return nothing but null, so it makes no sense to assign that value to a variable.

The reason is most likely that a function or method is imcomplete or has been reduced for debug purposes.

Loading history...
170
		$newAsset = Datastore::getAsset($assetData, $request->input('id'));
0 ignored issues
show
Bug introduced by
$assetData of type void is incompatible with the type string expected by parameter $type of Phpsa\Datastore\Datastore::getAsset(). ( Ignorable by Annotation )

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

170
		$newAsset = Datastore::getAsset(/** @scrutinizer ignore-type */ $assetData, $request->input('id'));
Loading history...
171
172
		$form = $request->all();
173
174
		$to_delete = (isset($form['assetRemove'])) ? $form['assetRemove'] : false;
175
		unset($form['assetRemove']);
176
177
178
		$form_valid	 = $newAsset->validate($form);
179
		if(!$form_valid){
0 ignored issues
show
introduced by
The condition $form_valid is always true.
Loading history...
180
			die("@TODO STILL");
0 ignored issues
show
Best Practice introduced by
Using exit here is not recommended.

In general, usage of exit should be done with care and only when running in a scripting context like a CLI script.

Loading history...
181
		}
182
183
		$newAsset->populateAsset($form);
184
185
		if ($to_delete)
186
		{
187
			foreach ($to_delete as $kill_asset => $del)
188
			{
189
				foreach ($del as $uniq => $a)
190
				{
191
					if ($a['id'])
192
					{
193
						$nnasset = Datastore::getAssetById($id);
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $id seems to be never defined.
Loading history...
194
						if ($nnasset->ownDatastore())
195
						{
196
							foreach ($nnasset->ownDatastore() as $e)
197
							{
198
								Datastore::getAssetById($e->id);
199
							}
200
						}
201
						$nnasset->delete();
0 ignored issues
show
Bug introduced by
The method delete() does not exist on Phpsa\Datastore\Datastore. ( Ignorable by Annotation )

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

201
						$nnasset->/** @scrutinizer ignore-call */ 
202
                delete();

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
202
					}
203
					unset($form['assetInjectionform'][$kill_asset][$uniq]);
204
				}
205
			}
206
		}
207
		$kill_list = array();
208
		// check what we are to remove
209
		if (!empty($form['related_id']))
210
		{
211
			foreach ($form['related_id'] as $remove)
212
			{
213
				if (!in_array($remove, $form['related_assets']))
214
				{
215
					$kill_list[] = $remove;
216
				}
217
			}
218
		}
219
220
221
222
		$id = $newAsset->store();
223
224
225
		// check for multiforms
226
		if (isset($form['assetInjectionform']))
227
		{
228
			//dd($form['assetInjectionform']);exit;
229
			foreach ($form['assetInjectionform'] as $masset => $mdata)
230
			{
231
				foreach ($mdata as $childform)
232
				{
233
					$childformId = !empty($childform['id']) ? $childform['id'] : null;
234
					$childasset = Datastore::getAsset($masset, $childformId);
235
					$childasset->populateAsset($childform);
236
					$nid = $childasset->store($id);
0 ignored issues
show
Unused Code introduced by
The assignment to $nid is dead and can be removed.
Loading history...
237
238
					$newAsset->ownDatastore[] = $childasset;
239
240
					//$this->db->query('update datastore set datastore_id = ? where id = ?', array($id, $nid));
241
					// now we fikken cheat coz this isn't working the way it should
242
					// now add them as children to the asset
243
					//zp('debug')->pre($childasset);
244
				}
245
			}
246
		}
247
248
		if (!empty($form['related_assets']))
249
		{
250
			foreach ($form['related_assets'] as $asset)
251
			{
252
				DatastoreDatastore::firstOrCreate(['datastore_id' => $id, 'datastore2_id' => $asset]);
253
				// $found = $this->db->query('select id from datastore_datastore where datastore_id = ? and datastore2_id = ?', array($id, $asset))->row();
254
255
				// // not found, we need to add it
256
				// if (!$found)
257
				// {
258
				// 	$this->db->query('insert into datastore_datastore (datastore_id, datastore2_id) values (?, ?)', array($id, $asset));
259
				// }
260
			}
261
		}
262
263
		if ($kill_list)
264
		{
265
			foreach ($kill_list as $r)
266
			{
267
				$deletedRows = DatastoreDatastore::where('datastore_id', $id)->where('datastore2_id', $r)->delete();
0 ignored issues
show
Unused Code introduced by
The assignment to $deletedRows is dead and can be removed.
Loading history...
268
				// $found = $this->db->query('select id from datastore_datastore where datastore_id = ? and datastore2_id = ?', array($id, $r))->row();
269
270
				// //if found, remove it
271
				// if ($found)
272
				// {
273
				// 	$this->db->query('delete from datastore_datastore where id =?', array($found));
274
				// }
275
			}
276
		}
277
278
		if(!empty($form['page_title']) && !empty($form['page_slug'])){
279
			$pageData = DatastorePages::firstOrNew(['asset' => $id]);
280
			$pageData->title = $form['page_title'];
281
			$pageData->slug = $form['page_slug'];
282
			$pageData->asset = $id;
283
			$pageData->save();
284
		}
285
286
		return redirect()->route('admin.ams.content.list', $assetType)->withFlashSuccess(__('phpsa-datastore::backend.labels.content.created'));
287
288
289
	}
290
291
292
	public function destroy($id, Request $request){
293
		$asset = DatastoreModel::findOrFail($id);
294
		if(!$asset || $asset->namespace !== 'asset'){
0 ignored issues
show
introduced by
$asset is of type Phpsa\Datastore\Models\Datastore, thus it always evaluated to true.
Loading history...
295
			throw new GeneralException("NOT FOUND");
296
		}
297
		$path = $asset->content_path;
0 ignored issues
show
Unused Code introduced by
The assignment to $path is dead and can be removed.
Loading history...
298
		$asset->delete();
299
300
		return redirect()->route('admin.ams.content.list', $asset->content_path)->withFlashSuccess(__('phpsa-datastore::backend.labels.content.deleted'));
301
302
303
	}
304
305
	public function slug(Request $request)
306
	{
307
		DB::enableQueryLog();
308
309
		$slug	 = $request->input('page_slug');
310
		$id		 = (int)$request->input('id');
311
		$generate = $request->input('generate');
312
313
314
		if($generate){
315
			$slug = Str::slug($slug);
316
		}
317
318
		$exists = DatastorePages::where('slug', $slug)->where('asset', '!=', $id)->exists();
319
320
		if($generate){
321
			return response()->json([
322
				'slug' => $slug,
323
				'available' => $exists ? 0 : 1
324
			]);
325
		}
326
		return response()->json($exists ? "Slug already in use": true);
327
328
329
	}
330
331
	public function file(Request $request) {
332
		$this->validate($request, [
333
            'file' => 'required'
334
		 ]);
335
336
		 $originalFile= $request->file('file');
337
338
		 $t = time();
339
		 $filename = Str::slug($t.$originalFile->getClientOriginalName(),".");
340
341
		 $path = $request->file('file')->storeAs(
0 ignored issues
show
Unused Code introduced by
The assignment to $path is dead and can be removed.
Loading history...
342
			'public', $filename
343
		);
344
345
		return response()->json(["file" => $filename]);
346
	}
347
348
	public function image(Request $request) {
349
		$this->validate($request, [
350
            'file' => 'image|required|mimes:jpeg,png,jpg,gif,svg'
351
		 ]);
352
353
		 $originalImage= $request->file('file');
354
355
		 $t = time();
356
		 $filename = Str::slug($t.$originalImage->getClientOriginalName(),".");
357
358
359
		if(!is_dir(public_path().'/vendor/phpsa-datastore/thumbs')){
360
			mkdir(public_path().'/vendor/phpsa-datastore/thumbs', 0755, true);
361
		}
362
363
364
		 $thumbnailImage = Image::make($originalImage);
365
		 $thumbnailPath = public_path().'/vendor/phpsa-datastore/img/';
366
		 $originalPath = public_path().'/vendor/phpsa-datastore/thumbs/';
367
		 $thumbnailImage->save($originalPath.$filename);
368
369
		 $thumbnailImage->resize(150,150, function ($constraint) {
370
			$constraint->aspectRatio();
371
		});
372
		 $thumbnailImage->save($thumbnailPath.$filename);
373
374
375
		return response()->json(["file" => $filename]);
376
	}
377
378
379
380
	public function indentityAutocomplete(Request $request){
381
		$search = urldecode($request->input('q'));
382
		$results = [];
383
		if( strlen($search) >= 3 )
384
		{
385
			$userModel = config('auth.providers.users.model');
386
			$records = $userModel::whereRaw("concat_ws(' ', first_name, last_name) like ? ", ["{$search}%"])->limit(10)->get(['id','first_name','last_name']);
387
			foreach($records as $record)
388
			{
389
				$result = [
390
					'value' => $record->id,
391
					'label' => $record->first_name . ' ' . $record->last_name
392
				];
393
				$results[] = $result;
394
			}
395
		}
396
		return response()->json($results);
397
	}
398
399
400
401
	//Testing CallbacksAuth::attempt([
402
		public function getTypeData(Request $request) {
403
			$term = $request->input('term');
404
			$q = $request->input('q');
405
406
        if ($term) {
407
            $vars = array();
0 ignored issues
show
Unused Code introduced by
The assignment to $vars is dead and can be removed.
Loading history...
408
            $type = null;
409
410
            //determine what to look for
411
            switch ($q) {
412
                case "checkbox":
413
                    $type = \Phpsa\CamsGallery\Ams\Gallery\ImageAsset::class;
0 ignored issues
show
Bug introduced by
The type Phpsa\CamsGallery\Ams\Gallery\ImageAsset was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
414
                    break;
415
416
                case "radio":
417
                    $type = Phpsa\Datastore\Ams\BooleanAsset::class;
0 ignored issues
show
Bug introduced by
The type Phpsa\Datastore\Http\Con...astore\Ams\BooleanAsset was not found. Did you mean Phpsa\Datastore\Ams\BooleanAsset? If so, make sure to prefix the type with \.
Loading history...
418
                    break;
419
420
                case "textfield":
421
                    $type = Phpsa\Datastore\Ams\BooleanAsset::class;
422
                    break;
423
424
                case "textarea":
425
                    $type = Phpsa\Datastore\Ams\BooleanAsset::class;
426
                    break;
427
428
                case "fieldset":
429
                    $type = Phpsa\Datastore\Ams\BooleanAsset::class;
430
                    break;
431
432
                default:
433
                    return false;
434
            }
435
436
437
			$query = DatastoreModel::where('value','like','%' . $term . '%')
438
			->where('type', $type);
439
			if($q == 'fieldset'){
440
				$query->order_by('value');
441
			}
442
			$data = $query->get(['value as label', 'id as value']);
443
			return response()->json($data );
444
/*
445
			//db query
446
			if ($q == 'fieldset') {
447
				$sql = "select value as label, id as value from datastore where value like :a AND type = :t group by value";
448
			} else {
449
				$sql = "select value as label, id as value from datastore where value like :a AND type = :t";
450
			}
451
            $vars[':a'] = '%' . $term . '%';
452
            $vars[':t'] = $type;
453
454
            $data = db::getAll($sql, $vars);
455
            echo json_encode($data);
456
            exit;*/
457
        }
458
        return response()->json( []);
459
    }
460
461
}
462