Home > Net >  Finding where my Class Account is called twice
Finding where my Class Account is called twice

Time:10-24

I encounter this error while developping my App :

Fatal error: Cannot declare class App\Backend\Entity\Account, because the name is already in use in C:\MAMP\htdocs\BlogYo\App\Backend\Entity\Account.php on line 6

I cannot find where the class Account is called twice or declared twice, exemples I find on forums do not match my situation. It must be a stupid mistake so I’m sorry, I’m new to this and I feel there is a subtlety about namespaces that escapes my comprehension…

So the Account class is define in Acount.php (one of my permanent my entity) and called in 3 files which code you can find below :

• AccountController.php
• AccountManager.php
• AccountManagerPDO.php which extends AccountManager
    ◦ I want to allow an accsess to my DB throught another interface than PDO later, which explain those to managers file

I cannot find where the logic fails regarding the Account use. Those files worked fine when only my Account creation action was coded then seemed to fail when I added the action to modify an account. Yet, both actions go throught a same private function (processForm) which require the Account file once.

I have tried using aliases (three different aliases) in the three files requiring Account but the error remains…

Can you guide me through this ? Thank you for your help :)

Account.php:

    <?php
namespace App\Backend\Entity;

use OCFram\Entity;

class Account extends Entity
{
    protected $id,
            $name,
            $pseudo,
            $pass,
            $email,
            $secretQ,
            $secretA,
            $createdAt,
            $updatedAt,
            $lastConnexion;

  const NAME_NOT_VALIDE = 1;
    const PSEUDO_NOT_VALIDE = 2;
    const PASS_NOT_VALIDE = 3;
    const EMAIL_NOT_VALIDE = 4;
    const SECRET_QUESTION_NOT_VALIDE = 5;
    const SECRET_ANSWER_NOT_VALIDE = 6;

  //use for directing account data modification toward creation or update
  public function isNew(){
    return null !== $this->getId();
  }

  public function isValid(){
    return empty($this->id);
  }

  // GETTERS //
  public function getId()
  {
    return $this->id;
  }

  public function getName()
  {
   return $this->name;
  }

  public function getPseudo()
  {
    return $this->pseudo;
  }

  public function getEmail()
  {
   return $this->email;
  }

  public function getPass()
  {
    return $this->pass;
  }

   public function getSecretQ()
  {
    return $this->secretQ;
  }

   public function getSecretA()
  {
    return $this->secretA;
  }

  public function getCreatedAt()
  {
    return $this->createdAt;
  }

  public function getUpdatedAt()
  {
    return $this->updatedAt;
  }

  public function getLastConnexion()
  {
    return $this->lastConnexion;
  }


 // SETTERS //
  public function setId($id)
  {
    $this->id = $id;
  }

  public function setName($name)
  {
    if (!is_string($name) || empty($name))
    {
      $this->erreurs[] = self::NOM_NON_VALIDE;
    }
    $this->name = $name;
  }

  public function setPseudo($pseudo)
  {
    if (!is_string($pseudo) || empty($pseudo))
    {
      $this->erreurs[] = self::PSEUDO_NOT_VALIDE;
    }
    $this->pseudo = $pseudo;
  }

  public function setEmail($email)
  {
    if (!is_string($email) || empty($email))
    {
      if(!preg_match("/^([w\-.] )@((?:[w] .) )([a-zA-Z]{2,4})/i", $email)){
        $this->erreurs[] = self::EMAIL_NOT_VALIDE;
      }
    }
    $this->email = $email;
  }

  public function setPass($pass)
  {
    if (!is_string($pass) || empty($pass))
    {
      if(!preg_match("/^([w\-.] )@((?:[w] .) )([a-zA-Z]{2,4})/i", $pass)){
        $this->erreurs[] = self::PASS_NOT_VALIDE;
      }
    }
    $this->pass = $pass;
  }

   public function setSecretQ($secretQ)
  {
    if (!is_string($secretQ) || empty($secretQ))
    {
      $this->erreurs[] = self::SECRET_QUESTION_NOT_VALIDE;
    }
    $this->secretQ = $secretQ;
  }

