upload_of.php 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. <?php namespace System\Validation\Rules;
  2. use System\File;
  3. use System\Input;
  4. use System\Validation\Rule;
  5. class Upload_Of extends Rule {
  6. /**
  7. * The acceptable file types.
  8. *
  9. * @var array
  10. */
  11. public $types = array();
  12. /**
  13. * The maximum file size in bytes.
  14. *
  15. * @var int
  16. */
  17. public $maximum;
  18. /**
  19. * Evaluate the validity of an attribute.
  20. *
  21. * @param string $attribute
  22. * @param array $attributes
  23. * @return void
  24. */
  25. public function check($attribute, $attributes)
  26. {
  27. if ( ! array_key_exists($attribute, Input::file()))
  28. {
  29. return true;
  30. }
  31. $file = Input::file($attribute);
  32. if ( ! is_null($this->maximum) and $file['size'] > $this->maximum)
  33. {
  34. $this->error = 'file_too_big';
  35. return false;
  36. }
  37. foreach ($this->types as $type)
  38. {
  39. if ( ! File::is($type, $file['tmp_name']))
  40. {
  41. $this->error = 'file_wrong_type';
  42. return false;
  43. }
  44. }
  45. return true;
  46. }
  47. /**
  48. * Set the acceptable file types.
  49. *
  50. * @return Upload_Of
  51. */
  52. public function is()
  53. {
  54. $this->types = func_get_args();
  55. return $this;
  56. }
  57. /**
  58. * Set the maximum file size in bytes.
  59. *
  60. * @param int $maximum
  61. * @return Upload_Of
  62. */
  63. public function less_than($maximum)
  64. {
  65. $this->maximum = $maximum;
  66. return $this;
  67. }
  68. }