2
\$\begingroup\$

I'm trying to define parameters for my API. It's a super basic one and the first I've made. I'm trying to instantiate my class and set parameters but to me it seems super messy. Is this really the best way to set a bunch of properties on a class and check them?

API Class:

class Api {
    private $_fields;
    public  $parameters;

    public function __construct($fields) {
        // Set fields
        $this->_fields = $fields;

        // Define parameters and their defaults
        $aperture = $fields['aperture'] ? $fields['aperture']['value'] : null;
        $focalLength = $fields['focal_length']['value'] ? $fields['focal_length']['value'] : null;
        $calculatedAperture = $fields['aperture']['value'] ? $fields['aperture']['value'] * $fields['crop_factor']['value'] : null;

        $width = (float) $fields['width']['values'];
        $height = (float) $fields['height']['value'];
        $sensor = Api::getInfo(
            "sensors", 
            "crop_factor", 
            $fields["crop_factor"]["value"]
        );

        if (!$sensor) {
            $sensor = [
                'width' => $width ? $width : null,
                'height' => $height ? $height : null
            ];
        }

        // Set parameters
        $this->parameters = [
            'original' => [
                'aperture' => $aperture ? (float) $aperture : null,
                'focal_length' => $focalLength ? (float) $focalLength : null,
            ],
            'calculated' => [
                'aperture' => null,
                'focal_length' => (float) $fields['focal_length'] * $fields['crop_factor']['value']
            ],
            'crop_factor' => (float) $fields['crop_factor']['value'],
            'sensor' => $sensor ? $sensor : null
        ];

        var_dump($this->parameters);

        $this->responseJson = $this->checkFields();
    }
}

Sometimes certain parameters will contain nothing, so I'm using a ternary to check the value and then set something depending on the result. All parameters I'm going to use Type Juggling to make sure they are the type I want but that too seems super messy. I'm trying to avoid this whole nested ternary inside of ternary but I don't see a way to avoid it.

I would also like to say here that this code does work, although I haven't gone through and made every check.

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.