|
1
|
|
|
<?php |
|
2
|
|
|
declare(strict_types=1); |
|
3
|
|
|
|
|
4
|
|
|
namespace Thinktomorrow\Chief\Templates; |
|
5
|
|
|
|
|
6
|
|
|
use Illuminate\Database\Eloquent\Model; |
|
7
|
|
|
use Illuminate\Database\Eloquent\Relations\Relation; |
|
8
|
|
|
use Webmozart\Assert\Assert; |
|
9
|
|
|
|
|
10
|
|
|
class ApplyTemplate |
|
11
|
|
|
{ |
|
12
|
|
|
/** @var array */ |
|
13
|
|
|
private $applicators; |
|
14
|
|
|
|
|
15
|
|
|
public function __construct(array $applicators) |
|
16
|
|
|
{ |
|
17
|
|
|
Assert::allIsInstanceOf($applicators, TemplateApplicator::class); |
|
18
|
|
|
|
|
19
|
|
|
$this->applicators = $applicators; |
|
20
|
|
|
} |
|
21
|
|
|
|
|
22
|
|
|
public function handle(string $sourceClassName, string $sourceId, string $targetClassName, string $targetId): void |
|
23
|
|
|
{ |
|
24
|
|
|
$sourceModel = $this->findModel($sourceClassName, $sourceId); |
|
25
|
|
|
$targetModel = $this->findModel($targetClassName, $targetId); |
|
26
|
|
|
|
|
27
|
|
|
/** @var TemplateApplicator $applicator */ |
|
28
|
|
|
foreach($this->applicators as $applicator) { |
|
29
|
|
|
if(!$applicator->shouldApply($sourceModel, $targetModel)) { |
|
30
|
|
|
continue; |
|
31
|
|
|
} |
|
32
|
|
|
|
|
33
|
|
|
$applicator->handle($sourceModel, $targetModel); |
|
34
|
|
|
|
|
35
|
|
|
return; |
|
36
|
|
|
} |
|
37
|
|
|
|
|
38
|
|
|
$availableApplicatorsString = implode(array_map(function($applicator){ return get_class($applicator);}, $this->applicators), ','); |
|
|
|
|
|
|
39
|
|
|
|
|
40
|
|
|
throw new \RuntimeException("No proper template applicator found. $sourceClassName [$sourceId] cannot be applied as template. Available applicators: [$availableApplicatorsString]"); |
|
41
|
|
|
} |
|
42
|
|
|
|
|
43
|
|
|
/** |
|
44
|
|
|
* For now we assume that each class references an Eloquent Model. |
|
45
|
|
|
* |
|
46
|
|
|
* @param string $className |
|
47
|
|
|
* @param string $sourceId |
|
48
|
|
|
*/ |
|
49
|
|
|
private function findModel(string $className, string $sourceId): Model |
|
50
|
|
|
{ |
|
51
|
|
|
if($morphedClassName = Relation::getMorphedModel($className)) { |
|
52
|
|
|
$className = $morphedClassName; |
|
53
|
|
|
} |
|
54
|
|
|
|
|
55
|
|
|
return (new $className)->findOrFail($sourceId); |
|
56
|
|
|
} |
|
57
|
|
|
} |
|
58
|
|
|
|
This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.
If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress. Please note the @ignore annotation hint above.