浏览代码

Add existence check

mscherer 3 年之前
父节点
当前提交
3cb6e10344
共有 2 个文件被更改,包括 35 次插入0 次删除
  1. 9 0
      docs/Helper/Icon.md
  2. 26 0
      src/View/Icon/IconCollection.php

+ 9 - 0
docs/Helper/Icon.md

@@ -141,6 +141,15 @@ foreach ($icons as $iconSet => $list) {
 }
 ```
 
+## Configuration
+
+You can enable `checkExistence` to ensure each icon exists or otherwise throws a warning in logs:
+```php
+'Icon' => [
+    'checkExistence' => true,
+    ...
+],
+```
 
 ## Tips
 

+ 26 - 0
src/View/Icon/IconCollection.php

@@ -26,6 +26,11 @@ class IconCollection {
 	protected $iconSets = [];
 
 	/**
+	 * @var array|null
+	 */
+	protected $names;
+
+	/**
 	 * @param array<string, mixed> $config
 	 */
 	public function __construct(array $config = []) {
@@ -67,6 +72,10 @@ class IconCollection {
 	 * @return array<string, array<string>>
 	 */
 	public function names(): array {
+		if ($this->names !== null) {
+			return $this->names;
+		}
+
 		$names = [];
 		foreach ($this->iconSets as $name => $set) {
 			$iconNames = $set->names();
@@ -74,6 +83,7 @@ class IconCollection {
 		}
 
 		ksort($names);
+		$this->names = $names;
 
 		return $names;
 	}
@@ -120,7 +130,23 @@ class IconCollection {
 
 		unset($options['attributes']);
 
+		if ($this->getConfig('checkExistence') && !$this->exists($icon, $set)) {
+			trigger_error(sprintf('Icon `%s` does not exist', $set . ':' . $icon), E_USER_WARNING);
+		}
+
 		return $this->iconSets[$set]->render($icon, $options, $attributes);
 	}
 
+	/**
+	 * @param string $icon
+	 * @param string $set
+	 *
+	 * @return bool
+	 */
+	protected function exists(string $icon, string $set): bool {
+		$names = $this->names();
+
+		return !empty($names[$set]) && in_array($icon, $names[$set], true);
+	}
+
 }