TypeConverterTrait.php 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. <?php
  2. /**
  3. * CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
  4. * Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
  5. *
  6. * Licensed under The MIT License
  7. * For full copyright and license information, please see the LICENSE.txt
  8. * Redistributions of files must retain the above copyright notice.
  9. *
  10. * @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
  11. * @link http://cakephp.org CakePHP(tm) Project
  12. * @since 3.0.0
  13. * @license http://www.opensource.org/licenses/mit-license.php MIT License
  14. */
  15. namespace Cake\Database;
  16. /**
  17. * Type converter trait
  18. */
  19. trait TypeConverterTrait
  20. {
  21. /**
  22. * Converts a give value to a suitable database value based on type
  23. * and return relevant internal statement type
  24. *
  25. * @param mixed $value The value to cast
  26. * @param \Cake\Database\Type|string $type The type name or type instance to use.
  27. * @return array list containing converted value and internal type
  28. */
  29. public function cast($value, $type)
  30. {
  31. if (is_string($type)) {
  32. $type = Type::build($type);
  33. }
  34. if ($type instanceof Type) {
  35. $value = $type->toDatabase($value, $this->_driver);
  36. $type = $type->toStatement($value, $this->_driver);
  37. }
  38. return [$value, $type];
  39. }
  40. /**
  41. * Matches columns to corresponding types
  42. *
  43. * Both $columns and $types should either be numeric based or string key based at
  44. * the same time.
  45. *
  46. * @param array $columns list or associative array of columns and parameters to be bound with types
  47. * @param array $types list or associative array of types
  48. * @return array
  49. */
  50. public function matchTypes($columns, $types)
  51. {
  52. if (!is_int(key($types))) {
  53. $positions = array_intersect_key(array_flip($columns), $types);
  54. $types = array_intersect_key($types, $positions);
  55. $types = array_combine($positions, $types);
  56. }
  57. return $types;
  58. }
  59. }