Advertisement
Guest User

Untitled

a guest
Apr 24th, 2017
63
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.39 KB | None | 0 0
  1. <?php
  2.  
  3. class B
  4. {
  5. public $id = 123;
  6. }
  7.  
  8. class C
  9. {
  10. private $values = [1, 2, 3];
  11. private $ident = 'abc';
  12. }
  13.  
  14. class A
  15. {
  16. private $b;
  17. public $c;
  18. private $age = 42;
  19. private $name = 'Foo';
  20.  
  21. public function __construct(B $b)
  22. {
  23. $this->b = $b;
  24. }
  25. }
  26.  
  27. class D
  28. {
  29. public $name = 'Test';
  30. private $age = 42;
  31. }
  32.  
  33. $a = new A(new B());
  34. $a->c = new C();
  35.  
  36. $d = new D();
  37. //print serialize($d);
  38.  
  39. function serialized(stdClass $std, string $class): string
  40. {
  41. return sprintf(
  42. 'O:%d:"%s"%s',
  43. strlen($class),
  44. $class,
  45. strstr(strstr(serialize($std), '"'), ':')
  46. );
  47. }
  48.  
  49. function cast(stdClass $std, string $class, array $properties = [])
  50. {
  51. foreach($std as $key => $prop) {
  52. if ($prop instanceof stdClass) {
  53. $std->{$key} = cast($prop, $properties[$key]);
  54. }
  55. }
  56.  
  57. $serialized = preg_replace(
  58. '/^O:\d+:"[^"]++"/',
  59. 'O:' . strlen($class) . ':"' . $class . '"',
  60. serialize($std)
  61. );
  62.  
  63. if ($class === A::class) {
  64. print_r($serialized);
  65. exit;
  66. }
  67.  
  68. return unserialize($serialized);
  69. }
  70.  
  71. var_dump($d);
  72. var_dump($a);
  73.  
  74. print '====' . PHP_EOL;
  75.  
  76. $std1 = json_decode('{"name":"Test"}');
  77. var_dump(cast($std1, D::class));
  78. $std2 = json_decode('{"b":{"id":123},"c":{"values":[1,2,3],"ident":"abc"},"age":42,"name":"Foo"}');
  79. var_dump(cast($std2, A::class, ['b' => B::class, 'c' => C::class]));
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement