|
- <?php
-
- namespace App\Http\API\SMBC\BankAccountRegister;
-
- use App\Util\EncodingUtil;
- use Exception;
- use Illuminate\Support\Collection;
- use Illuminate\Support\Str;
-
- class PollResult
- {
- // 共通
- private const IDX_RECORD_CODE = 0;
- // ヘッダー
- private const IDX_HEADER_RESULT = 1;
- private const IDX_HEADER_MESSAGE = 2;
- // ボディー
- private const IDX_FOOTER_COUNT = 1;
- // フッター
-
- private const RECORD_CODE_HEADER = "10";
- private const RECORD_CODE_BODY = "20";
- private const RECORD_CODE_FOOTER = "80";
- private const RESULT_CODE_SUCCESS = ["000000", "943037"];
-
-
- /**
- * @var Collection<int, Collection<int, string>>
- */
- private Collection $lines;
-
- /**
- * @var Collection<int, PollResultRecord>
- */
- private Collection $body;
-
- private bool $success = false;
- private string $message = "";
- private int $count = 0;
-
- public function __construct(string $data)
- {
- $this->lines = collect();
- $lines = Str::of($data)->replace('"', '')->explode("\r\n");
- foreach ($lines as $lineStr) {
- if ($lineStr) {
- $lineStr = EncodingUtil::toUtf8FromSjis($lineStr);
- $this->lines->push(Str::of($lineStr)->explode(','));
- }
- }
-
- if (!$this->parseHeader()) {
- return;
- }
- if (!$this->parseBody()) {
- return;
- }
- if (!$this->parseFooter()) {
- return;
- }
-
- $this->success = true;
- }
-
- public function ok(): bool
- {
- return $this->success;
- }
- public function getMessage(): string
- {
- return $this->message;
- }
-
- public function getRecord()
- {
- return $this->body;
- }
-
- public function getCount(): int
- {
- return $this->count;
- }
-
- private function parseHeader(): bool
- {
- $header = $this->lines->first();
- if (!$header) {
- $this->success = false;
- $this->message = "ヘッダーなし";
- return false;
- }
-
- $resultCode = $header->get(self::IDX_HEADER_RESULT);
- if (!in_array($resultCode, self::RESULT_CODE_SUCCESS)) {
- $this->success = false;
- $this->message = sprintf("結果コードNG %s", $resultCode);
- $readMessage = EncodingUtil::toUtf8FromSjis($header->get(self::IDX_HEADER_MESSAGE));
- return false;
- }
- return true;
- }
-
- private function parseBody(): bool
- {
- $this->body = collect();
-
- try {
- foreach ($this->lines as $line) {
- if ($line[self::IDX_RECORD_CODE] === self::RECORD_CODE_BODY) {
- $this->body->push(new PollResultRecord($line));
- }
- }
- } catch (Exception $e) {
- $this->success = false;
- $this->message = sprintf("Bodyパース失敗 %s", $e->getMessage());
- return false;
- }
-
- // Mypage経由で登録したものだけを対象とする
- $this->body = $this->body->filter(function (PollResultRecord $record) {
- return $record->address5 === SMBC::CONDITION_ADDR5_FROM_MY_PAGE;
- });
-
- return true;
- }
-
- private function parseFooter(): bool
- {
- $footer = $this->lines->last();
-
- if (!$footer) {
- $this->success = false;
- $this->message = "フッターなし";
- return false;
- }
-
- $this->count = $this->body->count();
-
- return true;
- }
- }
|