| 1 |
<?php |
| 2 |
|
| 3 |
namespace Amp; |
| 4 |
|
| 5 |
/** |
| 6 |
* A "safe" struct trait for public property aggregators. |
| 7 |
* |
| 8 |
* This trait is intended to make using public properties a little safer by throwing when |
| 9 |
* nonexistent property names are read or written. |
| 10 |
*/ |
| 11 |
trait Struct |
| 12 |
{ |
| 13 |
/** |
| 14 |
* The minimum percentage [0-100] at which to recommend a similar property |
| 15 |
* name when generating error messages. |
| 16 |
*/ |
| 17 |
private $__propertySuggestThreshold = 70; |
| 18 |
|
| 19 |
/** |
| 20 |
* @param string $property |
| 21 |
* |
| 22 |
* @psalm-return no-return |
| 23 |
*/ |
| 24 |
public function __get(string $property) |
| 25 |
{ |
| 26 |
throw new \Error( |
| 27 |
$this->generateStructPropertyError($property) |
| 28 |
); |
| 29 |
} |
| 30 |
|
| 31 |
/** |
| 32 |
* @param string $property |
| 33 |
* @param mixed $value |
| 34 |
* |
| 35 |
* @psalm-return no-return |
| 36 |
*/ |
| 37 |
public function __set(string $property, $value) |
| 38 |
{ |
| 39 |
throw new \Error( |
| 40 |
$this->generateStructPropertyError($property) |
| 41 |
); |
| 42 |
} |
| 43 |
|
| 44 |
private function generateStructPropertyError(string $property): string |
| 45 |
{ |
| 46 |
$suggestion = $this->suggestPropertyName($property); |
| 47 |
$suggestStr = ($suggestion == "") ? "" : " ... did you mean \"{$suggestion}?\""; |
| 48 |
|
| 49 |
return \sprintf( |
| 50 |
"%s property \"%s\" does not exist%s", |
| 51 |
\str_replace("\0", "@", \get_class($this)), // Handle anonymous class names. |
| 52 |
$property, |
| 53 |
$suggestStr |
| 54 |
); |
| 55 |
} |
| 56 |
|
| 57 |
private function suggestPropertyName(string $badProperty): string |
| 58 |
{ |
| 59 |
$badProperty = \strtolower($badProperty); |
| 60 |
$bestMatch = ""; |
| 61 |
$bestMatchPercentage = 0; |
| 62 |
|
| 63 |
/** @psalm-suppress RawObjectIteration */ |
| 64 |
foreach ($this as $property => $value) { |
| 65 |
// Never suggest properties that begin with an underscore |
| 66 |
if ($property[0] === "_") { |
| 67 |
continue; |
| 68 |
} |
| 69 |
\similar_text($badProperty, \strtolower($property), $byRefPercentage); |
| 70 |
if ($byRefPercentage > $bestMatchPercentage) { |
| 71 |
$bestMatchPercentage = $byRefPercentage; |
| 72 |
$bestMatch = $property; |
| 73 |
} |
| 74 |
} |
| 75 |
|
| 76 |
return ($bestMatchPercentage >= $this->__propertySuggestThreshold) ? $bestMatch : ""; |
| 77 |
} |
| 78 |
} |
| 79 |
|