mardi 21 avril 2020

PHP: Checking two file_exists paths

Good day. Today I created the following class, which checks the availability of a file (and displays it) on the corresponding server with respect to the incoming information:

class partnermediation_abbyycontroller {

private $servers_dir = null;
private $application_id = null;

public function get_cont($pathToFile)
{
    $GetContentFile = file_get_contents($pathToFile);
        if ($GetContentFile[0]=='<')
            {
                header("Content-type:text/xml");
                $result = new DOMDocument();
                $result->loadXML($GetContentFile);
                echo $result->saveXML();
            }
        else 
            {
                header('Content-Type: text/plain;charset=utf8');
                echo $GetContentFile;
            }
}

public function __construct($parts)
    {
        switch ($parts[0]) {
            case 'prod': $this->servers_dir = "//srvap2082/C$/temp/"; break;
            case 'preprod': $this->servers_dir = "//srvap2027/C$/temp/"; break;
            case 'preprod_ft': $this->servers_dir = "//srvap2026/C$/temp/"; break;
            case 'test': $this->servers_dir = "//srvap2030/C$/temp/"; break;
        }

        switch ($parts[3]) {
            case 'close': $this->application_id=trim($parts[1]).'_beforeClose.xml'; break;
            case 'save': $this->application_id=trim($parts[1]).'_beforeSave.xml'; break;
            default: $this->application_id=trim($parts[1]).'_beforeSaveAndForward.xml'; break;
        }

        ($parts[2]=='Request')?$this->application_id=trim($parts[1]).'_afterRead.xml':$this->application_id;

        $pathToFile = $this->servers_dir.$this->application_id;


        if ($parts[0] == 'prod'){
            if (file_exists($pathToFile)){
                $this->get_cont($pathToFile);
            }
            else
            {
                $pathToFile = $this->servers_dir = "//srvap2087/C$/temp/".$this->application_id;
                if (file_exists($pathToFile)){
                    $this->get_cont($pathToFile);
                }
            }
        }
        else 
        {
            if (file_exists($pathToFile)){
                $this->get_cont($pathToFile);
            }
            else
            {
                echo 'File not found: '.$pathToFile.'';
            }
        }

    }}

My question is how to make the code more adequate? I'm talking about $this-> get_cont ($pathToFile); More specific: In case the server is prod = case 'prod', I need to check file_exists first on one server, then on another. If this is not a prod, just check if there is a file on one server. I did it through ififelseif and code removal if successful in a separate get_cont function ... How to make the code more rational and beautiful? Thanks.

Aucun commentaire:

Enregistrer un commentaire