ValidatesAttributes.php 82 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922
  1. <?php
  2. namespace Illuminate\Validation\Concerns;
  3. use Brick\Math\BigDecimal;
  4. use Brick\Math\BigNumber;
  5. use Brick\Math\Exception\MathException as BrickMathException;
  6. use DateTime;
  7. use DateTimeInterface;
  8. use DateTimeZone;
  9. use Egulias\EmailValidator\EmailValidator;
  10. use Egulias\EmailValidator\Validation\DNSCheckValidation;
  11. use Egulias\EmailValidator\Validation\Extra\SpoofCheckValidation;
  12. use Egulias\EmailValidator\Validation\MultipleValidationWithAnd;
  13. use Egulias\EmailValidator\Validation\NoRFCWarningsValidation;
  14. use Egulias\EmailValidator\Validation\RFCValidation;
  15. use Exception;
  16. use Illuminate\Container\Container;
  17. use Illuminate\Database\Eloquent\Model;
  18. use Illuminate\Support\Arr;
  19. use Illuminate\Support\Collection;
  20. use Illuminate\Support\Exceptions\MathException;
  21. use Illuminate\Support\Facades\Date;
  22. use Illuminate\Support\Str;
  23. use Illuminate\Validation\Rules\Exists;
  24. use Illuminate\Validation\Rules\Unique;
  25. use Illuminate\Validation\ValidationData;
  26. use InvalidArgumentException;
  27. use Symfony\Component\HttpFoundation\File\File;
  28. use Symfony\Component\HttpFoundation\File\UploadedFile;
  29. use ValueError;
  30. trait ValidatesAttributes
  31. {
  32. /**
  33. * Validate that an attribute was "accepted".
  34. *
  35. * This validation rule implies the attribute is "required".
  36. *
  37. * @param string $attribute
  38. * @param mixed $value
  39. * @return bool
  40. */
  41. public function validateAccepted($attribute, $value)
  42. {
  43. $acceptable = ['yes', 'on', '1', 1, true, 'true'];
  44. return $this->validateRequired($attribute, $value) && in_array($value, $acceptable, true);
  45. }
  46. /**
  47. * Validate that an attribute was "accepted" when another attribute has a given value.
  48. *
  49. * @param string $attribute
  50. * @param mixed $value
  51. * @param mixed $parameters
  52. * @return bool
  53. */
  54. public function validateAcceptedIf($attribute, $value, $parameters)
  55. {
  56. $acceptable = ['yes', 'on', '1', 1, true, 'true'];
  57. $this->requireParameterCount(2, $parameters, 'accepted_if');
  58. [$values, $other] = $this->parseDependentRuleParameters($parameters);
  59. if (in_array($other, $values, is_bool($other) || is_null($other))) {
  60. return $this->validateRequired($attribute, $value) && in_array($value, $acceptable, true);
  61. }
  62. return true;
  63. }
  64. /**
  65. * Validate that an attribute was "declined".
  66. *
  67. * This validation rule implies the attribute is "required".
  68. *
  69. * @param string $attribute
  70. * @param mixed $value
  71. * @return bool
  72. */
  73. public function validateDeclined($attribute, $value)
  74. {
  75. $acceptable = ['no', 'off', '0', 0, false, 'false'];
  76. return $this->validateRequired($attribute, $value) && in_array($value, $acceptable, true);
  77. }
  78. /**
  79. * Validate that an attribute was "declined" when another attribute has a given value.
  80. *
  81. * @param string $attribute
  82. * @param mixed $value
  83. * @param mixed $parameters
  84. * @return bool
  85. */
  86. public function validateDeclinedIf($attribute, $value, $parameters)
  87. {
  88. $acceptable = ['no', 'off', '0', 0, false, 'false'];
  89. $this->requireParameterCount(2, $parameters, 'declined_if');
  90. [$values, $other] = $this->parseDependentRuleParameters($parameters);
  91. if (in_array($other, $values, is_bool($other) || is_null($other))) {
  92. return $this->validateRequired($attribute, $value) && in_array($value, $acceptable, true);
  93. }
  94. return true;
  95. }
  96. /**
  97. * Validate that an attribute is an active URL.
  98. *
  99. * @param string $attribute
  100. * @param mixed $value
  101. * @return bool
  102. */
  103. public function validateActiveUrl($attribute, $value)
  104. {
  105. if (! is_string($value)) {
  106. return false;
  107. }
  108. if ($url = parse_url($value, PHP_URL_HOST)) {
  109. try {
  110. $records = $this->getDnsRecords($url.'.', DNS_A | DNS_AAAA);
  111. if (is_array($records) && count($records) > 0) {
  112. return true;
  113. }
  114. } catch (Exception) {
  115. return false;
  116. }
  117. }
  118. return false;
  119. }
  120. /**
  121. * Get the DNS records for the given hostname.
  122. *
  123. * @param string $hostname
  124. * @param int $type
  125. * @return array|false
  126. */
  127. protected function getDnsRecords($hostname, $type)
  128. {
  129. return dns_get_record($hostname, $type);
  130. }
  131. /**
  132. * Validate that an attribute is 7 bit ASCII.
  133. *
  134. * @param string $attribute
  135. * @param mixed $value
  136. * @return bool
  137. */
  138. public function validateAscii($attribute, $value)
  139. {
  140. return Str::isAscii($value);
  141. }
  142. /**
  143. * "Break" on first validation fail.
  144. *
  145. * Always returns true, just lets us put "bail" in rules.
  146. *
  147. * @return bool
  148. */
  149. public function validateBail()
  150. {
  151. return true;
  152. }
  153. /**
  154. * Validate the date is before a given date.
  155. *
  156. * @param string $attribute
  157. * @param mixed $value
  158. * @param array<int, int|string> $parameters
  159. * @return bool
  160. */
  161. public function validateBefore($attribute, $value, $parameters)
  162. {
  163. $this->requireParameterCount(1, $parameters, 'before');
  164. return $this->compareDates($attribute, $value, $parameters, '<');
  165. }
  166. /**
  167. * Validate the date is before or equal a given date.
  168. *
  169. * @param string $attribute
  170. * @param mixed $value
  171. * @param array<int, int|string> $parameters
  172. * @return bool
  173. */
  174. public function validateBeforeOrEqual($attribute, $value, $parameters)
  175. {
  176. $this->requireParameterCount(1, $parameters, 'before_or_equal');
  177. return $this->compareDates($attribute, $value, $parameters, '<=');
  178. }
  179. /**
  180. * Validate the date is after a given date.
  181. *
  182. * @param string $attribute
  183. * @param mixed $value
  184. * @param array<int, int|string> $parameters
  185. * @return bool
  186. */
  187. public function validateAfter($attribute, $value, $parameters)
  188. {
  189. $this->requireParameterCount(1, $parameters, 'after');
  190. return $this->compareDates($attribute, $value, $parameters, '>');
  191. }
  192. /**
  193. * Validate the date is equal or after a given date.
  194. *
  195. * @param string $attribute
  196. * @param mixed $value
  197. * @param array<int, int|string> $parameters
  198. * @return bool
  199. */
  200. public function validateAfterOrEqual($attribute, $value, $parameters)
  201. {
  202. $this->requireParameterCount(1, $parameters, 'after_or_equal');
  203. return $this->compareDates($attribute, $value, $parameters, '>=');
  204. }
  205. /**
  206. * Compare a given date against another using an operator.
  207. *
  208. * @param string $attribute
  209. * @param mixed $value
  210. * @param array<int, int|string> $parameters
  211. * @param string $operator
  212. * @return bool
  213. */
  214. protected function compareDates($attribute, $value, $parameters, $operator)
  215. {
  216. if (! is_string($value) && ! is_numeric($value) && ! $value instanceof DateTimeInterface) {
  217. return false;
  218. }
  219. if ($format = $this->getDateFormat($attribute)) {
  220. return $this->checkDateTimeOrder($format, $value, $parameters[0], $operator);
  221. }
  222. if (is_null($date = $this->getDateTimestamp($parameters[0]))) {
  223. $date = $this->getDateTimestamp($this->getValue($parameters[0]));
  224. }
  225. return $this->compare($this->getDateTimestamp($value), $date, $operator);
  226. }
  227. /**
  228. * Get the date format for an attribute if it has one.
  229. *
  230. * @param string $attribute
  231. * @return string|null
  232. */
  233. protected function getDateFormat($attribute)
  234. {
  235. if ($result = $this->getRule($attribute, 'DateFormat')) {
  236. return $result[1][0];
  237. }
  238. }
  239. /**
  240. * Get the date timestamp.
  241. *
  242. * @param mixed $value
  243. * @return int|null
  244. */
  245. protected function getDateTimestamp($value)
  246. {
  247. $date = is_null($value) ? null : $this->getDateTime($value);
  248. return $date?->getTimestamp();
  249. }
  250. /**
  251. * Given two date/time strings, check that one is after the other.
  252. *
  253. * @param string $format
  254. * @param string $first
  255. * @param string $second
  256. * @param string $operator
  257. * @return bool
  258. */
  259. protected function checkDateTimeOrder($format, $first, $second, $operator)
  260. {
  261. $firstDate = $this->getDateTimeWithOptionalFormat($format, $first);
  262. $format = $this->getDateFormat($second) ?: $format;
  263. if (! $secondDate = $this->getDateTimeWithOptionalFormat($format, $second)) {
  264. if (is_null($second = $this->getValue($second))) {
  265. return true;
  266. }
  267. $secondDate = $this->getDateTimeWithOptionalFormat($format, $second);
  268. }
  269. return ($firstDate && $secondDate) && $this->compare($firstDate, $secondDate, $operator);
  270. }
  271. /**
  272. * Get a DateTime instance from a string.
  273. *
  274. * @param string $format
  275. * @param string $value
  276. * @return \DateTime|null
  277. */
  278. protected function getDateTimeWithOptionalFormat($format, $value)
  279. {
  280. if ($date = DateTime::createFromFormat('!'.$format, $value)) {
  281. return $date;
  282. }
  283. return $this->getDateTime($value);
  284. }
  285. /**
  286. * Get a DateTime instance from a string with no format.
  287. *
  288. * @param string $value
  289. * @return \DateTime|null
  290. */
  291. protected function getDateTime($value)
  292. {
  293. try {
  294. return @Date::parse($value) ?: null;
  295. } catch (Exception) {
  296. //
  297. }
  298. }
  299. /**
  300. * Validate that an attribute contains only alphabetic characters.
  301. * If the 'ascii' option is passed, validate that an attribute contains only ascii alphabetic characters.
  302. *
  303. * @param string $attribute
  304. * @param mixed $value
  305. * @param array<int, int|string> $parameters
  306. * @return bool
  307. */
  308. public function validateAlpha($attribute, $value, $parameters)
  309. {
  310. if (isset($parameters[0]) && $parameters[0] === 'ascii') {
  311. return is_string($value) && preg_match('/\A[a-zA-Z]+\z/u', $value);
  312. }
  313. return is_string($value) && preg_match('/\A[\pL\pM]+\z/u', $value);
  314. }
  315. /**
  316. * Validate that an attribute contains only alpha-numeric characters, dashes, and underscores.
  317. * If the 'ascii' option is passed, validate that an attribute contains only ascii alpha-numeric characters,
  318. * dashes, and underscores.
  319. *
  320. * @param string $attribute
  321. * @param mixed $value
  322. * @param array<int, int|string> $parameters
  323. * @return bool
  324. */
  325. public function validateAlphaDash($attribute, $value, $parameters)
  326. {
  327. if (! is_string($value) && ! is_numeric($value)) {
  328. return false;
  329. }
  330. if (isset($parameters[0]) && $parameters[0] === 'ascii') {
  331. return preg_match('/\A[a-zA-Z0-9_-]+\z/u', $value) > 0;
  332. }
  333. return preg_match('/\A[\pL\pM\pN_-]+\z/u', $value) > 0;
  334. }
  335. /**
  336. * Validate that an attribute contains only alpha-numeric characters.
  337. * If the 'ascii' option is passed, validate that an attribute contains only ascii alpha-numeric characters.
  338. *
  339. * @param string $attribute
  340. * @param mixed $value
  341. * @param array<int, int|string> $parameters
  342. * @return bool
  343. */
  344. public function validateAlphaNum($attribute, $value, $parameters)
  345. {
  346. if (! is_string($value) && ! is_numeric($value)) {
  347. return false;
  348. }
  349. if (isset($parameters[0]) && $parameters[0] === 'ascii') {
  350. return preg_match('/\A[a-zA-Z0-9]+\z/u', $value) > 0;
  351. }
  352. return preg_match('/\A[\pL\pM\pN]+\z/u', $value) > 0;
  353. }
  354. /**
  355. * Validate that an attribute is an array.
  356. *
  357. * @param string $attribute
  358. * @param mixed $value
  359. * @param array<int, int|string> $parameters
  360. * @return bool
  361. */
  362. public function validateArray($attribute, $value, $parameters = [])
  363. {
  364. if (! is_array($value)) {
  365. return false;
  366. }
  367. if (empty($parameters)) {
  368. return true;
  369. }
  370. return empty(array_diff_key($value, array_fill_keys($parameters, '')));
  371. }
  372. /**
  373. * Validate that an attribute is a list.
  374. *
  375. * @param string $attribute
  376. * @param mixed $value
  377. * @return bool
  378. */
  379. public function validateList($attribute, $value)
  380. {
  381. return is_array($value) && array_is_list($value);
  382. }
  383. /**
  384. * Validate that an array has all of the given keys.
  385. *
  386. * @param string $attribute
  387. * @param mixed $value
  388. * @param array<int, int|string> $parameters
  389. * @return bool
  390. */
  391. public function validateRequiredArrayKeys($attribute, $value, $parameters)
  392. {
  393. if (! is_array($value)) {
  394. return false;
  395. }
  396. foreach ($parameters as $param) {
  397. if (! Arr::exists($value, $param)) {
  398. return false;
  399. }
  400. }
  401. return true;
  402. }
  403. /**
  404. * Validate the size of an attribute is between a set of values.
  405. *
  406. * @param string $attribute
  407. * @param mixed $value
  408. * @param array<int, int|string> $parameters
  409. * @return bool
  410. */
  411. public function validateBetween($attribute, $value, $parameters)
  412. {
  413. $this->requireParameterCount(2, $parameters, 'between');
  414. try {
  415. $size = BigNumber::of($this->getSize($attribute, $value));
  416. return $size->isGreaterThanOrEqualTo($this->trim($parameters[0])) && $size->isLessThanOrEqualTo($this->trim($parameters[1]));
  417. } catch (MathException) {
  418. return false;
  419. }
  420. }
  421. /**
  422. * Validate that an attribute is a boolean.
  423. *
  424. * @param string $attribute
  425. * @param mixed $value
  426. * @param array{0: 'strict'} $parameters
  427. * @return bool
  428. */
  429. public function validateBoolean($attribute, $value, $parameters)
  430. {
  431. $acceptable = [true, false, 0, 1, '0', '1'];
  432. if (($parameters[0] ?? null) === 'strict') {
  433. $acceptable = [true, false];
  434. }
  435. return in_array($value, $acceptable, true);
  436. }
  437. /**
  438. * Validate that an attribute has a matching confirmation.
  439. *
  440. * @param string $attribute
  441. * @param mixed $value
  442. * @param array{0: string} $parameters
  443. * @return bool
  444. */
  445. public function validateConfirmed($attribute, $value, $parameters)
  446. {
  447. return $this->validateSame($attribute, $value, [$parameters[0] ?? $attribute.'_confirmation']);
  448. }
  449. /**
  450. * Validate an attribute contains a list of values.
  451. *
  452. * @param string $attribute
  453. * @param mixed $value
  454. * @param array<int, int|string> $parameters
  455. * @return bool
  456. */
  457. public function validateContains($attribute, $value, $parameters)
  458. {
  459. if (! is_array($value)) {
  460. return false;
  461. }
  462. foreach ($parameters as $parameter) {
  463. if (! in_array($parameter, $value)) {
  464. return false;
  465. }
  466. }
  467. return true;
  468. }
  469. /**
  470. * Validate an attribute does not contain a list of values.
  471. *
  472. * @param string $attribute
  473. * @param mixed $value
  474. * @param array<int, int|string> $parameters
  475. * @return bool
  476. */
  477. public function validateDoesntContain($attribute, $value, $parameters)
  478. {
  479. if (! is_array($value)) {
  480. return false;
  481. }
  482. foreach ($parameters as $parameter) {
  483. if (in_array($parameter, $value)) {
  484. return false;
  485. }
  486. }
  487. return true;
  488. }
  489. /**
  490. * Validate that the password of the currently authenticated user matches the given value.
  491. *
  492. * @param string $attribute
  493. * @param mixed $value
  494. * @param array<int, int|string> $parameters
  495. * @return bool
  496. */
  497. protected function validateCurrentPassword($attribute, $value, $parameters)
  498. {
  499. $auth = $this->container->make('auth');
  500. $hasher = $this->container->make('hash');
  501. $guard = $auth->guard(Arr::first($parameters));
  502. if ($guard->guest()) {
  503. return false;
  504. }
  505. return $hasher->check($value, $guard->user()->getAuthPassword());
  506. }
  507. /**
  508. * Validate that an attribute is a valid date.
  509. *
  510. * @param string $attribute
  511. * @param mixed $value
  512. * @return bool
  513. */
  514. public function validateDate($attribute, $value)
  515. {
  516. if ($value instanceof DateTimeInterface) {
  517. return true;
  518. }
  519. try {
  520. if ((! is_string($value) && ! is_numeric($value)) || strtotime($value) === false) {
  521. return false;
  522. }
  523. } catch (Exception) {
  524. return false;
  525. }
  526. $date = date_parse($value);
  527. return checkdate($date['month'], $date['day'], $date['year']);
  528. }
  529. /**
  530. * Validate that an attribute matches a date format.
  531. *
  532. * @param string $attribute
  533. * @param mixed $value
  534. * @param array<int, int|string> $parameters
  535. * @return bool
  536. */
  537. public function validateDateFormat($attribute, $value, $parameters)
  538. {
  539. $this->requireParameterCount(1, $parameters, 'date_format');
  540. if (! is_string($value) && ! is_numeric($value)) {
  541. return false;
  542. }
  543. foreach ($parameters as $format) {
  544. try {
  545. $date = DateTime::createFromFormat('!'.$format, $value, new DateTimeZone('UTC'));
  546. if ($date && $date->format($format) == $value) {
  547. return true;
  548. }
  549. } catch (ValueError) {
  550. return false;
  551. }
  552. }
  553. return false;
  554. }
  555. /**
  556. * Validate that an attribute is equal to another date.
  557. *
  558. * @param string $attribute
  559. * @param mixed $value
  560. * @param array<int, int|string> $parameters
  561. * @return bool
  562. */
  563. public function validateDateEquals($attribute, $value, $parameters)
  564. {
  565. $this->requireParameterCount(1, $parameters, 'date_equals');
  566. return $this->compareDates($attribute, $value, $parameters, '=');
  567. }
  568. /**
  569. * Validate that an attribute has a given number of decimal places.
  570. *
  571. * @param string $attribute
  572. * @param mixed $value
  573. * @param array<int, int|string> $parameters
  574. * @return bool
  575. */
  576. public function validateDecimal($attribute, $value, $parameters)
  577. {
  578. $this->requireParameterCount(1, $parameters, 'decimal');
  579. if (! $this->validateNumeric($attribute, $value, [])) {
  580. return false;
  581. }
  582. $matches = [];
  583. if (preg_match('/^[+-]?\d*\.?(\d*)$/', $value, $matches) !== 1) {
  584. return false;
  585. }
  586. $decimals = strlen(end($matches));
  587. if (! isset($parameters[1])) {
  588. return $decimals == $parameters[0];
  589. }
  590. return $decimals >= $parameters[0] &&
  591. $decimals <= $parameters[1];
  592. }
  593. /**
  594. * Validate that an attribute is different from another attribute.
  595. *
  596. * @param string $attribute
  597. * @param mixed $value
  598. * @param array<int, int|string> $parameters
  599. * @return bool
  600. */
  601. public function validateDifferent($attribute, $value, $parameters)
  602. {
  603. $this->requireParameterCount(1, $parameters, 'different');
  604. foreach ($parameters as $parameter) {
  605. if (Arr::has($this->data, $parameter)) {
  606. $other = Arr::get($this->data, $parameter);
  607. if ($value === $other) {
  608. return false;
  609. }
  610. }
  611. }
  612. return true;
  613. }
  614. /**
  615. * Validate that an attribute has a given number of digits.
  616. *
  617. * @param string $attribute
  618. * @param mixed $value
  619. * @param array<int, int|string> $parameters
  620. * @return bool
  621. */
  622. public function validateDigits($attribute, $value, $parameters)
  623. {
  624. $this->requireParameterCount(1, $parameters, 'digits');
  625. return (is_numeric($value) || is_string($value)) &&
  626. ! preg_match('/[^0-9]/', $value) &&
  627. strlen((string) $value) == $parameters[0];
  628. }
  629. /**
  630. * Validate that an attribute is between a given number of digits.
  631. *
  632. * @param string $attribute
  633. * @param mixed $value
  634. * @param array<int, int|string> $parameters
  635. * @return bool
  636. */
  637. public function validateDigitsBetween($attribute, $value, $parameters)
  638. {
  639. $this->requireParameterCount(2, $parameters, 'digits_between');
  640. $length = strlen((string) $value);
  641. return ! preg_match('/[^0-9]/', $value)
  642. && $length >= $parameters[0] && $length <= $parameters[1];
  643. }
  644. /**
  645. * Validate the dimensions of an image matches the given values.
  646. *
  647. * @param string $attribute
  648. * @param mixed $value
  649. * @param array<int, int|string> $parameters
  650. * @return bool
  651. */
  652. public function validateDimensions($attribute, $value, $parameters)
  653. {
  654. if ($this->isValidFileInstance($value) && in_array($value->getMimeType(), ['image/svg+xml', 'image/svg'])) {
  655. return true;
  656. }
  657. if (! $this->isValidFileInstance($value)) {
  658. return false;
  659. }
  660. $dimensions = method_exists($value, 'dimensions')
  661. ? $value->dimensions()
  662. : @getimagesize($value->getRealPath());
  663. if (! $dimensions) {
  664. return false;
  665. }
  666. $this->requireParameterCount(1, $parameters, 'dimensions');
  667. [$width, $height] = $dimensions;
  668. $parameters = $this->parseNamedParameters($parameters);
  669. return ! (
  670. $this->failsBasicDimensionChecks($parameters, $width, $height) ||
  671. $this->failsRatioCheck($parameters, $width, $height) ||
  672. $this->failsMinRatioCheck($parameters, $width, $height) ||
  673. $this->failsMaxRatioCheck($parameters, $width, $height)
  674. );
  675. }
  676. /**
  677. * Test if the given width and height fail any conditions.
  678. *
  679. * @param array<string,string> $parameters
  680. * @param int $width
  681. * @param int $height
  682. * @return bool
  683. */
  684. protected function failsBasicDimensionChecks($parameters, $width, $height)
  685. {
  686. return (isset($parameters['width']) && $parameters['width'] != $width) ||
  687. (isset($parameters['min_width']) && $parameters['min_width'] > $width) ||
  688. (isset($parameters['max_width']) && $parameters['max_width'] < $width) ||
  689. (isset($parameters['height']) && $parameters['height'] != $height) ||
  690. (isset($parameters['min_height']) && $parameters['min_height'] > $height) ||
  691. (isset($parameters['max_height']) && $parameters['max_height'] < $height);
  692. }
  693. /**
  694. * Determine if the given parameters fail a dimension ratio check.
  695. *
  696. * @param array<string,string> $parameters
  697. * @param int $width
  698. * @param int $height
  699. * @return bool
  700. */
  701. protected function failsRatioCheck($parameters, $width, $height)
  702. {
  703. if (! isset($parameters['ratio'])) {
  704. return false;
  705. }
  706. [$numerator, $denominator] = array_replace(
  707. [1, 1], array_filter(sscanf($parameters['ratio'], '%f/%d'))
  708. );
  709. $precision = 1 / (max(($width + $height) / 2, $height) + 1);
  710. return abs($numerator / $denominator - $width / $height) > $precision;
  711. }
  712. /**
  713. * Determine if the given parameters fail a dimension minimum ratio check.
  714. *
  715. * @param array<string,string> $parameters
  716. * @param int $width
  717. * @param int $height
  718. * @return bool
  719. */
  720. private function failsMinRatioCheck($parameters, $width, $height)
  721. {
  722. if (! isset($parameters['min_ratio'])) {
  723. return false;
  724. }
  725. [$minNumerator, $minDenominator] = array_replace(
  726. [1, 1], array_filter(sscanf($parameters['min_ratio'], '%f/%d'))
  727. );
  728. return ($width / $height) > ($minNumerator / $minDenominator);
  729. }
  730. /**
  731. * Determine if the given parameters fail a dimension maximum ratio check.
  732. *
  733. * @param array<string,string> $parameters
  734. * @param int $width
  735. * @param int $height
  736. * @return bool
  737. */
  738. private function failsMaxRatioCheck($parameters, $width, $height)
  739. {
  740. if (! isset($parameters['max_ratio'])) {
  741. return false;
  742. }
  743. [$maxNumerator, $maxDenominator] = array_replace(
  744. [1, 1], array_filter(sscanf($parameters['max_ratio'], '%f/%d'))
  745. );
  746. return ($width / $height) < ($maxNumerator / $maxDenominator);
  747. }
  748. /**
  749. * Validate an attribute is unique among other values.
  750. *
  751. * @param string $attribute
  752. * @param mixed $value
  753. * @param array<int, int|string> $parameters
  754. * @return bool
  755. */
  756. public function validateDistinct($attribute, $value, $parameters)
  757. {
  758. $data = Arr::except($this->getDistinctValues($attribute), $attribute);
  759. if (in_array('ignore_case', $parameters)) {
  760. return empty(preg_grep('/^'.preg_quote($value, '/').'$/iu', $data));
  761. }
  762. return ! in_array($value, array_values($data), in_array('strict', $parameters));
  763. }
  764. /**
  765. * Get the values to distinct between.
  766. *
  767. * @param string $attribute
  768. * @return array
  769. */
  770. protected function getDistinctValues($attribute)
  771. {
  772. $attributeName = $this->getPrimaryAttribute($attribute);
  773. if (! property_exists($this, 'distinctValues')) {
  774. return $this->extractDistinctValues($attributeName);
  775. }
  776. if (! array_key_exists($attributeName, $this->distinctValues)) {
  777. $this->distinctValues[$attributeName] = $this->extractDistinctValues($attributeName);
  778. }
  779. return $this->distinctValues[$attributeName];
  780. }
  781. /**
  782. * Extract the distinct values from the data.
  783. *
  784. * @param string $attribute
  785. * @return array
  786. */
  787. protected function extractDistinctValues($attribute)
  788. {
  789. $attributeData = ValidationData::extractDataFromPath(
  790. ValidationData::getLeadingExplicitAttributePath($attribute), $this->data
  791. );
  792. $pattern = str_replace('\*', '[^.]+', preg_quote($attribute, '#'));
  793. return Arr::where(Arr::dot($attributeData), function ($value, $key) use ($pattern) {
  794. return (bool) preg_match('#^'.$pattern.'\z#u', $key);
  795. });
  796. }
  797. /**
  798. * Validate that an attribute is a valid e-mail address.
  799. *
  800. * @param string $attribute
  801. * @param mixed $value
  802. * @param array<int, int|string> $parameters
  803. * @return bool
  804. */
  805. public function validateEmail($attribute, $value, $parameters)
  806. {
  807. if (! is_string($value) && ! (is_object($value) && method_exists($value, '__toString'))) {
  808. return false;
  809. }
  810. if (preg_match('/[\r\n]/', (string) $value) > 0) {
  811. return false;
  812. }
  813. $validations = (new Collection($parameters))
  814. ->unique()
  815. ->map(fn ($validation) => match (true) {
  816. $validation === 'strict' => new NoRFCWarningsValidation(),
  817. $validation === 'dns' => new DNSCheckValidation(),
  818. $validation === 'spoof' => new SpoofCheckValidation(),
  819. $validation === 'filter' => new FilterEmailValidation(),
  820. $validation === 'filter_unicode' => FilterEmailValidation::unicode(),
  821. is_string($validation) && class_exists($validation) => $this->container->make($validation),
  822. default => new RFCValidation(),
  823. })
  824. ->values()
  825. ->all() ?: [new RFCValidation];
  826. $emailValidator = Container::getInstance()->make(EmailValidator::class);
  827. return $emailValidator->isValid($value, new MultipleValidationWithAnd($validations));
  828. }
  829. /**
  830. * Validate the encoding of an attribute.
  831. *
  832. * @param string $attribute
  833. * @param mixed $value
  834. * @param array<int, int|string> $parameters
  835. * @return bool
  836. */
  837. public function validateEncoding($attribute, $value, $parameters)
  838. {
  839. $this->requireParameterCount(1, $parameters, 'encoding');
  840. if (! in_array(mb_strtolower($parameters[0]), array_map(mb_strtolower(...), mb_list_encodings()))) {
  841. throw new InvalidArgumentException("Validation rule encoding parameter [{$parameters[0]}] is not a valid encoding.");
  842. }
  843. return mb_check_encoding($value instanceof File ? $value->getContent() : $value, $parameters[0]);
  844. }
  845. /**
  846. * Validate the existence of an attribute value in a database table.
  847. *
  848. * @param string $attribute
  849. * @param mixed $value
  850. * @param array<int, int|string> $parameters
  851. * @return bool
  852. */
  853. public function validateExists($attribute, $value, $parameters)
  854. {
  855. $this->requireParameterCount(1, $parameters, 'exists');
  856. [$connection, $table] = $this->parseTable($parameters[0]);
  857. // The second parameter position holds the name of the column that should be
  858. // verified as existing. If this parameter is not specified we will guess
  859. // that the columns being "verified" shares the given attribute's name.
  860. $column = $this->getQueryColumn($parameters, $attribute);
  861. $expected = is_array($value) ? count(array_unique($value)) : 1;
  862. if ($expected === 0) {
  863. return true;
  864. }
  865. return $this->getExistCount(
  866. $connection, $table, $column, $value, $parameters
  867. ) >= $expected;
  868. }
  869. /**
  870. * Get the number of records that exist in storage.
  871. *
  872. * @param mixed $connection
  873. * @param string $table
  874. * @param string $column
  875. * @param mixed $value
  876. * @param array<int, int|string> $parameters
  877. * @return int
  878. */
  879. protected function getExistCount($connection, $table, $column, $value, $parameters)
  880. {
  881. $verifier = $this->getPresenceVerifier($connection);
  882. $extra = $this->getExtraConditions(
  883. array_values(array_slice($parameters, 2))
  884. );
  885. if ($this->currentRule instanceof Exists) {
  886. $extra = array_merge($extra, $this->currentRule->queryCallbacks());
  887. }
  888. return is_array($value)
  889. ? $verifier->getMultiCount($table, $column, $value, $extra)
  890. : $verifier->getCount($table, $column, $value, null, null, $extra);
  891. }
  892. /**
  893. * Validate the uniqueness of an attribute value on a given database table.
  894. *
  895. * If a database column is not specified, the attribute will be used.
  896. *
  897. * @param string $attribute
  898. * @param mixed $value
  899. * @param array<int, int|string> $parameters
  900. * @return bool
  901. */
  902. public function validateUnique($attribute, $value, $parameters)
  903. {
  904. $this->requireParameterCount(1, $parameters, 'unique');
  905. [$connection, $table, $idColumn] = $this->parseTable($parameters[0]);
  906. // The second parameter position holds the name of the column that needs to
  907. // be verified as unique. If this parameter isn't specified we will just
  908. // assume that this column to be verified shares the attribute's name.
  909. $column = $this->getQueryColumn($parameters, $attribute);
  910. $id = null;
  911. if (isset($parameters[2])) {
  912. [$idColumn, $id] = $this->getUniqueIds($idColumn, $parameters);
  913. if (! is_null($id)) {
  914. $id = stripslashes($id);
  915. }
  916. }
  917. // The presence verifier is responsible for counting rows within this store
  918. // mechanism which might be a relational database or any other permanent
  919. // data store like Redis, etc. We will use it to determine uniqueness.
  920. $verifier = $this->getPresenceVerifier($connection);
  921. $extra = $this->getUniqueExtra($parameters);
  922. if ($this->currentRule instanceof Unique) {
  923. $extra = array_merge($extra, $this->currentRule->queryCallbacks());
  924. }
  925. return $verifier->getCount(
  926. $table, $column, $value, $id, $idColumn, $extra
  927. ) == 0;
  928. }
  929. /**
  930. * Get the excluded ID column and value for the unique rule.
  931. *
  932. * @param string|null $idColumn
  933. * @param array<int, int|string> $parameters
  934. * @return array
  935. */
  936. protected function getUniqueIds($idColumn, $parameters)
  937. {
  938. $idColumn ??= $parameters[3] ?? 'id';
  939. return [$idColumn, $this->prepareUniqueId($parameters[2])];
  940. }
  941. /**
  942. * Prepare the given ID for querying.
  943. *
  944. * @param mixed $id
  945. * @return int
  946. */
  947. protected function prepareUniqueId($id)
  948. {
  949. if (preg_match('/\[(.*)\]/', $id, $matches)) {
  950. $id = $this->getValue($matches[1]);
  951. }
  952. if (strtolower($id) === 'null') {
  953. $id = null;
  954. }
  955. if (filter_var($id, FILTER_VALIDATE_INT) !== false) {
  956. $id = (int) $id;
  957. }
  958. return $id;
  959. }
  960. /**
  961. * Get the extra conditions for a unique rule.
  962. *
  963. * @param array<int, int|string> $parameters
  964. * @return array
  965. */
  966. protected function getUniqueExtra($parameters)
  967. {
  968. if (isset($parameters[4])) {
  969. return $this->getExtraConditions(array_slice($parameters, 4));
  970. }
  971. return [];
  972. }
  973. /**
  974. * Parse the connection / table for the unique / exists rules.
  975. *
  976. * @param string $table
  977. * @return array
  978. */
  979. public function parseTable($table)
  980. {
  981. [$connection, $table] = str_contains($table, '.') ? explode('.', $table, 2) : [null, $table];
  982. if (str_contains($table, '\\') && class_exists($table) && is_a($table, Model::class, true)) {
  983. $model = new $table;
  984. $table = $model->getTable();
  985. $connection ??= $model->getConnectionName();
  986. if (str_contains($table, '.') && Str::startsWith($table, $connection)) {
  987. $connection = null;
  988. }
  989. $idColumn = $model->getKeyName();
  990. }
  991. return [$connection, $table, $idColumn ?? null];
  992. }
  993. /**
  994. * Get the column name for an exists / unique query.
  995. *
  996. * @param array<int, int|string> $parameters
  997. * @param string $attribute
  998. * @return int|string
  999. */
  1000. public function getQueryColumn($parameters, $attribute)
  1001. {
  1002. return isset($parameters[1]) && $parameters[1] !== 'NULL'
  1003. ? $parameters[1]
  1004. : $this->guessColumnForQuery($attribute);
  1005. }
  1006. /**
  1007. * Guess the database column from the given attribute name.
  1008. *
  1009. * @param string $attribute
  1010. * @return string
  1011. */
  1012. public function guessColumnForQuery($attribute)
  1013. {
  1014. if (in_array($attribute, Arr::collapse($this->implicitAttributes))
  1015. && ! is_numeric($last = last(explode('.', $attribute)))) {
  1016. return $last;
  1017. }
  1018. return $attribute;
  1019. }
  1020. /**
  1021. * Get the extra conditions for a unique / exists rule.
  1022. *
  1023. * @param array $segments
  1024. * @return array
  1025. */
  1026. protected function getExtraConditions(array $segments)
  1027. {
  1028. $extra = [];
  1029. $count = count($segments);
  1030. for ($i = 0; $i < $count; $i += 2) {
  1031. $extra[$segments[$i]] = $segments[$i + 1];
  1032. }
  1033. return $extra;
  1034. }
  1035. /**
  1036. * Validate the extension of a file upload attribute is in a set of defined extensions.
  1037. *
  1038. * @param string $attribute
  1039. * @param mixed $value
  1040. * @param array<int, int|string> $parameters
  1041. * @return bool
  1042. */
  1043. public function validateExtensions($attribute, $value, $parameters)
  1044. {
  1045. if (! $this->isValidFileInstance($value)) {
  1046. return false;
  1047. }
  1048. if ($this->shouldBlockPhpUpload($value, $parameters)) {
  1049. return false;
  1050. }
  1051. return in_array(strtolower($value->getClientOriginalExtension()), $parameters);
  1052. }
  1053. /**
  1054. * Validate the given value is a valid file.
  1055. *
  1056. * @param string $attribute
  1057. * @param mixed $value
  1058. * @return bool
  1059. */
  1060. public function validateFile($attribute, $value)
  1061. {
  1062. return $this->isValidFileInstance($value);
  1063. }
  1064. /**
  1065. * Validate the given attribute is filled if it is present.
  1066. *
  1067. * @param string $attribute
  1068. * @param mixed $value
  1069. * @return bool
  1070. */
  1071. public function validateFilled($attribute, $value)
  1072. {
  1073. if (Arr::has($this->data, $attribute)) {
  1074. return $this->validateRequired($attribute, $value);
  1075. }
  1076. return true;
  1077. }
  1078. /**
  1079. * Validate that an attribute is greater than another attribute.
  1080. *
  1081. * @param string $attribute
  1082. * @param mixed $value
  1083. * @param array<int, int|string> $parameters
  1084. * @return bool
  1085. */
  1086. public function validateGt($attribute, $value, $parameters)
  1087. {
  1088. $this->requireParameterCount(1, $parameters, 'gt');
  1089. $comparedToValue = $this->getValue($parameters[0]);
  1090. $this->shouldBeNumeric($attribute, 'Gt');
  1091. if (is_null($comparedToValue) && (is_numeric($value) && is_numeric($parameters[0]))) {
  1092. try {
  1093. return BigNumber::of($this->getSize($attribute, $value))->isGreaterThan($this->trim($parameters[0]));
  1094. } catch (MathException) {
  1095. return false;
  1096. }
  1097. }
  1098. if (is_numeric($parameters[0])) {
  1099. return false;
  1100. }
  1101. if ($this->hasRule($attribute, $this->numericRules) && is_numeric($value) && is_numeric($comparedToValue)) {
  1102. try {
  1103. return BigNumber::of($this->trim($value))->isGreaterThan($this->trim($comparedToValue));
  1104. } catch (MathException) {
  1105. return false;
  1106. }
  1107. }
  1108. if (! $this->isSameType($value, $comparedToValue)) {
  1109. return false;
  1110. }
  1111. try {
  1112. return $this->getSize($attribute, $value) > $this->getSize($attribute, $comparedToValue);
  1113. } catch (MathException) {
  1114. return false;
  1115. }
  1116. }
  1117. /**
  1118. * Validate that an attribute is less than another attribute.
  1119. *
  1120. * @param string $attribute
  1121. * @param mixed $value
  1122. * @param array<int, int|string> $parameters
  1123. * @return bool
  1124. */
  1125. public function validateLt($attribute, $value, $parameters)
  1126. {
  1127. $this->requireParameterCount(1, $parameters, 'lt');
  1128. $comparedToValue = $this->getValue($parameters[0]);
  1129. $this->shouldBeNumeric($attribute, 'Lt');
  1130. if (is_null($comparedToValue) && (is_numeric($value) && is_numeric($parameters[0]))) {
  1131. try {
  1132. return BigNumber::of($this->getSize($attribute, $value))->isLessThan($this->trim($parameters[0]));
  1133. } catch (MathException) {
  1134. return false;
  1135. }
  1136. }
  1137. if (is_numeric($parameters[0])) {
  1138. return false;
  1139. }
  1140. if ($this->hasRule($attribute, $this->numericRules) && is_numeric($value) && is_numeric($comparedToValue)) {
  1141. return BigNumber::of($this->trim($value))->isLessThan($this->trim($comparedToValue));
  1142. }
  1143. if (! $this->isSameType($value, $comparedToValue)) {
  1144. return false;
  1145. }
  1146. try {
  1147. return $this->getSize($attribute, $value) < $this->getSize($attribute, $comparedToValue);
  1148. } catch (MathException) {
  1149. return false;
  1150. }
  1151. }
  1152. /**
  1153. * Validate that an attribute is greater than or equal another attribute.
  1154. *
  1155. * @param string $attribute
  1156. * @param mixed $value
  1157. * @param array<int, int|string> $parameters
  1158. * @return bool
  1159. */
  1160. public function validateGte($attribute, $value, $parameters)
  1161. {
  1162. $this->requireParameterCount(1, $parameters, 'gte');
  1163. $comparedToValue = $this->getValue($parameters[0]);
  1164. $this->shouldBeNumeric($attribute, 'Gte');
  1165. if (is_null($comparedToValue) && (is_numeric($value) && is_numeric($parameters[0]))) {
  1166. try {
  1167. return BigNumber::of($this->getSize($attribute, $value))->isGreaterThanOrEqualTo($this->trim($parameters[0]));
  1168. } catch (MathException) {
  1169. return false;
  1170. }
  1171. }
  1172. if (is_numeric($parameters[0])) {
  1173. return false;
  1174. }
  1175. if ($this->hasRule($attribute, $this->numericRules) && is_numeric($value) && is_numeric($comparedToValue)) {
  1176. try {
  1177. return BigNumber::of($this->trim($value))->isGreaterThanOrEqualTo($this->trim($comparedToValue));
  1178. } catch (MathException) {
  1179. return false;
  1180. }
  1181. }
  1182. if (! $this->isSameType($value, $comparedToValue)) {
  1183. return false;
  1184. }
  1185. try {
  1186. return $this->getSize($attribute, $value) >= $this->getSize($attribute, $comparedToValue);
  1187. } catch (MathException) {
  1188. return false;
  1189. }
  1190. }
  1191. /**
  1192. * Validate that an attribute is less than or equal another attribute.
  1193. *
  1194. * @param string $attribute
  1195. * @param mixed $value
  1196. * @param array<int, int|string> $parameters
  1197. * @return bool
  1198. */
  1199. public function validateLte($attribute, $value, $parameters)
  1200. {
  1201. $this->requireParameterCount(1, $parameters, 'lte');
  1202. $comparedToValue = $this->getValue($parameters[0]);
  1203. $this->shouldBeNumeric($attribute, 'Lte');
  1204. if (is_null($comparedToValue) && (is_numeric($value) && is_numeric($parameters[0]))) {
  1205. try {
  1206. return BigNumber::of($this->getSize($attribute, $value))->isLessThanOrEqualTo($this->trim($parameters[0]));
  1207. } catch (MathException) {
  1208. return false;
  1209. }
  1210. }
  1211. if (is_numeric($parameters[0])) {
  1212. return false;
  1213. }
  1214. if ($this->hasRule($attribute, $this->numericRules) && is_numeric($value) && is_numeric($comparedToValue)) {
  1215. return BigNumber::of($this->trim($value))->isLessThanOrEqualTo($this->trim($comparedToValue));
  1216. }
  1217. if (! $this->isSameType($value, $comparedToValue)) {
  1218. return false;
  1219. }
  1220. try {
  1221. return $this->getSize($attribute, $value) <= $this->getSize($attribute, $comparedToValue);
  1222. } catch (MathException) {
  1223. return false;
  1224. }
  1225. }
  1226. /**
  1227. * Validate that an attribute is lowercase.
  1228. *
  1229. * @param string $attribute
  1230. * @param mixed $value
  1231. * @param array<int, int|string> $parameters
  1232. * @return bool
  1233. */
  1234. public function validateLowercase($attribute, $value, $parameters)
  1235. {
  1236. return Str::lower($value) === $value;
  1237. }
  1238. /**
  1239. * Validate that an attribute is uppercase.
  1240. *
  1241. * @param string $attribute
  1242. * @param mixed $value
  1243. * @param array<int, int|string> $parameters
  1244. * @return bool
  1245. */
  1246. public function validateUppercase($attribute, $value, $parameters)
  1247. {
  1248. return Str::upper($value) === $value;
  1249. }
  1250. /**
  1251. * Validate that an attribute is a valid HEX color.
  1252. *
  1253. * @param string $attribute
  1254. * @param mixed $value
  1255. * @return bool
  1256. */
  1257. public function validateHexColor($attribute, $value)
  1258. {
  1259. return preg_match('/^#(?:(?:[0-9a-f]{3}){1,2}|(?:[0-9a-f]{4}){1,2})$/i', $value) === 1;
  1260. }
  1261. /**
  1262. * Validate the MIME type of a file is an image MIME type.
  1263. *
  1264. * @param string $attribute
  1265. * @param mixed $value
  1266. * @param array<int, string> $parameters
  1267. * @return bool
  1268. */
  1269. public function validateImage($attribute, $value, $parameters = [])
  1270. {
  1271. $mimes = ['jpg', 'jpeg', 'png', 'gif', 'bmp', 'webp'];
  1272. if (is_array($parameters) && in_array('allow_svg', $parameters)) {
  1273. $mimes[] = 'svg';
  1274. }
  1275. return $this->validateMimes($attribute, $value, $mimes);
  1276. }
  1277. /**
  1278. * Validate an attribute is contained within a list of values.
  1279. *
  1280. * @param string $attribute
  1281. * @param mixed $value
  1282. * @param array<int, int|string> $parameters
  1283. * @return bool
  1284. */
  1285. public function validateIn($attribute, $value, $parameters)
  1286. {
  1287. if (is_array($value) && $this->hasRule($attribute, 'Array')) {
  1288. foreach ($value as $element) {
  1289. if (is_array($element)) {
  1290. return false;
  1291. }
  1292. }
  1293. return count(array_diff($value, $parameters)) === 0;
  1294. }
  1295. return ! is_array($value) && in_array((string) $value, $parameters);
  1296. }
  1297. /**
  1298. * Validate that the values of an attribute are in another attribute.
  1299. *
  1300. * @param string $attribute
  1301. * @param mixed $value
  1302. * @param array<int, int|string> $parameters
  1303. * @return bool
  1304. */
  1305. public function validateInArray($attribute, $value, $parameters)
  1306. {
  1307. $this->requireParameterCount(1, $parameters, 'in_array');
  1308. $explicitPath = ValidationData::getLeadingExplicitAttributePath($parameters[0]);
  1309. $attributeData = ValidationData::extractDataFromPath($explicitPath, $this->data);
  1310. $otherValues = Arr::where(Arr::dot($attributeData), function ($value, $key) use ($parameters) {
  1311. return Str::is($parameters[0], $key);
  1312. });
  1313. return in_array($value, $otherValues);
  1314. }
  1315. /**
  1316. * Validate that an array has at least one of the given keys.
  1317. *
  1318. * @param string $attribute
  1319. * @param mixed $value
  1320. * @param array<int, int|string> $parameters
  1321. * @return bool
  1322. */
  1323. public function validateInArrayKeys($attribute, $value, $parameters)
  1324. {
  1325. if (! is_array($value)) {
  1326. return false;
  1327. }
  1328. if (empty($parameters)) {
  1329. return false;
  1330. }
  1331. foreach ($parameters as $param) {
  1332. if (Arr::exists($value, $param)) {
  1333. return true;
  1334. }
  1335. }
  1336. return false;
  1337. }
  1338. /**
  1339. * Validate that an attribute is an integer.
  1340. *
  1341. * @param string $attribute
  1342. * @param mixed $value
  1343. * @param array{0?: 'strict'} $parameters
  1344. * @return bool
  1345. */
  1346. public function validateInteger($attribute, $value, array $parameters = [])
  1347. {
  1348. if (($parameters[0] ?? null) === 'strict') {
  1349. return is_int($value);
  1350. }
  1351. return filter_var($value, FILTER_VALIDATE_INT) !== false;
  1352. }
  1353. /**
  1354. * Validate that an attribute is a valid IP.
  1355. *
  1356. * @param string $attribute
  1357. * @param mixed $value
  1358. * @return bool
  1359. */
  1360. public function validateIp($attribute, $value)
  1361. {
  1362. return filter_var($value, FILTER_VALIDATE_IP) !== false;
  1363. }
  1364. /**
  1365. * Validate that an attribute is a valid IPv4.
  1366. *
  1367. * @param string $attribute
  1368. * @param mixed $value
  1369. * @return bool
  1370. */
  1371. public function validateIpv4($attribute, $value)
  1372. {
  1373. return filter_var($value, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4) !== false;
  1374. }
  1375. /**
  1376. * Validate that an attribute is a valid IPv6.
  1377. *
  1378. * @param string $attribute
  1379. * @param mixed $value
  1380. * @return bool
  1381. */
  1382. public function validateIpv6($attribute, $value)
  1383. {
  1384. return filter_var($value, FILTER_VALIDATE_IP, FILTER_FLAG_IPV6) !== false;
  1385. }
  1386. /**
  1387. * Validate that an attribute is a valid MAC address.
  1388. *
  1389. * @param string $attribute
  1390. * @param mixed $value
  1391. * @return bool
  1392. */
  1393. public function validateMacAddress($attribute, $value)
  1394. {
  1395. return filter_var($value, FILTER_VALIDATE_MAC) !== false;
  1396. }
  1397. /**
  1398. * Validate the attribute is a valid JSON string.
  1399. *
  1400. * @param string $attribute
  1401. * @param mixed $value
  1402. * @return bool
  1403. */
  1404. public function validateJson($attribute, $value)
  1405. {
  1406. if (is_array($value) || is_null($value)) {
  1407. return false;
  1408. }
  1409. if (! is_scalar($value) && ! method_exists($value, '__toString')) {
  1410. return false;
  1411. }
  1412. return json_validate($value);
  1413. }
  1414. /**
  1415. * Validate the size of an attribute is less than or equal to a maximum value.
  1416. *
  1417. * @param string $attribute
  1418. * @param mixed $value
  1419. * @param array<int, int|string> $parameters
  1420. * @return bool
  1421. */
  1422. public function validateMax($attribute, $value, $parameters)
  1423. {
  1424. $this->requireParameterCount(1, $parameters, 'max');
  1425. if ($value instanceof UploadedFile && ! $value->isValid()) {
  1426. return false;
  1427. }
  1428. try {
  1429. return BigNumber::of($this->getSize($attribute, $value))->isLessThanOrEqualTo($this->trim($parameters[0]));
  1430. } catch (MathException) {
  1431. return false;
  1432. }
  1433. }
  1434. /**
  1435. * Validate that an attribute has a maximum number of digits.
  1436. *
  1437. * @param string $attribute
  1438. * @param mixed $value
  1439. * @param array<int, int|string> $parameters
  1440. * @return bool
  1441. */
  1442. public function validateMaxDigits($attribute, $value, $parameters)
  1443. {
  1444. $this->requireParameterCount(1, $parameters, 'max_digits');
  1445. $length = strlen((string) $value);
  1446. return ! preg_match('/[^0-9]/', $value) && $length <= $parameters[0];
  1447. }
  1448. /**
  1449. * Validate the guessed extension of a file upload is in a set of file extensions.
  1450. *
  1451. * @param string $attribute
  1452. * @param mixed $value
  1453. * @param array<int, int|string> $parameters
  1454. * @return bool
  1455. */
  1456. public function validateMimes($attribute, $value, $parameters)
  1457. {
  1458. if (! $this->isValidFileInstance($value)) {
  1459. return false;
  1460. }
  1461. if ($this->shouldBlockPhpUpload($value, $parameters)) {
  1462. return false;
  1463. }
  1464. if (in_array('jpg', $parameters) || in_array('jpeg', $parameters)) {
  1465. $parameters = array_unique(array_merge($parameters, ['jpg', 'jpeg']));
  1466. }
  1467. return $value->getPath() !== '' && in_array($value->guessExtension(), $parameters);
  1468. }
  1469. /**
  1470. * Validate the MIME type of a file upload attribute is in a set of MIME types.
  1471. *
  1472. * @param string $attribute
  1473. * @param mixed $value
  1474. * @param array<int, int|string> $parameters
  1475. * @return bool
  1476. */
  1477. public function validateMimetypes($attribute, $value, $parameters)
  1478. {
  1479. if (! $this->isValidFileInstance($value)) {
  1480. return false;
  1481. }
  1482. if ($this->shouldBlockPhpUpload($value, $parameters)) {
  1483. return false;
  1484. }
  1485. return $value->getPath() !== '' &&
  1486. (in_array($value->getMimeType(), $parameters) ||
  1487. in_array(explode('/', $value->getMimeType())[0].'/*', $parameters));
  1488. }
  1489. /**
  1490. * Check if PHP uploads are explicitly allowed.
  1491. *
  1492. * @param mixed $value
  1493. * @param array<int, int|string> $parameters
  1494. * @return bool
  1495. */
  1496. protected function shouldBlockPhpUpload($value, $parameters)
  1497. {
  1498. if (in_array('php', $parameters)) {
  1499. return false;
  1500. }
  1501. $phpExtensions = [
  1502. 'php', 'php3', 'php4', 'php5', 'php7', 'php8', 'phtml', 'phar',
  1503. ];
  1504. return ($value instanceof UploadedFile)
  1505. ? in_array(trim(strtolower($value->getClientOriginalExtension())), $phpExtensions)
  1506. : in_array(trim(strtolower($value->getExtension())), $phpExtensions);
  1507. }
  1508. /**
  1509. * Validate the size of an attribute is greater than or equal to a minimum value.
  1510. *
  1511. * @param string $attribute
  1512. * @param mixed $value
  1513. * @param array<int, int|string> $parameters
  1514. * @return bool
  1515. */
  1516. public function validateMin($attribute, $value, $parameters)
  1517. {
  1518. $this->requireParameterCount(1, $parameters, 'min');
  1519. try {
  1520. return BigNumber::of($this->getSize($attribute, $value))->isGreaterThanOrEqualTo($this->trim($parameters[0]));
  1521. } catch (MathException) {
  1522. return false;
  1523. }
  1524. }
  1525. /**
  1526. * Validate that an attribute has a minimum number of digits.
  1527. *
  1528. * @param string $attribute
  1529. * @param mixed $value
  1530. * @param array<int, int|string> $parameters
  1531. * @return bool
  1532. */
  1533. public function validateMinDigits($attribute, $value, $parameters)
  1534. {
  1535. $this->requireParameterCount(1, $parameters, 'min_digits');
  1536. $length = strlen((string) $value);
  1537. return ! preg_match('/[^0-9]/', $value) && $length >= $parameters[0];
  1538. }
  1539. /**
  1540. * Validate that an attribute is missing.
  1541. *
  1542. * @param string $attribute
  1543. * @param mixed $value
  1544. * @param array<int, int|string> $parameters
  1545. * @return bool
  1546. */
  1547. public function validateMissing($attribute, $value, $parameters)
  1548. {
  1549. return ! Arr::has($this->data, $attribute);
  1550. }
  1551. /**
  1552. * Validate that an attribute is missing when another attribute has a given value.
  1553. *
  1554. * @param string $attribute
  1555. * @param mixed $value
  1556. * @param array<int, int|string> $parameters
  1557. * @return bool
  1558. */
  1559. public function validateMissingIf($attribute, $value, $parameters)
  1560. {
  1561. $this->requireParameterCount(2, $parameters, 'missing_if');
  1562. [$values, $other] = $this->parseDependentRuleParameters($parameters);
  1563. if (in_array($other, $values, is_bool($other) || is_null($other))) {
  1564. return $this->validateMissing($attribute, $value, $parameters);
  1565. }
  1566. return true;
  1567. }
  1568. /**
  1569. * Validate that an attribute is missing unless another attribute has a given value.
  1570. *
  1571. * @param string $attribute
  1572. * @param mixed $value
  1573. * @param array<int, int|string> $parameters
  1574. * @return bool
  1575. */
  1576. public function validateMissingUnless($attribute, $value, $parameters)
  1577. {
  1578. $this->requireParameterCount(2, $parameters, 'missing_unless');
  1579. [$values, $other] = $this->parseDependentRuleParameters($parameters);
  1580. if (! in_array($other, $values, is_bool($other) || is_null($other))) {
  1581. return $this->validateMissing($attribute, $value, $parameters);
  1582. }
  1583. return true;
  1584. }
  1585. /**
  1586. * Validate that an attribute is missing when any given attribute is present.
  1587. *
  1588. * @param string $attribute
  1589. * @param mixed $value
  1590. * @param array<int, int|string> $parameters
  1591. * @return bool
  1592. */
  1593. public function validateMissingWith($attribute, $value, $parameters)
  1594. {
  1595. $this->requireParameterCount(1, $parameters, 'missing_with');
  1596. if (Arr::hasAny($this->data, $parameters)) {
  1597. return $this->validateMissing($attribute, $value, $parameters);
  1598. }
  1599. return true;
  1600. }
  1601. /**
  1602. * Validate that an attribute is missing when all given attributes are present.
  1603. *
  1604. * @param string $attribute
  1605. * @param mixed $value
  1606. * @param array<int, int|string> $parameters
  1607. * @return bool
  1608. */
  1609. public function validateMissingWithAll($attribute, $value, $parameters)
  1610. {
  1611. $this->requireParameterCount(1, $parameters, 'missing_with_all');
  1612. if (Arr::has($this->data, $parameters)) {
  1613. return $this->validateMissing($attribute, $value, $parameters);
  1614. }
  1615. return true;
  1616. }
  1617. /**
  1618. * Validate the value of an attribute is a multiple of a given value.
  1619. *
  1620. * @param string $attribute
  1621. * @param mixed $value
  1622. * @param array<int, int|string> $parameters
  1623. * @return bool
  1624. */
  1625. public function validateMultipleOf($attribute, $value, $parameters)
  1626. {
  1627. $this->requireParameterCount(1, $parameters, 'multiple_of');
  1628. if (! $this->validateNumeric($attribute, $value, []) || ! $this->validateNumeric($attribute, $parameters[0], [])) {
  1629. return false;
  1630. }
  1631. try {
  1632. $numerator = BigDecimal::of($this->trim($value));
  1633. $denominator = BigDecimal::of($this->trim($parameters[0]));
  1634. if ($numerator->isZero() && $denominator->isZero()) {
  1635. return false;
  1636. }
  1637. if ($numerator->isZero()) {
  1638. return true;
  1639. }
  1640. if ($denominator->isZero()) {
  1641. return false;
  1642. }
  1643. return $numerator->remainder($denominator)->isZero();
  1644. } catch (BrickMathException $e) {
  1645. throw new MathException('An error occurred while handling the multiple_of input values.', previous: $e);
  1646. }
  1647. }
  1648. /**
  1649. * "Indicate" validation should pass if value is null.
  1650. *
  1651. * Always returns true, just lets us put "nullable" in rules.
  1652. *
  1653. * @return bool
  1654. */
  1655. public function validateNullable()
  1656. {
  1657. return true;
  1658. }
  1659. /**
  1660. * Validate an attribute is not contained within a list of values.
  1661. *
  1662. * @param string $attribute
  1663. * @param mixed $value
  1664. * @param array<int, int|string> $parameters
  1665. * @return bool
  1666. */
  1667. public function validateNotIn($attribute, $value, $parameters)
  1668. {
  1669. return ! $this->validateIn($attribute, $value, $parameters);
  1670. }
  1671. /**
  1672. * Validate that an attribute is numeric.
  1673. *
  1674. * @param string $attribute
  1675. * @param mixed $value
  1676. * @param array{0: 'strict'} $parameters
  1677. * @return bool
  1678. */
  1679. public function validateNumeric($attribute, $value, array $parameters)
  1680. {
  1681. if (($parameters[0] ?? null) === 'strict' && is_string($value)) {
  1682. return false;
  1683. }
  1684. return is_numeric($value);
  1685. }
  1686. /**
  1687. * Validate that an attribute exists even if not filled.
  1688. *
  1689. * @param string $attribute
  1690. * @param mixed $value
  1691. * @return bool
  1692. */
  1693. public function validatePresent($attribute, $value)
  1694. {
  1695. return Arr::has($this->data, $attribute);
  1696. }
  1697. /**
  1698. * Validate that an attribute is present when another attribute has a given value.
  1699. *
  1700. * @param string $attribute
  1701. * @param mixed $value
  1702. * @param array<int, int|string> $parameters
  1703. * @return bool
  1704. */
  1705. public function validatePresentIf($attribute, $value, $parameters)
  1706. {
  1707. $this->requireParameterCount(2, $parameters, 'present_if');
  1708. [$values, $other] = $this->parseDependentRuleParameters($parameters);
  1709. if (in_array($other, $values, is_bool($other) || is_null($other))) {
  1710. return $this->validatePresent($attribute, $value);
  1711. }
  1712. return true;
  1713. }
  1714. /**
  1715. * Validate that an attribute is present unless another attribute has a given value.
  1716. *
  1717. * @param string $attribute
  1718. * @param mixed $value
  1719. * @param array<int, int|string> $parameters
  1720. * @return bool
  1721. */
  1722. public function validatePresentUnless($attribute, $value, $parameters)
  1723. {
  1724. $this->requireParameterCount(2, $parameters, 'present_unless');
  1725. [$values, $other] = $this->parseDependentRuleParameters($parameters);
  1726. if (! in_array($other, $values, is_bool($other) || is_null($other))) {
  1727. return $this->validatePresent($attribute, $value);
  1728. }
  1729. return true;
  1730. }
  1731. /**
  1732. * Validate that an attribute is present when any given attribute is present.
  1733. *
  1734. * @param string $attribute
  1735. * @param mixed $value
  1736. * @param array<int, int|string> $parameters
  1737. * @return bool
  1738. */
  1739. public function validatePresentWith($attribute, $value, $parameters)
  1740. {
  1741. $this->requireParameterCount(1, $parameters, 'present_with');
  1742. if (Arr::hasAny($this->data, $parameters)) {
  1743. return $this->validatePresent($attribute, $value);
  1744. }
  1745. return true;
  1746. }
  1747. /**
  1748. * Validate that an attribute is present when all given attributes are present.
  1749. *
  1750. * @param string $attribute
  1751. * @param mixed $value
  1752. * @param array<int, int|string> $parameters
  1753. * @return bool
  1754. */
  1755. public function validatePresentWithAll($attribute, $value, $parameters)
  1756. {
  1757. $this->requireParameterCount(1, $parameters, 'present_with_all');
  1758. if (Arr::has($this->data, $parameters)) {
  1759. return $this->validatePresent($attribute, $value);
  1760. }
  1761. return true;
  1762. }
  1763. /**
  1764. * Validate that an attribute passes a regular expression check.
  1765. *
  1766. * @param string $attribute
  1767. * @param mixed $value
  1768. * @param array<int, int|string> $parameters
  1769. * @return bool
  1770. */
  1771. public function validateRegex($attribute, $value, $parameters)
  1772. {
  1773. if (! is_string($value) && ! is_numeric($value)) {
  1774. return false;
  1775. }
  1776. $this->requireParameterCount(1, $parameters, 'regex');
  1777. return preg_match($parameters[0], $value) > 0;
  1778. }
  1779. /**
  1780. * Validate that an attribute does not pass a regular expression check.
  1781. *
  1782. * @param string $attribute
  1783. * @param mixed $value
  1784. * @param array<int, int|string> $parameters
  1785. * @return bool
  1786. */
  1787. public function validateNotRegex($attribute, $value, $parameters)
  1788. {
  1789. if (! is_string($value) && ! is_numeric($value)) {
  1790. return false;
  1791. }
  1792. $this->requireParameterCount(1, $parameters, 'not_regex');
  1793. return preg_match($parameters[0], $value) < 1;
  1794. }
  1795. /**
  1796. * Validate that a required attribute exists.
  1797. *
  1798. * @param string $attribute
  1799. * @param mixed $value
  1800. * @return bool
  1801. */
  1802. public function validateRequired($attribute, $value)
  1803. {
  1804. if (is_null($value)) {
  1805. return false;
  1806. } elseif (is_string($value) && trim($value) === '') {
  1807. return false;
  1808. } elseif (is_countable($value) && count($value) < 1) {
  1809. return false;
  1810. } elseif ($value instanceof File) {
  1811. return (string) $value->getPath() !== '';
  1812. }
  1813. return true;
  1814. }
  1815. /**
  1816. * Validate that an attribute exists when another attribute has a given value.
  1817. *
  1818. * @param string $attribute
  1819. * @param mixed $value
  1820. * @param mixed $parameters
  1821. * @return bool
  1822. */
  1823. public function validateRequiredIf($attribute, $value, $parameters)
  1824. {
  1825. $this->requireParameterCount(2, $parameters, 'required_if');
  1826. if (! Arr::has($this->data, $parameters[0])) {
  1827. return true;
  1828. }
  1829. [$values, $other] = $this->parseDependentRuleParameters($parameters);
  1830. if (in_array($other, $values, is_bool($other) || is_null($other))) {
  1831. return $this->validateRequired($attribute, $value);
  1832. }
  1833. return true;
  1834. }
  1835. /**
  1836. * Validate that an attribute exists when another attribute was "accepted".
  1837. *
  1838. * @param string $attribute
  1839. * @param mixed $value
  1840. * @param mixed $parameters
  1841. * @return bool
  1842. */
  1843. public function validateRequiredIfAccepted($attribute, $value, $parameters)
  1844. {
  1845. $this->requireParameterCount(1, $parameters, 'required_if_accepted');
  1846. if ($this->validateAccepted($parameters[0], $this->getValue($parameters[0]))) {
  1847. return $this->validateRequired($attribute, $value);
  1848. }
  1849. return true;
  1850. }
  1851. /**
  1852. * Validate that an attribute exists when another attribute was "declined".
  1853. *
  1854. * @param string $attribute
  1855. * @param mixed $value
  1856. * @param mixed $parameters
  1857. * @return bool
  1858. */
  1859. public function validateRequiredIfDeclined($attribute, $value, $parameters)
  1860. {
  1861. $this->requireParameterCount(1, $parameters, 'required_if_declined');
  1862. if ($this->validateDeclined($parameters[0], $this->getValue($parameters[0]))) {
  1863. return $this->validateRequired($attribute, $value);
  1864. }
  1865. return true;
  1866. }
  1867. /**
  1868. * Validate that an attribute does not exist or is an empty string.
  1869. *
  1870. * @param string $attribute
  1871. * @param mixed $value
  1872. * @return bool
  1873. */
  1874. public function validateProhibited($attribute, $value)
  1875. {
  1876. return ! $this->validateRequired($attribute, $value);
  1877. }
  1878. /**
  1879. * Validate that an attribute does not exist when another attribute has a given value.
  1880. *
  1881. * @param string $attribute
  1882. * @param mixed $value
  1883. * @param mixed $parameters
  1884. * @return bool
  1885. */
  1886. public function validateProhibitedIf($attribute, $value, $parameters)
  1887. {
  1888. $this->requireParameterCount(2, $parameters, 'prohibited_if');
  1889. [$values, $other] = $this->parseDependentRuleParameters($parameters);
  1890. if (in_array($other, $values, is_bool($other) || is_null($other))) {
  1891. return ! $this->validateRequired($attribute, $value);
  1892. }
  1893. return true;
  1894. }
  1895. /**
  1896. * Validate that an attribute does not exist when another attribute was "accepted".
  1897. *
  1898. * @param string $attribute
  1899. * @param mixed $value
  1900. * @param mixed $parameters
  1901. * @return bool
  1902. */
  1903. public function validateProhibitedIfAccepted($attribute, $value, $parameters)
  1904. {
  1905. $this->requireParameterCount(1, $parameters, 'prohibited_if_accepted');
  1906. if ($this->validateAccepted($parameters[0], $this->getValue($parameters[0]))) {
  1907. return $this->validateProhibited($attribute, $value);
  1908. }
  1909. return true;
  1910. }
  1911. /**
  1912. * Validate that an attribute does not exist when another attribute was "declined".
  1913. *
  1914. * @param string $attribute
  1915. * @param mixed $value
  1916. * @param mixed $parameters
  1917. * @return bool
  1918. */
  1919. public function validateProhibitedIfDeclined($attribute, $value, $parameters)
  1920. {
  1921. $this->requireParameterCount(1, $parameters, 'prohibited_if_declined');
  1922. if ($this->validateDeclined($parameters[0], $this->getValue($parameters[0]))) {
  1923. return $this->validateProhibited($attribute, $value);
  1924. }
  1925. return true;
  1926. }
  1927. /**
  1928. * Validate that an attribute does not exist unless another attribute has a given value.
  1929. *
  1930. * @param string $attribute
  1931. * @param mixed $value
  1932. * @param mixed $parameters
  1933. * @return bool
  1934. */
  1935. public function validateProhibitedUnless($attribute, $value, $parameters)
  1936. {
  1937. $this->requireParameterCount(2, $parameters, 'prohibited_unless');
  1938. [$values, $other] = $this->parseDependentRuleParameters($parameters);
  1939. if (! in_array($other, $values, is_bool($other) || is_null($other))) {
  1940. return ! $this->validateRequired($attribute, $value);
  1941. }
  1942. return true;
  1943. }
  1944. /**
  1945. * Validate that other attributes do not exist when this attribute exists.
  1946. *
  1947. * @param string $attribute
  1948. * @param mixed $value
  1949. * @param mixed $parameters
  1950. * @return bool
  1951. */
  1952. public function validateProhibits($attribute, $value, $parameters)
  1953. {
  1954. if ($this->validateRequired($attribute, $value)) {
  1955. foreach ($parameters as $parameter) {
  1956. if ($this->validateRequired($parameter, Arr::get($this->data, $parameter))) {
  1957. return false;
  1958. }
  1959. }
  1960. }
  1961. return true;
  1962. }
  1963. /**
  1964. * Indicate that an attribute is excluded.
  1965. *
  1966. * @return bool
  1967. */
  1968. public function validateExclude()
  1969. {
  1970. return false;
  1971. }
  1972. /**
  1973. * Indicate that an attribute should be excluded when another attribute has a given value.
  1974. *
  1975. * @param string $attribute
  1976. * @param mixed $value
  1977. * @param mixed $parameters
  1978. * @return bool
  1979. */
  1980. public function validateExcludeIf($attribute, $value, $parameters)
  1981. {
  1982. $this->requireParameterCount(2, $parameters, 'exclude_if');
  1983. if (! Arr::has($this->data, $parameters[0])) {
  1984. return true;
  1985. }
  1986. [$values, $other] = $this->parseDependentRuleParameters($parameters);
  1987. return ! in_array($other, $values, is_bool($other) || is_null($other));
  1988. }
  1989. /**
  1990. * Indicate that an attribute should be excluded when another attribute does not have a given value.
  1991. *
  1992. * @param string $attribute
  1993. * @param mixed $value
  1994. * @param mixed $parameters
  1995. * @return bool
  1996. */
  1997. public function validateExcludeUnless($attribute, $value, $parameters)
  1998. {
  1999. $this->requireParameterCount(2, $parameters, 'exclude_unless');
  2000. [$values, $other] = $this->parseDependentRuleParameters($parameters);
  2001. return in_array($other, $values, is_bool($other) || is_null($other));
  2002. }
  2003. /**
  2004. * Validate that an attribute exists when another attribute does not have a given value.
  2005. *
  2006. * @param string $attribute
  2007. * @param mixed $value
  2008. * @param mixed $parameters
  2009. * @return bool
  2010. */
  2011. public function validateRequiredUnless($attribute, $value, $parameters)
  2012. {
  2013. $this->requireParameterCount(2, $parameters, 'required_unless');
  2014. [$values, $other] = $this->parseDependentRuleParameters($parameters);
  2015. if (! in_array($other, $values, is_bool($other) || is_null($other))) {
  2016. return $this->validateRequired($attribute, $value);
  2017. }
  2018. return true;
  2019. }
  2020. /**
  2021. * Indicate that an attribute should be excluded when another attribute presents.
  2022. *
  2023. * @param string $attribute
  2024. * @param mixed $value
  2025. * @param mixed $parameters
  2026. * @return bool
  2027. */
  2028. public function validateExcludeWith($attribute, $value, $parameters)
  2029. {
  2030. $this->requireParameterCount(1, $parameters, 'exclude_with');
  2031. if (! Arr::has($this->data, $parameters[0])) {
  2032. return true;
  2033. }
  2034. return false;
  2035. }
  2036. /**
  2037. * Indicate that an attribute should be excluded when another attribute is missing.
  2038. *
  2039. * @param string $attribute
  2040. * @param mixed $value
  2041. * @param mixed $parameters
  2042. * @return bool
  2043. */
  2044. public function validateExcludeWithout($attribute, $value, $parameters)
  2045. {
  2046. $this->requireParameterCount(1, $parameters, 'exclude_without');
  2047. if ($this->anyFailingRequired($parameters)) {
  2048. return false;
  2049. }
  2050. return true;
  2051. }
  2052. /**
  2053. * Prepare the values and the other value for validation.
  2054. *
  2055. * @param array<int, int|string> $parameters
  2056. * @return array
  2057. */
  2058. public function parseDependentRuleParameters($parameters)
  2059. {
  2060. $other = Arr::get($this->data, $parameters[0]);
  2061. $values = array_slice($parameters, 1);
  2062. if ($this->shouldConvertToBoolean($parameters[0]) || is_bool($other)) {
  2063. $values = $this->convertValuesToBoolean($values);
  2064. }
  2065. if (is_null($other)) {
  2066. $values = $this->convertValuesToNull($values);
  2067. }
  2068. return [$values, $other];
  2069. }
  2070. /**
  2071. * Check if parameter should be converted to boolean.
  2072. *
  2073. * @param string $parameter
  2074. * @return bool
  2075. */
  2076. protected function shouldConvertToBoolean($parameter)
  2077. {
  2078. return in_array('boolean', $this->rules[$parameter] ?? []);
  2079. }
  2080. /**
  2081. * Convert the given values to boolean if they are string "true" / "false".
  2082. *
  2083. * @param array $values
  2084. * @return array
  2085. */
  2086. protected function convertValuesToBoolean($values)
  2087. {
  2088. return array_map(fn ($value) => match ($value) {
  2089. 'true' => true,
  2090. 'false' => false,
  2091. default => $value,
  2092. }, $values);
  2093. }
  2094. /**
  2095. * Convert the given values to null if they are string "null".
  2096. *
  2097. * @param array $values
  2098. * @return array
  2099. */
  2100. protected function convertValuesToNull($values)
  2101. {
  2102. return array_map(function ($value) {
  2103. return Str::lower($value) === 'null' ? null : $value;
  2104. }, $values);
  2105. }
  2106. /**
  2107. * Validate that an attribute exists when any other attribute exists.
  2108. *
  2109. * @param string $attribute
  2110. * @param mixed $value
  2111. * @param mixed $parameters
  2112. * @return bool
  2113. */
  2114. public function validateRequiredWith($attribute, $value, $parameters)
  2115. {
  2116. if (! $this->allFailingRequired($parameters)) {
  2117. return $this->validateRequired($attribute, $value);
  2118. }
  2119. return true;
  2120. }
  2121. /**
  2122. * Validate that an attribute exists when all other attributes exist.
  2123. *
  2124. * @param string $attribute
  2125. * @param mixed $value
  2126. * @param mixed $parameters
  2127. * @return bool
  2128. */
  2129. public function validateRequiredWithAll($attribute, $value, $parameters)
  2130. {
  2131. if (! $this->anyFailingRequired($parameters)) {
  2132. return $this->validateRequired($attribute, $value);
  2133. }
  2134. return true;
  2135. }
  2136. /**
  2137. * Validate that an attribute exists when another attribute does not.
  2138. *
  2139. * @param string $attribute
  2140. * @param mixed $value
  2141. * @param mixed $parameters
  2142. * @return bool
  2143. */
  2144. public function validateRequiredWithout($attribute, $value, $parameters)
  2145. {
  2146. if ($this->anyFailingRequired($parameters)) {
  2147. return $this->validateRequired($attribute, $value);
  2148. }
  2149. return true;
  2150. }
  2151. /**
  2152. * Validate that an attribute exists when all other attributes do not.
  2153. *
  2154. * @param string $attribute
  2155. * @param mixed $value
  2156. * @param mixed $parameters
  2157. * @return bool
  2158. */
  2159. public function validateRequiredWithoutAll($attribute, $value, $parameters)
  2160. {
  2161. if ($this->allFailingRequired($parameters)) {
  2162. return $this->validateRequired($attribute, $value);
  2163. }
  2164. return true;
  2165. }
  2166. /**
  2167. * Determine if any of the given attributes fail the required test.
  2168. *
  2169. * @param array $attributes
  2170. * @return bool
  2171. */
  2172. protected function anyFailingRequired(array $attributes)
  2173. {
  2174. foreach ($attributes as $key) {
  2175. if (! $this->validateRequired($key, $this->getValue($key))) {
  2176. return true;
  2177. }
  2178. }
  2179. return false;
  2180. }
  2181. /**
  2182. * Determine if all of the given attributes fail the required test.
  2183. *
  2184. * @param array $attributes
  2185. * @return bool
  2186. */
  2187. protected function allFailingRequired(array $attributes)
  2188. {
  2189. foreach ($attributes as $key) {
  2190. if ($this->validateRequired($key, $this->getValue($key))) {
  2191. return false;
  2192. }
  2193. }
  2194. return true;
  2195. }
  2196. /**
  2197. * Validate that two attributes match.
  2198. *
  2199. * @param string $attribute
  2200. * @param mixed $value
  2201. * @param array<int, int|string> $parameters
  2202. * @return bool
  2203. */
  2204. public function validateSame($attribute, $value, $parameters)
  2205. {
  2206. $this->requireParameterCount(1, $parameters, 'same');
  2207. $other = Arr::get($this->data, $parameters[0]);
  2208. return $value === $other;
  2209. }
  2210. /**
  2211. * Validate the size of an attribute.
  2212. *
  2213. * @param string $attribute
  2214. * @param mixed $value
  2215. * @param array<int, int|string> $parameters
  2216. * @return bool
  2217. */
  2218. public function validateSize($attribute, $value, $parameters)
  2219. {
  2220. $this->requireParameterCount(1, $parameters, 'size');
  2221. try {
  2222. return BigNumber::of($this->getSize($attribute, $value))->isEqualTo($this->trim($parameters[0]));
  2223. } catch (MathException) {
  2224. return false;
  2225. }
  2226. }
  2227. /**
  2228. * "Validate" optional attributes.
  2229. *
  2230. * Always returns true, just lets us put sometimes in rules.
  2231. *
  2232. * @return bool
  2233. */
  2234. public function validateSometimes()
  2235. {
  2236. return true;
  2237. }
  2238. /**
  2239. * Validate the attribute starts with a given substring.
  2240. *
  2241. * @param string $attribute
  2242. * @param mixed $value
  2243. * @param array<int, int|string> $parameters
  2244. * @return bool
  2245. */
  2246. public function validateStartsWith($attribute, $value, $parameters)
  2247. {
  2248. return Str::startsWith($value, $parameters);
  2249. }
  2250. /**
  2251. * Validate the attribute does not start with a given substring.
  2252. *
  2253. * @param string $attribute
  2254. * @param mixed $value
  2255. * @param array<int, int|string> $parameters
  2256. * @return bool
  2257. */
  2258. public function validateDoesntStartWith($attribute, $value, $parameters)
  2259. {
  2260. return ! Str::startsWith($value, $parameters);
  2261. }
  2262. /**
  2263. * Validate the attribute ends with a given substring.
  2264. *
  2265. * @param string $attribute
  2266. * @param mixed $value
  2267. * @param array<int, int|string> $parameters
  2268. * @return bool
  2269. */
  2270. public function validateEndsWith($attribute, $value, $parameters)
  2271. {
  2272. return Str::endsWith($value, $parameters);
  2273. }
  2274. /**
  2275. * Validate the attribute does not end with a given substring.
  2276. *
  2277. * @param string $attribute
  2278. * @param mixed $value
  2279. * @param array<int, int|string> $parameters
  2280. * @return bool
  2281. */
  2282. public function validateDoesntEndWith($attribute, $value, $parameters)
  2283. {
  2284. return ! Str::endsWith($value, $parameters);
  2285. }
  2286. /**
  2287. * Validate that an attribute is a string.
  2288. *
  2289. * @param string $attribute
  2290. * @param mixed $value
  2291. * @return bool
  2292. */
  2293. public function validateString($attribute, $value)
  2294. {
  2295. return is_string($value);
  2296. }
  2297. /**
  2298. * Validate that an attribute is a valid timezone.
  2299. *
  2300. * @param string $attribute
  2301. * @param mixed $value
  2302. * @param array<string, null|string> $parameters
  2303. * @return bool
  2304. */
  2305. public function validateTimezone($attribute, $value, $parameters = [])
  2306. {
  2307. return in_array($value, timezone_identifiers_list(
  2308. constant(DateTimeZone::class.'::'.Str::upper($parameters[0] ?? 'ALL')),
  2309. isset($parameters[1]) ? Str::upper($parameters[1]) : null,
  2310. ), true);
  2311. }
  2312. /**
  2313. * Validate that an attribute is a valid URL.
  2314. *
  2315. * @param string $attribute
  2316. * @param mixed $value
  2317. * @param array<int, string> $parameters
  2318. * @return bool
  2319. */
  2320. public function validateUrl($attribute, $value, $parameters = [])
  2321. {
  2322. return Str::isUrl($value, $parameters);
  2323. }
  2324. /**
  2325. * Validate that an attribute is a valid ULID.
  2326. *
  2327. * @param string $attribute
  2328. * @param mixed $value
  2329. * @return bool
  2330. */
  2331. public function validateUlid($attribute, $value)
  2332. {
  2333. return Str::isUlid($value);
  2334. }
  2335. /**
  2336. * Validate that an attribute is a valid UUID.
  2337. *
  2338. * @param string $attribute
  2339. * @param mixed $value
  2340. * @param array<int, int<0, 8>|'max'> $parameters
  2341. * @return bool
  2342. */
  2343. public function validateUuid($attribute, $value, $parameters)
  2344. {
  2345. $version = null;
  2346. if ($parameters !== null && count($parameters) === 1) {
  2347. $version = $parameters[0];
  2348. if ($version !== 'max') {
  2349. $version = (int) $parameters[0];
  2350. }
  2351. }
  2352. return Str::isUuid($value, $version);
  2353. }
  2354. /**
  2355. * Get the size of an attribute.
  2356. *
  2357. * @param string $attribute
  2358. * @param mixed $value
  2359. * @return int|string
  2360. */
  2361. protected function getSize($attribute, $value)
  2362. {
  2363. $hasNumeric = $this->hasRule($attribute, $this->numericRules);
  2364. // This method will determine if the attribute is a number, string, or file and
  2365. // return the proper size accordingly. If it is a number, then number itself
  2366. // is the size. If it is a file, we take kilobytes, and for a string the
  2367. // entire length of the string will be considered the attribute size.
  2368. if (is_numeric($value) && $hasNumeric) {
  2369. return (string) $this->ensureExponentWithinAllowedRange($attribute, $this->trim($value));
  2370. } elseif (is_array($value)) {
  2371. return count($value);
  2372. } elseif ($value instanceof File) {
  2373. return (string) ($value->getSize() / 1024);
  2374. }
  2375. return mb_strlen($value ?? '');
  2376. }
  2377. /**
  2378. * Check that the given value is a valid file instance.
  2379. *
  2380. * @param mixed $value
  2381. * @return bool
  2382. */
  2383. public function isValidFileInstance($value)
  2384. {
  2385. if ($value instanceof UploadedFile && ! $value->isValid()) {
  2386. return false;
  2387. }
  2388. return $value instanceof File;
  2389. }
  2390. /**
  2391. * Determine if a comparison passes between the given values.
  2392. *
  2393. * @param mixed $first
  2394. * @param mixed $second
  2395. * @param string $operator
  2396. * @return bool
  2397. *
  2398. * @throws \InvalidArgumentException
  2399. */
  2400. protected function compare($first, $second, $operator)
  2401. {
  2402. return match ($operator) {
  2403. '<' => $first < $second,
  2404. '>' => $first > $second,
  2405. '<=' => $first <= $second,
  2406. '>=' => $first >= $second,
  2407. '=' => $first == $second,
  2408. default => throw new InvalidArgumentException,
  2409. };
  2410. }
  2411. /**
  2412. * Parse named parameters to $key => $value items.
  2413. *
  2414. * @param array<int, int|string> $parameters
  2415. * @return array
  2416. */
  2417. public function parseNamedParameters($parameters)
  2418. {
  2419. return array_reduce($parameters, function ($result, $item) {
  2420. [$key, $value] = array_pad(explode('=', $item, 2), 2, null);
  2421. $result[$key] = $value;
  2422. return $result;
  2423. });
  2424. }
  2425. /**
  2426. * Require a certain number of parameters to be present.
  2427. *
  2428. * @param int $count
  2429. * @param array<int, int|string> $parameters
  2430. * @param string $rule
  2431. * @return void
  2432. *
  2433. * @throws \InvalidArgumentException
  2434. */
  2435. public function requireParameterCount($count, $parameters, $rule)
  2436. {
  2437. if (count($parameters) < $count) {
  2438. throw new InvalidArgumentException("Validation rule $rule requires at least $count parameters.");
  2439. }
  2440. }
  2441. /**
  2442. * Check if the parameters are of the same type.
  2443. *
  2444. * @param mixed $first
  2445. * @param mixed $second
  2446. * @return bool
  2447. */
  2448. protected function isSameType($first, $second)
  2449. {
  2450. return gettype($first) == gettype($second);
  2451. }
  2452. /**
  2453. * Adds the existing rule to the numericRules array if the attribute's value is numeric.
  2454. *
  2455. * @param string $attribute
  2456. * @param string $rule
  2457. * @return void
  2458. */
  2459. protected function shouldBeNumeric($attribute, $rule)
  2460. {
  2461. if (is_numeric($this->getValue($attribute))) {
  2462. $this->numericRules[] = $rule;
  2463. }
  2464. }
  2465. /**
  2466. * Trim the value if it is a string.
  2467. *
  2468. * @param mixed $value
  2469. * @return string
  2470. */
  2471. protected function trim($value)
  2472. {
  2473. return is_string($value) ? trim($value) : (string) $value;
  2474. }
  2475. /**
  2476. * Ensure the exponent is within the allowed range.
  2477. *
  2478. * @param string $attribute
  2479. * @param mixed $value
  2480. * @return mixed
  2481. *
  2482. * @throws \Illuminate\Support\Exceptions\MathException
  2483. */
  2484. protected function ensureExponentWithinAllowedRange($attribute, $value)
  2485. {
  2486. $stringValue = (string) $value;
  2487. if (! is_numeric($value) || ! Str::contains($stringValue, 'e', ignoreCase: true)) {
  2488. return $value;
  2489. }
  2490. $scale = (int) (Str::contains($stringValue, 'e')
  2491. ? Str::after($stringValue, 'e')
  2492. : Str::after($stringValue, 'E'));
  2493. $withinRange = (
  2494. $this->ensureExponentWithinAllowedRangeUsing ?? fn ($scale) => $scale <= 1000 && $scale >= -1000
  2495. )($scale, $attribute, $value);
  2496. if (! $withinRange) {
  2497. throw new MathException('Scientific notation exponent outside of allowed range.');
  2498. }
  2499. return $value;
  2500. }
  2501. }