пытается исправить функцию publi c - PullRequest
0 голосов
/ 09 июля 2020

Первый пост здесь, извините за отсутствие контента, скажите мне, если вам нужно больше кода или больше объяснений. Я работаю над веб-сайтом в php, используя структуру laravel. Я работаю над исправлением ошибки: есть инструмент для создания опроса на веб-сайте, инструмент (SurveyMaster) должен создать файл excel с результатом, но когда вы пытаетесь вставить какой-то текст вместо вопроса , в файле excel ничего нет.

Я почти уверен, что за эту ошибку отвечает эта функция

    public function setDataResult()
    {
        $questions = $this->getQuestions();
        foreach ($questions as $question) {
            if (is_array($question)) { // it's not a page
                $this->resultMap[$question['name']] = $this->replaceValueByText($this->searchAnswer($question['name']),
                    $question['name']);
            } else {
                $this->resultMap[$question] = "";
            }
        }

        return $this->resultMap;
    }

Есть что-то подозрительное с if условие, но я не вижу, что не так. Условие для включения текста в опрос json?

Спасибо, если вам нужна дополнительная информация, сообщите мне!

Edit;

Вот функция getQuestions (), и да, я полагаю, текст и вопросы - это две отдельные сущности.

public function getQuestions(): array
    {
        $questions = ['Questions'];

        foreach (json_decode($this->getDefinition())->pages as $page) {
            $questions[] = $page->name;
            foreach ($page->elements as $question) {
                $questions[] = [
                    'name' => $question->name,
                    'title' => $this->questionTitle($question->title ?? null, $question->name),
                ];
                if ($question->type === 'panel') {
                    foreach ($question->elements as $panelQuestion) {
                        $questions[] = [
                            'name' => $panelQuestion->name,
                            'title' => $this->questionTitle($panelQuestion->title ?? null, $panelQuestion->name),
                        ];
                    }
                } elseif ($question->type === "matrix" || $question->type === "matrixdropdown") {
                    foreach ($question->rows as $row) {
                        $questions[] = [
                            'name' => $question->name . "[" . $row . "]",
                            'title' => $question->name . '-' . $row,
                        ];
                    }
                } elseif ($question->type === "matrixdynamic") {
                    foreach ($question->columns as $column) {
                        $questions[] = [
                            'name' => $question->name . "[" . $column->name . "]",
                            'title' => $question->name . '-' . $column->name,
                        ];
                    }

                }
                if (isset($question->hasComment)) {
                    $questions[] = [
                        'name' => $question->name . '-' . 'Comment',
                        'title' => $this->questionTitle($question->title ?? null,
                                $question->name) . ' - ' . (isset($question->commentText) ? $question->commentText : 'Comment'),
                    ];
                }
            }

        }
        return $questions;
    }

Редактировать 2: На самом деле, должно быть лучше, если я пропущу два полных файла, потому что я не понимаю, где находятся массивы.

<?php

namespace App\Helpers\Backend;

use Illuminate\Support\Facades\App;
use Nahid\JsonQ\Jsonq;


class SurveyJson
{
    protected $jsonDefinition;
    protected $jsonResult;
    protected $askFriendQuestions = [];
    protected $askFriendUsernames = [];
    protected $jsonq;
    protected $multipages = false;
    protected $resultMap = [];

    public function __construct($jsonDefinition, $jsonResult, $askFriendQuestions, $askFriendUsernames)
    {
        $this->jsonDefinition = $jsonDefinition;
        $this->jsonResult = $jsonResult;
        $this->jsonq = new Jsonq();
        $this->jsonq->json($this->jsonDefinition);
        $this->multipages = $this->isMultiPages();
        $this->askFriendQuestions = explode(',', $askFriendQuestions);
        $this->askFriendUsernames = explode(',', $askFriendUsernames);
    }

    protected function reset()
    {
        $this->jsonq->json($this->jsonDefinition);
    }

    public function isMultiPages()
    {
        return $this->jsonq->from('pages')->count() > 1;
    }

    public function getJsonq()
    {
        return $this->jsonq;
    }

    public function getDefinition()
    {
        return $this->jsonDefinition;
    }

    public function getResult()
    {
        return $this->jsonResult;
    }


    private function searchQuestionInElements($idQuestion, $elements)
    {
        foreach ($elements as $element) {
            if (isset($element->elements)) {
                if ($result = $this->searchQuestionInElements($idQuestion, $element->elements)) {
                    return $result;
                }
            } else {
                if (isset($element->name) && $element->name === $idQuestion) {
                    return $element;
                }
            }
        }

        return null;
    }

    public function searchQuestion($idQuestion)
    {
        foreach (json_decode($this->getDefinition())->pages as $page) {
            return $this->searchQuestionInElements($idQuestion, $page->elements);
        }

        return null;
    }

    private function questionTitle($title, $name)
    {
        if ($title) {
            if (is_object($title)) { //there is a translation of the question's title
                $locale = App::getLocale();
                if (isset($title->$locale)) {
                    return $title->$locale;
                }
                return $title->default;
            } else {
                return $title;
            }
        } else {
            return $name;
        }
    }

