2016-12-28
@final I do not use the PHP «final» keyword here to allow refine the return type using PHPDoc.
@used-by charge()
@param bool $capture
@return object|array(string => mixed)
553016
private function chargeNew($capture) {return dfc($this, function($capture) {
		$fc = $this->fCharge(); /** @var fCharge $fc */
		/**
		 * 2017-06-11
		 * Some PSPs like Moip require 2 steps to make a payment:
		 * 1) Creating an «order».
		 * 2) Creating a «payment».
		 * To implement such a scheme, the @uses \Df\StripeClone\P\Charge::request()
		 * should return data for the both requests,
		 * and then @uses \Df\StripeClone\Facade\Charge::create() should make the both requests.
		 */
		/** @var array(string => mixed) $preorderParams */
		if ($needPreorder = $fc->needPreorder() /** @var bool $needPreorder */) {
			$preorderParams = pPreorder::request($this);
			df_sentry_extra($this, 'Preorder Params', $preorderParams);
			$fc->preorderSet(fPreorder::s($this)->create($preorderParams));
		}
		$p = pCharge::request($this, $capture); /** @var array(string => mixed) $p */
		df_sentry_extra($this, 'Request Params', $p);
		$result = $fc->create($p); /** @var object|array(string => mixed) $result */
		if ($this->isCard()) {
			/**
			 * 2017-07-24
			 * Unfortunately, the one-liner fails on PHP 5.6.30:
			 * $this->iiaAdd((CardFormatter::s($this, $fc->card($result)))->ii());
			 * «syntax error, unexpected '->' (T_OBJECT_OPERATOR)»
			 * https://github.com/mage2pro/core/issues/15
			 * See also: https://github.com/mage2pro/core/issues/16
			 *
			 * 2017-07-31
			 * Interestingly, the following code works on all PHP versions >= 5.4.0:
			 * class A {function f() {return __METHOD__;}
			 * echo (new A)->f();
			 * https://3v4l.org/nANqg
			 *
			 * The following code works on all PHP versions >= 5.0.0:
			 *	class A {
			 *		function f() {return __METHOD__;}
			 *		static function s() {return new self;}
			 *	}
			 *	echo A::s()->f();
			 * https://3v4l.org/1qr48
			 *
			 * The same is true for the following code:
			 *	class A {
			 *		function f() {return $this->_v;}
			 *		final protected function __construct($v) {$this->_v = $v;}
			 *		private $_v;
			 *		final static function s($v) {return new self($v);}
			 *	}
			 *	echo A::s('test')->f();
			 * https://3v4l.org/2E8H6
			 *
			 * So, I was unable to reproduce the issue...
			 * Maybe the problem customer uses a non-standard (patched) PHP version?
			 *
			 * 2017-11-08
			 * Note 1.
			 * One-liners like (!($e = $a->e())->b()) are really not supported by PHP < 7:
			 * https://3v4l.org/lJjvS
			 * Note 2.
			 * At the same time, some `))->` one-liners are supported by PHP >= 5.4, e.g:
			 * static function p() {return (new self())->b();}
			 * https://3v4l.org/LJlDE
			 * Note 3.   
			 * If we add extra brackets to the code from the Note 2,
			 * then the code will be incompatible with PHP < 7:
			 * static function p() {return ((new self()))->b();}
			 */
			$cf = CardFormatter::s($this, $fc->card($result)); /** @var CardFormatter $cf */
			$this->iiaAdd($cf->ii());
		}
		$this->transInfo($result, $p + (!$needPreorder ? [] : ['df_preorder' => $preorderParams]));
		$needRedirect = $this->redirectNeeded($result); /** @var bool $needRedirect */
		$i = $this->ii(); /** @var II|OP|QP $i */
		/**
		 * 2016-03-15
		 * Иначе операция «void» (отмена авторизации платежа) будет недоступна:
		 * «How is a payment authorization voiding implemented?»
		 * https://mage2.pro/t/938
		 * https://github.com/magento/magento2/blob/2.1.0/app/code/Magento/Sales/Model/Order/Payment.php#L540-L555
		 * @used-by \Magento\Sales\Model\Order\Payment::canVoid()
		 *
		 * 2016-12-16
		 * Раньше мы окончание не добавляли, и это приводило к проблеме https://mage2.pro/t/2381
		 * При Refund из интерфейса Stripe метод \Dfe\Stripe\Handler\Charge\Refunded::process()
		 * находил транзакцию типа «capture» путём добавления окончания «-capture»
		 * к идентификатору платежа в Stripe.
		 * Однако если у платежа не было стадии «authorize»,
		 * то в данной точке кода окончание «capture» не добавлялось,
		 * а вот поэтому Refund из интерфейса Stripe не работал.
		 */
		$i->setTransactionId($this->e2i($fc->id($result),
			$needRedirect ? $this->transPrefixForRedirectCase() :
				($capture ? Ev::T_CAPTURE : Ev::T_AUTHORIZE)
		));
		/**
		 * 2016-03-15
		 * Если оставить открытой транзакцию «capture»,
		 * то операция «void» (отмена авторизации платежа) будет недоступна:
		 * https://github.com/magento/magento2/blob/2.1.0/app/code/Magento/Sales/Model/Order/Payment.php#L540-L555
		 * @used-by \Magento\Sales\Model\Order\Payment::canVoid()
		 * Транзакция считается закрытой, если явно не указать «false».
		 *
		 * 2017-01-16
		 * Наоборот: если закрыть транзакцию типа «authorize»,
		 * то операция «Capture Online» из административного интерфейса будет недоступна:
		 * @see \Magento\Sales\Model\Order\Payment::canCapture()
		 *		if ($authTransaction && $authTransaction->getIsClosed()) {
		 *			$orderTransaction = $this->transactionRepository->getByTransactionType(
		 *				Transaction::TYPE_ORDER,
		 *				$this->getId(),
		 *				$this->getOrder()->getId()
		 *			);
		 *			if (!$orderTransaction) {
		 *				return false;
		 *			}
		 *		}
		 * https://github.com/magento/magento2/blob/2.1.3/app/code/Magento/Sales/Model/Order/Payment.php#L263-L281
		 * «How is \Magento\Sales\Model\Order\Payment::canCapture() implemented and used?»
		 * https://mage2.pro/t/650
		 * «How does Magento 2 decide whether to show the «Capture Online» dropdown
		 * on a backend's invoice screen?»: https://mage2.pro/t/2475
		 */
		$i->setIsTransactionClosed($capture && !$needRedirect);
		if ($needRedirect) {
			/**
			 * 2016-07-10
			 * @uses \Magento\Sales\Model\Order\Payment\Transaction::TYPE_PAYMENT —
			 * это единственный транзакция без специального назначения,
			 * и поэтому мы можем безопасно его использовать
			 * для сохранения информации о нашем запросе к платёжной системе.
			 * 2017-01-12
			 * Сделал по аналогии с @see \Df\PaypalClone\Method::addTransaction()
			 * Иначе транзакция не будет записана.
			 * Что интересно, если првоерка 3D Secure не нужна,
			 * то и этой специальной операции записи транзакции не нужно:
			 * она будет записана автоматически.
			 */
			$i->addTransaction(T::TYPE_PAYMENT);
		}
		return $result;
	}, func_get_args());}
355565
public function attach($value, $capture = null)
    {
        if (null === $capture) {
            $capture = $this->captureType;
        }

        switch ($capture) {
            case self::APPEND:
                $this->append($value);
                break;
            case self::PREPEND:
                $this->prepend($value);
                break;
            case self::SET:
                $this->set($value);
                break;
            default:
                throw new InvalidArgumentException(sprintf(
                    'Invalid capture type provided; must be any of the capture '
                    . 'type constants, "%s" received.',
                    is_scalar($capture) ? $capture : gettype($capture)
                ));
        }

        return $this;
    }
13884
public function captureEnd()
    {
        $capture = array_pop($this->capture);
        array_unshift($capture['args'], ob_get_clean());
        call_user_func_array(
            [$this, $capture['func']],
            $capture['args']
        );
        return $this;
    }
585448
public function capture($transaction = null)
    {
        if (!($transaction instanceof TransactionReference)) {
            $transactionReference = new TransactionReference();
            $transactionReference->transactionId = $transaction;
            $transactionReference->paymentMethodType = PaymentMethodType::CREDIT;
            $transaction = $transactionReference;
        }

        return (new ManagementBuilder(TransactionType::CAPTURE))
            ->withPaymentMethod($transaction);
    }
66891
public function parse(&$var, BasicObject $o)
    {
        $o->type = \strtolower(\gettype($var));

        if (!$this->applyPlugins($var, $o, self::TRIGGER_BEGIN)) {
            return $o;
        }

        switch ($o->type) {
            case 'array':
                return $this->parseArray($var, $o);
            case 'boolean':
            case 'double':
            case 'integer':
            case 'null':
                return $this->parseGeneric($var, $o);
            case 'object':
                return $this->parseObject($var, $o);
            case 'resource':
                return $this->parseResource($var, $o);
            case 'string':
                return $this->parseString($var, $o);
            default:
                return $this->parseUnknown($var, $o);
        }
    }
264563
public function fetch($type = self::FETCH_TYPE_NUM)
    {
        if ($this->_allFetched) {
            $row = false;
            if (isset($this->buffer[$this->index])) {
                $row = $this->buffer[$this->index];
            }
            $this->index += 1;

            if ($row && $type === static::FETCH_TYPE_NUM) {
                return array_values($row);
            }

            return $row;
        }

        $record = $this->statement->fetch($type);
        if ($record === false) {
            $this->_allFetched = true;
            $this->statement->closeCursor();

            return false;
        }
        $this->buffer[] = $record;

        return $record;
    }
67784
public static function dump($var, bool $return = false)
    {
        if ($return) {
            \ob_start();
            Dumper::dump($var, [
                Dumper::DEPTH => self::$maxDepth,
                Dumper::TRUNCATE => self::$maxLength,
            ]);

            return \ob_get_clean();
        }

        if (!self::isProductionMode()) {
            Dumper::dump($var, [
                Dumper::DEPTH => self::$maxDepth,
                Dumper::TRUNCATE => self::$maxLength,
                Dumper::LOCATION => self::$showLocation,
            ]);
        }

        return $var;
    }
538127
public function fetch($return = self::RETURN_COLLECTION) {
        /** We replace Post.xx by post.xx */
        foreach ($this->_entities as $entity) {
            $class = $this->_getTableEntity($entity);

            if ($entity != $class->name()) {
                $this->_query = preg_replace('#(.*)' . $entity . '\.(.*)#isU', '$1' . $class->name() . '.$2', $this->_query);
            }
        }

        /** Query execution */
        $sql = new Sql();
        $sql->vars($this->_vars);
        $sql->query('orm-' . $this->_token, $this->_query);

        if ($this->_type == self::QUERY_COUNT) {
            return $sql->fetch('orm-' . $this->_token, Sql::PARAM_FETCHCOLUMN);
        }
        else {
            $sql->fetch('orm-' . $this->_token, Sql::PARAM_FETCH);
        }

        $collection = $sql->data($this->_getEntityName($this->_entity->name()));

        /** We can do SELECT OR SELECT DISTINCT OR SELECT RAW */
        if (in_array($this->_type, [self::QUERY_DISTINCT, self::QUERY_RAW])) {
            $nLines = $collection->count();
            $in = '';

            /** @var $value \Gcs\Framework\Core\Orm\Entity\Entity */
            foreach ($collection as $key => $value) {
                $in .= $value->fields()[$value->primary()]->value;

                if ($key < $nLines - 1) {
                    $in .= ', ';
                }
            }

            $builder = new Builder($this->_entity);
            $collection = $builder->find()->where($this->_entity->name() . '.' . $this->_entity->primary() . ' IN (' . $in . ')')->fetch();
        }

        /** If we have fields with a relation ONE TO MANY OR MANY TO MANY */
        foreach ($this->_entity->fields() as $field) {
            if ($field->foreign != null && in_array($field->foreign->type(), [ForeignKey::ONE_TO_MANY, ForeignKey::MANY_TO_MANY])) {
                /** we loop through the results to add each time */
                switch ($field->foreign->type()) {
                    case ForeignKey::ONE_TO_MANY :
                        $collection = $this->_dataOneToMany($field, $collection);
                        break;

                    case ForeignKey::MANY_TO_MANY :
                        $collection = $this->_dataManyToMany($field, $collection);
                        break;
                }
            }
        }

        if ($return == self::RETURN_ENTITY && $collection->count() <= 1) {
            return $collection->first();
        }
        else {
            return $collection;
        }
    }
1344975
public static function getWebhookPayload($returnObject = false) {
        $data = file_get_contents("php://input");
        if ($data) {
            return self::jsonDecode($data, !$returnObject);
        } else {
            return null;
        }
    }
85380
private function getBoolQuery($field, array $values, $operator)
    {
        $type = ('or' === strtolower($operator) ? BoolQuery::SHOULD : BoolQuery::MUST);

        $query = new BoolQuery();
        foreach ($values as $value) {
            $query->add(new TermQuery($field, $value), $type);
        }

        return $query;
    }
241111
public function get()
    {
        if ($this->date) {
            $result = $this->historical($this->date, $this->base, $this->targets);
        } else {
            $result = $this->latest($this->base, $this->targets);
        }

        // Ensure the result object is valid.
        if (!$result instanceof ResultContract) {
            throw new UnexpectedValueException('Invalid result type');
        }

        // Perform conversion if requested.
        if ($this->amount !== 1) {
            $converted = $result->rates;

            foreach ($converted as $key => $value) {
                $converted[$key] = round($this->amount * $value, 2);
            }

            // Attach converted values to results.
            $result->setConverted($converted);
        }

        return $result;
    }
1256026
public function getSql($count = false){
        if ($count){
            $select = 'count(*)';
        }else{
            $select = $this->voDatum->getSelect();
        }
        $sql = "select $select from $this->dbName ";
        $params = array();
        foreach ($this->joins as $k => $v){
            list($joinSql, $ps) = $v;
            $sql .= $joinSql;
            foreach ($ps as $p)
                $params[] = $p;
        }

        $where = $this->where->getString();
        if ($where)
            $sql .= ' where ' . $where;
        if (!$count)
            $sql .= $this->getOrder();
        if (is_numeric($this->limit))
            $sql .= " limit $this->limit ";
        if (is_numeric($this->offset))
            $sql .= " offset $this->offset ";

        foreach ($this->where->getParams() as $p)
            $params[] = $p;
        return array($sql, $params);
    }
214297
public function capture($amount = null)
    {
        return (new ManagementBuilder(TransactionType::CAPTURE))
            ->withPaymentMethod($this->transactionReference)
            ->withAmount($amount);
    }
927789
public function getValue($returnObject = false){

        $returnValue = null;

        if(!is_null($this->value)){
            $returnValue = ($returnObject) ? $this->value : $this->value->getValue(); //return mixed
        }

        return $returnValue;
    }
466660
public function fetch($type = null) {

		if(null !== $type && false === is_string($type)) {
			return trigger_error(sprintf('Argument 1 passed to %s() must be of the type string, "%s" given', __METHOD__, gettype($query)), E_USER_ERROR);
		}

		$results = new ResultSet([], $type);

		//Returns a copy of a value
		$copy 	= function($a) { return $a; };
		$amount = count($this -> stmt);

		foreach($this -> stmt as $stmt) {

			//Execute statement and store results
			$stmt 	= $this -> executeStatement($stmt);
			$result = [];

			if(false !== $stmt && 0 !== $stmt -> field_count && 0 === $stmt -> errno) {
				
				$vars = $this -> bind($stmt);

				while($stmt -> fetch()) {

					if($amount === 1) {
				    	$results -> append(array_map($copy, $vars));
				    }
				    else {
				    	$result[] = array_map($copy, $vars);
				    }
				}
			}
			
			if($amount > 1) {
				$results -> append($result);
			}
		}

		$this -> shadow = $this -> stmt;
		$this -> reset();

		return $results;
	}
882162
public function createSearch( $default = false )
	{
		if( $default === true )
		{
			$object = $this->_createSearch( 'price' );
			$currencyid = $this->_getContext()->getLocale()->getCurrencyId();

			if( $currencyid !== null )
			{
				$expr = array(
					$object->compare( '==', 'price.currencyid', $currencyid ),
					$object->getConditions(),
				);

				$object->setConditions( $object->combine( '&&', $expr ) );
			}

			return $object;
		}

		return parent::createSearch();
	}
950110
public static function transaction($closure, $execute=true)
    {
        $transaction = self::instance()->connection()->transaction();
        $transaction->callback($closure);

        if($execute)
            $transaction->execute();

        return $transaction;
    }