<?php

namespace MightyPork\Exceptions;

trait ExceptionConstructorTrait
{
	/**
	 * Create from (Cause), or (Message, Cause).
	 * Cause is Exception.
	 *
	 * @param mixed $arg1 Cause, or Message if second arg is Cause
	 * @param mixed|null $arg2 Cause
	 */
	public function __construct($arg1 = null, $arg2 = null)
	{
		$cause = null;
		$message = "";
		if ($arg1 instanceof \Exception) {
			// Invoked without a message, only cause
			$cause = $arg1;
			$message = $cause->getMessage(); // Repeat the message so it's easy to see in the logs
		} elseif (is_string($arg1)) {
			// First is message
			$message = $arg1;
			// Second, optional, is a cause
			if ($arg2 instanceof \Exception) {
				$cause = $arg2;
			}
		}
		// call Exception constructor
		parent::__construct($message, 0, $cause);
	}
}