1: <?php
2: namespace Worldline\Connect\Sdk;
3:
4: /**
5: * Class BodyHandler
6: * A utility class that can be used to support binary responses. Its handleBodyPart method can be used as
7: * callback to methods that require a body handler callable.
8: *
9: * @package Worldline\Connect\Sdk
10: */
11: class BodyHandler
12: {
13: /**
14: * @var bool
15: */
16: private bool $initialized = false;
17:
18: /**
19: * Initializes this body handler if not done yet, then calls doHandleBodyPart.
20: *
21: * @param string $bodyPart
22: * @param array $headers
23: *
24: * @return void
25: */
26: final public function handleBodyPart(string $bodyPart, array $headers): void
27: {
28: if (!$this->initialized) {
29: $this->initialize($headers);
30: $this->initialized = true;
31: }
32: $this->doHandleBodyPart($bodyPart);
33: }
34:
35: /**
36: * Calls doCleanup, then marks this body handler as not initialized.
37: * Afterwards this instance can be reused again.
38: *
39: * @return void
40: */
41: final public function close(): void
42: {
43: $this->doCleanup();
44: $this->initialized = false;
45: }
46:
47: /**
48: * Can be used to initialize this body handler based on the given headers.
49: * The default implementation does nothing.
50: *
51: * @param array $headers
52: *
53: * @return void
54: */
55: protected function initialize(array $headers): void
56: {
57: }
58:
59: /**
60: * Can be used to handle a single body part.
61: * The default implementation does nothing.
62: *
63: * @param string $bodyPart
64: *
65: * @return void
66: */
67: protected function doHandleBodyPart(string $bodyPart): void
68: {
69: }
70:
71: /**
72: * Can be used to do cleanup resources allocated by this body handler.
73: * The default implementation does nothing.
74: *
75: * @return void
76: */
77: protected function doCleanup(): void
78: {
79: }
80: }
81: