friendship ended with social-app. php is my new best friend
1---
2title: Working with Enums
3description: Guide on using enums in the Fetch PHP client package
4---
5
6# Working with Enums
7
8Fetch PHP makes extensive use of PHP 8.1's enum feature to provide type safety and better developer experience. This guide explains how to effectively work with the three main enums in the package: `Method`, `ContentType`, and `Status`.
9
10## Overview of Enums in Fetch PHP
11
12Fetch PHP includes three key enums that represent common HTTP concepts:
13
141. **Method** - HTTP methods like GET, POST, PUT, etc.
152. **ContentType** - MIME types for HTTP request and response bodies
163. **Status** - HTTP status codes and their meanings
17
18These enums provide several benefits:
19
20- Type safety and autocompletion in your IDE
21- Helper methods for common operations
22- Documentation and standardization
23- Improved code readability
24
25## Using the Method Enum
26
27The `Method` enum represents HTTP methods and helps ensure you're using valid methods in your requests.
28
29```php
30use Fetch\Enum\Method;
31
32// Using enum values directly
33$response = fetch('https://api.example.com/users', [
34 'method' => Method::GET
35]);
36
37// Using string values (automatically converted)
38$response = fetch('https://api.example.com/users', [
39 'method' => 'POST'
40]);
41
42// Using with the ClientHandler
43$response = fetch_client()
44 ->request(Method::PUT, 'https://api.example.com/users/1', $data);
45```
46
47### Method Enum Features
48
49#### Available Values
50
51```php
52Method::GET // "GET"
53Method::POST // "POST"
54Method::PUT // "PUT"
55Method::PATCH // "PATCH"
56Method::DELETE // "DELETE"
57Method::HEAD // "HEAD"
58Method::OPTIONS // "OPTIONS"
59```
60
61#### Converting Strings to Method Enum
62
63```php
64// Convert a string to a Method enum (throws ValueError if invalid)
65$method = Method::fromString('get'); // Returns Method::GET
66$method = Method::fromString('post'); // Returns Method::POST
67
68// Safely try to convert a string to a Method enum
69$method = Method::tryFromString('get'); // Returns Method::GET
70$method = Method::tryFromString('invalid', Method::GET); // Returns Method::GET (default)
71```
72
73#### Checking Method Properties
74
75```php
76// Check if a method supports a request body
77if (Method::POST->supportsRequestBody()) {
78 // Add body to the request
79}
80
81// Only methods that support request bodies will return true
82Method::POST->supportsRequestBody(); // true
83Method::PUT->supportsRequestBody(); // true
84Method::PATCH->supportsRequestBody(); // true
85Method::DELETE->supportsRequestBody(); // true
86Method::GET->supportsRequestBody(); // false
87Method::HEAD->supportsRequestBody(); // false
88```
89
90## Using the ContentType Enum
91
92The `ContentType` enum represents MIME types for HTTP content and provides utilities for working with different content formats.
93
94```php
95use Fetch\Enum\ContentType;
96
97// Using enum in request methods
98$response = fetch_client()->post(
99 'https://api.example.com/users',
100 ['name' => 'John Doe'],
101 ContentType::JSON
102);
103
104// Setting headers with enum values
105$response = fetch_client()
106 ->withHeader('Content-Type', ContentType::FORM_URLENCODED->value)
107 ->post('https://api.example.com/login', $formData);
108```
109
110### ContentType Enum Features
111
112#### Available Values
113
114```php
115ContentType::JSON // "application/json"
116ContentType::FORM_URLENCODED // "application/x-www-form-urlencoded"
117ContentType::MULTIPART // "multipart/form-data"
118ContentType::TEXT // "text/plain"
119ContentType::HTML // "text/html"
120ContentType::XML // "application/xml"
121ContentType::XML_TEXT // "text/xml"
122ContentType::BINARY // "application/octet-stream"
123ContentType::PDF // "application/pdf"
124ContentType::CSV // "text/csv"
125ContentType::ZIP // "application/zip"
126ContentType::JAVASCRIPT // "application/javascript"
127ContentType::CSS // "text/css"
128```
129
130#### Converting Strings to ContentType Enum
131
132```php
133// Convert a string to a ContentType enum
134$type = ContentType::fromString('application/json'); // Returns ContentType::JSON
135
136// Safely try to convert a string to a ContentType enum
137$type = ContentType::tryFromString('application/json'); // Returns ContentType::JSON
138$type = ContentType::tryFromString('invalid/type'); // Returns null
139```
140
141#### Normalizing Content Types
142
143The `normalizeContentType()` method is particularly useful when your API needs to accept both string content types and enum values:
144
145```php
146use Fetch\Enum\ContentType;
147
148function processRequest($data, string|ContentType $contentType) {
149 // Normalize the content type
150 $normalizedType = ContentType::normalizeContentType($contentType);
151
152 // If it's a known enum value, we can use the helper methods
153 if ($normalizedType instanceof ContentType) {
154 if ($normalizedType->isJson()) {
155 return json_decode($data, true);
156 }
157 }
158
159 // Otherwise, work with it as a string
160 return $data;
161}
162
163// Both of these work:
164processRequest($data, ContentType::JSON);
165processRequest($data, 'application/json');
166```
167
168#### Checking Content Type Properties
169
170```php
171// Check if a content type is JSON
172ContentType::JSON->isJson(); // true
173ContentType::HTML->isJson(); // false
174
175// Check if a content type is form-urlencoded
176ContentType::FORM_URLENCODED->isForm(); // true
177ContentType::MULTIPART->isForm(); // false
178
179// Check if a content type is multipart form data
180ContentType::MULTIPART->isMultipart(); // true
181ContentType::JSON->isMultipart(); // false
182
183// Check if a content type is text-based
184ContentType::JSON->isText(); // true
185ContentType::HTML->isText(); // true
186ContentType::MULTIPART->isText(); // false
187ContentType::BINARY->isText(); // false
188```
189
190## Using the Status Enum
191
192The `Status` enum represents HTTP status codes and provides utilities for working with different response types.
193
194```php
195use Fetch\Enum\Status;
196
197// Get a response
198$response = fetch('https://api.example.com/users');
199
200// Check status using enum comparison
201if ($response->getStatus() === Status::OK) {
202 // Process successful response
203}
204
205// Or using helper methods
206if ($response->getStatus()->isSuccess()) {
207 // Process successful response
208} elseif ($response->getStatus()->isClientError()) {
209 // Handle client error
210}
211```
212
213### Status Enum Features
214
215#### Available Values
216
217The Status enum includes all standard HTTP status codes. Here are some common ones:
218
219```php
220// 2xx Success
221Status::OK // 200
222Status::CREATED // 201
223Status::ACCEPTED // 202
224Status::NO_CONTENT // 204
225
226// 3xx Redirection
227Status::MOVED_PERMANENTLY // 301
228Status::FOUND // 302
229Status::NOT_MODIFIED // 304
230
231// 4xx Client Error
232Status::BAD_REQUEST // 400
233Status::UNAUTHORIZED // 401
234Status::FORBIDDEN // 403
235Status::NOT_FOUND // 404
236Status::METHOD_NOT_ALLOWED // 405
237Status::UNPROCESSABLE_ENTITY // 422
238Status::TOO_MANY_REQUESTS // 429
239
240// 5xx Server Error
241Status::INTERNAL_SERVER_ERROR // 500
242Status::BAD_GATEWAY // 502
243Status::SERVICE_UNAVAILABLE // 503
244Status::GATEWAY_TIMEOUT // 504
245```
246
247See the [Status Enum API Reference](/api/status-enum) for a complete list of available status codes.
248
249#### Converting Integers to Status Enum
250
251```php
252// Convert an integer to a Status enum
253$status = Status::fromInt(200); // Returns Status::OK
254
255// Safely try to convert an integer to a Status enum
256$status = Status::tryFromInt(200); // Returns Status::OK
257$status = Status::tryFromInt(999, Status::OK); // Returns Status::OK (default)
258```
259
260#### Getting the Reason Phrase
261
262```php
263// Get the reason phrase for a status code
264Status::OK->phrase(); // "OK"
265Status::NOT_FOUND->phrase(); // "Not Found"
266Status::INTERNAL_SERVER_ERROR->phrase(); // "Internal Server Error"
267```
268
269#### Checking Status Code Categories
270
271```php
272// Informational responses (100-199)
273Status::CONTINUE->isInformational(); // true
274Status::OK->isInformational(); // false
275
276// Success responses (200-299)
277Status::OK->isSuccess(); // true
278Status::CREATED->isSuccess(); // true
279Status::NOT_FOUND->isSuccess(); // false
280
281// Redirection responses (300-399)
282Status::FOUND->isRedirection(); // true
283Status::MOVED_PERMANENTLY->isRedirection(); // true
284Status::OK->isRedirection(); // false
285
286// Client error responses (400-499)
287Status::BAD_REQUEST->isClientError(); // true
288Status::NOT_FOUND->isClientError(); // true
289Status::OK->isClientError(); // false
290
291// Server error responses (500-599)
292Status::INTERNAL_SERVER_ERROR->isServerError(); // true
293Status::BAD_GATEWAY->isServerError(); // true
294Status::NOT_FOUND->isServerError(); // false
295
296// Any error (either client or server)
297Status::NOT_FOUND->isError(); // true
298Status::INTERNAL_SERVER_ERROR->isError(); // true
299Status::OK->isError(); // false
300```
301
302#### Special Status Properties
303
304```php
305// Check if a status code indicates the resource was not modified
306Status::NOT_MODIFIED->isNotModified(); // true
307Status::OK->isNotModified(); // false
308
309// Check if a status code indicates an empty response
310Status::NO_CONTENT->isEmpty(); // true
311Status::NOT_MODIFIED->isEmpty(); // true
312Status::OK->isEmpty(); // false
313
314// Check if a response with this status is cacheable
315Status::OK->isCacheable(); // true
316Status::NOT_FOUND->isCacheable(); // true
317Status::NO_CONTENT->isCacheable(); // false
318```
319
320## Best Practices for Working with Enums
321
3221. **Use Enum Values Directly** - When possible, use enum values directly for better type safety:
323
324```php
325// Good - uses enum
326$response = fetch_client()->request(Method::POST, '/users', $data);
327
328// Also good - string is automatically converted
329$response = fetch_client()->request('POST', '/users', $data);
330```
331
3322. **Take Advantage of Helper Methods** - Enums provide semantic helper methods:
333
334```php
335// Instead of checking numeric ranges
336if ($status >= 200 && $status < 300) { ... }
337
338// Use the helper methods
339if ($status->isSuccess()) { ... }
340```
341
3423. **Leverage IDE Autocompletion** - Enums provide excellent autocomplete support:
343
344```php
345// Start typing Method:: and see all available options
346$method = Method::POST;
347
348// Similarly with ContentType:: and Status::
349$contentType = ContentType::JSON;
350$status = Status::OK;
351```
352
3534. **Accept Both Strings and Enums in Your APIs** - Use union types and normalizers:
354
355```php
356function sendRequest(string|Method $method, string $url) {
357 // Convert string to enum if needed
358 $methodEnum = $method instanceof Method
359 ? $method
360 : Method::tryFromString($method, Method::GET);
361
362 // Now you can use the enum features
363 if ($methodEnum->supportsRequestBody()) {
364 // Add body
365 }
366}
367```
368
3695. **Compose with Enums** - Use enums for more expressive code:
370
371```php
372// Build a request with enums
373$request = fetch_client()
374 ->withHeader('Content-Type', ContentType::JSON->value)
375 ->withBody($data, ContentType::JSON)
376 ->sendRequest(Method::POST, 'https://api.example.com/users');
377
378// Check response using enums
379if ($response->getStatus() === Status::CREATED) {
380 // Resource was created
381}
382```
383
384## Integration with Response Object
385
386The Fetch PHP Response object integrates well with Status and ContentType enums:
387
388```php
389$response = fetch('https://api.example.com/users');
390
391// Get status as enum
392$statusEnum = $response->statusEnum();
393
394// Check specific status
395if ($statusEnum === Status::OK) {
396 // Process OK response
397}
398
399// Get content type as enum
400$contentTypeEnum = $response->contentTypeEnum();
401
402// Check content type
403if ($contentTypeEnum === ContentType::JSON) {
404 // Process JSON response
405}
406
407// Or use the helper methods
408if ($response->hasJsonContent()) {
409 $data = $response->json();
410}
411```
412
413## Next Steps
414
415- Learn about [Working with Responses](/guide/working-with-responses) to see how Status enums are used in response handling
416- Discover [Error Handling](/guide/error-handling) techniques using Status enums for different error scenarios
417- See [Making Requests](/guide/making-requests) for more examples of using Method and ContentType enums
418- Check out [Helper Functions](/guide/helper-functions) to see how enums integrate with the library's helper functions
419- Explore [Authentication](/guide/authentication) to learn how Method enums are used in authentication flows