Skip to content

Fatal error: Uncaught TypeError: deletePostById(): Argument #1 ($id) must be of type string, null given

 <?php

include_once 'Post.php';

const DATA_FILE = 'posts.txt';


savePost(new Post(null, "title", "text 2"));

print postsToString(getAllPosts());
function getAllPosts() : array {
    $lines = file(DATA_FILE);
    $posts = [];
    foreach ($lines as $line) {
        [$id, $title, $text] = explode(';', trim($line));
        $posts[] = new Post(urldecode($id), urldecode($title), urldecode($text));
    }
    return $posts;
}

function savePost(Post $post): void {

    if ($post->id) {
        deletePostById($post->id);
    }

    $post->id = $post->id ?? getNewId();

    file_put_contents(DATA_FILE,
        postToTextLine($post), FILE_APPEND);
}
function postToTextLine(Post $post): string {
    return urlencode($post->id) . ';'
        . urlencode($post->title) . ';'
        . urlencode($post->text) . PHP_EOL;
}
function deletePostById(string $id): void {

    $posts = getAllPosts();
    $lines = [];
    foreach ($posts as $post) {
        if ($post->id !== $id) {
            $lines[] = postToTextLine($post);
        }

    }
    file_put_contents(DATA_FILE, implode('', $lines));
}

function getNewId(): string {
    $id = file_get_contents('next-id.txt');
    file_put_contents('next-id.txt', intval($id) + 1);
    return $id;
}

function postsToString(array $posts): string {
    $result = '';
    foreach ($posts as $post) {
        $result .= $post . PHP_EOL;
    }
    return $result;
}

TEST:function canDeletePosts() {

    chdir(getProjectDirectory() . '/ex4/posts');

    require_once 'post-functions.php';

    $title = getRandomString(10);

    $post = new Post(null, $title, '');

    $id = savePost($post);

    deletePostById($id);

    assertDoesNotContainPostWithTitle(getAllPosts(), $title);
}