sentence1
stringlengths
52
3.87M
sentence2
stringlengths
1
47.2k
label
stringclasses
1 value
public static function riverHasBeenDealt($message = null) { $defaultMessage = 'The River has already been dealt!'; $message = null === $message ? $defaultMessage : $message; return new static($message); }
@param null|string $message @return static
entailment
public static function playerTryingToActOutOfTurn(Player $player, Player $actualPlayer, $message = null) { $defaultMessage = sprintf('%s tried to act out of turn! It\'s %ss turn.', $player, $actualPlayer); $message = null === $message ? $defaultMessage : $message; return new static($message); }
@param null|string $message @return static
entailment
public static function noPlayerActionsNeeded($message = null) { $defaultMessage = 'A player is trying to act when there is no valid player actions left.'; $message = null === $message ? $defaultMessage : $message; return new static($message); }
@param null $message @return static
entailment
public static function cantCheckWithBetActive($message = null) { $defaultMessage = 'Cannot check when there has been a bet made'; $message = null === $message ? $defaultMessage : $message; return new static($message); }
@param null $message @return static
entailment
public static function raiseNotHighEnough(Chips $raise, Chips $bet, $message = null) { $defaultMessage = sprintf( 'Cannot make a raise of %d when there is a bet of %d active.', $raise->amount(), $bet->amount() ); $message = null === $message ? $defaultMessage : $message; return new static($message); }
@param null $message @return static
entailment
public function setup(PlayerCollection $players): self { $collection = $players->map(function (Player $player, $seatNumber) { // everyone is still left to act return [ 'seat' => $seatNumber, 'player' => $player->name(), 'action' => self::STILL_TO_ACT, ]; }); return self::make($collection->toArray()); }
Sets all players actions to STILL_TO_ACT. @param PlayerCollection $players @return LeftToAct
entailment
public function setupWithoutDealer(PlayerCollection $players): self { $collection = $this->setup($players); // move the dealer to last $collection = $collection->movePlayerToLastInQueue(); return self::make($collection->values()->toArray()); }
Resets all players, and move dealer to the bottom of queue. @param PlayerCollection $players @return LeftToAct
entailment
public function setActivity($player, int $activity): self { // var_dump($this); $result = $this ->filter(function ($array) use ($player) { return $array['player'] === $player; }) ; $array = $result->first(); $array['action'] = $activity; $this->put($result->keys()->first(), $array); return self::make($this->values()->toArray()); }
@param Player $player @param int $activity @return LeftToAct
entailment
public static function evaluate(CardCollection $board, Hand $hand): CardResults { $cards = $board->merge($hand->cards()); if (($result = static::royalFlush($cards)) !== false) { return SevenCardResult::createRoyalFlush($result, $hand); } if (($result = static::straightFlush($cards)) !== false) { return SevenCardResult::createStraightFlush($result, $hand); } if (($result = static::fourOfAKind($cards)) !== false) { return SevenCardResult::createFourOfAKind($result, $hand); } if (($result = static::fullHouse($cards)) !== false) { return SevenCardResult::createFullHouse($result, $hand); } if (($result = static::flush($cards)) !== false) { return SevenCardResult::createFlush($result, $hand); } if (($result = static::straight($cards)) !== false) { return SevenCardResult::createStraight($result, $hand); } if (($result = static::threeOfAKind($cards)) !== false) { return SevenCardResult::createThreeOfAKind($result, $hand); } if (($result = static::twoPair($cards)) !== false) { return SevenCardResult::createTwoPair($result, $hand); } if (($result = static::onePair($cards)) !== false) { return SevenCardResult::createOnePair($result, $hand); } return SevenCardResult::createHighCard(static::highCard($cards), $hand); }
@param CardCollection $board @param Hand $hand @return CardResults
entailment
public function evaluateHands(CardCollection $board, HandCollection $playerHands): ResultCollection { $playerHands = $playerHands // evaluate hands ->map(function (Hand $hand) use ($board) { return static::evaluate($board, $hand); }) // sort the hands by their hand rank ->sortByDesc(function (SevenCardResult $result) { return [$result->rank(), $result->value()]; }) // group by the hand rank ->groupBy(function (SevenCardResult $result) { return $result->rank(); }) ; // if all hands in the first collection are equal $handsAreEqual = $playerHands ->first() ->groupBy(function (SevenCardResult $result) { return array_sum($result->value()); }) ; $winningResults = SevenCardResultCollection::make($handsAreEqual->first()->toArray()); return $winningResults; }
@param CardCollection $board @param HandCollection $playerHands @return ResultCollection
entailment
public static function royalFlush(CardCollection $cards) { // check for straight flush if (!static::straightFlush($cards)) { return false; } // make sure that TJQKA exist in hand $royalFlushHand = $cards ->switchAceValue() ->filter(function (Card $card) { return $card->isFaceCard() || $card->value() === 10; }); if ($royalFlushHand->count() < 5) { return false; } return $royalFlushHand->sortByValue(); }
@param CardCollection $cards @return bool|CardCollection
entailment
public static function straightFlush(CardCollection $cards) { // check for flush if (($flushCards = static::flush($cards)) === false) { return false; } // check for straight, using the flush cards if (($straight = static::straight($flushCards)) === false) { return false; } return $straight; }
@param CardCollection $cards @return bool|CardCollection
entailment
public static function fourOfAKind(CardCollection $cards) { $judgedHand = self::nNumberOfCardsInSet($cards, 4); if ($judgedHand === null) { return false; } $highCard = self::highCard($cards->diff($judgedHand))->last(); return $judgedHand ->push($highCard) ->switchAceValue() ->sortByValue(); }
@param CardCollection $cards @return CardCollection|false
entailment
public static function fullHouse(CardCollection $cards) { $threeOfAKind = self::nNumberOfCardsInSet($cards, 3); $twoOfAKind = self::nNumberOfCardsInSet($cards->diff($threeOfAKind), 2); if ($threeOfAKind === null || $twoOfAKind === null) { return false; } return $threeOfAKind->merge($twoOfAKind); }
@param CardCollection $cards @return bool|CardCollection
entailment
public static function flush(CardCollection $cards) { $groupedBySuit = $cards ->switchAceValue() ->groupBy(function (Card $card) { return $card->suit()->name(); }) ->sortByDesc(function ($group) { return count($group); }); if ($groupedBySuit->first()->count() < 5) { return false; } return $groupedBySuit ->first() ->sortByValue() ->take(-5) ->values(); }
@param CardCollection $cards @return CardCollection|bool
entailment
public static function straight(CardCollection $cardCollection) { // a straight has to have a 5 or 10 in if ($cardCollection->whereValue(5)->count() === 0 && $cardCollection->whereValue(10)->count() === 0) { return false; } // we only care about the first instance of a card number $cardCollection = $cardCollection->uniqueByValue(); // check with ace == 1 $check = static::checkForStraight($cardCollection->sortByValue()->unique()); if ($check !== false) { return $check; } // check with ace == 14 $check = static::checkForStraight($cardCollection->switchAceValue()->sortByValue()->unique()); if ($check !== false) { return $check; } return false; }
@param CardCollection $cardCollection @return bool|CardCollection
entailment
public static function threeOfAKind(CardCollection $cards) { $judgedHand = self::nNumberOfCardsInSet($cards, 3); if ($judgedHand === null) { return false; } $highCards = $cards->diff($judgedHand)->sortByValue()->reverse()->take(2); return $judgedHand ->merge($highCards) ->switchAceValue() ->sortByValue(); }
@param CardCollection $cards @return CardCollection|bool
entailment
public static function twoPair(CardCollection $cards) { $pairOne = self::nNumberOfCardsInSet($cards, 2); $pairTwo = self::nNumberOfCardsInSet($cards->diff($pairOne), 2); if ($pairTwo === null) { return false; } $pairs = $pairOne->merge($pairTwo); $highCard = self::highCard($cards->diff($pairs))->last(); return $pairs ->push($highCard) ->switchAceValue(); }
@param CardCollection $cards @return CardCollection|bool
entailment
public static function onePair(CardCollection $cards) { $cards = $cards->switchAceValue(); $pair = self::nNumberOfCardsInSet($cards, 2); if ($pair === null) { return false; } $otherCardsInResult = $cards->diff($pair) ->sortByValue() ->reverse() ->take(3) ; return $pair->merge($otherCardsInResult); }
@param CardCollection $cards @return CardCollection|false
entailment
public static function highCard(CardCollection $cards): CardCollection { return $cards ->switchAceValue() ->sortByValue() ->reverse() ->take(5) ->reverse() ->values(); }
@param CardCollection $cards @return CardCollection
entailment
private static function checkForStraight(CardCollection $cards) { // check 2-6 $cardsToCheck = static::isStraight($cards->only(range(2, 6))); if ($cardsToCheck !== false) { return $cardsToCheck; } // check 1-5 $cardsToCheck = static::isStraight($cards->only(range(1, 5))); if ($cardsToCheck !== false) { return $cardsToCheck; } // check 0-4 $cardsToCheck = static::isStraight($cards->only(range(0, 4))); if ($cardsToCheck !== false) { return $cardsToCheck; } return false; }
@param CardCollection $cards @return bool|CardCollection
entailment
private static function isStraight(CardCollection $cards) { if ($cards->count() !== 5) { return false; } $uniqueCards = $cards->map->value()->unique(); if ($cards->count() !== $uniqueCards->count()) { return false; } if ($cards->sumByValue() === array_sum(range( $cards->sortByValue()->first()->value(), $cards->sortByValue()->last()->value() ))) { return $cards->sortByValue()->values(); } return false; }
@author Derecho @param CardCollection $cards @return bool|CardCollection
entailment
private static function nNumberOfCardsInSet(CardCollection $cards, int $numberOfCardsOfType) { $judgedHand = $cards ->groupBy(function (Card $card) { return $card->value(); }) ->filter(function (CardCollection $group) use ($numberOfCardsOfType) { return $group->count() === $numberOfCardsOfType; }) ->sortBy(function (CardCollection $group) { return $group->count(); }) ->values() ->last() ; return $judgedHand; }
@param CardCollection $cards @param int $numberOfCardsOfType @return CardCollection
entailment
public function dealCommunityCards(int $cards = 1) { // burn one $this->burnCards()->push($this->dealCard()); // deal for ($i = 0; $i < $cards; ++$i) { $this->communityCards()->push($this->dealCard()); } }
Adds a card to the BurnCards(), also Adds a card to the CommunityCards(). @param int $cards
entailment
public function checkCommunityCards() { if ($this->communityCards()->count() === 5) { return; } if ($this->communityCards()->count() === 0) { $this->dealCommunityCards(3); } if ($this->communityCards()->count() === 3) { $this->dealCommunityCards(1); } if ($this->communityCards()->count() === 4) { $this->dealCommunityCards(1); } }
Deals the remainder of the community cards, whilst taking burn cards into account.
entailment
public function playerHand(PlayerContract $player): Hand { $hand = $this->hands()->findByPlayer($player); if ($hand === null) { throw RoundException::playerHasNoHand($player); } return $hand; }
@param PlayerContract $player @return Hand
entailment
public function evaluateHands(CardCollection $board, HandCollection $playerHands): ResultCollection { return $this->cardEvaluationRules->evaluateHands($board, $playerHands); }
@param CardCollection $board @param HandCollection $playerHands @return ResultCollection
entailment
public function selectRenderer(ViewEvent $event) { $model = $event->getModel(); if ($model instanceof Model\PdfModel) { return $this->renderer; } return null; }
Detect if we should use the PdfRenderer based on model type @param ViewEvent $event @return null|PdfRenderer
entailment
public function injectResponse(ViewEvent $event) { $renderer = $event->getRenderer(); if ($renderer !== $this->renderer) { // Discovered renderer is not ours; do nothing return; } $result = $event->getResult(); if (!is_string($result)) { // No output to display. Good bye! return; } $response = $event->getResponse(); $response->setContent($result); $model = $event->getModel(); $options = $model->getOptions(); $fileName = $options['fileName']; $dispositionType = $options['display']; if (substr($fileName, -4) != '.pdf') { $fileName .= '.pdf'; } $headerValue = sprintf('%s; filename="%s"', $dispositionType, $fileName); $response->getHeaders()->addHeaderLine('Content-Disposition', $headerValue); $response->getHeaders()->addHeaderLine('Content-Length', strlen($result)); $response->getHeaders()->addHeaderLine('Content-Type', 'application/pdf'); }
Inject the response with the PDF payload and appropriate Content-Type header @param ViewEvent $e @return void
entailment
public static function fromClient(Client $client, Chips $chipCount = null): PlayerContract { return new self($client->id(), $client->name(), $client->wallet(), $chipCount); }
@param Client $client @param Chips $chipCount @return PlayerContract
entailment
public static function start(Uuid $id, Table $table, GameParameters $gameRules): Round { return new static($id, $table, $gameRules); }
Start a Round of poker. @param Uuid $id @param Table $table @param GameParameters $gameRules @return Round
entailment
public function end() { $this->dealer()->checkCommunityCards(); $this->collectChipTotal(); $this->distributeWinnings(); $this->table()->moveButton(); }
Run the cleanup procedure for an end of Round.
entailment
private function distributeWinnings() { $this->chipPots() ->reverse() ->each(function (ChipPot $chipPot) { // if only 1 player participated to pot, he wins it no arguments if ($chipPot->players()->count() === 1) { $potTotal = $chipPot->chips()->total(); $chipPot->players()->first()->chipStack()->add($potTotal); $this->chipPots()->remove($chipPot); return; } $activePlayers = $chipPot->players()->diff($this->foldedPlayers()); $playerHands = $this->dealer()->hands()->findByPlayers($activePlayers); $evaluate = $this->dealer()->evaluateHands($this->dealer()->communityCards(), $playerHands); // if just 1, the player with that hand wins if ($evaluate->count() === 1) { $player = $evaluate->first()->hand()->player(); $potTotal = $chipPot->chips()->total(); $player->chipStack()->add($potTotal); $this->chipPots()->remove($chipPot); } else { // if > 1 hand is evaluated as highest, split the pot evenly between the players $potTotal = $chipPot->chips()->total(); // split the pot between the number of players $splitTotal = Chips::fromAmount(($potTotal->amount() / $evaluate->count())); $evaluate->each(function (CardResults $result) use ($splitTotal) { $result->hand()->player()->chipStack()->add($splitTotal); }); $this->chipPots()->remove($chipPot); } }) ; }
Runs over each chipPot and assigns the chips to the winning player.
entailment
public function playerIsStillIn(PlayerContract $actualPlayer) { $playerCount = $this->playersStillIn()->filter->equals($actualPlayer)->count(); return $playerCount === 1; }
@param Player $actualPlayer @return bool
entailment
public function dealFlop() { if ($this->dealer()->communityCards()->count() !== 0) { throw RoundException::flopHasBeenDealt(); } if ($player = $this->whosTurnIsIt()) { throw RoundException::playerStillNeedsToAct($player); } $this->collectChipTotal(); $seat = $this->table()->findSeat($this->playerWithSmallBlind()); $this->resetPlayerList($seat); $this->dealer()->dealCommunityCards(3); $this->actions()->push(new Action($this->dealer(), Action::DEALT_FLOP, [ 'communityCards' => $this->dealer()->communityCards()->only(range(0, 2)), ])); }
Deal the Flop.
entailment
public function dealTurn() { if ($this->dealer()->communityCards()->count() !== 3) { throw RoundException::turnHasBeenDealt(); } if (($player = $this->whosTurnIsIt()) !== false) { throw RoundException::playerStillNeedsToAct($player); } $this->collectChipTotal(); $seat = $this->table()->findSeat($this->playerWithSmallBlind()); $this->resetPlayerList($seat); $this->dealer()->dealCommunityCards(1); $this->actions()->push(new Action($this->dealer(), Action::DEALT_TURN, [ 'communityCards' => $this->dealer()->communityCards()->only(3), ])); }
Deal the turn card.
entailment
public function dealRiver() { if ($this->dealer()->communityCards()->count() !== 4) { throw RoundException::riverHasBeenDealt(); } if (($player = $this->whosTurnIsIt()) !== false) { throw RoundException::playerStillNeedsToAct($player); } $this->collectChipTotal(); $seat = $this->table()->findSeat($this->playerWithSmallBlind()); $this->resetPlayerList($seat); $this->dealer()->dealCommunityCards(1); $this->actions()->push(new Action($this->dealer(), Action::DEALT_RIVER, [ 'communityCards' => $this->dealer()->communityCards()->only(4), ])); }
Deal the river card.
entailment
public function playerCalls(PlayerContract $player) { $this->checkPlayerTryingToAct($player); $highestChipBet = $this->highestBet(); // current highest bet - currentPlayersChipStack $amountLeftToBet = Chips::fromAmount($highestChipBet->amount() - $this->playerBetStack($player)->amount()); $chipStackLeft = Chips::fromAmount($player->chipStack()->amount() - $amountLeftToBet->amount()); if ($chipStackLeft->amount() <= 0) { $amountLeftToBet = Chips::fromAmount($player->chipStack()->amount()); $chipStackLeft = Chips::zero(); } $action = $chipStackLeft->amount() === 0 ? Action::ALLIN : Action::CALL; $this->actions->push(new Action($player, $action, ['chips' => $amountLeftToBet])); $this->placeChipBet($player, $amountLeftToBet); $action = $chipStackLeft->amount() === 0 ? LeftToAct::ALLIN : LeftToAct::ACTIONED; $this->leftToAct = $this->leftToAct()->playerHasActioned($player, $action); }
@param PlayerContract $player @throws RoundException
entailment
public function playerRaises(PlayerContract $player, Chips $chips) { $this->checkPlayerTryingToAct($player); $highestChipBet = $this->highestBet(); if ($chips->amount() < $highestChipBet->amount()) { throw RoundException::raiseNotHighEnough($chips, $highestChipBet); } $chipStackLeft = Chips::fromAmount($player->chipStack()->amount() - $chips->amount()); if ($chipStackLeft->amount() === 0) { return $this->playerPushesAllIn($player, $chips); } $betAmount = Chips::fromAmount($highestChipBet->amount() + $chips->amount()); $this->actions->push(new Action($player, Action::RAISE, ['chips' => $betAmount])); $this->placeChipBet($player, $betAmount); $action = $chipStackLeft->amount() === 0 ? LeftToAct::ALLIN : LeftToAct::AGGRESSIVELY_ACTIONED; $this->leftToAct = $this->leftToAct()->playerHasActioned($player, $action); }
@param PlayerContract $player @param Chips $chips @throws RoundException
entailment
public function playerFoldsHand(PlayerContract $player) { $this->checkPlayerTryingToAct($player); $this->actions()->push(new Action($player, Action::FOLD)); $this->foldedPlayers->push($player); $this->leftToAct = $this->leftToAct()->removePlayer($player); }
@param PlayerContract $player @throws RoundException
entailment
public function playerPushesAllIn(PlayerContract $player) { $this->checkPlayerTryingToAct($player); // got the players chipStack $chips = $player->chipStack(); // gotta create a new chip obj here cause of PHPs /awesome/ objRef ability :D $this->actions()->push(new Action($player, Action::ALLIN, ['chips' => Chips::fromAmount($chips->amount())])); $this->placeChipBet($player, $chips); $this->leftToAct = $this->leftToAct()->playerHasActioned($player, LeftToAct::ALLIN); }
@param PlayerContract $player @throws RoundException
entailment
public function playerChecks(PlayerContract $player) { $this->checkPlayerTryingToAct($player); if ($this->playerBetStack($player)->amount() !== $this->betStacks()->max()->amount()) { throw RoundException::cantCheckWithBetActive(); } $this->actions()->push(new Action($player, Action::CHECK)); $this->leftToAct = $this->leftToAct()->playerHasActioned($player, LeftToAct::ACTIONED); }
@param PlayerContract $player @throws RoundException
entailment
private function resetBetStacks() { $this->players()->each(function (PlayerContract $player) { $this->betStacks->put($player->name(), Chips::zero()); }); }
Reset the chip stack for all players.
entailment
private function setupLeftToAct() { if ($this->players()->count() === 2) { $this->leftToAct = $this->leftToAct()->setup($this->players()); return; } $this->leftToAct = $this->leftToAct ->setup($this->players()) ->resetPlayerListFromSeat($this->table()->button() + 1); }
Reset the leftToAct collection.
entailment
public static function setUp(Uuid $id, DealerContract $dealer, PlayerCollection $players) { return new self($id, $dealer, $players); }
@param Uuid $id @param DealerContract $dealer @param PlayerCollection $players @return Table
entailment
public function giveButtonToPlayer(PlayerContract $player) { $playerIndex = $this->playersSatDown() ->filter ->equals($player) ->keys() ->first(); if ($playerIndex === null) { throw TableException::invalidButtonPosition(); } $this->button = $playerIndex; }
@param PlayerContract $player @throws TableException
entailment
public function moveButton() { $this->button = $this->button + 1; if ($this->button >= $this->playersSatDown()->count()) { $this->button = 0; } }
Moves the button along the table seats.
entailment
public function createService(ServiceLocatorInterface $serviceLocator) { return (new PdfRenderer()) ->setResolver($serviceLocator->get('ViewResolver')) ->setHtmlRenderer($serviceLocator->get('ViewRenderer')) ->setEngine($serviceLocator->get('dompdf')); }
Create and return the PDF view renderer @param ServiceLocatorInterface $serviceLocator @return PdfRenderer
entailment
public function run() { $emitter = new Response\SapiEmitter(); try { $packages = $this->getPackages(); /** @var PackageInterface $package */ foreach ($packages as $package) { if ($package instanceof FiltersProviderInterface) { if (!$package->getFilterEngine()->filter($this)) { continue; } } if ($package instanceof ConfigProviderInterface) { $this->getConfig()->merge($package->getConfig()); } if ($package instanceof PackagesInitListener) { $this->getEventsHandler()->bind(WorkflowEvent::PACKAGES_INIT, [$package, 'onPackagesInit']); } if ($package instanceof PackagesReadyListener) { $this->getEventsHandler()->bind(WorkflowEvent::PACKAGES_READY, [$package, 'onPackagesReady']); } } // read configuration if (is_dir($this->getConfigPath())) { $this->getConfig()->hydrate((new FileLoader())->load($this->getConfigPath())); } $this->triggerWorkflowEvent(WorkflowEvent::PACKAGES_INIT); // load services /** @var ServiceDefinition[] $servicesDefinitions */ $servicesDefinitions = $this->getConfig()->getRaw(ServiceDefinition::KEY); foreach ($servicesDefinitions as $id => $servicesDefinition) { $service = array_merge(['id' => $id], $servicesDefinition->getSpecifications()); $this->getServicesFactory()->registerRawService($service); } $this->triggerWorkflowEvent(WorkflowEvent::PACKAGES_READY); $this->triggerWorkflowEvent(WorkflowEvent::ROUTING_START); $this->setRoutingResult($this->getRouter()->route($this->getRequest(), $this)); if ($this->getRoutingResult()->didMatch()) { $this->getMiddlewares()->registerMiddleware($this->getRoutingResult()->getMatchedRoute()->getAction()); } $this->triggerWorkflowEvent(WorkflowEvent::ROUTING_DONE); $this->triggerWorkflowEvent(WorkflowEvent::REQUEST_HANDLING_START, $this); $response = $this->handle($this->getRequest()); $this->triggerWorkflowEvent(WorkflowEvent::REQUEST_HANDLING_DONE, $this, ['response' => $response]); if ($buffer = $this->cleanBuffer()) { $response->getBody()->rewind(); $content = $buffer . $response->getBody()->getContents(); $response = $response->withBody(new Stream('php://memory', 'wb+')); $response->getBody()->write($content); } $emitter->emit($response); ob_start(); $this->triggerWorkflowEvent(WorkflowEvent::RESPONSE_SENT); } catch (\Throwable $exception) { $request = $this->getRequest() ->withAttribute('exception', $exception) ->withAttribute('buffer', $this->cleanBuffer()) ->withAttribute('headers', headers_list()); $response = $this->handleException($request); $emitter->emit($response); } }
{@inheritdoc}
entailment
public function handle(ServerRequestInterface $request): ResponseInterface { /** @var MiddlewareInterface $middleware */ $middleware = $this->getNextMiddleware(); if (!$middleware) { if ($this->getRoutingResult()->didMatch()) { throw new WorkflowException('No suitable middleware was found to handle the request.', 404); } throw new WorkflowException('No route matched requested URL', 404); } $this->getServicesFactory()->injectDependencies($middleware); $this->triggerWorkflowEvent('application.workflow.middleware.before', $middleware); $response = $middleware->process($request, $this); $this->triggerWorkflowEvent('application.workflow.middleware.after', $middleware); return $response; }
@param ServerRequestInterface $request @return ResponseInterface @throws WorkflowException @throws \ObjectivePHP\Events\Exception\EventException @throws \ObjectivePHP\Primitives\Exception @throws \ObjectivePHP\ServicesFactory\Exception\ServiceNotFoundException @throws \ObjectivePHP\ServicesFactory\Exception\ServicesFactoryException
entailment
public function handleException(ServerRequestInterface $request): ResponseInterface { /** @var MiddlewareInterface $middleware */ $middleware = $this->getExceptionHandlers()->getNextMiddleware(); if (!$middleware) { throw new WorkflowException( 'No suitable middleware was found to handle the uncaught exception.', null, $request->getAttribute('exception') ); } $this->getServicesFactory()->injectDependencies($middleware); $response = $middleware->process($request, $this); return $response; }
@param ServerRequestInterface $request @return ResponseInterface @throws WorkflowException @throws \ObjectivePHP\ServicesFactory\Exception\ServicesFactoryException
entailment
public function setMoney($number, $moeda='BRL'){ $this->money = Money::BRL($number, new Currency($moeda)); return $this; }
@param mixed $money @return self
entailment
public function setFilesLinks($filesLinks,$local='',$additional=''){ if($local!='start' && $local!='end'){$local='end';} $this->filesLinks[$local][$filesLinks] = $additional; }
/* GETTRES AND SETTRES
entailment
public function setFilesScripts($filesScripts,$local='',$additional=''){ if($local!='start' && $local!='end'){$local='end';} $this->filesScripts[$local][$filesScripts] = $additional; }
FilesScripts
entailment
public static function sizeFormat($bytes, $decimals = 0){ $bytes = floatval($bytes); if ($bytes < 1024) { return number_format($bytes, $decimals, '.', '') . ' B'; } elseif ($bytes < pow(1024, 2)) { return number_format($bytes / 1024, $decimals, '.', '') . ' KB'; } elseif ($bytes < pow(1024, 3)) { return number_format($bytes / pow(1024, 2), $decimals, '.', '') . ' MB'; } elseif ($bytes < pow(1024, 4)) { return number_format($bytes / pow(1024, 3), $decimals, '.', '') . ' GB'; } elseif ($bytes < pow(1024, 5)) { return number_format($bytes / pow(1024, 4), $decimals, '.', '') . ' TB'; } elseif ($bytes < pow(1024, 6)) { return number_format($bytes / pow(1024, 5), $decimals, '.', '') . ' PB'; } else { return number_format($bytes / pow(1024, 5), $decimals, '.', '') . ' PB'; } }
Formatação agradável para tamanhos de computador (Bytes). @param integer $bytes O número em bytes para formatar @param integer $decimals O número de pontos decimais a incluir @return string
entailment
function convertMemorySize($strval, string $to_unit = 'b'){ $strval = strtolower(str_replace(' ', '', $strval)); $val = floatval($strval); $to_unit = strtolower(trim($to_unit))[0]; $from_unit = str_replace($val, '', $strval); $from_unit = empty($from_unit) ? 'b' : trim($from_unit)[0]; $units = 'kmgtph'; // (k)ilobyte, (m)egabyte, (g)igabyte and so on... // Convert to bytes if ($from_unit !== 'b'){ $val *= 1024 ** (strpos($units, $from_unit) + 1); } // Convert to unit if ($to_unit !== 'b'){ $val /= 1024 ** (strpos($units, $to_unit) + 1); } $val = $val.' '.($to_unit!='b'?strtoupper($to_unit).'B':'B'); return $val; }
Formatação agradável para tamanhos de computador (Bytes). @param integer $bytes O número com medida ex: 1T @param integer $decimals O tipo de saída @return string
entailment
protected function triggerWorkflowEvent($eventName, $origin = null, $context = []) { $this->getEventsHandler()->trigger($eventName, $origin, $context, new WorkflowEvent($this)); }
@param $eventName @param null $origin @param array $context @throws \ObjectivePHP\Events\Exception\EventException @throws \ObjectivePHP\Primitives\Exception @throws \ObjectivePHP\ServicesFactory\Exception\ServiceNotFoundException
entailment
public function process($value) { if ($this->isMandatory() && !$value) { throw new Exception($this->getMessage(self::IS_MISSING, ['param', $this->reference])); } $dataProcessor = $this->getDataProcessor(); if ($dataProcessor instanceof ApplicationAwareInterface) { $dataProcessor->setApplication($this->getApplication()); } $processedValue = $dataProcessor->process($value); if($this->isMandatory() && is_null($processedValue)) { throw new Exception($this->getMessage(self::IS_MISSING, ['param', $this->reference])); } return $processedValue; }
Process a value The processed value will be stored as parameter value @param mixed $value @return mixed @throws Exception
entailment
public function setMessage($code, $message) { $this->messages[$code] = Str::cast($message); return $this; }
@param string $message @return $this
entailment
public function init() { $this->path = $this->config('path'); $this->baseURL = $this->config('baseURL'); $this->errorsHandle(); $this->autoloads(); }
Application Initialization method @return void
entailment
protected function errorsHandle() { $debug = $this->config('debug'); error_reporting(($debug) ? E_ALL : E_ERROR & ~E_NOTICE); set_error_handler(function ($type, $message, $file, $line) { throw new \ErrorException($message, 0, $type, $file, $line); }); set_exception_handler(function (\Exception $e) { $exception = new ExceptionsMiddleware; $log = $this->getLog(); // Force Slim to append log to env if not already $env = $this->environment(); $env['slim.log'] = $log; $env['slim.log']->error($e); $this->contentType('text/html'); $this->response()->status(500); echo $this->response()->body($exception->renderBody($env, $e)); }); register_shutdown_function(function () { if ( !is_null($options = error_get_last()) ) { $title = 'Slimore Application Error Shutdown'; $html = html($title, [ '<meta http-equiv="X-UA-Compatible" content="IE=edge" />', '<meta name="renderer" content="webkit" />', '<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no" />', style([ '*{margin:0;padding:0;}', 'html {font-size: 62.5%;}', 'html, body {max-width: 100%;width: 100%;}', 'body {font-size: 1.4rem;font-family: "Microsoft Yahei", Helvetica, Tahoma, STXihei, arial,verdana,sans-serif;background:#fff;color:#555;}', 'img {border: none;}', 'pre, pre code {font-family:Consolas, arial,verdana,sans-serif;}', '#layout {padding: 6rem;}', '#main {margin: 0 auto;line-height: 1.5;}', '#main > h1 {font-size: 10rem;margin-bottom: 1rem;}', '#main > h3 {margin-bottom: 2rem; font-size: 1.8rem;}', '#main > h4 {margin-bottom: 1rem; font-size: 1.8rem;}', '#main pre {margin: 1.5rem 0;white-space: pre-wrap;word-wrap: break-word;}', '#main > p {white-space: pre-wrap;word-wrap: break-word;line-height: 1.3;margin-bottom: 0.6rem;}', '#main > p > strong {width: 7rem;display:inline-block;}', '.logo {text-align: left;border-top:1px solid #eee;margin-top: 5rem;padding: 3rem 0 0;color: #ccc;}', '.logo > h1 {font-weight: normal;font-size: 5rem;}', '.logo img {margin-left: -2rem;}', '.trace-line {padding: 0.3rem 0.6rem;margin-left:-0.6rem;-webkit-transition: background-color 300ms ease-out;transition: background-color 300ms ease-out;}', '.trace-line:hover {background:#fffccc;}' ]) ], [ '<div id="layout">', '<div id="main">', '<h1>:(</h1>', '<h3>' . $title . '</h3>', '<h4>Details :</h4>', '<p><strong>Type: </strong> ' . $options['type'] . '</p>', '<p><strong>Message: </strong> ' . $options['message'] . '</p>', '<p><strong>File: </strong> ' . $options['file'] . '</p>', '<p><strong>Line: </strong> ' . $options['line'] . '</p>', '<div class="logo">', '<h1>Slimore</h1>', '<p>The fully (H)MVC framework, based on the Slim PHP Framwork.</p>', '</div>', '</div>', '</div>' ]); echo $html; exit; } }); }
Errors / Exceptions handle @return void
entailment
public function dbConnection(array $configs = null, $name = 'default', $enableQueryLog = true) { $db = new DB(); $db->addConnection(($configs) ? $configs : $this->config('db'), $name); $db->setEventDispatcher(new Dispatcher(new Container)); $db->setAsGlobal(); $db->bootEloquent(); if ($enableQueryLog) { DB::connection()->enableQueryLog(); } $this->db = $db; return $db; }
Configure the database and boot Eloquent @param array $configs null @param string $name default @param bool $enableQueryLog true @return mixed
entailment
public function autoRoute($stop = false) { if ($stop) { return $this; } $app = self::getInstance(); $app->get('(/)', 'IndexController:index'); $app->get('/:action', function($action = 'index') use ($app) { if ( !class_exists('IndexController') ) { $app->notFound(); return ; } $this->controllerName = 'index'; $this->actionName = $action; $controller = new \IndexController; if ( !method_exists($controller, $action) ) { $app->notFound(); return ; } $controller->$action(); }); $app->get('/:controller/:action', function($controller = 'index', $action = 'index') use ($app) { $this->controllerName = $controller; $this->actionName = $action; $controller = ucwords($controller) . 'Controller'; if ( !class_exists($controller) ) { $app->notFound(); return ; } $controller = new $controller(); if ( !method_exists($controller, $action) ) { $app->notFound(); return ; } $controller->$action(); }); $app->get('/:module/:controller/:action', function($module, $controller = 'index', $action = 'index') use ($app) { $this->moduleName = $module; $this->controllerName = $controller; $this->actionName = $action; $controller = ucwords($module) . '\Controllers\\' . ucwords($controller) . 'Controller'; if ( !class_exists($controller) ) { $app->notFound(); return ; } $controller = new $controller(); if ( !method_exists($controller, $action) ) { $app->notFound(); return ; } $controller->$action(); }); }
Auto router method @param bool $stop false @return void
entailment
protected function __autoload($className) { // Single modules autoload foreach ($this->config('defaultAutoloads') as $key => $dir) { $fileName = $dir . DIRECTORY_SEPARATOR . $className . '.php'; $fileName = str_replace('\\', DIRECTORY_SEPARATOR, $fileName); if (file_exists($fileName) && !class_exists($className)) { $this->loadFiles[$className] = $fileName; require $fileName; } } // Multi-Modules autoload $modules = array_merge([], $this->config('modules')); foreach ($modules as $key => $module) { $module = ($module == '') ? $module : $module . DIRECTORY_SEPARATOR; foreach ($this->config('mvcDirs') as $k => $mvc) { $phpFile = explode("\\", $className); $phpFile = $phpFile[count($phpFile) - 1]; $fileName = $this->path . str_replace('\\', DIRECTORY_SEPARATOR, strtolower(str_replace($phpFile, '', $className))). $phpFile . '.php'; if (file_exists($fileName) && !class_exists($className)) { $this->loadFiles[$className] = $fileName; require $fileName; } } } // User custom autoloads foreach ($this->config('autoloads') as $key => $dir) { $fileName = realpath($dir) . DIRECTORY_SEPARATOR . $className . '.php'; $fileName = str_replace('\\', DIRECTORY_SEPARATOR, $fileName); if (file_exists($fileName) && !class_exists($className)) { $this->loadFiles[$className] = $fileName; require $fileName; } } }
Autoload callable method @param string $className @return void
entailment
public function timeStart() { $now = explode(" ", microtime()); $this->startTime = $now[1] + $now[0]; return $this->startTime; }
Run time start @return number
entailment
public function timeEnd($decimal = 6) { $now = explode(" ", microtime()); $end = $now[1] + $now[0]; $total = ($end - $this->startTime); return number_format($total, $decimal); }
Run end time @param int $decimal 6 @return number
entailment
public function setCompileDirectory() { $compilePath = $this->getTemplatesDirectory() . DIRECTORY_SEPARATOR . $this->compileDirectoryName . DIRECTORY_SEPARATOR; if (!file_exists($compilePath)) { static::mkdir($compilePath); } $this->compilePath = $compilePath; }
Set/Create template compile directory @return void
entailment
public function setCompileFile($filename) { $filename = (($this->compileFileNameMd5) ? md5(md5($filename)) : $filename); $this->templateCompileFile = $this->compilePath . $filename . $this->compileFileSuffix; }
Set template compile file path @param string $filename @return void
entailment
public function render($template, $data = null) { $this->templateName = $template; $this->templateFile = $this->getTemplatePathname($template); if (!is_file($this->templateFile)) { throw new \RuntimeException("Slimore\\Mvc\\View cannot render `$template` because the template does not exist"); } $this->setCompileDirectory(); $this->setCompileFile($template); ob_start(); $data = array_merge($this->data->all(), (array) $data); $data = array_merge(static::$globals, $data); static::getProperties([ 'data' => $data, 'compileCached' => $this->compileCached, 'templatePath' => $this->getTemplatesDirectory() . DIRECTORY_SEPARATOR, 'compilePath' => $this->compilePath, 'compileFileNameMd5' => $this->compileFileNameMd5, 'compileFileSuffix' => $this->compileFileSuffix ]); extract($data); //echo "this->compileCached =>" . ($this->compileCached ? 'true' : 'false'); if (!$this->compileCached) { $tpl = $this->read($this->templateFile); $tpl = static::parser($tpl); $this->write($this->templateCompileFile, $tpl); } else { if (!file_exists($this->templateCompileFile) || (filemtime($this->templateFile) > filemtime($this->templateCompileFile)) ) { $tpl = $this->read($this->templateFile); $tpl = static::parser($tpl); $this->write($this->templateCompileFile, $tpl); } } require $this->templateCompileFile; echo ob_get_clean(); }
Template render @param string $template @param array $data @return mixed
entailment
public static function mkdir($dir) { if ( file_exists($dir) ) { return $dir; } mkdir($dir, 0777, true); chmod($dir, 0777); return $dir; }
Create template compile directory @param string $dir @return string
entailment
public static function includeFile($file) { $data = static::$properties['data']; $templatePath = static::$properties['templatePath']; $compilePath = static::$properties['compilePath']; $compileCached = static::$properties['compileCached']; $compileFileNameMd5 = static::$properties['compileFileNameMd5']; $compileFileSuffix = static::$properties['compileFileSuffix']; $templateFile = $templatePath . $file; if ( !file_exists($templateFile) ) { throw new \InvalidArgumentException('included template file ' . $file . ' not found.'); } $pathInfo = pathinfo($file); $filename = $pathInfo['filename']; if (!$compileFileNameMd5 && !file_exists($compilePath . $pathInfo['dirname'])) { static::mkdir($compilePath . $pathInfo['dirname']); } $filenameMd5 = (($compileFileNameMd5) ? md5(md5($filename)) : $pathInfo['dirname'] . DIRECTORY_SEPARATOR . $filename); $compileFile = $compilePath . $filenameMd5 . $compileFileSuffix; if ($compileCached) { if (!file_exists($compileFile) || (filemtime($templateFile) > filemtime($compileFile))) { $tpl = file_get_contents($templateFile); $tpl = static::parser($tpl); file_put_contents($compileFile, $tpl); } } else { $tpl = file_get_contents($templateFile); $tpl = static::parser($tpl); file_put_contents($compileFile, $tpl); } return $compileFile; }
Parse & require included template file @param string $file @return string
entailment
public static function parser($tpl) { $viewClass = '\Slimore\Mvc\View::'; // Parse for in $tpl = preg_replace_callback('/\<\!\-\-\s*\{for\s+(\S+)\s+in\s+(\S+)\}\s*\-\-\>/is', function($matchs) { //print_r($matchs); $output = '<?php if (isset(' . $matchs[2] . ') && is_array(' . $matchs[2] . ')) { ?>'; $output .= "\r"; $output .= '<?php foreach (' . $matchs[2] . ' as $key => ' . $matchs[1] . ') { ?>'; $output .= "\r"; return $output; }, $tpl); // Parse foreach $tpl = preg_replace_callback('/\<\!\-\-\s*\{foreach\s+(\S+)\s+(\S+)\s+(\S+)\}\s*\-\-\>/is', function($matchs) { print_r($matchs); $output = '<?php if (isset(' . $matchs[1] . ') && is_array(' . $matchs[1] . ')) { ?>'; $output .= "\r"; $output .= '<?php foreach (' . $matchs[1] . ' as ' . $matchs[2] . ' => ' . $matchs[3] . ') { ?>'; $output .= "\r"; return $output; }, $tpl); $regexs = [ '/\<\!\-\-\s*\{if\s+(\S+)\}\s*\-\-\>/is', '/\<\!\-\-\s*\{elseif\s+(\S+)\}\s*\-\-\>/is', '/\<\!\-\-\s*\{else}\s*\-\-\>/is', '/\<\!\-\-\s*\{\/if}\s*\-\-\>/is', '/\<\!\-\-\s*\{\/for}\s*\-\-\>/is', '/\<\!\-\-\s*\{\/foreach}\s*\-\-\>/is', '/\<\!\-\-\s*\{(.+?)\}\s*\-\-\>/is', '/\{include\s+(.+?)\}/is', '/\{([A-Z][A-Z0-9_]*)\}/s', '/\{(\$[a-zA-Z0-9_\[\]\'\"\$\x7f-\xff]+)\}/is' ]; $replacements = [ '<?php if (\\1) { ?>', '<?php } elseif (\\1) { ?>', '<?php } else { ?>', '<?php } ?>', '<?php } } ?>', '<?php } } ?>', '{\\1}', '<?php include ' . $viewClass . 'includeFile(\\1); ?>', '<?php if ( defined(\'\\1\') ) { echo \\1; } ?>', '<?php if ( isset(\\1) && !is_array(\\1)) { echo \\1; } ?>' ]; $tpl = preg_replace($regexs, $replacements, $tpl); // Parse functions $tpl = preg_replace('/\{(([@&\\\$a-zA-Z0-9_]+)\(([^\}]*)\))?\}/is', '<?php echo \\1; ?>', $tpl); // Parse ternary $tpl = preg_replace_callback('/\{(([^\}]*)\s+\?\s+([^\}]*)\s+:\s+([^\}]*))?\}/is', function($matchs) { //print_r($matchs); $output = '<?php echo ' . $matchs[1] . '; ?>'; return str_replace(';; ?>', '; ?>', $output); }, $tpl); // Parse Objects $tpl = preg_replace_callback('/\{(([\$\\\w+]+)([:-\>]*)([^\}]*))?\}/is', function($matchs) { //print_r($matchs); $output = '<?php echo ' . $matchs[1] . '; ?>'; return str_replace(';; ?>', '; ?>', $output); }, $tpl); // Parse line comment $tpl = preg_replace('/\{(\/\/([^\}]*))?\}/is', '<?php \\1; ?>', $tpl); return $tpl; }
Template parser @param string $tpl @return string
entailment
public function view(UserPolicy $user, Gallery $gallery) { if ($user->canDo('gallery.gallery.view') && $user->isAdmin()) { return true; } return $gallery->user_id == user_id() && $gallery->user_type == user_type(); }
Determine if the given user can view the gallery. @param UserPolicy $user @param Gallery $gallery @return bool
entailment
public function destroy(UserPolicy $user, Gallery $gallery) { return $gallery->user_id == user_id() && $gallery->user_type == user_type(); }
Determine if the given user can delete the given gallery. @param UserPolicy $user @param Gallery $gallery @return bool
entailment
public function renderBody(&$env, $exception) { $title = 'Slimore Application ErrorException'; $code = $exception->getCode(); $message = $exception->getMessage(); $file = $exception->getFile(); $line = $exception->getLine(); $type = get_class($exception); $trace = str_replace(array('#', "\n"), array('<div class="trace-line">#', '</div>'), $exception->getTraceAsString()); $html = html($title, [ '<meta http-equiv="X-UA-Compatible" content="IE=edge" />', '<meta name="renderer" content="webkit" />', '<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no" />', style([ '*{margin:0;padding:0;}', 'html {font-size: 62.5%;}', 'html, body {max-width: 100%;width: 100%;}', 'body {font-size: 1.4rem;font-family: "Microsoft Yahei", Helvetica, Tahoma, STXihei, arial,verdana,sans-serif;background:#fff;color:#555;}', 'img {border: none;}', 'pre, pre code {font-family:Consolas, arial,verdana,sans-serif;}', '#layout {padding: 6rem;}', '#main {margin: 0 auto;line-height: 1.5;}', '#main > h1 {font-size: 10rem;margin-bottom: 1rem;}', '#main > h3 {margin-bottom: 2rem; font-size: 1.8rem;}', '#main > h4 {margin-bottom: 1rem; font-size: 1.8rem;}', '#main pre {margin: 1.5rem 0;white-space: pre-wrap;word-wrap: break-word;}', '#main > p {white-space: pre-wrap;word-wrap: break-word;line-height: 1.3;margin-bottom: 0.6rem;}', '#main > p > strong {width: 7rem;display:inline-block;}', '.logo {text-align: left;border-top:1px solid #eee;margin-top: 5rem;padding: 3rem 0 0;color: #ccc;}', '.logo > h1 {font-weight: normal;font-size: 5rem;}', '.logo img {margin-left: -2rem;}', '.trace-line {padding: 0.3rem 0.6rem;margin-left:-0.6rem;-webkit-transition: background-color 300ms ease-out;transition: background-color 300ms ease-out;}', '.trace-line:hover {background:#fffccc;}' ]) ], [ '<div id="layout">', '<div id="main">', '<h1>:(</h1>', '<h3>' . $type . '</h3>', '<h4>Details :</h4>', '<p><strong>Type: </strong> ' . $type . '</p>', '<p><strong>Message: </strong> ' . $message . '</p>', '<p><strong>File: </strong> ' . $file . '</p>', '<p><strong>Line: </strong> ' . $line . '</p>', '<br/>', '<h4>Trace:</h4>', '<pre>' . $trace . '</pre>', '<div class="logo">', '<h1>Slimore</h1>', '<p>The fully (H)MVC framework, based on the Slim PHP Framwork.</p>', '</div>', '</div>', '</div>' ]); return $html; }
Render response body @param array $env @param \Exception $exception @return string
entailment
public function register() { $this->mergeConfigFrom(__DIR__ . '/../../config/config.php', 'litecms.gallery'); // Bind facade $this->app->bind('litecms.gallery', function ($app) { return $this->app->make('Litecms\Gallery\Gallery'); }); // Bind Gallery to repository $this->app->bind( 'Litecms\Gallery\Interfaces\GalleryRepositoryInterface', \Litecms\Gallery\Repositories\Eloquent\GalleryRepository::class ); $this->app->register(\Litecms\Gallery\Providers\AuthServiceProvider::class); $this->app->register(\Litecms\Gallery\Providers\RouteServiceProvider::class); }
Register the service provider. @return void
entailment
public static function filterPort(?int $port, string $scheme = ''): ?int { if (null === $port) { return null; } $port = (int) $port; if (self::MIN_PORT > $port || self::MAX_PORT < $port) { throw new \InvalidArgumentException( sprintf('Invalid port: %d. Must be between %d and %d', $port, self::MIN_PORT, self::MAX_PORT) ); } if (DefaultPortIdentifier::isDefaultPort($scheme, $port)) { $port = null; } return $port; }
@param int|null $port @param string $scheme @return int|null
entailment
public static function isHttps($trust_proxy_headers = false){ // Verifique o cabeçalho HTTPS padrão if (isset($_SERVER['HTTPS']) && !empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] != 'off') { return isset($_SERVER['HTTPS']) && !empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] != 'off'; } // Verifique os cabeçalhos de proxy, se permitido return $trust_proxy_headers && isset($_SERVER['X-FORWARDED-PROTO']) && $_SERVER['X-FORWARDED-PROTO'] == 'https'; // Padrão para não SSL return false; }
Verifica se a página está sendo servidor por SSL ou não @return boolean
entailment
public static function isNotPubliclyRoutable(UriInterface $url): bool { $host = $url->getHost(); if ('' === $host) { return true; } $hostObject = new Host($host); if (!$hostObject->isPubliclyRoutable()) { return true; } $hostContainsDots = substr_count($host, '.'); if (!$hostContainsDots) { return true; } if ('.' === $host[0] || '.' === $host[-1]) { return true; } return false; }
Can a URL fail to be accessed over the public internet? There are certain cases where we can be certain that a URL cannot be accessed over the public internet: - no host - having a host that is not publicly routable (such as a within a private IP range) - having a hostname lacking dots - having a hostname starting or ending with a dot @param UriInterface $url @return bool @throws InvalidExpressionException
entailment
public function getImageInfo($image) { if ( empty($image) || !file_exists($image)) { throw new \InvalidArgumentException('Image file not found.'); } $pathInfo = pathinfo($image); $info = getimagesize($image); if ( !in_array($pathInfo['extension'], $this->types) ) { throw new \InvalidArgumentException('Unsupported image file extension.'); } $info['width'] = $info[0]; $info['height'] = $info[1]; $info['ext'] = $info['type'] = $pathInfo['extension']; $info['size'] = filesize($image); $info['dir'] = $pathInfo['dirname']; $info['path'] = str_replace('/', DIRECTORY_SEPARATOR, $image); $info['fullname'] = $pathInfo['basename']; $info['filename'] = $pathInfo['filename']; $info['type'] = ($info['type'] == 'jpg') ? 'jpeg' : $info['type']; return $info; }
Get image info array @param string $image @return array
entailment
public function source($src) { $this->source = $this->getImageInfo($src); $type = $this->source['type']; $createFrom = 'ImageCreateFrom' . $type; $this->sourceImage = $createFrom($src); return $this; }
Set local image source @param string $src @return $this
entailment
public function create($width, $height, $type = null) { if ( !is_numeric($width) ) { throw new \InvalidArgumentException('Image create failed, width must be numeric'); } if ( !is_numeric($height) ) { throw new \InvalidArgumentException('Image create failed, height must be numeric'); } $type = $this->getType($type); if ($type !== 'gif' && function_exists('imagecreatetruecolor')) { $newImage = imagecreatetruecolor($width, $height); // Unsupport gif file } else { $newImage = imagecreate($width, $height); } imagealphablending($newImage, true); $transparent = imagecolorallocatealpha($newImage, 255, 255, 255, 0); imagefilledrectangle($newImage, 0, 0, imagesx($newImage), imagesy($newImage), $transparent); imagefill($newImage, 0, 0, $transparent); imagesavealpha($newImage, true); $this->newImage = $newImage; return $this; }
Create new canvas image @param int $width @param int $height @param string $type null @return $this
entailment
public function createFrom($image) { $type = pathinfo($image, PATHINFO_EXTENSION); $type = ($type === 'jpg') ? 'jpeg' : $type; $createFrom = 'ImageCreateFrom' . $type; return $createFrom($image); }
Create image from type @param string $image @return mixed
entailment
public function crop($width, $height, $mode = 'tl') { if ( !is_numeric($width) ) { throw new \InvalidArgumentException('$width must be numeric'); } if ( !is_numeric($height) ) { throw new \InvalidArgumentException('$height must be numeric'); } if ( $this->newImage ) { $this->sourceImage = $this->newImage; } $oldWidth = ($this->newImage) ? imagesx($this->newImage) : $this->source['width']; $oldHeight = ($this->newImage) ? imagesy($this->newImage) : $this->source['height']; $this->create($width, $height); $startX = $startY = 0; $cropWidth = $sourceWidth = $width; $cropHeight = $sourceHeight = $height; if ( is_array($mode) ) { $startX = $mode[0]; $startY = $mode[1]; } if ($mode === self::CROP_TOP_CENTER) { $startX = ($oldWidth - $cropWidth) / 2; } else if ($mode === self::CROP_TOP_RIGHT) { $startX = $oldWidth - $cropWidth; } else if ($mode === self::CROP_CENTER_LEFT) { $startY = ($oldHeight - $cropHeight) / 2; } else if ($mode === self::CROP_CENTER_CENTER) { $startX = ($oldWidth - $cropWidth) / 2; $startY = ($oldHeight - $cropHeight) / 2; } else if ($mode === self::CROP_CENTER_RIGHT) { $startX = $oldWidth - $cropWidth; $startY = ($oldHeight - $cropHeight) / 2; } else if ($mode === self::CROP_BOTTOM_LEFT) { $startY = $oldHeight - $cropHeight; } else if ($mode === self::CROP_BOTTOM_CENTER) { $startX = ($oldWidth - $cropWidth) / 2; $startY = $oldHeight - $cropHeight; } else if ($mode === self::CROP_BOTTOM_RIGHT) { $startX = $oldWidth - $cropWidth; $startY = $oldHeight - $cropHeight; } else { } imagecopyresampled( $this->newImage, $this->sourceImage, 0, 0, $startX, $startY, $cropWidth, $cropHeight, $sourceWidth, $sourceHeight); return $this; }
Crop image file @param int $width @param int $height @param string $mode tl @return $this
entailment
public function thumb($width, $height, $mode = 0, $amplify = false) { if ( !is_numeric($width) ) { throw new \InvalidArgumentException('$width must be numeric'); } if ( !is_numeric($height) ) { throw new \InvalidArgumentException('$height must be numeric'); } if ( $this->newImage ) { $this->sourceImage = $this->newImage; } $oldWidth = ($this->newImage) ? imagesx($this->newImage) : $this->source['width']; $oldHeight = ($this->newImage) ? imagesy($this->newImage) : $this->source['height']; $this->create($width, $height); if ($oldWidth < $width && $oldHeight < $height && !$amplify) { return false; } $thumbWidth = $width; $thumbHeight = $height; $startX = $startY = 0; if ($mode === self::THUMB_EQUAL_RATIO) { $scale = min($width / $oldWidth, $height / $oldHeight); $thumbWidth = (int) ($oldWidth * $scale); $thumbHeight = (int) ($oldHeight * $scale); $sourceWidth = $oldWidth; $sourceHeight = $oldHeight; } else if ($mode === self::THUMB_CENTER_CENTER) { $scale1 = round($width / $height, 2); $scale2 = round($oldWidth / $oldHeight, 2); if ($scale1 > $scale2) { $sourceWidth = $oldWidth; $sourceHeight = round($oldWidth / $scale1, 2); $startY = ($oldHeight - $sourceHeight) / 2; } else { $sourceWidth = round($oldHeight * $scale1, 2); $sourceHeight = $oldHeight; $startX = ($oldWidth - $sourceWidth) / 2; } } else if ($mode === self::THUMB_LEFT_TOP) { $scale1 = round($width / $height, 2); $scale2 = round($oldWidth / $oldHeight, 2); if ($scale1 > $scale2) { $sourceHeight = round($oldWidth / $scale1, 2); $sourceWidth = $oldWidth; } else { $sourceWidth = round($oldHeight * $scale1, 2); $sourceHeight = $oldHeight; } } imagecopyresampled( $this->newImage, $this->sourceImage, 0, 0, $startX, $startY, $thumbWidth, $thumbHeight, $sourceWidth, $sourceHeight); return $this; }
Image thumbnail @param int $width @param int $height @param int $mode 0 @param bool $amplify false @return $this|bool
entailment
public function resize($width, $height, $x = 0, $y = 0) { if ( !$this->newImage ) { $this->create($width, $height); } if ( !is_numeric($width) ) { throw new \InvalidArgumentException('$width must be numeric'); } if ( !is_numeric($height) ) { throw new \InvalidArgumentException('$height must be numeric'); } $type = $this->source['type']; imagecopyresampled( $this->newImage, $this->sourceImage, 0, 0, $x, $y, $width, $height, $this->source['width'], $this->source['height']); return $this; }
Image resize @param int $width @param int $height @param int $x 0 @param int $y 0 @return $this
entailment
public function resizePercent($percent = 50) { if ( $percent < 1) { throw new \InvalidArgumentException('percent must be >= 1'); } $this->resize($this->source['width'] * ($percent / 100), $this->source['height'] * ($percent / 100)); return $this; }
Image resize by percent @param int $percent 50 @return $this
entailment
public function watermark($water, $pos = 0, $tile = false) { $waterInfo = $this->getImageInfo($water); if ( empty($waterInfo['width']) || empty($waterInfo['height']) ) { throw new \InvalidArgumentException('Get watermark file information is failed.'); } $this->waterImage = $this->createFrom($water); if (!$this->newImage || !is_resource($this->newImage)) { $this->newImage = $this->sourceImage; $sourceWidth = $this->source['width']; $sourceHeight = $this->source['height']; } else { $sourceWidth = imagesx($this->newImage); $sourceHeight = imagesy($this->newImage); } $waterWidth = ($waterInfo['width'] > $sourceWidth) ? $sourceWidth : $waterInfo['width']; $waterHeight = ($waterInfo['height'] > $sourceHeight) ? $sourceHeight : $waterInfo['height']; if ($tile) { imagealphablending($this->waterImage, true); imagesettile($this->newImage, $this->waterImage); imagefilledrectangle($this->newImage, 0, 0, $sourceWidth, $sourceHeight, IMG_COLOR_TILED); } else { $position = $this->position($pos, $sourceWidth, $sourceHeight, $waterWidth, $waterHeight); imagecopy($this->newImage, $this->waterImage, $position['x'], $position['y'], 0, 0, $waterWidth, $waterHeight); } return $this; }
Image watermark @param string $water @param int $pos 0 @param bool $tile false @return $this
entailment
public function watermarkText($text, $pos = 0, $fontSize = 14, array $color = null, $font = null, $shadow = true) { if (!$color) { $color = [255, 255, 255, 0, 0, 0]; } $font = (!$font) ? $this->fontFile : $font; if (!$this->newImage || !is_resource($this->newImage)) { $this->newImage = $this->sourceImage; $sourceWidth = $this->source['width']; $sourceHeight = $this->source['height']; } else { $sourceWidth = imagesx($this->newImage); $sourceHeight = imagesy($this->newImage); } $textImage = imagecreatetruecolor($sourceWidth, $sourceHeight); $textColor = imagecolorallocate($textImage, $color[0], $color[1], $color[2]); $shadowColor = imagecolorallocate($textImage, $color[3], $color[4], $color[5]); // get 8 corners coordinates of the text watermark $size = imagettfbbox($fontSize, 0, $font, $text); $textWidth = $size[4]; $textHeight = abs($size[7]); $position = $this->position($pos, $sourceWidth, $sourceHeight, $textWidth + 4, $textHeight, true, $fontSize); $posX = $position['x']; $posY = $position['y']; imagealphablending($textImage, true); imagesavealpha($textImage, true); imagecopymerge($textImage, $this->newImage, 0, 0, 0, 0, $sourceWidth, $sourceHeight, 100); if ($shadow) { imagettftext($textImage, $fontSize, 0, $posX + 1, $posY + 1, $shadowColor, $font, $text); } imagettftext($textImage, $fontSize, 0, $posX, $posY, $textColor, $font, $text); $this->newImage = $textImage; return $this; }
Text watermark for image @param string $text @param int|array $pos 0 @param int $fontSize 14 @param array $color null @param string $font null @param bool $shadow true @return $this
entailment
private function position($pos, $oldWidth, $oldHeight, $waterWidth, $waterHeight, $isText = false, $fontSize = 14) { if ( is_array($pos) ) { return [ 'x' => $pos[0], 'y' => $pos[1] ]; } if ($pos === self::POS_TOP_LEFT) { $posX = 0; $posY = ($isText) ? $waterHeight : 0; } elseif ($pos === self::POS_TOP_CENTER) { $posX = ($oldWidth - $waterWidth) / 2; $posY = ($isText) ? $waterHeight : 0; } elseif ($pos === self::POS_TOP_RIGHT) { $posX = $oldWidth - $waterWidth; $posY = ($isText) ? $waterHeight : 0; } elseif ($pos === self::POS_CENTER_LEFT) { $posX = 0; $posY = ($isText) ? (($oldHeight - $waterHeight) / 2) + $fontSize : ($oldHeight - $waterHeight) / 2; } elseif ($pos === self::POS_CENTER_CENTER) { $posX = ($oldWidth - $waterWidth) / 2; $posY = ($isText) ? (($oldHeight - $waterHeight) / 2) + $fontSize : ($oldHeight - $waterHeight) / 2; } elseif ($pos === self::POS_CENTER_RIGHT) { $posX = $oldWidth - $waterWidth; $posY = ($isText) ? (($oldHeight - $waterHeight) / 2) + $fontSize : ($oldHeight - $waterHeight) / 2; } elseif ($pos === self::POS_BOTTOM_LEFT) { $posX = 0; $posY = ($isText) ? ($oldHeight - $waterHeight) + $fontSize : $oldHeight - $waterHeight; } elseif ($pos === self::POS_BOTTOM_CENTER) { $posX = ($oldWidth - $waterWidth) / 2; $posY = ($isText) ? ($oldHeight - $waterHeight) + $fontSize : $oldHeight - $waterHeight; } elseif ($pos === self::POS_BOTTOM_RIGHT) { $posX = $oldWidth - $waterWidth; $posY = ($isText) ? ($oldHeight - $waterHeight) + $fontSize : $oldHeight - $waterHeight; } else { $posX = rand(0, ($oldWidth - $waterWidth)); $posY = rand(0, ($oldHeight - $waterHeight)); } return [ "x" => $posX, "y" => $posY ]; }
Watermark position @param int|string $pos @param int $oldWidth @param int $oldHeight @param int $waterWidth @param int $waterHeight @param bool $isText @param int $fontSize @return array
entailment
public function setFontFile($fontFile) { if (!file_exists($fontFile)) { throw new \InvalidArgumentException('font file ' .$fontFile . ' not found.'); } $this->fontFile = $fontFile; return $this; }
Set font file (FreeType font) @param string $fontFile @return $this @throws \InvalidArgumentException
entailment
public function display($type = 'jpeg') { $type = $this->getType($type); header('Content-Type: image/' . $type); if ($type === 'jpeg') { imageinterlace($this->newImage, true); } $imageFunc = 'image' . $type; $imageFunc($this->newImage); $this->destroyAll(); return $this; }
Display on browser @param string $type jpeg @return $this
entailment
public function save($saveName, $quality = 80) { $type = $this->getType(pathinfo($saveName, PATHINFO_EXTENSION)); $imageFunc = 'image' . $type; $errorMessage = 'Image saved is failed! Check the directory is can write?'; if ($type === 'jpeg') { imageinterlace($this->newImage, true); if ( !$imageFunc($this->newImage, $saveName, $quality) ) { throw new \ErrorException($errorMessage); } } else { if (!$imageFunc($this->newImage, $saveName)) { throw new \ErrorException($errorMessage); } } $this->destroyAll(); return $this; }
Saved image file @param string $saveName @param int $quality 80 @return $this @throws \ErrorException
entailment
public function dataUrl($type = 'jpeg') { $type = $this->getType($type); $imageFunc = 'image' . $type; ob_start(); $imageFunc($this->newImage); $data = ob_get_contents(); ob_end_clean(); $this->destroyAll(); $dataUrl = 'data:image/'. $type . ';base64,' . base64_encode($data); return $dataUrl; }
Image to data url base64 @param string $type jpeg @return string
entailment
public function destroyAll() { if ($this->newImage) { $this->destroy($this->newImage); } if ($this->sourceImage) { $this->destroy($this->sourceImage); } }
Destroy all image resource @return void
entailment
public static function execute($var, $func){ if(is_array($var)) foreach($var as $index => $value) $var[$index] = self::execute($value, $func); else $var = $func($var); return $var; }
/* EXECUTE
entailment
public static function UrlAmigavel($string){ $table = array('Š'=>'S', 'š'=>'s', 'Đ'=>'Dj', 'đ'=>'dj', 'Ž'=>'Z','ž'=>'z', 'Č'=>'C', 'č'=>'c', 'Ć'=>'C', 'ć'=>'c','À'=>'A', 'Á'=>'A', 'Â'=>'A', 'Ã'=>'A', 'Ä'=>'A','Å'=>'A', 'Æ'=>'A', 'Ç'=>'C', 'È'=>'E', 'É'=>'E','Ê'=>'E', 'Ë'=>'E', 'Ì'=>'I', 'Í'=>'I', 'Î'=>'I','Ï'=>'I', 'Ñ'=>'N', 'Ò'=>'O', 'Ó'=>'O', 'Ô'=>'O','Õ'=>'O', 'Ö'=>'O', 'Ø'=>'O', 'Ù'=>'U', 'Ú'=>'U','Û'=>'U', 'Ü'=>'U', 'Ý'=>'Y', 'Þ'=>'B', 'ß'=>'Ss','à'=>'a', 'á'=>'a', 'â'=>'a', 'ã'=>'a', 'ä'=>'a','å'=>'a', 'æ'=>'a', 'ç'=>'c', 'è'=>'e', 'é'=>'e','ê'=>'e', 'ë'=>'e', 'ì'=>'i', 'í'=>'i', 'î'=>'i','ï'=>'i', 'ð'=>'o', 'ñ'=>'n', 'ò'=>'o', 'ó'=>'o','ô'=>'o', 'õ'=>'o', 'ö'=>'o', 'ø'=>'o', 'ù'=>'u','ú'=>'u', 'û'=>'u', 'ý'=>'y', 'ý'=>'y', 'þ'=>'b','ÿ'=>'y', 'Ŕ'=>'R', 'ŕ'=>'r'); $string = strtr($string, $table); $string = strtolower($string); $string = preg_replace("/[^a-z0-9_\s-]/", "", $string); $string = preg_replace("/[\s-]+/", " ", $string); $string = preg_replace("/[\s_]/", "-", $string); return $string; }
cria url amigavel conforme nome passado
entailment
public static function ShortURL($tamanho=10,$maiusculas=true,$numeros=true){ $lmin = 'abcdefghijklmnopqrstuvwxyz'; $lmai = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'; $num = '1234567890'; $retorno = ''; $caracteres = ''; $caracteres .= $lmin; if($maiusculas) $caracteres.= $lmai; if($numeros) $caracteres.= $num; $len = strlen($caracteres); for($n=1;$n<= $tamanho;$n++){ $rand = mt_rand(1,$len); $retorno .=$caracteres[$rand-1]; } return $retorno; }
cria um código aleatório conforme solicitado via parâmetro
entailment
public static function headerJson($objJson=array()){ if(strpos($_SERVER['SCRIPT_NAME'], 'phpunit')===false){ header('Expires: Fri, 14 Mar 1980 20:53:00 GMT'); header('Last-Modified: '.gmdate('D, d M Y H:i:s').' GMT'); header('Cache-Control: no-cache, must-revalidate'); header('Pragma: no-cache'); header('Content-Type: application/json'); } $a_tmp = array(); foreach ($objJson as $key => $value) { $a_tmp[] = '"'.$key.'":"'.$value.'"'; } return json_decode('{'.implode(',',$a_tmp).'}'); }
/* HEADER AJAX
entailment
public static function CheckEmail($email){ if(preg_match("/^[\-\!\#\$\%\&\'\*\+\.\/0-9\=\?A-Z\^\_\`a-z\{\|\}\~]+\@([\-\!\#\$\%\&\'\*\+\/0-9\=\?A-Z\^\_\`a-z\{\|\}\~]+\.)+[a-zA-Z]{2,6}$/", $email)){ $var=explode("@",$email); $var=array_pop($var); if(checkdnsrr($var,"MX")){return true;}else{return false;} }else{ return false; } }
verifica se o e-mail é válido
entailment