lesterchan / wp-polls

Adds an AJAX poll system to your WordPress blog. You can also easily add a poll into your WordPress's blog post/page.
https://wordpress.org/plugins/wp-polls/
91 stars 78 forks source link

refactor vote_poll to work outside of ajax call #125

Closed kasn closed 5 years ago

kasn commented 5 years ago

Intention

I'm currently migrating a project to use a modern frontend written in react. For fetching data from the backend I'm using wp-graphql. I don't want to replace battle tested and loved by editors and users plugins like wp-polls. To make everything work I need to write custom graphql queries and mutations. During this process, I got stuck on the current implementation of vote_poll. My main issue is the fact that the function does everything at once. Nonce validation, request parsing and validation, displaying output and the core voting stuff. Additionally, it calls exit() and stops the scripts before the response is sent. For my graphql usecase I just need to cast the vote and can ignore the wordpress ajax validation, but can't work on the $_REQUEST and have to access to $_POST

What did I do? My focus in this PR was the process case in the view switch (Starting Line 1349). I separated the voting validation and logic into its own function that receives the required parameters to cast a vote. The old vote_poll function still exists, does all the necessary request validation and passes the parameters to the new vote_poll_process function. The vote_poll_process function can now be called programmatically, as I'm doing in my graphql resolvers. I replaced all the error messages with Exceptions in order to prevent code to display something which will break the graphql request. Outside of the call to vote_poll_process exceptions are caught and displayed. The behavior on the outside remains unchanged.

Also, I took // The multiple ifs is ugly, I know it. Feel free to send a PR to fix it to heart and flattened the ident hadooken

If you are interested, I'll be happy to add the graphql mutations in another PR.

best regards

Karsten

lesterchan commented 5 years ago

Wow this looks really good! Thanks for this. Once u remove the debug statement, I will merge it in!