    public function getQuestions(): array
    {
        $questions = ['Questions'];

        foreach (json_decode($this->getDefinition())->pages as $page) {
            $questions[] = $page->name;
            foreach ($page->elements as $question) {
                $questions[] = [
                    'name' => $question->name,
                    'title' => $this->questionTitle($question->title ?? null, $question->name),
                ];
                if ($question->type === 'panel') {
                    foreach ($question->elements as $panelQuestion) {
                        $questions[] = [
                            'name' => $panelQuestion->name,
                            'title' => $this->questionTitle($panelQuestion->title ?? null, $panelQuestion->name),
                        ];
                    }
                } elseif ($question->type === "matrix" || $question->type === "matrixdropdown") {
                    foreach ($question->rows as $row) {
                        $questions[] = [
                            'name' => $question->name . "[" . $row . "]",
                            'title' => $question->name . '-' . $row,
                        ];
                    }
                } elseif ($question->type === "matrixdynamic") {
                    foreach ($question->columns as $column) {
                        $questions[] = [
                            'name' => $question->name . "[" . $column->name . "]",
                            'title' => $question->name . '-' . $column->name,
                        ];
                    }

                }
                if (isset($question->hasComment)) {
                    $questions[] = [
                        'name' => $question->name . '-' . 'Comment',
                        'title' => $this->questionTitle($question->title ?? null,
                                $question->name) . ' - ' . (isset($question->commentText) ? $question->commentText : 'Comment'),
                    ];
                }
            }

        }
        return $questions;
    }

    public function searchAnswer(string $idQuestion): ?string
    {
        if (in_array($idQuestion, $this->askFriendQuestions)) {
            $str = '(Transférée à ' . ($this->askFriendUsernames[array_search($idQuestion,
                        $this->askFriendQuestions)] ?? 'inconnu') . ') ';
        } else {
            $str = '';
        }

        foreach (json_decode($this->jsonResult) as $name => $answer) {
            if ($name === $idQuestion) {
                if (is_object($answer)) {
                    return $str;
                }
                return $str . (is_array($answer) ? array_reduce($answer, function ($carry, $item) {
                        return (is_string($carry) && strlen($carry) > 0 ? $carry . ', ' : '') . (is_object($item) ? '' : $item); //same as an implode() but doesn't crash on objects
                    }) : $answer);
            } elseif (preg_match('/' . addcslashes($name, '/') . '\[(.+)\]/', $idQuestion,
                $matches)) { //if question has subquestions (matrix)
                list(, $idSubQuestion) = $matches;
                if (isset($answer->$idSubQuestion)) { //matrix or matrixdropdown
                    if (is_object($subAnswers = $answer->$idSubQuestion)) {
                        return $str . implode(',', get_object_vars($subAnswers));
                    } else {
                        return $str . $answer->$idSubQuestion;
                    }
                } else { //matrixdynamic
                    return $str . array_reduce($answer, function ($carry, $item) use ($idSubQuestion) {
                            return (is_string($carry) ? $carry . ', ' : '') . $item->$idSubQuestion;
                        });
                }
            }
        }
        return $str;
    }

    public function replaceValueByText($value, $idQuestion)
    {
        $question = $this->searchQuestion($idQuestion);

        if ($question && isset($question->choices)) {
            foreach ($question->choices as $choice) {
                if (isset ($choice->value, $choice->text) && $choice->value === $value) {
                    return $choice->text;
                }
            }
        }

        return $value;
    }

    public function setDataResult()
    {
        $questions = $this->getQuestions();
        foreach ($questions as $question) {
            if (is_array($question)) { // it's not a page
                $this->resultMap[$question['name']] = $this->replaceValueByText($this->searchAnswer($question['name']),
                    $question['name']);
            } else {
                $this->resultMap[$question] = "";
            }
        }

        return $this->resultMap;
    }
}

и второй, ResultSurveyExport. php

<?php

namespace App\ExportSurvey;

use App\Helpers\Backend\SurveyJson;
use App\Repositories\Backend\Survey\SurveyResultRepository;
use Illuminate\Support\Arr;
use Maatwebsite\Excel\Concerns\Exportable;
use Maatwebsite\Excel\Concerns\WithMultipleSheets;

class ResultSurveyExport implements WithMultipleSheets
{
    use Exportable;


    protected $workflowId;

    protected $surveyResultRepository;

    public function __construct(int $workflowId)
    {
        $this->workflowId = $workflowId;
        $this->surveyResultRepository = new SurveyResultRepository();
    }

    /**
     * @return array
     */
    public function sheets(): array
    {
        $sheets = [];

        $results = $this->surveyResultRepository->exportByWorkflowId($this->workflowId);

        foreach ($results->groupBy('survey_name') as $onglet => $result) {
            $tmp = collect();
            foreach ($result as $r) {
                $t = new SurveyJson($r->json_definition, $r->json_result, $r->askfriend_questions,
                    $r->askfriend_usernames);
                $tmp->push(array_merge([
                    'firstname' => $r->first_name,
                    'lastname' => $r->last_name,
                    'email' => $r->email,
                    'date_created' => $r->created_at,
                    'date_updated' => $r->updated_at,
                ], $t->setDataResult()));
            }
            $data = collect();
            if (isset($t)) {
                foreach (array_merge([
                    'firstname',
                    'lastname',
                    'email',
                    'date_created',
                    'date_updated',
                ], $t->getQuestions()) as $question) {
                    $data->push(array_merge([$question['title'] ?? $question],
                        Arr::pluck($tmp, $question['name'] ?? $question)));
                }
            }
            $sheets[] = new ResultSurveyPerInstanceSheet($onglet, $data);
        }

        return $sheets;
    }
}

и вуаля!

...