CustomComponent.php 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104
  1. <?php
  2. /**
  3. * PHP表单生成器
  4. *
  5. * @package FormBuilder
  6. * @author xaboy <xaboy2005@qq.com>
  7. * @version 2.0
  8. * @license MIT
  9. * @link https://github.com/xaboy/form-builder
  10. */
  11. namespace FormBuilder\Driver;
  12. use FormBuilder\Contract\CustomComponentInterface;
  13. use FormBuilder\Rule\BaseRule;
  14. use FormBuilder\Rule\CallPropsRule;
  15. use FormBuilder\Rule\ChildrenRule;
  16. use FormBuilder\Rule\EmitRule;
  17. use FormBuilder\Rule\PropsRule;
  18. use FormBuilder\Rule\ValidateRule;
  19. /**
  20. * 自定义组件
  21. * Class CustomComponent
  22. */
  23. class CustomComponent implements CustomComponentInterface, \JsonSerializable, \ArrayAccess
  24. {
  25. use BaseRule;
  26. use ChildrenRule;
  27. use EmitRule;
  28. use PropsRule;
  29. use ValidateRule;
  30. use CallPropsRule;
  31. protected static $propsRule = [];
  32. protected $defaultProps = [];
  33. /**
  34. * CustomComponent constructor.
  35. * @param null|string $type
  36. */
  37. public function __construct($type = null)
  38. {
  39. $this->setRuleType(is_null($type) ? $this->getComponentName() : $type)->props($this->defaultProps);
  40. }
  41. public function __toString()
  42. {
  43. return $this->toJson();
  44. }
  45. public function __invoke()
  46. {
  47. return $this->build();
  48. }
  49. public function toJson()
  50. {
  51. return json_encode($this->build());
  52. }
  53. protected function getComponentName()
  54. {
  55. return lcfirst(basename(str_replace('\\', '/', get_class($this))));
  56. }
  57. public function build()
  58. {
  59. return array_merge(
  60. $this->parseBaseRule(),
  61. $this->parseEmitRule(),
  62. $this->parsePropsRule(),
  63. $this->parseValidateRule(),
  64. $this->parseChildrenRule()
  65. );
  66. }
  67. public function jsonSerialize()
  68. {
  69. return $this->build();
  70. }
  71. public function offsetExists($offset)
  72. {
  73. return isset($this->props[$offset]);
  74. }
  75. public function offsetGet($offset)
  76. {
  77. return $this->props[$offset];
  78. }
  79. public function offsetSet($offset, $value)
  80. {
  81. $this->props[$offset] = $value;
  82. }
  83. public function offsetUnset($offset)
  84. {
  85. unset($this->props[$offset]);
  86. }
  87. }