   public function setSecretA($secretA)
  {
    if (!is_string($secretA) || empty($secretA))
    {
      $this->erreurs[] = self::SECRET_ANSWER_NOT_VALIDE;
    }
    $this->secretA = $secretA;
  }

  public function setCreatedAt(\DateTime $creationDate)
  {
    $this->createdAt = $createdAt;
  }

  public function setUpdatedAt(\DateTime $creationDate)
  {
    $this->updatedAt = $updatedAt;
  }

  public function setLastConnexion(\DateTime $creationDate)
  {
    $this->lastConnexion = $lastConnexion;
  }
}

AccountController.php:

 <?php
namespace App\Frontend\Modules\Account;

use OCFram\BackController;
use OCFram\HTTPRequest;
use App\Backend\Entity\Account;
use App\Backend\Model\AccountManagerPDO;

class AccountController extends BackController {

    //access to connexion form 
    public function executeIndex (HTTPRequest $request){

        if ($request->postExists('pseudo')) {
            
            $passEntered = $request->postData('pass');
            $PseudoEntered = $request->postData('pseudo');

            var_dump('hola', $PseudoEntered);
            $managerA = $this->managers->getManagerOf('Account');
            $account = $managerA->getAccountPerPseudo($PseudoEntered);
            $registeredPass = $account['pass'];

            //confirming pass entered
            if(password_verify($passEntered, $registeredPass)) {
                //setup connexion indicator and other session variable
                $this->app->user()->setAuthenticated(true);

                $this->app->user()->setAttribute('id', $account['id']);
                $this->app->user()->setAttribute('pseudo', $account['pseudo']);

                $this->app->user()->setFlash('Vous êtes connecté, nous sommes ravis de votre retour !');

                $this->app->httpResponse()->redirect('bootstrap.php?action=blogList');
            }

            else {
                $this->app->user()->setFlash('Votre nom d\'utilisateur ou votre mot de passe sont incorrect.');
            }
        }
    }

    public function executeDisconnect (HTTPRequest $request){

        $this->app->user()->setAuthenticated(false);
        $this->app->user()->destroy();

        $this->app->httpResponse()->redirect('bootstrap.php?action=index'); 
    }

    //Create an account
    public function executeCreateAccount (HTTPRequest $request){

        $this->page->addVar('title', 'Créez votre compte');

        $managerA = $this->managers->getManagerOf('Account');

        if ($request->postExists('name'))
        {
            //checking pseudo availability (must be unique for connexion mgmt)
            if (!empty ($managerA->checkPseudo($request->postData('pseudo')))){
                $this->app->user()->setFlash('Ce pseudo n\'est pas disponible.');                           
            } else {
                $uppercase = preg_match('@[A-Z]@', $request->postData('pass'));
                $lowercase = preg_match('@[a-z]@', $request->postData('pass'));
                $number    = preg_match('@[0-9]@', $request->postData('pass'));
                $password = $request->postData('pass');

                if(!$uppercase || !$lowercase || !$number || strlen($password) < 8) {
                    $this->app->user()->setFlash('Votre mot de passe doit contenir au moins 8 caractères dont 1 majuscule, 1 minuscule, un nombre et un caractère spécial.');
                } else {
                    //checking the 2 form pass matching
                    if ( $request->postData('pass') != $request->postData('confPass')){
                        $this->app->user()->setFlash('Vous avez saisie 2 mots de passe différents.');
                    } else {
                        //pass encryption
                        $pass = password_hash($request->postData('pass'), PASSWORD_DEFAULT);
                        $secretA = password_hash($request->postData('secretA'), PASSWORD_DEFAULT);

                        $this->processForm($request, $pass, $secretA, $managerA);
                    }
                }
            }
        }      
    }


