PHP ловит исключение из другого класса в цикле - PullRequest
0 голосов
/ 20 мая 2018

Я новичок в PHP, учусь при создании следующего приложения.Я застрял, пытаясь поймать исключение, которое разрывает цикл в классе Basic.Исключение составляет класс ProductVariation.Функция generateRandomItems должна генерировать случайные элементы на основе файла класса Product и product.json и пропускать productVariation, когда цвет равен нулю.

<?php

class Product implements Item
{
    public $id;
    public $name;
    public $price;
    public $quantity;

    public function __construct($file)
    {
        if (!file_exists($file)) {
            throw new Exception('ProductFileNotFound');
        }
        $data = file_get_contents($file);
        $product = json_decode($data);

        $id = $product->id;
        $name = $product->name;
        $price = $product->price;
        $quantity = $product->quantity;

        $this->id = $id;
        $this->name = $name;
        $this->price = $price;
        $this->quantity = $quantity;

    }
    public function getAmount()
    {
        $this->amount = $this->price * $this->quantity;
        return $this->amount;
    }
    public function __toString()
    {
        $output = '';
        foreach ($this as $key => $val) {
            $output .= $key . ': ' . $val . "<br>";
        }
        return $output;
    }
    public function getId()
    {
        return $this->id;
    }
    public function getNet($vat = 0.23)
    {
        return round($this->price / (1 + $vat), 2);
    }
}

class ProductVariation extends Product
{
    public $color;
    public function __construct($file, $color)
    {
        parent::__construct($file);
        $this->color = $color;
        if (!is_string($color)) {
            throw new Exception('UndefinedVariantColor');
        }
        return $this->color;
    }
}

interface Item
{
    public function getId();
    public function getNet($vat);
}

class Products extends ArrayIterator
{
    public function __construct($file, $color)
    {
        $this->product = new Product($file);
        $this->productVariation = new ProductVariation($file, $color);
    }
}

class Basic
{
    public function generateRandomString($randomLength)
    {
        $characters = 'abcdefghijklmnopqrstuvwxyz';
        $charactersLength = strlen($characters);
        $randomString = '';
        for ($i = 0; $i < $randomLength; $i++) {
            $randomString .= $characters[rand(0, $charactersLength - 1)];
        }
        return $randomString;
    }
    public function generateRandomItems($length)
    {
        $colors = array(
            "red", "green", "blue",
            "white", "black", null,
        );
        $list = [];
        for ($i = 2; $i < $length + 2; $i += 2) {
            $color = $colors[array_rand($colors, 1)];
            $products = new Products('product.json', $color);
            $products->product->id = $i - 1;
            $products->product->name = $this->generateRandomString(rand(3, 15));
            $products->product->price = rand(99, 10000) / 100;
            $products->product->quantity = rand(0, 99);

            $products->productVariation->id = $i;
            $products->productVariation->name = $this->generateRandomString(rand(3, 15));
            $products->productVariation->price = rand(99, 10000) / 100;
            $products->productVariation->quantity = rand(0, 99);

            echo $products->product;
            echo $products->productVariation;

            array_push($list, $products->product, $products->productVariation);
        }
        $uid = uniqid();
        $fp = fopen("products/" . $uid . '.json', 'w');
        fwrite($fp, json_encode($list));
        fclose($fp);
    }
}

product.json Содержимое файла равно {"id": 1, "name":"Продукт теста", "цена": 13,99, "количество": 19}

1 Ответ

0 голосов
/ 20 мая 2018

Например, проверка должна предшествовать присвоению, чтобы проверить, является ли она нулевой (это в вашем базовом классе).

  // put check first 
    if (!is_string($color)) {
        throw new Exception('UndefinedVariantColor');
    }
       $this->color = $color;
...