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 ? $defaultMess... | @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... | 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'] = $activit... | @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::straightF... | @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 ha... | @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(functio... | @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) {
... | @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($hig... | @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 ... | @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);
... | @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 c... | @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
... | @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);
$highC... | @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()
->rev... | @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->on... | @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() ... | @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) {
... | @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->dealCommuni... | 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)) {
/... | 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 = $chipP... | 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();
... | 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->collectC... | 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->collec... | 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)->amo... | @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);
}
... | @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($p... | @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($pl... | @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... | 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();
}
... | @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) {
... | {@inheritdoc} | entailment |
public function handle(ServerRequestInterface $request): ResponseInterface
{
/** @var MiddlewareInterface $middleware */
$middleware = $this->getNextMiddleware();
if (!$middleware) {
if ($this->getRoutingResult()->didMatch()) {
throw new WorkflowException('No sui... | @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\ServicesFa... | entailment |
public function handleException(ServerRequestInterface $request): ResponseInterface
{
/** @var MiddlewareInterface $middleware */
$middleware = $this->getExceptionHandlers()->getNextMiddleware();
if (!$middleware) {
throw new WorkflowException(
'No suitable middle... | @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';
}... | 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... | 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 instance... | 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);
});
... | 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... | 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') )
{... | 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) && !clas... | 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 = $compi... | 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 t... | 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'];
... | 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] . '... | 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($exc... | 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 reposito... | 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... | @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';
}
... | 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;
}
$hostContains... | 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... | 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['exten... | 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, he... | 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');
}
... | 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');
... | 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($h... | 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.');
}
... | 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($thi... | 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... | 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->newImag... | 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')
{
... | 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:i... | 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... | 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.= ... | 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 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{re... | verifica se o e-mail é válido | entailment |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.