    //Update the account
    public function executeModifyAccount (HTTPRequest $request){

        $this->page->addVar('title', 'Mise à jour de votre compte');

        $managerA = $this->managers->getManagerOf('Account');

        $account = $managerA->getAccount($this->app->user()->getAttribute('id'));

        //checking is first field is empty. If yes, we send account data to put default value in the form
        if (empty($request->postData('name'))){
            $this->page->addVar('account', $account);
        } else {
            $pseudo = $managerA->checkPseudo($request->postData('pseudo'));
            //cheking pseudo availability
            if (!empty($pseudo)){
                //if a pseudo is found, we check its his pseudo
                if ($request->postData('pseudo') == $this->app->user()->getAttribute('pseudo')){

                    $pass = $formAccount['pass'];
                    $secretA = password_hash($request->postData('secretA'), PASSWORD_DEFAULT);

                    $this->processForm($request, $pass, $secretA, $managerA);
                } else {
                    $this->app->user()->setFlash('Ce nom d\'utilisateur n\'est pas disponible.');
                }   
            } else {//pseudo is new and unique
                $pass = $formAccount['pass']; 
                $secretA = password_hash($request->postData('secretA'), PASSWORD_DEFAULT);

                $this->processForm($request, $pass, $secretA, $managerA);
            }
        }

    }

    //See account informations
    public function executeSeeAccount (HTTPRequest $request) {

        $this->page->addVar('title', 'Paramètre du compte');

        $managerA = $this->managers->getManagerOf('Account');

        $account = $managerA->getAccount($this->app->user()->getAttribute('id'));
     /*   var_dump($account);die;*/
        $this->page->addVar('account', $account);   
    }

    //Ask for a new account password
    public function executeAskPass (HTTPRequest $request){
        $this->page->addVar('title', 'Mise à jour du mot de passe');

        $managerA = $this->managers->getManagerOf('Account');
        $account = $managerA->getAccountPerPseudo($request->postData('pseudo'));
        if(empty($account)){
            $accountStep2 = $managerA->getAccountPerPseudo($request->postData('hiddenPseudo'));
        }

        if (empty($account) && empty($request->postData('newPass')))  {
            $this->app->user()->setFlash('Entrez un nom d\'utilisateur valide pour modifier votre mot de passe.');
            $this->app->httpResponse()->redirect('bootstrap.php?action=index');
        }elseif(!empty($account)){
                $secretQ = $account['secret_q'];
                $this->page->addVar('secretQ', $secretQ);
                $this->page->addVar('pseudo', $request->postData('pseudo'));
        }else{
            $newPass = $request->postData('newPass');
            $uppercase = preg_match('@[A-Z]@', $newPass);
            $lowercase = preg_match('@[a-z]@', $newPass);
            $number = preg_match('@[0-9]@', $newPass);

            if(!$uppercase || !$lowercase || !$number || strlen($newPass) < 8) {
                $this->app->user()->setFlash('Votre mot de passe doit contenir au moins 8 caractères dont 1 majuscule, 1 minuscule, un nombre et un caractère spécial.');
            } else {

                //checking the 2 form pass matching
                if ( $request->postData('newPass') != $request->postData('confNewPass')){
                    $this->app->user()->setFlash('Vous avez saisie 2 mots de passe différents.');
                } else {

                    //security question validation
                    $secretA = password_hash($request->postData('secretA'), PASSWORD_DEFAULT);

                    if (!password_verify($secretA, $accountStep2['secret-a'])){
                        $this->app->user()->setFlash('Vous n\'avez pas entré la bonne réponse à votre question secrète.');
                        $this->app->httpResponse()->redirect('bootstrap.php?action=index');
                    } else {
                        $pass = password_hash($request->postData('newPass'), PASSWORD_DEFAULT);

                        $managerA->updatePass($request->postData('pseudo'), $pass);

                        $this->app->user()->setFlash('Votre mot de passe a bien été mis à jour !');

                        //On redirigre sur la page "Paramètre du compte" ou l'utilisateur voit les infos à jour
                        $this->app->httpResponse()->redirect('bootstrap.php?action=seeAccount');
                    }
                }
            }
        }
    }

