php – split long method in different methods

Here is a suggestion. I do not know in which class is your method createExcel()that is why I put all new defined methods and properties into MyClass.

Please pay attention, that this code contains simple refactorings like avoiding array() keyword in defining arrays. I also avoided to use else{...} blocks if possible by returning in if{...} block. By this way you can reduce the depth of your if-else logic and the core becomes more readable.

class MyClass {

    private $spreadsheet;
    private $task = null;
    private $project = null;
    private $projectTitle = null;

    private $style_header = [];
    private $style_content = [];
    private $dataku = [];

    public function createExcel(Task $task = null, Project $project = null, $projectTitle = null) {

        $this->initializeProperties($task, $project, $projectTitle);

        $this->setHeaderContent();

        $this->setMainContent($task, $project, $projectTitle);

        $this->doOutput();

    }

    /*-----------------------------------------------------------------

    PRIVATE METHODS

    -----------------------------------------------------------------*/
    /**
     * Initializes properties
     *
     *
     */
    private function initializeProperties(Task $task, Project $project, $projectTitle){
        $this->spreadsheet = new Spreadsheet();
        $this->task = $task;
        $this->project = $project;
        $this->projectTitle = $projectTitle;

        $default_border = [
            'style' => Border::BORDER_THIN,
            'color' => ['rgb' => '1006A3']
        ];

        $this->style_header = [
            'borders' => [
                'bottom' => $default_border,
                'left' => $default_border,
                'top' => $default_border,
                'right' => $default_border,
            ],
            'fill' => [
                'type' => Fill::FILL_SOLID,
                'color' => ['rgb' => 'E1E0F7'],
            ],
            'font' => [
                'bold' => true,
                'size' => 16,
            ]
        ];

        $this->style_content = [
            'borders' => [
                'bottom' => $default_border,
                'left' => $default_border,
                'top' => $default_border,
                'right' => $default_border,
            ],
            'fill' => [
                'type' => Fill::FILL_SOLID,
                'color' => ['rgb' => 'eeeeee'],
            ],
            'font' => [
                'size' => 12,
            ]
        ];
    }

    /**
     * Sets the header information of the excel sheet
     *
     *
     */
    private function setHeaderContent(){
        $this->spreadsheet->setActiveSheetIndex(0)
            ->setCellValue('A1', 'Zoekterm')
            ->setCellValue('B1', 'Website')
            ->setCellValue('C1', 'Pagina')
            ->setCellValue('D1', 'Paginatitel')
            ->setCellValue('E1', 'Paginabeschrijving')
            ->setCellValue('F1', 'KvK-nummer')
            ->setCellValue('G1', 'Vestigingsnummer')
            ->setCellValue('H1', 'Adresgegevens');
        $this->spreadsheet->getActiveSheet()->getStyle('A1:H1')->applyFromArray($this->style_header); // give style to header
    }

    /**
     * Sets the main excel content
     *
     *
     */
    private function setMainContent(){

        $this->prepareDataku();

        $firststyle="A2";
        $dataku = &$this->dataku;// define alias
        for ($i = 0; $i < count($dataku); $i++) {
            $urut = $i + 2;
            $search_query = 'A' . $urut;
            $page_url="B" . $urut;
            $page_link = 'C' . $urut;
            $page_title="D" . $urut;
            $page_description = 'E' . $urut;
            $coc_number="F" . $urut;
            $branch_code="G" . $urut;
            $address="H" . $urut;
            $this->spreadsheet->setActiveSheetIndex(0)
                ->setCellValue($search_query, $dataku[$i][0])
                ->setCellValue($page_url, $dataku[$i][1])
                ->setCellValue($page_link, $dataku[$i][2])
                ->setCellValue($page_title, $dataku[$i][3])
                ->setCellValue($page_description, $dataku[$i][4])
                ->setCellValue($coc_number, $dataku[$i][5])
                ->setCellValue($branch_code, $dataku[$i][6])
                ->setCellValue($address, $dataku[$i][7]);

            $laststyle = $page_description;
        }

        $this->spreadsheet->getActiveSheet()->getStyle($firststyle . ':' . $laststyle)->applyFromArray($this->style_content);
    }

    /**
     * Prepares dataku array needed by setMainContent()
     *
     *
     */
    private function prepareDataku() {

        // Pay attention to "!=". This block is the else block in your code
        if ($this->projectTitle != BoolState::TRUE) {
            foreach ($this->task->activeResults as $result){
                $this->dataku[] = [$result->task->search_query, $result->page_url, $result->page_link, $result->page_title, $result->page_description, $result->coc_number, $result->branch_code, $result->address];
            }
            return;
        }

        foreach ($this->project->tasks as $task) {
            if ($task->status_id == TaskStatus::CLOSED) {
                foreach ($task->activeResults as $result) {
                    $this->dataku[] = [$result->task->search_query, $result->page_url, $result->page_link, $result->page_title, $result->page_description, $result->coc_number, $result->branch_code, $result->address];
                }
            }
        }
    }

    /**
     * Saves the generated excel file on the local disc or writes it to the output stream.
     *
     *
     *
     */
    private function doOutput(){

        $writer = $this->outType == 'xlsx' ? new PhpOfficePhpSpreadsheetWriterXlsx($this->spreadsheet) : new Xls($this->spreadsheet);
        // var_dump($this->stream);

        # Save the excel file on the disc
        if (!$this->stream) {
            $writer->save($this->filename);
            return;
        }

        # Print the excel to the output stream
        $this->filename = $this->filename == null ? $this->title : $this->filename;

        $filename = "NVWA HDT ". ucfirst($this->projectTitle ? $this->task->project->description : $this->task->search_query) . '.Xls';
        $this->cleanOutput();
        header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
        header('Pragma: public');
        header('Cache-Control: max-age=0');
        header('Content-Disposition: attachment;filename="' . $filename . '"'); // file name of excel
        header('Content-type: application/vnd.ms-excel');
        $writer->save('php://output');
        Yii::app()->end();
    }

}

Leave a Comment