ValidatesAttributes.php 49KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674
  1. <?php
  2. namespace Illuminate\Validation\Concerns;
  3. use DateTime;
  4. use Countable;
  5. use Exception;
  6. use Throwable;
  7. use DateTimeZone;
  8. use DateTimeInterface;
  9. use Illuminate\Support\Arr;
  10. use Illuminate\Support\Str;
  11. use InvalidArgumentException;
  12. use Illuminate\Support\Carbon;
  13. use Illuminate\Validation\Rules\Exists;
  14. use Illuminate\Validation\Rules\Unique;
  15. use Illuminate\Validation\ValidationData;
  16. use Symfony\Component\HttpFoundation\File\File;
  17. use Symfony\Component\HttpFoundation\File\UploadedFile;
  18. trait ValidatesAttributes
  19. {
  20. /**
  21. * Validate that an attribute was "accepted".
  22. *
  23. * This validation rule implies the attribute is "required".
  24. *
  25. * @param string $attribute
  26. * @param mixed $value
  27. * @return bool
  28. */
  29. public function validateAccepted($attribute, $value)
  30. {
  31. $acceptable = ['yes', 'on', '1', 1, true, 'true'];
  32. return $this->validateRequired($attribute, $value) && in_array($value, $acceptable, true);
  33. }
  34. /**
  35. * Validate that an attribute is an active URL.
  36. *
  37. * @param string $attribute
  38. * @param mixed $value
  39. * @return bool
  40. */
  41. public function validateActiveUrl($attribute, $value)
  42. {
  43. if (! is_string($value)) {
  44. return false;
  45. }
  46. if ($url = parse_url($value, PHP_URL_HOST)) {
  47. try {
  48. return count(dns_get_record($url, DNS_A | DNS_AAAA)) > 0;
  49. } catch (Exception $e) {
  50. return false;
  51. }
  52. }
  53. return false;
  54. }
  55. /**
  56. * "Break" on first validation fail.
  57. *
  58. * Always returns true, just lets us put "bail" in rules.
  59. *
  60. * @return bool
  61. */
  62. public function validateBail()
  63. {
  64. return true;
  65. }
  66. /**
  67. * Validate the date is before a given date.
  68. *
  69. * @param string $attribute
  70. * @param mixed $value
  71. * @param array $parameters
  72. * @return bool
  73. */
  74. public function validateBefore($attribute, $value, $parameters)
  75. {
  76. $this->requireParameterCount(1, $parameters, 'before');
  77. return $this->compareDates($attribute, $value, $parameters, '<');
  78. }
  79. /**
  80. * Validate the date is before or equal a given date.
  81. *
  82. * @param string $attribute
  83. * @param mixed $value
  84. * @param array $parameters
  85. * @return bool
  86. */
  87. public function validateBeforeOrEqual($attribute, $value, $parameters)
  88. {
  89. $this->requireParameterCount(1, $parameters, 'before_or_equal');
  90. return $this->compareDates($attribute, $value, $parameters, '<=');
  91. }
  92. /**
  93. * Validate the date is after a given date.
  94. *
  95. * @param string $attribute
  96. * @param mixed $value
  97. * @param array $parameters
  98. * @return bool
  99. */
  100. public function validateAfter($attribute, $value, $parameters)
  101. {
  102. $this->requireParameterCount(1, $parameters, 'after');
  103. return $this->compareDates($attribute, $value, $parameters, '>');
  104. }
  105. /**
  106. * Validate the date is equal or after a given date.
  107. *
  108. * @param string $attribute
  109. * @param mixed $value
  110. * @param array $parameters
  111. * @return bool
  112. */
  113. public function validateAfterOrEqual($attribute, $value, $parameters)
  114. {
  115. $this->requireParameterCount(1, $parameters, 'after_or_equal');
  116. return $this->compareDates($attribute, $value, $parameters, '>=');
  117. }
  118. /**
  119. * Compare a given date against another using an operator.
  120. *
  121. * @param string $attribute
  122. * @param mixed $value
  123. * @param array $parameters
  124. * @param string $operator
  125. * @return bool
  126. */
  127. protected function compareDates($attribute, $value, $parameters, $operator)
  128. {
  129. if (! is_string($value) && ! is_numeric($value) && ! $value instanceof DateTimeInterface) {
  130. return false;
  131. }
  132. if ($format = $this->getDateFormat($attribute)) {
  133. return $this->checkDateTimeOrder($format, $value, $parameters[0], $operator);
  134. }
  135. if (! $date = $this->getDateTimestamp($parameters[0])) {
  136. $date = $this->getDateTimestamp($this->getValue($parameters[0]));
  137. }
  138. return $this->compare($this->getDateTimestamp($value), $date, $operator);
  139. }
  140. /**
  141. * Get the date format for an attribute if it has one.
  142. *
  143. * @param string $attribute
  144. * @return string|null
  145. */
  146. protected function getDateFormat($attribute)
  147. {
  148. if ($result = $this->getRule($attribute, 'DateFormat')) {
  149. return $result[1][0];
  150. }
  151. }
  152. /**
  153. * Get the date timestamp.
  154. *
  155. * @param mixed $value
  156. * @return int
  157. */
  158. protected function getDateTimestamp($value)
  159. {
  160. if ($value instanceof DateTimeInterface) {
  161. return $value->getTimestamp();
  162. }
  163. if ($this->isTestingRelativeDateTime($value)) {
  164. $date = $this->getDateTime($value);
  165. if (! is_null($date)) {
  166. return $date->getTimestamp();
  167. }
  168. }
  169. return strtotime($value);
  170. }
  171. /**
  172. * Given two date/time strings, check that one is after the other.
  173. *
  174. * @param string $format
  175. * @param string $first
  176. * @param string $second
  177. * @param string $operator
  178. * @return bool
  179. */
  180. protected function checkDateTimeOrder($format, $first, $second, $operator)
  181. {
  182. $firstDate = $this->getDateTimeWithOptionalFormat($format, $first);
  183. if (! $secondDate = $this->getDateTimeWithOptionalFormat($format, $second)) {
  184. $secondDate = $this->getDateTimeWithOptionalFormat($format, $this->getValue($second));
  185. }
  186. return ($firstDate && $secondDate) && ($this->compare($firstDate, $secondDate, $operator));
  187. }
  188. /**
  189. * Get a DateTime instance from a string.
  190. *
  191. * @param string $format
  192. * @param string $value
  193. * @return \DateTime|null
  194. */
  195. protected function getDateTimeWithOptionalFormat($format, $value)
  196. {
  197. if ($date = DateTime::createFromFormat('!'.$format, $value)) {
  198. return $date;
  199. }
  200. return $this->getDateTime($value);
  201. }
  202. /**
  203. * Get a DateTime instance from a string with no format.
  204. *
  205. * @param string $value
  206. * @return \DateTime|null
  207. */
  208. protected function getDateTime($value)
  209. {
  210. try {
  211. if ($this->isTestingRelativeDateTime($value)) {
  212. return new Carbon($value);
  213. }
  214. return new DateTime($value);
  215. } catch (Exception $e) {
  216. //
  217. }
  218. }
  219. /**
  220. * Check if the given value should be adjusted to Carbon::getTestNow().
  221. *
  222. * @param mixed $value
  223. * @return bool
  224. */
  225. protected function isTestingRelativeDateTime($value)
  226. {
  227. return Carbon::hasTestNow() && is_string($value) && (
  228. $value === 'now' || Carbon::hasRelativeKeywords($value)
  229. );
  230. }
  231. /**
  232. * Validate that an attribute contains only alphabetic characters.
  233. *
  234. * @param string $attribute
  235. * @param mixed $value
  236. * @return bool
  237. */
  238. public function validateAlpha($attribute, $value)
  239. {
  240. return is_string($value) && preg_match('/^[\pL\pM]+$/u', $value);
  241. }
  242. /**
  243. * Validate that an attribute contains only alpha-numeric characters, dashes, and underscores.
  244. *
  245. * @param string $attribute
  246. * @param mixed $value
  247. * @return bool
  248. */
  249. public function validateAlphaDash($attribute, $value)
  250. {
  251. if (! is_string($value) && ! is_numeric($value)) {
  252. return false;
  253. }
  254. return preg_match('/^[\pL\pM\pN_-]+$/u', $value) > 0;
  255. }
  256. /**
  257. * Validate that an attribute contains only alpha-numeric characters.
  258. *
  259. * @param string $attribute
  260. * @param mixed $value
  261. * @return bool
  262. */
  263. public function validateAlphaNum($attribute, $value)
  264. {
  265. if (! is_string($value) && ! is_numeric($value)) {
  266. return false;
  267. }
  268. return preg_match('/^[\pL\pM\pN]+$/u', $value) > 0;
  269. }
  270. /**
  271. * Validate that an attribute is an array.
  272. *
  273. * @param string $attribute
  274. * @param mixed $value
  275. * @return bool
  276. */
  277. public function validateArray($attribute, $value)
  278. {
  279. return is_array($value);
  280. }
  281. /**
  282. * Validate the size of an attribute is between a set of values.
  283. *
  284. * @param string $attribute
  285. * @param mixed $value
  286. * @param array $parameters
  287. * @return bool
  288. */
  289. public function validateBetween($attribute, $value, $parameters)
  290. {
  291. $this->requireParameterCount(2, $parameters, 'between');
  292. $size = $this->getSize($attribute, $value);
  293. return $size >= $parameters[0] && $size <= $parameters[1];
  294. }
  295. /**
  296. * Validate that an attribute is a boolean.
  297. *
  298. * @param string $attribute
  299. * @param mixed $value
  300. * @return bool
  301. */
  302. public function validateBoolean($attribute, $value)
  303. {
  304. $acceptable = [true, false, 0, 1, '0', '1'];
  305. return in_array($value, $acceptable, true);
  306. }
  307. /**
  308. * Validate that an attribute has a matching confirmation.
  309. *
  310. * @param string $attribute
  311. * @param mixed $value
  312. * @return bool
  313. */
  314. public function validateConfirmed($attribute, $value)
  315. {
  316. return $this->validateSame($attribute, $value, [$attribute.'_confirmation']);
  317. }
  318. /**
  319. * Validate that an attribute is a valid date.
  320. *
  321. * @param string $attribute
  322. * @param mixed $value
  323. * @return bool
  324. */
  325. public function validateDate($attribute, $value)
  326. {
  327. if ($value instanceof DateTimeInterface) {
  328. return true;
  329. }
  330. if ((! is_string($value) && ! is_numeric($value)) || strtotime($value) === false) {
  331. return false;
  332. }
  333. $date = date_parse($value);
  334. return checkdate($date['month'], $date['day'], $date['year']);
  335. }
  336. /**
  337. * Validate that an attribute matches a date format.
  338. *
  339. * @param string $attribute
  340. * @param mixed $value
  341. * @param array $parameters
  342. * @return bool
  343. */
  344. public function validateDateFormat($attribute, $value, $parameters)
  345. {
  346. $this->requireParameterCount(1, $parameters, 'date_format');
  347. if (! is_string($value) && ! is_numeric($value)) {
  348. return false;
  349. }
  350. $format = $parameters[0];
  351. $date = DateTime::createFromFormat('!'.$format, $value);
  352. return $date && $date->format($format) == $value;
  353. }
  354. /**
  355. * Validate that an attribute is equal to another date.
  356. *
  357. * @param string $attribute
  358. * @param mixed $value
  359. * @param array $parameters
  360. * @return bool
  361. */
  362. public function validateDateEquals($attribute, $value, $parameters)
  363. {
  364. $this->requireParameterCount(1, $parameters, 'date_equals');
  365. return $this->compareDates($attribute, $value, $parameters, '=');
  366. }
  367. /**
  368. * Validate that an attribute is different from another attribute.
  369. *
  370. * @param string $attribute
  371. * @param mixed $value
  372. * @param array $parameters
  373. * @return bool
  374. */
  375. public function validateDifferent($attribute, $value, $parameters)
  376. {
  377. $this->requireParameterCount(1, $parameters, 'different');
  378. foreach ($parameters as $parameter) {
  379. $other = Arr::get($this->data, $parameter);
  380. if (is_null($other) || $value === $other) {
  381. return false;
  382. }
  383. }
  384. return true;
  385. }
  386. /**
  387. * Validate that an attribute has a given number of digits.
  388. *
  389. * @param string $attribute
  390. * @param mixed $value
  391. * @param array $parameters
  392. * @return bool
  393. */
  394. public function validateDigits($attribute, $value, $parameters)
  395. {
  396. $this->requireParameterCount(1, $parameters, 'digits');
  397. return ! preg_match('/[^0-9]/', $value)
  398. && strlen((string) $value) == $parameters[0];
  399. }
  400. /**
  401. * Validate that an attribute is between a given number of digits.
  402. *
  403. * @param string $attribute
  404. * @param mixed $value
  405. * @param array $parameters
  406. * @return bool
  407. */
  408. public function validateDigitsBetween($attribute, $value, $parameters)
  409. {
  410. $this->requireParameterCount(2, $parameters, 'digits_between');
  411. $length = strlen((string) $value);
  412. return ! preg_match('/[^0-9]/', $value)
  413. && $length >= $parameters[0] && $length <= $parameters[1];
  414. }
  415. /**
  416. * Validate the dimensions of an image matches the given values.
  417. *
  418. * @param string $attribute
  419. * @param mixed $value
  420. * @param array $parameters
  421. * @return bool
  422. */
  423. public function validateDimensions($attribute, $value, $parameters)
  424. {
  425. if ($this->isValidFileInstance($value) && $value->getClientMimeType() == 'image/svg+xml') {
  426. return true;
  427. }
  428. if (! $this->isValidFileInstance($value) || ! $sizeDetails = @getimagesize($value->getRealPath())) {
  429. return false;
  430. }
  431. $this->requireParameterCount(1, $parameters, 'dimensions');
  432. list($width, $height) = $sizeDetails;
  433. $parameters = $this->parseNamedParameters($parameters);
  434. if ($this->failsBasicDimensionChecks($parameters, $width, $height) ||
  435. $this->failsRatioCheck($parameters, $width, $height)) {
  436. return false;
  437. }
  438. return true;
  439. }
  440. /**
  441. * Test if the given width and height fail any conditions.
  442. *
  443. * @param array $parameters
  444. * @param int $width
  445. * @param int $height
  446. * @return bool
  447. */
  448. protected function failsBasicDimensionChecks($parameters, $width, $height)
  449. {
  450. return (isset($parameters['width']) && $parameters['width'] != $width) ||
  451. (isset($parameters['min_width']) && $parameters['min_width'] > $width) ||
  452. (isset($parameters['max_width']) && $parameters['max_width'] < $width) ||
  453. (isset($parameters['height']) && $parameters['height'] != $height) ||
  454. (isset($parameters['min_height']) && $parameters['min_height'] > $height) ||
  455. (isset($parameters['max_height']) && $parameters['max_height'] < $height);
  456. }
  457. /**
  458. * Determine if the given parameters fail a dimension ratio check.
  459. *
  460. * @param array $parameters
  461. * @param int $width
  462. * @param int $height
  463. * @return bool
  464. */
  465. protected function failsRatioCheck($parameters, $width, $height)
  466. {
  467. if (! isset($parameters['ratio'])) {
  468. return false;
  469. }
  470. list($numerator, $denominator) = array_replace(
  471. [1, 1], array_filter(sscanf($parameters['ratio'], '%f/%d'))
  472. );
  473. $precision = 1 / max($width, $height);
  474. return abs($numerator / $denominator - $width / $height) > $precision;
  475. }
  476. /**
  477. * Validate an attribute is unique among other values.
  478. *
  479. * @param string $attribute
  480. * @param mixed $value
  481. * @param array $parameters
  482. * @return bool
  483. */
  484. public function validateDistinct($attribute, $value, $parameters)
  485. {
  486. $attributeName = $this->getPrimaryAttribute($attribute);
  487. $attributeData = ValidationData::extractDataFromPath(
  488. ValidationData::getLeadingExplicitAttributePath($attributeName), $this->data
  489. );
  490. $pattern = str_replace('\*', '[^.]+', preg_quote($attributeName, '#'));
  491. $data = Arr::where(Arr::dot($attributeData), function ($value, $key) use ($attribute, $pattern) {
  492. return $key != $attribute && (bool) preg_match('#^'.$pattern.'\z#u', $key);
  493. });
  494. if (in_array('ignore_case', $parameters)) {
  495. return empty(preg_grep('/^'.preg_quote($value, '/').'$/iu', $data));
  496. }
  497. return ! in_array($value, array_values($data));
  498. }
  499. /**
  500. * Validate that an attribute is a valid e-mail address.
  501. *
  502. * @param string $attribute
  503. * @param mixed $value
  504. * @return bool
  505. */
  506. public function validateEmail($attribute, $value)
  507. {
  508. return filter_var($value, FILTER_VALIDATE_EMAIL) !== false;
  509. }
  510. /**
  511. * Validate the existence of an attribute value in a database table.
  512. *
  513. * @param string $attribute
  514. * @param mixed $value
  515. * @param array $parameters
  516. * @return bool
  517. */
  518. public function validateExists($attribute, $value, $parameters)
  519. {
  520. $this->requireParameterCount(1, $parameters, 'exists');
  521. list($connection, $table) = $this->parseTable($parameters[0]);
  522. // The second parameter position holds the name of the column that should be
  523. // verified as existing. If this parameter is not specified we will guess
  524. // that the columns being "verified" shares the given attribute's name.
  525. $column = $this->getQueryColumn($parameters, $attribute);
  526. $expected = (is_array($value)) ? count($value) : 1;
  527. return $this->getExistCount(
  528. $connection, $table, $column, $value, $parameters
  529. ) >= $expected;
  530. }
  531. /**
  532. * Get the number of records that exist in storage.
  533. *
  534. * @param mixed $connection
  535. * @param string $table
  536. * @param string $column
  537. * @param mixed $value
  538. * @param array $parameters
  539. * @return int
  540. */
  541. protected function getExistCount($connection, $table, $column, $value, $parameters)
  542. {
  543. $verifier = $this->getPresenceVerifierFor($connection);
  544. $extra = $this->getExtraConditions(
  545. array_values(array_slice($parameters, 2))
  546. );
  547. if ($this->currentRule instanceof Exists) {
  548. $extra = array_merge($extra, $this->currentRule->queryCallbacks());
  549. }
  550. return is_array($value)
  551. ? $verifier->getMultiCount($table, $column, $value, $extra)
  552. : $verifier->getCount($table, $column, $value, null, null, $extra);
  553. }
  554. /**
  555. * Validate the uniqueness of an attribute value on a given database table.
  556. *
  557. * If a database column is not specified, the attribute will be used.
  558. *
  559. * @param string $attribute
  560. * @param mixed $value
  561. * @param array $parameters
  562. * @return bool
  563. */
  564. public function validateUnique($attribute, $value, $parameters)
  565. {
  566. $this->requireParameterCount(1, $parameters, 'unique');
  567. list($connection, $table) = $this->parseTable($parameters[0]);
  568. // The second parameter position holds the name of the column that needs to
  569. // be verified as unique. If this parameter isn't specified we will just
  570. // assume that this column to be verified shares the attribute's name.
  571. $column = $this->getQueryColumn($parameters, $attribute);
  572. list($idColumn, $id) = [null, null];
  573. if (isset($parameters[2])) {
  574. list($idColumn, $id) = $this->getUniqueIds($parameters);
  575. }
  576. // The presence verifier is responsible for counting rows within this store
  577. // mechanism which might be a relational database or any other permanent
  578. // data store like Redis, etc. We will use it to determine uniqueness.
  579. $verifier = $this->getPresenceVerifierFor($connection);
  580. $extra = $this->getUniqueExtra($parameters);
  581. if ($this->currentRule instanceof Unique) {
  582. $extra = array_merge($extra, $this->currentRule->queryCallbacks());
  583. }
  584. return $verifier->getCount(
  585. $table, $column, $value, $id, $idColumn, $extra
  586. ) == 0;
  587. }
  588. /**
  589. * Get the excluded ID column and value for the unique rule.
  590. *
  591. * @param array $parameters
  592. * @return array
  593. */
  594. protected function getUniqueIds($parameters)
  595. {
  596. $idColumn = $parameters[3] ?? 'id';
  597. return [$idColumn, $this->prepareUniqueId($parameters[2])];
  598. }
  599. /**
  600. * Prepare the given ID for querying.
  601. *
  602. * @param mixed $id
  603. * @return int
  604. */
  605. protected function prepareUniqueId($id)
  606. {
  607. if (preg_match('/\[(.*)\]/', $id, $matches)) {
  608. $id = $this->getValue($matches[1]);
  609. }
  610. if (strtolower($id) == 'null') {
  611. $id = null;
  612. }
  613. if (filter_var($id, FILTER_VALIDATE_INT) !== false) {
  614. $id = (int) $id;
  615. }
  616. return $id;
  617. }
  618. /**
  619. * Get the extra conditions for a unique rule.
  620. *
  621. * @param array $parameters
  622. * @return array
  623. */
  624. protected function getUniqueExtra($parameters)
  625. {
  626. if (isset($parameters[4])) {
  627. return $this->getExtraConditions(array_slice($parameters, 4));
  628. }
  629. return [];
  630. }
  631. /**
  632. * Parse the connection / table for the unique / exists rules.
  633. *
  634. * @param string $table
  635. * @return array
  636. */
  637. protected function parseTable($table)
  638. {
  639. return Str::contains($table, '.') ? explode('.', $table, 2) : [null, $table];
  640. }
  641. /**
  642. * Get the column name for an exists / unique query.
  643. *
  644. * @param array $parameters
  645. * @param string $attribute
  646. * @return bool
  647. */
  648. protected function getQueryColumn($parameters, $attribute)
  649. {
  650. return isset($parameters[1]) && $parameters[1] !== 'NULL'
  651. ? $parameters[1] : $this->guessColumnForQuery($attribute);
  652. }
  653. /**
  654. * Guess the database column from the given attribute name.
  655. *
  656. * @param string $attribute
  657. * @return string
  658. */
  659. public function guessColumnForQuery($attribute)
  660. {
  661. if (in_array($attribute, Arr::collapse($this->implicitAttributes))
  662. && ! is_numeric($last = last(explode('.', $attribute)))) {
  663. return $last;
  664. }
  665. return $attribute;
  666. }
  667. /**
  668. * Get the extra conditions for a unique / exists rule.
  669. *
  670. * @param array $segments
  671. * @return array
  672. */
  673. protected function getExtraConditions(array $segments)
  674. {
  675. $extra = [];
  676. $count = count($segments);
  677. for ($i = 0; $i < $count; $i += 2) {
  678. $extra[$segments[$i]] = $segments[$i + 1];
  679. }
  680. return $extra;
  681. }
  682. /**
  683. * Validate the given value is a valid file.
  684. *
  685. * @param string $attribute
  686. * @param mixed $value
  687. * @return bool
  688. */
  689. public function validateFile($attribute, $value)
  690. {
  691. return $this->isValidFileInstance($value);
  692. }
  693. /**
  694. * Validate the given attribute is filled if it is present.
  695. *
  696. * @param string $attribute
  697. * @param mixed $value
  698. * @return bool
  699. */
  700. public function validateFilled($attribute, $value)
  701. {
  702. if (Arr::has($this->data, $attribute)) {
  703. return $this->validateRequired($attribute, $value);
  704. }
  705. return true;
  706. }
  707. /**
  708. * Validate that an attribute is greater than another attribute.
  709. *
  710. * @param string $attribute
  711. * @param mixed $value
  712. * @param array $parameters
  713. * @return bool
  714. */
  715. public function validateGt($attribute, $value, $parameters)
  716. {
  717. $this->requireParameterCount(1, $parameters, 'gt');
  718. $comparedToValue = $this->getValue($parameters[0]);
  719. $this->shouldBeNumeric($attribute, 'Gt');
  720. if (is_null($comparedToValue) && (is_numeric($value) && is_numeric($parameters[0]))) {
  721. return $this->getSize($attribute, $value) > $parameters[0];
  722. }
  723. $this->requireSameType($value, $comparedToValue);
  724. return $this->getSize($attribute, $value) > $this->getSize($attribute, $comparedToValue);
  725. }
  726. /**
  727. * Validate that an attribute is less than another attribute.
  728. *
  729. * @param string $attribute
  730. * @param mixed $value
  731. * @param array $parameters
  732. * @return bool
  733. */
  734. public function validateLt($attribute, $value, $parameters)
  735. {
  736. $this->requireParameterCount(1, $parameters, 'lt');
  737. $comparedToValue = $this->getValue($parameters[0]);
  738. $this->shouldBeNumeric($attribute, 'Lt');
  739. if (is_null($comparedToValue) && (is_numeric($value) && is_numeric($parameters[0]))) {
  740. return $this->getSize($attribute, $value) < $parameters[0];
  741. }
  742. $this->requireSameType($value, $comparedToValue);
  743. return $this->getSize($attribute, $value) < $this->getSize($attribute, $comparedToValue);
  744. }
  745. /**
  746. * Validate that an attribute is greater than or equal another attribute.
  747. *
  748. * @param string $attribute
  749. * @param mixed $value
  750. * @param array $parameters
  751. * @return bool
  752. */
  753. public function validateGte($attribute, $value, $parameters)
  754. {
  755. $this->requireParameterCount(1, $parameters, 'gte');
  756. $comparedToValue = $this->getValue($parameters[0]);
  757. $this->shouldBeNumeric($attribute, 'Gte');
  758. if (is_null($comparedToValue) && (is_numeric($value) && is_numeric($parameters[0]))) {
  759. return $this->getSize($attribute, $value) >= $parameters[0];
  760. }
  761. $this->requireSameType($value, $comparedToValue);
  762. return $this->getSize($attribute, $value) >= $this->getSize($attribute, $comparedToValue);
  763. }
  764. /**
  765. * Validate that an attribute is less than or equal another attribute.
  766. *
  767. * @param string $attribute
  768. * @param mixed $value
  769. * @param array $parameters
  770. * @return bool
  771. */
  772. public function validateLte($attribute, $value, $parameters)
  773. {
  774. $this->requireParameterCount(1, $parameters, 'lte');
  775. $comparedToValue = $this->getValue($parameters[0]);
  776. $this->shouldBeNumeric($attribute, 'Lte');
  777. if (is_null($comparedToValue) && (is_numeric($value) && is_numeric($parameters[0]))) {
  778. return $this->getSize($attribute, $value) <= $parameters[0];
  779. }
  780. $this->requireSameType($value, $comparedToValue);
  781. return $this->getSize($attribute, $value) <= $this->getSize($attribute, $comparedToValue);
  782. }
  783. /**
  784. * Validate the MIME type of a file is an image MIME type.
  785. *
  786. * @param string $attribute
  787. * @param mixed $value
  788. * @return bool
  789. */
  790. public function validateImage($attribute, $value)
  791. {
  792. return $this->validateMimes($attribute, $value, ['jpeg', 'png', 'gif', 'bmp', 'svg']);
  793. }
  794. /**
  795. * Validate an attribute is contained within a list of values.
  796. *
  797. * @param string $attribute
  798. * @param mixed $value
  799. * @param array $parameters
  800. * @return bool
  801. */
  802. public function validateIn($attribute, $value, $parameters)
  803. {
  804. if (is_array($value) && $this->hasRule($attribute, 'Array')) {
  805. foreach ($value as $element) {
  806. if (is_array($element)) {
  807. return false;
  808. }
  809. }
  810. return count(array_diff($value, $parameters)) == 0;
  811. }
  812. return ! is_array($value) && in_array((string) $value, $parameters);
  813. }
  814. /**
  815. * Validate that the values of an attribute is in another attribute.
  816. *
  817. * @param string $attribute
  818. * @param mixed $value
  819. * @param array $parameters
  820. * @return bool
  821. */
  822. public function validateInArray($attribute, $value, $parameters)
  823. {
  824. $this->requireParameterCount(1, $parameters, 'in_array');
  825. $explicitPath = ValidationData::getLeadingExplicitAttributePath($parameters[0]);
  826. $attributeData = ValidationData::extractDataFromPath($explicitPath, $this->data);
  827. $otherValues = Arr::where(Arr::dot($attributeData), function ($value, $key) use ($parameters) {
  828. return Str::is($parameters[0], $key);
  829. });
  830. return in_array($value, $otherValues);
  831. }
  832. /**
  833. * Validate that an attribute is an integer.
  834. *
  835. * @param string $attribute
  836. * @param mixed $value
  837. * @return bool
  838. */
  839. public function validateInteger($attribute, $value)
  840. {
  841. return filter_var($value, FILTER_VALIDATE_INT) !== false;
  842. }
  843. /**
  844. * Validate that an attribute is a valid IP.
  845. *
  846. * @param string $attribute
  847. * @param mixed $value
  848. * @return bool
  849. */
  850. public function validateIp($attribute, $value)
  851. {
  852. return filter_var($value, FILTER_VALIDATE_IP) !== false;
  853. }
  854. /**
  855. * Validate that an attribute is a valid IPv4.
  856. *
  857. * @param string $attribute
  858. * @param mixed $value
  859. * @return bool
  860. */
  861. public function validateIpv4($attribute, $value)
  862. {
  863. return filter_var($value, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4) !== false;
  864. }
  865. /**
  866. * Validate that an attribute is a valid IPv6.
  867. *
  868. * @param string $attribute
  869. * @param mixed $value
  870. * @return bool
  871. */
  872. public function validateIpv6($attribute, $value)
  873. {
  874. return filter_var($value, FILTER_VALIDATE_IP, FILTER_FLAG_IPV6) !== false;
  875. }
  876. /**
  877. * Validate the attribute is a valid JSON string.
  878. *
  879. * @param string $attribute
  880. * @param mixed $value
  881. * @return bool
  882. */
  883. public function validateJson($attribute, $value)
  884. {
  885. if (! is_scalar($value) && ! method_exists($value, '__toString')) {
  886. return false;
  887. }
  888. json_decode($value);
  889. return json_last_error() === JSON_ERROR_NONE;
  890. }
  891. /**
  892. * Validate the size of an attribute is less than a maximum value.
  893. *
  894. * @param string $attribute
  895. * @param mixed $value
  896. * @param array $parameters
  897. * @return bool
  898. */
  899. public function validateMax($attribute, $value, $parameters)
  900. {
  901. $this->requireParameterCount(1, $parameters, 'max');
  902. if ($value instanceof UploadedFile && ! $value->isValid()) {
  903. return false;
  904. }
  905. return $this->getSize($attribute, $value) <= $parameters[0];
  906. }
  907. /**
  908. * Validate the guessed extension of a file upload is in a set of file extensions.
  909. *
  910. * @param string $attribute
  911. * @param mixed $value
  912. * @param array $parameters
  913. * @return bool
  914. */
  915. public function validateMimes($attribute, $value, $parameters)
  916. {
  917. if (! $this->isValidFileInstance($value)) {
  918. return false;
  919. }
  920. if ($this->shouldBlockPhpUpload($value, $parameters)) {
  921. return false;
  922. }
  923. return $value->getPath() !== '' && in_array($value->guessExtension(), $parameters);
  924. }
  925. /**
  926. * Validate the MIME type of a file upload attribute is in a set of MIME types.
  927. *
  928. * @param string $attribute
  929. * @param mixed $value
  930. * @param array $parameters
  931. * @return bool
  932. */
  933. public function validateMimetypes($attribute, $value, $parameters)
  934. {
  935. if (! $this->isValidFileInstance($value)) {
  936. return false;
  937. }
  938. if ($this->shouldBlockPhpUpload($value, $parameters)) {
  939. return false;
  940. }
  941. return $value->getPath() !== '' &&
  942. (in_array($value->getMimeType(), $parameters) ||
  943. in_array(explode('/', $value->getMimeType())[0].'/*', $parameters));
  944. }
  945. /**
  946. * Check if PHP uploads are explicitly allowed.
  947. *
  948. * @param mixed $value
  949. * @param array $parameters
  950. * @return bool
  951. */
  952. protected function shouldBlockPhpUpload($value, $parameters)
  953. {
  954. if (in_array('php', $parameters)) {
  955. return false;
  956. }
  957. return ($value instanceof UploadedFile)
  958. ? trim(strtolower($value->getClientOriginalExtension())) === 'php'
  959. : trim(strtolower($value->getExtension())) === 'php';
  960. }
  961. /**
  962. * Validate the size of an attribute is greater than a minimum value.
  963. *
  964. * @param string $attribute
  965. * @param mixed $value
  966. * @param array $parameters
  967. * @return bool
  968. */
  969. public function validateMin($attribute, $value, $parameters)
  970. {
  971. $this->requireParameterCount(1, $parameters, 'min');
  972. return $this->getSize($attribute, $value) >= $parameters[0];
  973. }
  974. /**
  975. * "Indicate" validation should pass if value is null.
  976. *
  977. * Always returns true, just lets us put "nullable" in rules.
  978. *
  979. * @return bool
  980. */
  981. public function validateNullable()
  982. {
  983. return true;
  984. }
  985. /**
  986. * Validate an attribute is not contained within a list of values.
  987. *
  988. * @param string $attribute
  989. * @param mixed $value
  990. * @param array $parameters
  991. * @return bool
  992. */
  993. public function validateNotIn($attribute, $value, $parameters)
  994. {
  995. return ! $this->validateIn($attribute, $value, $parameters);
  996. }
  997. /**
  998. * Validate that an attribute is numeric.
  999. *
  1000. * @param string $attribute
  1001. * @param mixed $value
  1002. * @return bool
  1003. */
  1004. public function validateNumeric($attribute, $value)
  1005. {
  1006. return is_numeric($value);
  1007. }
  1008. /**
  1009. * Validate that an attribute exists even if not filled.
  1010. *
  1011. * @param string $attribute
  1012. * @param mixed $value
  1013. * @return bool
  1014. */
  1015. public function validatePresent($attribute, $value)
  1016. {
  1017. return Arr::has($this->data, $attribute);
  1018. }
  1019. /**
  1020. * Validate that an attribute passes a regular expression check.
  1021. *
  1022. * @param string $attribute
  1023. * @param mixed $value
  1024. * @param array $parameters
  1025. * @return bool
  1026. */
  1027. public function validateRegex($attribute, $value, $parameters)
  1028. {
  1029. if (! is_string($value) && ! is_numeric($value)) {
  1030. return false;
  1031. }
  1032. $this->requireParameterCount(1, $parameters, 'regex');
  1033. return preg_match($parameters[0], $value) > 0;
  1034. }
  1035. /**
  1036. * Validate that an attribute does not pass a regular expression check.
  1037. *
  1038. * @param string $attribute
  1039. * @param mixed $value
  1040. * @param array $parameters
  1041. * @return bool
  1042. */
  1043. public function validateNotRegex($attribute, $value, $parameters)
  1044. {
  1045. if (! is_string($value) && ! is_numeric($value)) {
  1046. return false;
  1047. }
  1048. $this->requireParameterCount(1, $parameters, 'not_regex');
  1049. return preg_match($parameters[0], $value) < 1;
  1050. }
  1051. /**
  1052. * Validate that a required attribute exists.
  1053. *
  1054. * @param string $attribute
  1055. * @param mixed $value
  1056. * @return bool
  1057. */
  1058. public function validateRequired($attribute, $value)
  1059. {
  1060. if (is_null($value)) {
  1061. return false;
  1062. } elseif (is_string($value) && trim($value) === '') {
  1063. return false;
  1064. } elseif ((is_array($value) || $value instanceof Countable) && count($value) < 1) {
  1065. return false;
  1066. } elseif ($value instanceof File) {
  1067. return (string) $value->getPath() !== '';
  1068. }
  1069. return true;
  1070. }
  1071. /**
  1072. * Validate that an attribute exists when another attribute has a given value.
  1073. *
  1074. * @param string $attribute
  1075. * @param mixed $value
  1076. * @param mixed $parameters
  1077. * @return bool
  1078. */
  1079. public function validateRequiredIf($attribute, $value, $parameters)
  1080. {
  1081. $this->requireParameterCount(2, $parameters, 'required_if');
  1082. $other = Arr::get($this->data, $parameters[0]);
  1083. $values = array_slice($parameters, 1);
  1084. if (is_bool($other)) {
  1085. $values = $this->convertValuesToBoolean($values);
  1086. }
  1087. if (in_array($other, $values)) {
  1088. return $this->validateRequired($attribute, $value);
  1089. }
  1090. return true;
  1091. }
  1092. /**
  1093. * Convert the given values to boolean if they are string "true" / "false".
  1094. *
  1095. * @param array $values
  1096. * @return array
  1097. */
  1098. protected function convertValuesToBoolean($values)
  1099. {
  1100. return array_map(function ($value) {
  1101. if ($value === 'true') {
  1102. return true;
  1103. } elseif ($value === 'false') {
  1104. return false;
  1105. }
  1106. return $value;
  1107. }, $values);
  1108. }
  1109. /**
  1110. * Validate that an attribute exists when another attribute does not have a given value.
  1111. *
  1112. * @param string $attribute
  1113. * @param mixed $value
  1114. * @param mixed $parameters
  1115. * @return bool
  1116. */
  1117. public function validateRequiredUnless($attribute, $value, $parameters)
  1118. {
  1119. $this->requireParameterCount(2, $parameters, 'required_unless');
  1120. $data = Arr::get($this->data, $parameters[0]);
  1121. $values = array_slice($parameters, 1);
  1122. if (! in_array($data, $values)) {
  1123. return $this->validateRequired($attribute, $value);
  1124. }
  1125. return true;
  1126. }
  1127. /**
  1128. * Validate that an attribute exists when any other attribute exists.
  1129. *
  1130. * @param string $attribute
  1131. * @param mixed $value
  1132. * @param mixed $parameters
  1133. * @return bool
  1134. */
  1135. public function validateRequiredWith($attribute, $value, $parameters)
  1136. {
  1137. if (! $this->allFailingRequired($parameters)) {
  1138. return $this->validateRequired($attribute, $value);
  1139. }
  1140. return true;
  1141. }
  1142. /**
  1143. * Validate that an attribute exists when all other attributes exists.
  1144. *
  1145. * @param string $attribute
  1146. * @param mixed $value
  1147. * @param mixed $parameters
  1148. * @return bool
  1149. */
  1150. public function validateRequiredWithAll($attribute, $value, $parameters)
  1151. {
  1152. if (! $this->anyFailingRequired($parameters)) {
  1153. return $this->validateRequired($attribute, $value);
  1154. }
  1155. return true;
  1156. }
  1157. /**
  1158. * Validate that an attribute exists when another attribute does not.
  1159. *
  1160. * @param string $attribute
  1161. * @param mixed $value
  1162. * @param mixed $parameters
  1163. * @return bool
  1164. */
  1165. public function validateRequiredWithout($attribute, $value, $parameters)
  1166. {
  1167. if ($this->anyFailingRequired($parameters)) {
  1168. return $this->validateRequired($attribute, $value);
  1169. }
  1170. return true;
  1171. }
  1172. /**
  1173. * Validate that an attribute exists when all other attributes do not.
  1174. *
  1175. * @param string $attribute
  1176. * @param mixed $value
  1177. * @param mixed $parameters
  1178. * @return bool
  1179. */
  1180. public function validateRequiredWithoutAll($attribute, $value, $parameters)
  1181. {
  1182. if ($this->allFailingRequired($parameters)) {
  1183. return $this->validateRequired($attribute, $value);
  1184. }
  1185. return true;
  1186. }
  1187. /**
  1188. * Determine if any of the given attributes fail the required test.
  1189. *
  1190. * @param array $attributes
  1191. * @return bool
  1192. */
  1193. protected function anyFailingRequired(array $attributes)
  1194. {
  1195. foreach ($attributes as $key) {
  1196. if (! $this->validateRequired($key, $this->getValue($key))) {
  1197. return true;
  1198. }
  1199. }
  1200. return false;
  1201. }
  1202. /**
  1203. * Determine if all of the given attributes fail the required test.
  1204. *
  1205. * @param array $attributes
  1206. * @return bool
  1207. */
  1208. protected function allFailingRequired(array $attributes)
  1209. {
  1210. foreach ($attributes as $key) {
  1211. if ($this->validateRequired($key, $this->getValue($key))) {
  1212. return false;
  1213. }
  1214. }
  1215. return true;
  1216. }
  1217. /**
  1218. * Validate that two attributes match.
  1219. *
  1220. * @param string $attribute
  1221. * @param mixed $value
  1222. * @param array $parameters
  1223. * @return bool
  1224. */
  1225. public function validateSame($attribute, $value, $parameters)
  1226. {
  1227. $this->requireParameterCount(1, $parameters, 'same');
  1228. $other = Arr::get($this->data, $parameters[0]);
  1229. return $value === $other;
  1230. }
  1231. /**
  1232. * Validate the size of an attribute.
  1233. *
  1234. * @param string $attribute
  1235. * @param mixed $value
  1236. * @param array $parameters
  1237. * @return bool
  1238. */
  1239. public function validateSize($attribute, $value, $parameters)
  1240. {
  1241. $this->requireParameterCount(1, $parameters, 'size');
  1242. return $this->getSize($attribute, $value) == $parameters[0];
  1243. }
  1244. /**
  1245. * "Validate" optional attributes.
  1246. *
  1247. * Always returns true, just lets us put sometimes in rules.
  1248. *
  1249. * @return bool
  1250. */
  1251. public function validateSometimes()
  1252. {
  1253. return true;
  1254. }
  1255. /**
  1256. * Validate that an attribute is a string.
  1257. *
  1258. * @param string $attribute
  1259. * @param mixed $value
  1260. * @return bool
  1261. */
  1262. public function validateString($attribute, $value)
  1263. {
  1264. return is_string($value);
  1265. }
  1266. /**
  1267. * Validate that an attribute is a valid timezone.
  1268. *
  1269. * @param string $attribute
  1270. * @param mixed $value
  1271. * @return bool
  1272. */
  1273. public function validateTimezone($attribute, $value)
  1274. {
  1275. try {
  1276. new DateTimeZone($value);
  1277. } catch (Exception $e) {
  1278. return false;
  1279. } catch (Throwable $e) {
  1280. return false;
  1281. }
  1282. return true;
  1283. }
  1284. /**
  1285. * Validate that an attribute is a valid URL.
  1286. *
  1287. * @param string $attribute
  1288. * @param mixed $value
  1289. * @return bool
  1290. */
  1291. public function validateUrl($attribute, $value)
  1292. {
  1293. if (! is_string($value)) {
  1294. return false;
  1295. }
  1296. /*
  1297. * This pattern is derived from Symfony\Component\Validator\Constraints\UrlValidator (2.7.4).
  1298. *
  1299. * (c) Fabien Potencier <fabien@symfony.com> http://symfony.com
  1300. */
  1301. $pattern = '~^
  1302. ((aaa|aaas|about|acap|acct|acr|adiumxtra|afp|afs|aim|apt|attachment|aw|barion|beshare|bitcoin|blob|bolo|callto|cap|chrome|chrome-extension|cid|coap|coaps|com-eventbrite-attendee|content|crid|cvs|data|dav|dict|dlna-playcontainer|dlna-playsingle|dns|dntp|dtn|dvb|ed2k|example|facetime|fax|feed|feedready|file|filesystem|finger|fish|ftp|geo|gg|git|gizmoproject|go|gopher|gtalk|h323|ham|hcp|http|https|iax|icap|icon|im|imap|info|iotdisco|ipn|ipp|ipps|irc|irc6|ircs|iris|iris.beep|iris.lwz|iris.xpc|iris.xpcs|itms|jabber|jar|jms|keyparc|lastfm|ldap|ldaps|magnet|mailserver|mailto|maps|market|message|mid|mms|modem|ms-help|ms-settings|ms-settings-airplanemode|ms-settings-bluetooth|ms-settings-camera|ms-settings-cellular|ms-settings-cloudstorage|ms-settings-emailandaccounts|ms-settings-language|ms-settings-location|ms-settings-lock|ms-settings-nfctransactions|ms-settings-notifications|ms-settings-power|ms-settings-privacy|ms-settings-proximity|ms-settings-screenrotation|ms-settings-wifi|ms-settings-workplace|msnim|msrp|msrps|mtqp|mumble|mupdate|mvn|news|nfs|ni|nih|nntp|notes|oid|opaquelocktoken|pack|palm|paparazzi|pkcs11|platform|pop|pres|prospero|proxy|psyc|query|redis|rediss|reload|res|resource|rmi|rsync|rtmfp|rtmp|rtsp|rtsps|rtspu|secondlife|s3|service|session|sftp|sgn|shttp|sieve|sip|sips|skype|smb|sms|smtp|snews|snmp|soap.beep|soap.beeps|soldat|spotify|ssh|steam|stun|stuns|submit|svn|tag|teamspeak|tel|teliaeid|telnet|tftp|things|thismessage|tip|tn3270|turn|turns|tv|udp|unreal|urn|ut2004|vemmi|ventrilo|videotex|view-source|wais|webcal|ws|wss|wtai|wyciwyg|xcon|xcon-userid|xfire|xmlrpc\.beep|xmlrpc.beeps|xmpp|xri|ymsgr|z39\.50|z39\.50r|z39\.50s)):// # protocol
  1303. (([\pL\pN-]+:)?([\pL\pN-]+)@)? # basic auth
  1304. (
  1305. ([\pL\pN\pS-\.])+(\.?([\pL]|xn\-\-[\pL\pN-]+)+\.?) # a domain name
  1306. | # or
  1307. \d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3} # an IP address
  1308. | # or
  1309. \[
  1310. (?:(?:(?:(?:(?:(?:(?:[0-9a-f]{1,4})):){6})(?:(?:(?:(?:(?:[0-9a-f]{1,4})):(?:(?:[0-9a-f]{1,4})))|(?:(?:(?:(?:(?:25[0-5]|(?:[1-9]|1[0-9]|2[0-4])?[0-9]))\.){3}(?:(?:25[0-5]|(?:[1-9]|1[0-9]|2[0-4])?[0-9])))))))|(?:(?:::(?:(?:(?:[0-9a-f]{1,4})):){5})(?:(?:(?:(?:(?:[0-9a-f]{1,4})):(?:(?:[0-9a-f]{1,4})))|(?:(?:(?:(?:(?:25[0-5]|(?:[1-9]|1[0-9]|2[0-4])?[0-9]))\.){3}(?:(?:25[0-5]|(?:[1-9]|1[0-9]|2[0-4])?[0-9])))))))|(?:(?:(?:(?:(?:[0-9a-f]{1,4})))?::(?:(?:(?:[0-9a-f]{1,4})):){4})(?:(?:(?:(?:(?:[0-9a-f]{1,4})):(?:(?:[0-9a-f]{1,4})))|(?:(?:(?:(?:(?:25[0-5]|(?:[1-9]|1[0-9]|2[0-4])?[0-9]))\.){3}(?:(?:25[0-5]|(?:[1-9]|1[0-9]|2[0-4])?[0-9])))))))|(?:(?:(?:(?:(?:(?:[0-9a-f]{1,4})):){0,1}(?:(?:[0-9a-f]{1,4})))?::(?:(?:(?:[0-9a-f]{1,4})):){3})(?:(?:(?:(?:(?:[0-9a-f]{1,4})):(?:(?:[0-9a-f]{1,4})))|(?:(?:(?:(?:(?:25[0-5]|(?:[1-9]|1[0-9]|2[0-4])?[0-9]))\.){3}(?:(?:25[0-5]|(?:[1-9]|1[0-9]|2[0-4])?[0-9])))))))|(?:(?:(?:(?:(?:(?:[0-9a-f]{1,4})):){0,2}(?:(?:[0-9a-f]{1,4})))?::(?:(?:(?:[0-9a-f]{1,4})):){2})(?:(?:(?:(?:(?:[0-9a-f]{1,4})):(?:(?:[0-9a-f]{1,4})))|(?:(?:(?:(?:(?:25[0-5]|(?:[1-9]|1[0-9]|2[0-4])?[0-9]))\.){3}(?:(?:25[0-5]|(?:[1-9]|1[0-9]|2[0-4])?[0-9])))))))|(?:(?:(?:(?:(?:(?:[0-9a-f]{1,4})):){0,3}(?:(?:[0-9a-f]{1,4})))?::(?:(?:[0-9a-f]{1,4})):)(?:(?:(?:(?:(?:[0-9a-f]{1,4})):(?:(?:[0-9a-f]{1,4})))|(?:(?:(?:(?:(?:25[0-5]|(?:[1-9]|1[0-9]|2[0-4])?[0-9]))\.){3}(?:(?:25[0-5]|(?:[1-9]|1[0-9]|2[0-4])?[0-9])))))))|(?:(?:(?:(?:(?:(?:[0-9a-f]{1,4})):){0,4}(?:(?:[0-9a-f]{1,4})))?::)(?:(?:(?:(?:(?:[0-9a-f]{1,4})):(?:(?:[0-9a-f]{1,4})))|(?:(?:(?:(?:(?:25[0-5]|(?:[1-9]|1[0-9]|2[0-4])?[0-9]))\.){3}(?:(?:25[0-5]|(?:[1-9]|1[0-9]|2[0-4])?[0-9])))))))|(?:(?:(?:(?:(?:(?:[0-9a-f]{1,4})):){0,5}(?:(?:[0-9a-f]{1,4})))?::)(?:(?:[0-9a-f]{1,4})))|(?:(?:(?:(?:(?:(?:[0-9a-f]{1,4})):){0,6}(?:(?:[0-9a-f]{1,4})))?::))))
  1311. \] # an IPv6 address
  1312. )
  1313. (:[0-9]+)? # a port (optional)
  1314. (/?|/\S+|\?\S*|\#\S*) # a /, nothing, a / with something, a query or a fragment
  1315. $~ixu';
  1316. return preg_match($pattern, $value) > 0;
  1317. }
  1318. /**
  1319. * Get the size of an attribute.
  1320. *
  1321. * @param string $attribute
  1322. * @param mixed $value
  1323. * @return mixed
  1324. */
  1325. protected function getSize($attribute, $value)
  1326. {
  1327. $hasNumeric = $this->hasRule($attribute, $this->numericRules);
  1328. // This method will determine if the attribute is a number, string, or file and
  1329. // return the proper size accordingly. If it is a number, then number itself
  1330. // is the size. If it is a file, we take kilobytes, and for a string the
  1331. // entire length of the string will be considered the attribute size.
  1332. if (is_numeric($value) && $hasNumeric) {
  1333. return $value;
  1334. } elseif (is_array($value)) {
  1335. return count($value);
  1336. } elseif ($value instanceof File) {
  1337. return $value->getSize() / 1024;
  1338. }
  1339. return mb_strlen($value);
  1340. }
  1341. /**
  1342. * Check that the given value is a valid file instance.
  1343. *
  1344. * @param mixed $value
  1345. * @return bool
  1346. */
  1347. public function isValidFileInstance($value)
  1348. {
  1349. if ($value instanceof UploadedFile && ! $value->isValid()) {
  1350. return false;
  1351. }
  1352. return $value instanceof File;
  1353. }
  1354. /**
  1355. * Determine if a comparison passes between the given values.
  1356. *
  1357. * @param mixed $first
  1358. * @param mixed $second
  1359. * @param string $operator
  1360. * @return bool
  1361. */
  1362. protected function compare($first, $second, $operator)
  1363. {
  1364. switch ($operator) {
  1365. case '<':
  1366. return $first < $second;
  1367. case '>':
  1368. return $first > $second;
  1369. case '<=':
  1370. return $first <= $second;
  1371. case '>=':
  1372. return $first >= $second;
  1373. case '=':
  1374. return $first == $second;
  1375. default:
  1376. throw new InvalidArgumentException;
  1377. }
  1378. }
  1379. /**
  1380. * Parse named parameters to $key => $value items.
  1381. *
  1382. * @param array $parameters
  1383. * @return array
  1384. */
  1385. protected function parseNamedParameters($parameters)
  1386. {
  1387. return array_reduce($parameters, function ($result, $item) {
  1388. list($key, $value) = array_pad(explode('=', $item, 2), 2, null);
  1389. $result[$key] = $value;
  1390. return $result;
  1391. });
  1392. }
  1393. /**
  1394. * Require a certain number of parameters to be present.
  1395. *
  1396. * @param int $count
  1397. * @param array $parameters
  1398. * @param string $rule
  1399. * @return void
  1400. *
  1401. * @throws \InvalidArgumentException
  1402. */
  1403. protected function requireParameterCount($count, $parameters, $rule)
  1404. {
  1405. if (count($parameters) < $count) {
  1406. throw new InvalidArgumentException("Validation rule $rule requires at least $count parameters.");
  1407. }
  1408. }
  1409. /**
  1410. * Require comparison values to be of the same type.
  1411. *
  1412. * @param mixed $first
  1413. * @param mixed $second
  1414. * @return void
  1415. *
  1416. * @throws \InvalidArgumentException
  1417. */
  1418. protected function requireSameType($first, $second)
  1419. {
  1420. if (gettype($first) != gettype($second)) {
  1421. throw new InvalidArgumentException('The values under comparison must be of the same type');
  1422. }
  1423. }
  1424. /**
  1425. * Adds the existing rule to the numericRules array if the attribute's value is numeric.
  1426. *
  1427. * @param string $attribute
  1428. * @param string $rule
  1429. *
  1430. * @return void
  1431. */
  1432. protected function shouldBeNumeric($attribute, $rule)
  1433. {
  1434. if (is_numeric($this->getValue($attribute))) {
  1435. $this->numericRules[] = $rule;
  1436. }
  1437. }
  1438. }