    //Contact the site admin
    public function executeContactAdmin (HTTPRequest $request) {
        //getting back the mail data 
        $firstName = $request->postData('firstName');
        $name = $request->postData('name');
        $title = $request->postData('title');
        $content = $request->postData('content');

        if($this->app->user()->getAuthenticated() == true){
            $managerA = $this->managers->getManagerOf('Account');
            $account = $managerA->getAccount($this->app->user()->getId());
            $userMail = $account->email();
        } else {
            $userMail = $request->postData('userMail');
        }

        // creating 2 mail within the mailer
        $file = dirname(__FILE__).'/../../App/'.$this->name.'/config/param.json';

        $data = file_get_contents($file);

        $confirm = json_decode($data);

        $this->app->user()->setFlash('Votre message a été envoyé, vous allez recevoir un mail de confirmation');
        

    }

    protected function processForm(HTTPRequest $request, $pass, $secretA, $managerA) {

        $formAccount = new Account ([
        'name' => $request->postData('name'),
        'pseudo' => $request->postData('pseudo'),
        'email' => $request->postData('email'),
        'pass' => $pass,
        'secretQ' => $request->postData('secretQ'),
        'secretA' => $secretA
        ]);


        // if id exist, its an update 
        $idCheck = $this->app->user()->getAttribute('id');

        if (!empty($idCheck)){
          $pseudo = $this->app->user()->getAttribute('pseudo');
          $account = $managerA->getAccountPerPseudo($pseudo);

          $formAccount->setId($idCheck);
          $formAccount->setSecretA($account['secret_a']);
          $formAccount->setSecretQ($account['secret_q']);


          //update indicator for flash message mgmt
          $flashInd="id";
        }
        
        if ($formAccount->isValid()){
            $managerA->save($formAccount);

            $this->app->user()->setFlash(!empty($flashInd) ? 'Votre compte a été mis à jour !' : 'Votre compte a été créé, bienvenue sur BlogYo !');

            //connexion if previous step successful
                $this->app->user()->setAuthenticated(true);

                $this->app->user()->setAttribute('id', $formAccount['id']);
                $this->app->user()->setAttribute('pseudo', $formAccount['pseudo']);
                $this->app->user()->setAttribute('firstName', $formAccount['firstName']);

                $this->app->httpResponse()->redirect('bootstrap.php?action=blogList'); 
        } else {
            $this->app->user()->setFlash('Entrez au moins un caractère autre q\'un espace pour valider chaque champ');
            //different redirection based on creration or update of account
            !empty($idCheck) ? $this->app->httpResponse()->redirect('bootstrap.php?action=seeAccount'): $this->app->httpResponse()->redirect('bootstrap.php?action=index'); 
        }
    }
}

AccountManagerPDO.php:

<?php
namespace App\Backend\Model;
 
use App\Backend\Entity\Account;
 
class AccountManagerPDO extends AccountManager
{
   //used for connexion (id still unknown)
  public function getAccountPerPseudo($pseudo){

    $sql =$this->dao->prepare('SELECT id, name, pseudo, email, pass, secret_q, secret_a FROM account WHERE pseudo = :pseudo');

    $sql->bindValue(':pseudo', $pseudo);

    $sql->execute();

    $sql->setFetchMode(\PDO::FETCH_CLASS | \PDO::FETCH_PROPS_LATE, '\Entity\Account');
    $account = $sql->fetch();

    $sql->closeCursor();

    return $account; 
  }

  public function getAccount($id)
  {
    $sql =$this->dao->prepare('SELECT id, name, pseudo, email, pass, secret_q, secret_a FROM account WHERE id = :id');
    
    $sql->bindValue(':id', (int)$id, \PDO::PARAM_INT);
    $sql->execute();

    $sql->setFetchMode(\PDO::FETCH_CLASS | \PDO::FETCH_PROPS_LATE, '\Entity\Account');
    $account = $sql->fetch();

    $sql->closeCursor();

    return $account;
  }

