MOON
Server: Apache
System: Linux server1.studioinfinity.com.br 2.6.32-954.3.5.lve1.4.90.el6.x86_64 #1 SMP Tue Feb 21 12:26:30 UTC 2023 x86_64
User: artinside (517)
PHP: 7.4.33
Disabled: exec,passthru,shell_exec,system
Upload Files
File: //proc/self/cwd/lhh/source/Models/User.php
<?php

namespace Source\Models;

use Source\Core\Model;
use Source\Support\Pagarme;

/**
 * FSPHP | Class User Active Record Pattern
 *
 * @author Robson V. Leite <cursos@upinside.com.br>
 * @package Source\Models
 */
class User extends Model
{
    /**
     * User constructor.
     */
    public function __construct()
    {
        parent::__construct("users", ["id"], ["first_name", "last_name", "email", "password", "document", "phone", "datebirth", "type"]);
    }

    /**
     * @param string $firstName
     * @param string $lastName
     * @param string $email
     * @param string $password
     * @param string $document
     * @param string $phone
     * @param string $type
     * @param string $celular|null
     * @param string $datebirth

     * @return User
     */
    public function bootstrap(
        string $firstName,
        string $lastName,
        string $email,
        string $password,
        string $document,
        string $phone,
        string $datebirth,
        string $type,
        string $document2 = null,
        string $celular = null

    ): User {
        $this->first_name = $firstName;
        $this->last_name = $lastName;
        $this->email = $email;
        $this->password = $password;
        $this->document = preg_replace("/[^0-9]/", "", $document) ;
        $this->phone = $phone;
        $this->datebirth = date_fmt_back($datebirth);
        $this->document2 = $document2;
        $this->type = $type;
        $this->celular = $celular;

        return $this;
    }

    /**
     * @param string $email
     * @param string $columns
     * @return null|User
     */
    public function findByEmail(string $email, string $columns = "*"): ?User
    {
        $find = $this->find("email = :email", "email={$email}", $columns);
        return $find->fetch();
    }

    /**
     * @param string $email
     * @param string $columns
     * @return null|User
     */
    public function findByDocument(string $document, string $columns = "*"): ?User
    {
        $find = $this->find("document = :document", "document={$document}", $columns);
        return $find->fetch();
    }

    /**
     * @return string
     */
    public function fullName(): string
    {
        return "{$this->first_name} {$this->last_name}";
    }

    /**
     * @return string|null
     */
    public function photo(): ?string
    {
        if ($this->photo && file_exists(__DIR__ . "/../../" . CONF_UPLOAD_DIR . "/{$this->photo}")) {
            return $this->photo;
        }

        return null;
    }

    /**
     * @return bool
     */
    public function save(): bool
    {
        if (!$this->required()) {
            $this->message->warning("Campos com * são de preenchimento obrigatório");
            return false;
        }

        if (!is_email($this->email)) {
            $this->message->warning("O e-mail informado não tem um formato válido");
            return false;
        }

        if(!is_cpf($this->document)){
            if(!is_cnpj($this->document)) {
                $this->message->warning("O CPF ou CNPJ digitado é inválido, favor digitar um CPF válido.");
                return false;
            }
        }


        if($this->datebirth){
            $exDate = explode("-", $this->datebirth);
            if($exDate[0] <= date("Y", strtotime(date("Y"). " -120 years")) OR $exDate[0] >= date("Y", strtotime(date("Y"). " -15 years")) OR !checkdate($exDate[1],$exDate[2], $exDate[0])){
                $this->message->warning("A data de nascimento digitada é inválida");
                return false;
            }
        }

        if (!is_passwd($this->password)) {
            $min = CONF_PASSWD_MIN_LEN;
            $max = CONF_PASSWD_MAX_LEN;
            $this->message->warning("A senha deve ter entre {$min} e {$max} caracteres");
            return false;
        } else {
            $this->password = passwd($this->password);
        }

        /** User Update */
        if (!empty($this->id)) {
            $userId = $this->id;

            if ($this->find("email = :e AND id != :i", "e={$this->email}&i={$userId}", "id")->fetch()) {
                $this->message->warning("O e-mail informado já está cadastrado");
                return false;
            }


            $this->update($this->safe(), "id = :id", "id={$userId}");
            if ($this->fail()) {
                $this->message->error("Erro ao atualizar, verifique os dados");
                return false;
            }


        }

        /** User Create */
        if (empty($this->id)) {
            if ($this->findByEmail($this->email, "id")) {
                $this->message->warning("O e-mail informado já está cadastrado");
                return false;
            }

            if ($this->findByDocument($this->document, "id")) {
                $this->message->warning("O CPF informado já está cadastrado");
                return false;
            }
            $userId = $this->create($this->safe());


            $integration = new Pagarme();
            $integrationCustomer = $integration->createCustomer($userId, $this->type == "individual" ? $this->fullName() : $this->first_name, $this->email, $this->document,$this->type, $this->phone, date_fmt_back($this->datebirth));
            if($integration->getError()){
                $this->message->error("Erro ao Criar usuário favor entrar em contato com o suporte");
                $this->destroy();
                return false;
            }

            $this->integration_pagarme = $integrationCustomer->id;
            $this->update($this->safe(), "id = :id", "id={$userId}");


            if ($this->fail()) {
                $this->message->error("Erro ao cadastrar, verifique os dados");
                return false;
            }
        }

        $this->data = ($this->findById($userId))->data();
        return true;
    }
}