私は、Twilio 経由で着信 SMS メッセージを受信し、ハッシュタグと設定に基づいてユーザー設定を変更する PHP アプリケーションに取り組んでいます。たとえば、ユーザーがサイトからの SMS アラートを無効にしたい場合、テキスト メッセージを送信します#sms off
。
以下は、このタスクを処理するためにまとめたコードですが、肥大化しており、少しクリーンアップできると感じています。このタスクに別の(できればもっときちんとした)角度からアプローチする方法についての提案をいただければ幸いです。
着信ハッシュタグが任意の cAsE - #SMS off
、#Sms Off
などに含まれる可能性があるため、注意が必要です。コマンドと設定の両方を大文字にすることでこれに対処します。
これが私がこれまでに持っているものです-
<?php
$body = trim($_POST['Body']);
$pos = strripos($body, '#'); //Find position of hashtag in body
if ($pos != 0) {
//Hashtag was not first, therefor this is a normal incoming SMS
//without commands
echo "Normal SMS message";
} else if ($pos == 0) {
//This is a command SMS, we need to react to it
preg_match_all('/#(\w+)/',$body,$matches); // Isolate the hashtag
// Change hashtag, complete with #, to uppercase
//This is to prevent case issues in the incoming SMS
$command = strtoupper($matches[0][0]);
//Remove the hashtag from the SMS, convert the remaining string to upper,
//and trim it to isolate
$setting = str_ireplace($command, '', $body);
$setting = strtoupper(trim($setting));
//Switch for available commands
switch ($command) {
case '#DISPATCH':
if ($setting == 'ON') {
echo 'Dispatch alert has been turned on';
} else if ($setting == 'OFF') {
echo 'Dispatch alert has been turned off';
} else {
'Missing setting. Please reply with #dispatch on or #dispatch off to set.';
}
break;
case '#SMS':
if ($setting == 'ON') {
echo 'SMS alerts have been turned on';
} else if ($setting == 'OFF') {
echo 'SMS alerts have been turned off';
} else {
'Missing setting. Please reply with #sms on or #sms off to set.';
}
break;
default:
echo 'I do not recognize this command. Please enter either #dispatch or #sms followed by on or off to set.';
break;
}
}
ありがとう!