  public function add(Account $account){
    $sql = $this->dao->prepare('INSERT INTO account SET name = :name, pseudo = :pseudo, email = :email, pass = :pass, secret_q = :secret_q, secret_a = :secret_a, created_at = NOW(), updated_at = null');
  
    $sql->bindValue(':name', $account->getName());
    $sql->bindValue(':pseudo', $account->getPseudo());
    $sql->bindValue(':email', $account->getEmail());
    $sql->bindValue(':pass', $account->getPass());
    $sql->bindValue(':secret_q', $account->getSecretQ());
    $sql->bindValue(':secret_a', $account->getSecretA());

    $sql->execute();
  
    $account->setId($this->dao->lastInsertId());

    $sql->closeCursor();
  }

  public function modify(Account $account)
  { 

    $sql = $this->dao->prepare('UPDATE account SET name = :name, pseudo = :pseudo, email = :email, pass = :pass, secret_q = :secret_q, secret_a = :secret_a, updated_at = NOW() WHERE id= :id');
    
      $sql->bindValue(':id', $account->getId(), \PDO::PARAM_INT);
      $sql->bindValue(':name', $account->getName());
      $sql->bindValue(':pseudo', $account->getPseudo());
      $sql->bindValue(':email', $account->getEmail());
      $sql->bindValue(':pass', $account->getPass());
      $sql->bindValue(':secret_q', $account->getSecretQ());
      $sql->bindValue(':secret_a', $account->getSecretA());
 
      $sql->execute();

      $sql->closeCursor();
  } 

  public function checkPseudo($pseudo)
  {
    $sql =$this->dao->prepare('SELECT pseudo FROM account WHERE pseudo = :pseudo');
    $sql->bindValue(':pseudo', $pseudo);
    $sql->execute();

    $pseudo = $sql->fetch();

    $sql->closeCursor();

    return $pseudo;
  }

  public function updatePass($id, $pass){

    $sql->bindValue(':id', $account->getId(), \PDO::PARAM_INT);
    $sql = $this->dao->prepare('UPDATE account SET pass = :pass, updated_at = NOW() WHERE id= :id');

    $sql->bindValue(':id', $id, \PDO::PARAM_INT);
    $sql->bindValue(':pass', $pass->getPass());
var_dump('boule');
    $sql->execute();

    $sql->closeCursor();
  }

  public function delete($id){
    
  }
  public function getList($id){
    
  }
  public function count($id){
    
  }
}

AccountManager.php:

<?php
namespace App\Backend\Model;
 
use OCFram\Manager;
use App\Backend\Entity\Account;
 
abstract class AccountManager extends Manager
{
  abstract protected function add(Account $account);

  abstract protected function modify(Account $account);
 
  //add or modify 
  public function save(Account $account)
  {
    if ($account->isValid())
    {
      if($account->isNew() == false){
        $this->add($account);
      }else{
         $this->modify($account);
      }
    }
    else
    {
      throw new \RuntimeException('Respectez la forme des données à saisir');
    }
  }

  //updating user password
  abstract public function updatePass($id, $pass);

  abstract public function delete($id);

  //used for getting info about an account
  abstract public function getAccount($id);

  //checking pseudo availability
  abstract public function checkPseudo($pseudo);

  //used for connexion (id still unknown)
  abstract public function getAccountPerPseudo($peuso); 

  //used to get the account list
  abstract public function getList($id);

  //counts the number of Accounts
  abstract public function count($id);
 
}

CodePudding user response:

Maybe you already tried, but I think your IDE may help you. The usual shortcut is Ctrl Shift F (but it depends on your IDE) to search a string. Here you can search "App\Backend\Entity\Account" in your whole project and eventually identify multiple declarations.

If you do not find multiple declarations, it could be a autoloading problem, as pointed out by @IMSoP.

Hope this could help.

CodePudding user response:

Thank you for everyone's reply !

I've managed to avoid the "error" by replacing "require" by "require_once".

  • Related