1
0
mirror of https://github.com/danog/amp.git synced 2024-12-04 18:38:17 +01:00
amp/lib/Struct.php

83 lines
2.3 KiB
PHP
Raw Normal View History

<?php
2016-08-16 06:46:26 +02:00
2014-11-11 17:11:58 +01:00
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.
*/
2018-06-18 20:00:01 +02:00
trait Struct
{
/**
* The minimum percentage [0-100] at which to recommend a similar property
* name when generating error messages.
*/
private int $__propertySuggestThreshold = 70;
2020-03-28 22:20:44 +01:00
/**
* @param string $property
*
* @psalm-return no-return
*/
public function __get(string $property): void
2018-06-18 20:00:01 +02:00
{
throw new \Error(
$this->generateStructPropertyError($property)
2014-11-11 17:11:58 +01:00
);
}
2020-03-28 22:20:44 +01:00
/**
* @param string $property
* @param mixed $value
*
* @psalm-return no-return
*/
public function __set(string $property, mixed $value): void
2018-06-18 20:00:01 +02:00
{
throw new \Error(
$this->generateStructPropertyError($property)
2014-11-11 17:11:58 +01:00
);
}
2018-06-18 20:00:01 +02:00
private function generateStructPropertyError(string $property): string
{
$suggestion = $this->suggestPropertyName($property);
$suggestStr = ($suggestion == "") ? "" : " ... did you mean \"{$suggestion}?\"";
2016-08-18 05:25:54 +02:00
return \sprintf(
"%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.
$property,
$suggestStr
);
}
2018-06-18 20:00:01 +02:00
private function suggestPropertyName(string $badProperty): string
{
2016-08-18 05:25:54 +02:00
$badProperty = \strtolower($badProperty);
$bestMatch = "";
$bestMatchPercentage = 0;
$reflection = new \ReflectionClass($this);
2020-03-28 22:20:44 +01:00
/** @psalm-suppress RawObjectIteration */
foreach ($reflection->getProperties() as $property) {
$name = $property->getName();
// Never suggest properties that begin with an underscore
if ($name[0] === "_") {
continue;
}
\similar_text($badProperty, \strtolower($name), $byRefPercentage);
if ($byRefPercentage > $bestMatchPercentage) {
$bestMatchPercentage = $byRefPercentage;
$bestMatch = $name;
}
}
return ($bestMatchPercentage >= $this->__propertySuggestThreshold) ? $bestMatch : "";
2014-11-11 17:11:58 +01:00
}
}