• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

bleedingdeacons / confur / 43098764163

11 Nov 2026 08:54PM UTC coverage: 96.404% (+0.3%) from 96.056%
43098764163

push

github

web-flow
feat: save answers through a REST endpoint (#87)

* feat: save answers through a REST endpoint

POST confur/v1/answers/{slug} takes {"state", "answers"} as JSON, finds
the answer post by its slug and saves through SaveAnswers. It replaces
admin-post.php, which worked out the post from the Referer header.

- The slug is the credential, as it already is for viewing the page;
  there is no nonce, which would expire on cached, logged-out pages.
- A save returns {message, updated, state}; a cancelled registration is
  403, an unknown slug 404, a malformed body 400, anything else a
  generic 500.
- AssetService passes the page slug and both endpoint URLs to the page
  script with wp_localize_script on its own handle. The URLs come from
  rest_url(), so subdirectory installs and plain permalinks work; the
  old config was attached to 'jquery' and the script hard-coded
  /wp-json/ and /wp-admin/ paths.
- The page script sends only the answer fields and shows the server's
  reason when a save is refused.
- The admin-post route stays for one release and logs each use.
- README documents both endpoints.

* fix: only treat a readable JSON reply as a successful save

Addresses review on #87: a 200 that is not JSON (a proxy or login page)
was read as {} and treated as success, which cleared the group's local
copy of answers the server never received. A success must now parse and
carry the saved state.

* refactor: remove the admin-post submission fallback

Answers save only through POST confur/v1/answers/{slug} now.

- AnswerHandler keeps only the registration hook; handleSubmission and
  its two admin_post_* hooks are gone, along with the Referer lookup.
- [configure_form] renders nothing. It only added the hidden "action"
  field admin-post needed, but existing answer pages contain it, so it
  stays registered rather than showing as raw text.
- Constants::ACTION and Constants::TOKEN are removed (unused).
- The submission tests that covered behaviour not already t... (continued)

84 of 86 new or added lines in 5 files covered. (97.67%)

2413 of 2503 relevant lines covered (96.4%)

4.47 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

95.77
/src/API/AnswerAPI.php
1
<?php
2

3
namespace Confur\API;
4

5
use Confur\Application\SaveAnswers;
6
use Confur\Application\SubmissionRejected;
7
use Confur\Config\Constants;
8
use Confur\Repositories\AnswerRepository;
9
use Confur\Services\Mailer;
10
use Confur\Storage\AnswerStore;
11
use WP_Error;
12
use WP_REST_Response;
13

14
/**
15
 * REST endpoints for an answer page.
16
 *
17
 * Both are public. An answer page's slug has a random 16-character prefix and
18
 * is only ever sent to the group, so knowing the slug is what grants access —
19
 * the same model as viewing the page. There is deliberately no nonce: answer
20
 * pages are viewed logged out, often through a page cache, and a nonce baked
21
 * into a cached page expires and would make saves fail.
22
 *
23
 *   GET  answer/v1/status/{slug}      the page's state and last save time
24
 *   POST confur/v1/answers/{slug}     save answers: {"state": "Draft"|"Complete", "answers": {"c1_a1": "…"}}
25
 */
26
class AnswerAPI
27
{
28
    public const SAVE_NAMESPACE = 'confur/v1';
29
    public const SAVE_ROUTE = '/answers/(?P<slug>[a-zA-Z0-9_-]+)';
30

31
    private AnswerRepository $answerRepository;
32

33
    public function __construct(private ?SaveAnswers $saveAnswers = null)
13 ✔
34
    {
35
        $this->answerRepository = new AnswerRepository();
13 ✔
36
    }
37

38
    /**
39
     * Register REST API routes
40
     */
41
    public function registerRoutes(): void
3 ✔
42
    {
43
        $slugArg = [
3 ✔
44
            'required' => true,
3 ✔
45
            'validate_callback' => static fn ($param): bool => is_string($param) && preg_match('/^[a-zA-Z0-9_-]+$/', $param) === 1,
3 ✔
46
            'sanitize_callback' => 'sanitize_text_field',
3 ✔
47
        ];
3 ✔
48

49
        register_rest_route('answer/v1', '/status/(?P<n>[a-zA-Z0-9_-]+)', [
3 ✔
50
            'methods' => 'GET',
3 ✔
51
            'callback' => [$this, 'getAnswerPostStatus'],
3 ✔
52
            'permission_callback' => '__return_true',
3 ✔
53
            'args' => ['n' => $slugArg],
3 ✔
54
        ]);
3 ✔
55

56
        register_rest_route(self::SAVE_NAMESPACE, self::SAVE_ROUTE, [
3 ✔
57
            'methods' => 'POST',
3 ✔
58
            'callback' => [$this, 'saveAnswers'],
3 ✔
59
            // The slug is the credential; see the class comment.
60
            'permission_callback' => '__return_true',
3 ✔
61
            'args' => [
3 ✔
62
                'slug' => $slugArg,
3 ✔
63
                'state' => [
3 ✔
64
                    'type' => 'string',
3 ✔
65
                    'required' => false,
3 ✔
66
                ],
3 ✔
67
                'answers' => [
3 ✔
68
                    'type' => 'object',
3 ✔
69
                    'required' => true,
3 ✔
70
                ],
3 ✔
71
            ],
3 ✔
72
        ]);
3 ✔
73
    }
74

75
    /**
76
     * GET answer/v1/status/{slug}
77
     *
78
     * @param \WP_REST_Request|array<string, mixed> $request
79
     * @return WP_REST_Response|WP_Error
80
     */
81
    public function getAnswerPostStatus($request)
4 ✔
82
    {
83
        try {
84
            $postId = $this->findAnswerPost((string) ($request['n'] ?? ''));
4 ✔
85

86
            if ($postId instanceof WP_Error) {
4 ✔
87
                return $postId;
2 ✔
88
            }
89

90
            try {
91
                $status = $this->answerRepository->getAnswerStatus($postId);
2 ✔
92
            } catch (\Exception $e) {
1 ✔
93
                error_log("AnswerAPI::getAnswerPostStatus - Failed to read status for post $postId: " . $e->getMessage());
1 ✔
94
                return new WP_Error('repository_error', 'Failed to retrieve answer status.', ['status' => 500]);
1 ✔
95
            }
96

97
            return new WP_REST_Response($status, 200);
1 ✔
98
        } catch (\Exception $e) {
×
NEW
99
            error_log('AnswerAPI::getAnswerPostStatus - Unexpected error: ' . $e->getMessage());
×
NEW
100
            return new WP_Error('internal_error', 'An unexpected error occurred while processing your request.', ['status' => 500]);
×
101
        }
102
    }
103

104
    /**
105
     * POST confur/v1/answers/{slug}
106
     *
107
     * @param \WP_REST_Request|array<string, mixed> $request
108
     * @return WP_REST_Response|WP_Error
109
     */
110
    public function saveAnswers($request)
6 ✔
111
    {
112
        try {
113
            $postId = $this->findAnswerPost((string) ($request['slug'] ?? ''));
6 ✔
114

115
            if ($postId instanceof WP_Error) {
6 ✔
116
                return $postId;
1 ✔
117
            }
118

119
            $answers = $request['answers'] ?? null;
5 ✔
120

121
            if (!is_array($answers)) {
5 ✔
122
                return new WP_Error('invalid_request', 'answers must be an object of field name to text.', ['status' => 400]);
1 ✔
123
            }
124

125
            $result = $this->saveService()->save($postId, $answers, $request['state'] ?? null);
4 ✔
126

127
            return new WP_REST_Response([
2 ✔
128
                'message' => $result->message,
2 ✔
129
                'updated' => $result->updated,
2 ✔
130
                'state' => $result->state->value,
2 ✔
131
            ], 200);
2 ✔
132
        } catch (SubmissionRejected $e) {
2 ✔
133
            return new WP_Error('submission_rejected', $e->getMessage(), ['status' => $e->status]);
1 ✔
134
        } catch (\Exception $e) {
1 ✔
135
            error_log('AnswerAPI::saveAnswers - Unexpected error: ' . $e->getMessage());
1 ✔
136
            error_log('AnswerAPI::saveAnswers - Stack trace: ' . $e->getTraceAsString());
1 ✔
137
            return new WP_Error('internal_error', 'An error occurred while saving your answers. Please try again.', ['status' => 500]);
1 ✔
138
        }
139
    }
140

141
    /** The id of the answer post a slug names, or a WP_Error to return as-is. */
142
    private function findAnswerPost(string $slug): int|WP_Error
10 ✔
143
    {
144
        $slug = sanitize_text_field($slug);
10 ✔
145

146
        if ($slug === '') {
10 ✔
147
            return new WP_Error('invalid_request', 'Post name is required.', ['status' => 400]);
1 ✔
148
        }
149

150
        $post = get_page_by_path($slug, OBJECT, Constants::ANSWER_CUSTOM_TYPE);
9 ✔
151

152
        if (!$post instanceof \WP_Post) {
9 ✔
153
            return new WP_Error('invalid_post', 'The specified post does not exist.', ['status' => 404]);
2 ✔
154
        }
155

156
        return $post->ID;
7 ✔
157
    }
158

159
    private function saveService(): SaveAnswers
4 ✔
160
    {
161
        return $this->saveAnswers ??= new SaveAnswers(new AnswerStore(), Mailer::fromOptions());
4 ✔
162
    }
163
}
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE TRIAL · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc