| 1 |
<?php |
| 2 |
|
| 3 |
namespace FluentCart\App\Services\ShortCodeParser; |
| 4 |
|
| 5 |
use FluentCart\Framework\Support\Arr; |
| 6 |
use FluentCart\Framework\Support\Str; |
| 7 |
|
| 8 |
trait ValueTransformer |
| 9 |
{ |
| 10 |
public array $callableFunctions = [ |
| 11 |
'trim', |
| 12 |
'ucfirst', |
| 13 |
'strtolower', |
| 14 |
'strtoupper', |
| 15 |
'ucwords' |
| 16 |
]; |
| 17 |
|
| 18 |
public function transform($value, $code, $data) |
| 19 |
{ |
| 20 |
|
| 21 |
$conditions = $this->evaluateCondition($code); |
| 22 |
|
| 23 |
$transformer = Arr::get($conditions, 'transformer'); |
| 24 |
$defaultValue = Arr::get($conditions, 'default_value'); |
| 25 |
|
| 26 |
if (empty($value) && empty($defaultValue)) { |
| 27 |
$value = apply_filters($this->hookPrefix . 'smartcode_fallback', $value, $code, $data, $conditions); |
| 28 |
} |
| 29 |
|
| 30 |
if (empty($value) && !empty($defaultValue)) { |
| 31 |
$value = $defaultValue; |
| 32 |
} |
| 33 |
|
| 34 |
if (empty($transformer)) { |
| 35 |
return $value; |
| 36 |
} |
| 37 |
|
| 38 |
if (in_array($transformer, $this->callableFunctions)) { |
| 39 |
return call_user_func($transformer, $value); |
| 40 |
} |
| 41 |
|
| 42 |
switch ($transformer) { |
| 43 |
case 'concat_first': // usage: {{contact.first_name||concat_first|Hi |
| 44 |
if ($defaultValue && !empty($value)) { |
| 45 |
$value = trim($defaultValue . $value); |
| 46 |
} |
| 47 |
return $value; |
| 48 |
case 'concat_last': // usage: {{contact.first_name||concat_last|, => FIRST_NAME, |
| 49 |
if ($defaultValue && !empty($value)) { |
| 50 |
|
| 51 |
$value = trim($value . $defaultValue); |
| 52 |
} |
| 53 |
return $value; |
| 54 |
|
| 55 |
case 'title_case': |
| 56 |
if (empty($value)) { |
| 57 |
return $value; |
| 58 |
} |
| 59 |
return Str::title($value); |
| 60 |
|
| 61 |
case 'headline': |
| 62 |
if (empty($value)) { |
| 63 |
return $value; |
| 64 |
} |
| 65 |
return Str::headline($value); |
| 66 |
case 'show_if': // usage {{contact.first_name||show_if|First name exist |
| 67 |
if (!empty($value)) { |
| 68 |
$value = $defaultValue; |
| 69 |
} else { |
| 70 |
$value = ''; |
| 71 |
} |
| 72 |
return $value; |
| 73 |
default: |
| 74 |
return $value; |
| 75 |
} |
| 76 |
} |
| 77 |
|
| 78 |
|
| 79 |
public function evaluateCondition($smartCode): array |
| 80 |
{ |
| 81 |
$conditions = []; |
| 82 |
$parsedCode = explode('|', $smartCode); |
| 83 |
$codeCound = count($parsedCode); |
| 84 |
if ($codeCound >= 3) { |
| 85 |
$conditions = [ |
| 86 |
'transformer' => trim(Arr::get($parsedCode, '2') ?? ''), |
| 87 |
'default_value' => trim(Arr::get($parsedCode, '3') ?? ''), |
| 88 |
]; |
| 89 |
} else if ($codeCound === 2) { |
| 90 |
$conditions = [ |
| 91 |
'transformer' => null, |
| 92 |
'default_value' => trim(Arr::get($parsedCode, '1') ?? ''), |
| 93 |
]; |
| 94 |
} |
| 95 |
$conditions['accessor'] = trim(Arr::get($parsedCode, '0') ?? ''); |
| 96 |
|
| 97 |
return $conditions; |
| 98 |
} |
| 99 |
} |
| 100 |
|