2016-12-29 21:09:49 +01:00
|
|
|
<?php
|
2016-08-16 06:46:26 +02:00
|
|
|
|
2014-11-11 17:11:58 +01:00
|
|
|
namespace Amp;
|
|
|
|
|
2015-01-29 04:30:02 +01:00
|
|
|
/**
|
2017-04-24 15:39:08 +02:00
|
|
|
* A "safe" struct trait for public property aggregators.
|
2015-02-05 18:17:05 +01:00
|
|
|
*
|
2015-04-03 17:56:16 +02:00
|
|
|
* This trait is intended to make using public properties a little safer by throwing when
|
|
|
|
* nonexistent property names are read or written.
|
2015-01-29 04:30:02 +01:00
|
|
|
*/
|
2015-04-03 17:56:16 +02:00
|
|
|
trait Struct {
|
2015-05-13 16:05:23 +02:00
|
|
|
/**
|
|
|
|
* The minimum percentage [0-100] at which to recommend a similar property
|
|
|
|
* name when generating error messages.
|
|
|
|
*/
|
|
|
|
private $__propertySuggestThreshold = 70;
|
|
|
|
|
2016-08-18 05:25:54 +02:00
|
|
|
public function __get(string $property) {
|
2016-08-12 23:58:53 +02:00
|
|
|
throw new \Error(
|
2015-04-03 17:56:16 +02:00
|
|
|
$this->generateStructPropertyError($property)
|
2014-11-11 17:11:58 +01:00
|
|
|
);
|
|
|
|
}
|
|
|
|
|
2016-08-18 05:25:54 +02:00
|
|
|
public function __set(string $property, $value) {
|
2016-08-12 23:58:53 +02:00
|
|
|
throw new \Error(
|
2015-04-03 17:56:16 +02:00
|
|
|
$this->generateStructPropertyError($property)
|
2014-11-11 17:11:58 +01:00
|
|
|
);
|
|
|
|
}
|
|
|
|
|
2016-08-18 05:25:54 +02:00
|
|
|
private function generateStructPropertyError(string $property): string {
|
2015-05-13 16:05:23 +02:00
|
|
|
$suggestion = $this->suggestPropertyName($property);
|
|
|
|
$suggestStr = ($suggestion == "") ? "" : " ... did you mean \"{$suggestion}?\"";
|
2017-01-07 22:55:34 +01:00
|
|
|
|
2016-08-18 05:25:54 +02:00
|
|
|
return \sprintf(
|
2015-05-13 16:05:23 +02:00
|
|
|
"%s property \"%s\" does not exist%s",
|
2016-08-18 05:25:54 +02:00
|
|
|
\str_replace("\0", "@", \get_class($this)), // Handle anonymous class names.
|
2015-05-13 16:05:23 +02:00
|
|
|
$property,
|
|
|
|
$suggestStr
|
|
|
|
);
|
|
|
|
}
|
|
|
|
|
2016-08-18 05:25:54 +02:00
|
|
|
private function suggestPropertyName(string $badProperty): string {
|
|
|
|
$badProperty = \strtolower($badProperty);
|
2015-05-13 16:05:23 +02:00
|
|
|
$bestMatch = "";
|
2017-01-07 22:55:34 +01:00
|
|
|
$bestMatchPercentage = 0;
|
|
|
|
|
2015-05-13 16:05:23 +02:00
|
|
|
foreach ($this as $property => $value) {
|
|
|
|
// Never suggest properties that begin with an underscore
|
|
|
|
if ($property[0] === "_") {
|
|
|
|
continue;
|
|
|
|
}
|
2016-08-18 05:25:54 +02:00
|
|
|
\similar_text($badProperty, \strtolower($property), $byRefPercentage);
|
2015-05-13 16:05:23 +02:00
|
|
|
if ($byRefPercentage > $bestMatchPercentage) {
|
|
|
|
$bestMatchPercentage = $byRefPercentage;
|
|
|
|
$bestMatch = $property;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
return ($bestMatchPercentage >= $this->__propertySuggestThreshold) ? $bestMatch : "";
|
2014-11-11 17:11:58 +01:00
|
|
|
}
|
|
|
|
}
|