php-school/php8-appreciate

Stringable Interface

mikeymike opened this issue · 0 comments

Name: Stringify to Demystify

Brief

  • Ask them to take some json we provide in POST data
  • This data should be transformed into an object that represents a failed http request, e.g. status, headers, url
  • This object should implement Stringable and it's required methods
  • Pass this object to a debug function that will take a string message and a Stringable context to log out accordingly.

e.g.

<?php

function debug(string $message, Stringable $context = null) {
    echo $message;
    
    if (null !== $context) {
        echo "\n context: " . $context;
    }
}

class FailedResponse implements Stringable {
    
    public function __construct(public string $status) {}
    
    public function __toString()
    {
        return "Status: {$this->status} \n ...";
    
    }
    
}

$responseData = json_decode('{"status": "403"}', true);
$failedResponse = new FailedResponse($responseData['status']);

debug('The request failed', $failedResponse);

Verification

  • Check the object is sent to debug and doesn't create type error
  • Check output contains data from request