1
0
mirror of https://github.com/danog/amp.git synced 2024-12-15 19:07:22 +01:00
amp/lib/Struct.php

62 lines
1.9 KiB
PHP
Raw Normal View History

2014-11-11 17:11:58 +01:00
<?php
namespace Amp;
/**
* A "safe" struct trait for public property aggregators
2015-02-05 18:17:05 +01:00
*
* This trait is intended to make using public properties a little safer by throwing when
* nonexistent property names are read or written.
*/
trait Struct {
/**
* The minimum percentage [0-100] at which to recommend a similar property
* name when generating error messages.
*/
private $__propertySuggestThreshold = 70;
2014-11-11 17:11:58 +01:00
final public function __get($property) {
throw new \DomainException(
$this->generateStructPropertyError($property)
2014-11-11 17:11:58 +01:00
);
}
final public function __set($property, $value) {
throw new \DomainException(
$this->generateStructPropertyError($property)
2014-11-11 17:11:58 +01:00
);
}
private function generateStructPropertyError($property) {
$suggestion = $this->suggestPropertyName($property);
$suggestStr = ($suggestion == "") ? "" : " ... did you mean \"{$suggestion}?\"";
return sprintf(
"%s property \"%s\" does not exist%s",
get_class($this),
$property,
$suggestStr
);
}
private function suggestPropertyName($badProperty) {
$badProperty = strtolower($badProperty);
$bestMatch = "";
$bestMatchPercentage = 0.00;
$byRefPercentage = 0.00;
foreach ($this as $property => $value) {
// Never suggest properties that begin with an underscore
if ($property[0] === "_") {
continue;
}
\similar_text($badProperty, strtolower($property), $byRefPercentage);
if ($byRefPercentage > $bestMatchPercentage) {
$bestMatchPercentage = $byRefPercentage;
$bestMatch = $property;
}
}
return ($bestMatchPercentage >= $this->__propertySuggestThreshold) ? $bestMatch : "";
2014-11-11 17:11:58 +01:00
}
}