sentence1 stringlengths 52 3.87M | sentence2 stringlengths 1 47.2k | label stringclasses 1
value |
|---|---|---|
public function send(Nette\Http\IRequest $httpRequest, Nette\Http\IResponse $httpResponse): void
{
/**
* Disable tracy bar
*/
if (class_exists('\Tracy\Debugger') && property_exists('\Tracy\Debugger', 'productionMode')) {
\Tracy\Debugger::$productionMode = TRUE;
}
/**
* Set Content-Type header
*... | Sends response to output.
@param Nette\Http\IRequest $httpRequest
@param Nette\Http\IResponse $httpResponse
@return void | entailment |
protected function doRender(array $options)
{
if (!isset($this->templateEngine)) {
throw new InvalidArgumentException('Missing template engine');
}
if (!isset($this->label)) {
throw new InvalidArgumentException('Missing provider label');
}
if (isset(... | Performs share button rendering.
@param array $options
@return string
@throws \InvalidArgumentException if template engine is not set
@throws \InvalidArgumentException if provider label is not set | entailment |
public static function create($id)
{
$language = GettextLanguage::getById($id);
if ($language === null) {
throw new UserMessageException(t('Unknown locale identifier: %s', $id));
}
$pluralForms = [];
foreach ($language->categories as $category) {
$plur... | Create a new (unsaved and unapproved) Locale instance given its locale ID.
@param string $id
@return static | entailment |
public function handleRequest(RequestInterface $request, callable $next, callable $first)
{
$method = strtoupper($request->getMethod());
// if the request not is cachable, move to $next
if ('GET' !== $method && 'HEAD' !== $method) {
return $next($request);
}
// ... | {@inheritdoc} | entailment |
protected function isCacheable(ResponseInterface $response)
{
if (!in_array($response->getStatusCode(), [200, 203, 300, 301, 302, 404, 410])) {
return false;
}
if (!$this->config['respect_cache_headers']) {
return true;
}
if ($this->getCacheControlDire... | Verify that we can cache this response.
@param ResponseInterface $response
@return bool | entailment |
public function addVisit($type, $count = 1, DateTime $dateTime = null, AddressInterface $ipAddress = null)
{
$count = (int) $count;
if ($count > 0) {
if ($dateTime === null) {
$dateTime = new DateTime();
}
if ($ipAddress === null) {
... | Count a visit for a specified type.
@param string $type The type identifier
@param int $count The number of visits to count [default: 1]
@param DateTime $dateTime The date/time to record [default: now]
@param AddressInterface $ipAddress The IP address to record [default: the current one] | entailment |
public function clearVisits(DateTime $before, $type = null)
{
$query = 'delete from CommunityTranslationIPControl where dateTime < ?';
$params = [$before->format($this->connection->getDatabasePlatform()->getDateTimeFormatString())];
if ($type !== null) {
$query .= ' and type = ?'... | Clear visits older than a specified date/time.
@param DateTime $before
@param string|null $type The type identifier for the visits to be deleted. Set to null to delete logs for all types
@return int Returns the number of deleted records | entailment |
protected function approveTranslation($access, TranslationEntity $translation, UserEntity $user, $packageVersionID)
{
if ($access < Access::ADMIN) {
throw new UserMessageException(t('Access denied'));
}
if ($translation->isCurrent()) {
throw new UserMessageException(t... | @param int $access
@param TranslationEntity $translation
@param UserEntity $user
@param mixed $packageVersionID
@throws UserMessageException
@return \Symfony\Component\HttpFoundation\Response | entailment |
protected function denyTranslation($access, TranslationEntity $translation)
{
if ($access < Access::ADMIN) {
throw new UserMessageException(t('Access denied'));
}
if ($translation->isCurrent()) {
throw new UserMessageException(t('The selected translation is already th... | @param int $access
@param TranslationEntity $translation
@throws UserMessageException
@return \Symfony\Component\HttpFoundation\Response | entailment |
protected function reuseTranslation($access, TranslationEntity $translation, UserEntity $user, $packageVersionID)
{
if ($translation->isCurrent()) {
throw new UserMessageException(t('The selected translation is already the current one'));
}
$translationID = $translation->getID()... | @param int $access
@param TranslationEntity $translation
@param UserEntity $user
@param mixed $packageVersionID
@throws UserMessageException
@return \Symfony\Component\HttpFoundation\Response | entailment |
protected function setTranslationFromEditor($access, LocaleEntity $locale, TranslatableEntity $translatable, UserEntity $user, PackageVersionEntity $packageVersion = null)
{
$translation = null;
$strings = $this->post('translated');
$numStrings = ($translatable->getPlural() === '') ? 1 : $lo... | @param int $access
@param LocaleEntity $locale
@param TranslatableEntity $translatable
@param PackageVersionEntity $packageVersion
@throws UserMessageException
@return \Symfony\Component\HttpFoundation\Response | entailment |
protected function unsetTranslationFromEditor($access, LocaleEntity $locale, TranslatableEntity $translatable)
{
$currentTranslation = $this->app->make(TranslationRepository::class)->findOneBy([
'locale' => $locale,
'translatable' => $translatable,
'current' => true,
... | @param int $access
@param LocaleEntity $locale
@param TranslatableEntity $translatable
@throws UserMessageException
@return \Symfony\Component\HttpFoundation\Response | entailment |
private function convertTranslationToGettext(TranslationEntity $translation, $markAsFuzzy)
{
$translatable = $translation->getTranslatable();
$locale = $translation->getLocale();
$translations = new GettextTranslations();
$translations->setLanguage($locale->getID());
$t = $tr... | @param TranslationEntity $translation
@param bool $markAsFuzzy
@return GettextTranslations | entailment |
private function getPackageSubscription(PackageEntity $package)
{
$em = $this->getEntityManager();
$me = $this->getAccessHelper()->getUserEntity('current');
$repo = $this->app->make(PackageSubscriptionRepository::class);
/* @var PackageSubscriptionRepository $repo */
$ps = $r... | @param PackageEntity $package
@return PackageSubscriptionEntity | entailment |
private function getPackageVersionSubscriptions(PackageEntity $package)
{
$result = [];
$me = $this->getAccessHelper()->getUserEntity('current');
$repo = $this->app->make(PackageVersionSubscriptionRepository::class);
/* @var PackageVersionSubscriptionRepository $repo */
$pvsL... | @param PackageEntity $package
@return PackageVersionSubscriptionEntity[] | entailment |
public static function create($domain, $whois)
{
$tld = substr(strrchr($domain, '.'), 1);
$parserClass = 'Wisdom\\Whois\\Parser\\Tld\\'.ucfirst($tld);
if (!class_exists($parserClass)) {
throw new WhoisParserNotFoundException(sprintf(
'Whois parser for .%s domains ... | Creates whois parser for given domain name.
@param string $domain
@param string $whois
@return Interface | entailment |
public function register()
{
$this->mergeConfigFrom(__DIR__.'/../config/lightspeed-api.php', 'lightspeed-api');
$this->app->singleton(Lightspeed::class, function ($app) {
$config = $app['config']['lightspeed-api'];
return new Lightspeed($config);
});
$this-... | Register the application services. | entailment |
public function purchase(array $parameters = [])
{
if ($this->isOldApi()) {
$requestClass = OldPurchaseRequest::class;
} else {
$requestClass = PurchaseRequest::class;
}
return $this->createRequest($requestClass, $parameters);
} | @param array $parameters
@return \Omnipay\InterKassa\Message\PurchaseRequest|\Omnipay\InterKassa\Message\OldPurchaseRequest | entailment |
public function completePurchase(array $parameters = [])
{
if ($this->isOldApi()) {
$requestClass = OldCompletePurchaseRequest::class;
} else {
$requestClass = CompletePurchaseRequest::class;
}
return $this->createRequest($requestClass, $parameters);
} | @param array $parameters
@return \Omnipay\InterKassa\Message\CompletePurchaseRequest|\Omnipay\InterKassa\Message\OldCompletePurchaseRequest | entailment |
public function findById($id)
{
$id = (int) $id;
if ($id) {
$sql = sprintf("SELECT id, name, created_at FROM {$this->tableName} WHERE id=%d LIMIT 1", $id);
if ($row = $this->adapter->selectRow($sql)) {
return $this->_makeModel($row);
}
}
... | FindByID
@param int $id
@return \Blade\Migrations\Migration|null | entailment |
public function findLast()
{
$sql = sprintf("SELECT id, name, created_at FROM {$this->tableName} ORDER BY id DESC LIMIT 1");
if ($row = $this->adapter->selectRow($sql)) {
return $this->_makeModel($row);
}
return null;
} | FindLast
@return \Blade\Migrations\Migration|null | entailment |
public function all()
{
$sql ="SELECT id, name, created_at FROM {$this->tableName} ORDER BY id DESC";
$data = $this->adapter->selectAll($sql);
$result = [];
foreach ($data as $row) {
$result[] = $this->_makeModel($row);
}
return $result;
} | Получить список всех Миграций
@return Migration[] | entailment |
public function insert(Migration $migration)
{
$sql = sprintf("INSERT INTO {$this->tableName} (name, data) VALUES ('%s', '%s')",
$this->adapter->escape($migration->getName()),
$this->adapter->escape($migration->getSql())
);
$this->getAdapter()->execute($sql);
} | Добавить Миграцию в базу
@param Migration $migration | entailment |
public function delete(Migration $migration)
{
if ($migration->isNew()) {
throw new \InvalidArgumentException(__METHOD__.": Expected NOT NEW migration");
}
$this->adapter->execute(sprintf("DELETE FROM {$this->tableName} WHERE id='%d'", $migration->getId()));
} | Удалить Миграцию из базы
@param Migration $migration | entailment |
public static function getCurrentArch(): string
{
$arch = php_uname('m');
if ($arch === "x86_64") {
$arch = "amd64";
} elseif ($arch === "i386") {
$arch = "386";
} else {
// TODO: Whats here?
printf('ERROR: Unexpected, please contact t... | Returns the architecture of the current machine | entailment |
public static function getBinaryPath(): string
{
$binaryName = Utilities::getReleaseName();
$binaryPath = sprintf('%s/bin/%s', Utilities::getBasePath(), $binaryName);
return $binaryPath;
} | returns the binary name | entailment |
public static function downloadReleaseArchive(string $releaseName, string $version): bool
{
$archiveName = $releaseName . '.tar.gz';
$archivePath = sprintf('%s/%s', Utilities::getBasePath(), $archiveName);
$releaseUrl = sprintf(
'https://github.com/editorconfig-checker/editorconf... | Downloads the release from the release page | entailment |
public static function extractReleaseArchive(string $releaseName): bool
{
return Utilities::decompress($releaseName) && Utilities::unpack($releaseName);
} | decompresses and extracts the release archive | entailment |
public static function decompress(string $releaseName): bool
{
try {
$p = new \PharData(sprintf("%s/%s.tar.gz", Utilities::getBasePath(), $releaseName));
$p->decompress();
} catch (Exception $e) {
printf('ERROR: Can not decompress the archive%s%s', PHP_EOL, $e);
... | decompresses the release archive | entailment |
public static function unpack(string $releaseName): bool
{
try {
$p = new \PharData(sprintf("%s/%s.tar", Utilities::getBasePath(), $releaseName));
$p->extractTo(Utilities::getBasePath());
if (!unlink(sprintf("%s/%s.tar", Utilities::getBasePath(), $releaseName))) {
... | unpacks the release archive | entailment |
public static function constructStringFromArguments(array $arguments): string
{
$result = '';
foreach ($arguments as $argument) {
$result .= ' ' . $argument;
}
return $result;
} | Constructs the arguments the binary needs to be called by
the arguments providedunline | entailment |
public static function cleanup(): void
{
$releaseName = sprintf("%s/%s", Utilities::getBasePath(), Utilities::getReleaseName());
if (is_file($releaseName . '.tar.gz')) {
unlink($releaseName . '.tar.gz');
}
if (is_file($releaseName . '.tar')) {
unlink($release... | Removes all intermediate files | entailment |
public function setTopic($value)
{
$this->assertValidString($value, false);
if ($value === '') {
throw new \InvalidArgumentException('The topic must not be empty.');
}
$this->topic = $value;
} | Sets the topic.
@param string $value
@throws \InvalidArgumentException | entailment |
public function buildUrl($base)
{
$url = $base.$this::getApiName();
$parameters = http_build_query($this->getParams());
if (!empty($parameters)) {
$parameters = preg_replace(
'/%5B(?:[0-9]|[1-9][0-9]+)%5D=/',
'%5B%5D=',
$parameters
... | BuildUrl
@param string $base
@return string | entailment |
public function processParameters()
{
$parameters = $this->getParameters();
$factory = $this->buildFactory();
$parametersType = $this->buildParametersType();
$request = $factory->create($parametersType);
if (!is_null($parameters)) {
$processorFactory = new Paramet... | Fonction de process pour les parametres
@return mixed | entailment |
public function getAttributes()
{
$defaultPrefix = PhoneNumber::config()->get('default_country_code');
$attributes = [
'class' => 'text',
'placeholder' => _t(
__CLASS__ . '.Placeholder',
'Phone number links will be prefixed with +{prefix}... | Return field attributes
@param Null
@return Array | entailment |
public function validate($validator)
{
// Don't validate empty fields
$this->value = trim($this->value);
if (empty($this->value)) {
return true;
}
$phone = PhoneNumber::create()->setValue($this->value);
if (!$phone->Link()) {
$validator->val... | Return validation result
@param Validator $validator
@return Boolean | entailment |
public function setAction($action)
{
if (gettype($action) !== 'string') {
throw new BadParametersException(
sprintf(
' The action type ("%s") must be a string',
gettype($action)
)
);
}
$this->acti... | setAction
Setter pour le nom de l'action
@param string $action
@return \Navitia\Component\Request\CoverageRequest | entailment |
public function matches($filter, $topic)
{
// Created by Steffen (https://github.com/kernelguy)
$tokens = explode('/', $filter);
$parts = [];
for ($i = 0, $count = count($tokens); $i < $count; ++$i) {
$token = $tokens[$i];
switch ($token) {
cas... | Check if the given topic matches the filter.
@param string $filter e.g. A/B/+, A/B/#
@param string $topic e.g. A/B/C, A/B/foo/bar/baz
@return bool true if topic matches the pattern | entailment |
protected function log($message, $context)
{
$logger = $this->getLogger();
if ($logger !== null) {
$logger->error($message, $context);
}
} | Curl operation error logging function
@param string $message
@param array $context | entailment |
private function readRemainingLength(PacketStream $stream)
{
$this->remainingPacketLength = 0;
$multiplier = 1;
do {
$encodedByte = $stream->readByte();
$this->remainingPacketLength += ($encodedByte & 127) * $multiplier;
$multiplier *= 128;
... | Reads the remaining length from the given stream.
@param PacketStream $stream
@throws MalformedPacketException | entailment |
private function writeRemainingLength(PacketStream $stream)
{
$x = $this->remainingPacketLength;
do {
$encodedByte = $x % 128;
$x = (int) ($x / 128);
if ($x > 0) {
$encodedByte |= 128;
}
$stream->writeByte($encodedByte);
... | Writes the remaining length to the given stream.
@param PacketStream $stream | entailment |
protected function assertPacketFlags($value, $fromPacket = true)
{
if ($this->packetFlags !== $value) {
$this->throwException(
sprintf(
'Expected flags %02x but got %02x.',
$value,
$this->packetFlags
),
... | Asserts that the packet flags have a specific value.
@param int $value
@param bool $fromPacket
@throws MalformedPacketException
@throws \InvalidArgumentException | entailment |
protected function assertRemainingPacketLength($value = null, $fromPacket = true)
{
if ($value === null && $this->remainingPacketLength === 0) {
$this->throwException('Expected payload but remaining packet length is zero.', $fromPacket);
}
if ($value !== null && $this->remaining... | Asserts that the remaining length is greater than zero and has a specific value.
@param int|null $value value to test or null if any value greater than zero is valid
@param bool $fromPacket
@throws MalformedPacketException
@throws \InvalidArgumentException | entailment |
protected function assertValidStringLength($value, $fromPacket = true)
{
if (strlen($value) > 0xFFFF) {
$this->throwException(
sprintf(
'The string "%s" is longer than 65535 byte.',
substr($value, 0, 50)
),
$... | Asserts that the given string is a well-formed MQTT string.
@param string $value
@param bool $fromPacket
@throws MalformedPacketException
@throws \InvalidArgumentException | entailment |
protected function assertValidString($value, $fromPacket = true)
{
$this->assertValidStringLength($value, $fromPacket);
if (!mb_check_encoding($value, 'UTF-8')) {
$this->throwException(
sprintf(
'The string "%s" is not well-formed UTF-8.',
... | Asserts that the given string is a well-formed MQTT string.
@param string $value
@param bool $fromPacket
@throws MalformedPacketException
@throws \InvalidArgumentException | entailment |
protected function assertValidQosLevel($level, $fromPacket = true)
{
if ($level < 0 || $level > 2) {
$this->throwException(
sprintf(
'Expected a quality of service level between 0 and 2 but got %d.',
$level
),
... | Asserts that the given quality of service level is valid.
@param int $level
@param bool $fromPacket
@throws MalformedPacketException
@throws \InvalidArgumentException | entailment |
public function up(Migration $migration)
{
if (!$migration->isNew()) {
throw new \InvalidArgumentException(__METHOD__.": Expected NEW migration");
}
// Загрузить SQL
$this->fileRepository->loadSql($migration);
$func = function () use ($migration) {
$... | UP
@param Migration $migration
@throws \Exception | entailment |
public function down(Migration $migration, $loadFromFile = false)
{
if ($loadFromFile) {
$this->fileRepository->loadSql($migration);
} else {
$this->dbRepository->loadSql($migration);
}
$func = function () use ($migration) {
$this->_processMigrati... | DOWN
@param Migration $migration
@param bool $loadFromFile | entailment |
private function _processMigration(Migration $migration, callable $command)
{
if ($migration->isTransaction()) {
$this->getDbRepository()->getAdapter()->transaction($command);
} else {
if ($this->logger) {
$this->logger->alert('NO TRANSACTION!');
}... | Выполнить миграцию
@param Migration $migration
@param callable $command
@throws \Exception | entailment |
private function _processMigrationSql(array $sqlList)
{
foreach ($sqlList as $sql) {
if ($this->logger) {
$this->logger->info($sql.PHP_EOL);
}
$this->getDbRepository()->getAdapter()->execute($sql);
}
} | Выполнить полученный SQL
@param array $sqlList | entailment |
public static function run(array $arguments): int
{
$releaseName = Utilities::getReleaseName();
$binaryPath = Utilities::getBinaryPath();
if (!is_file($binaryPath)) {
Utilities::cleanup();
if (!Utilities::downloadReleaseArchive($releaseName, CORE_VERSION)) {
... | Entry point of this class to invoke all needed steps | entailment |
protected function applyCasts(bool $scalarOnly = false): void
{
// @codeCoverageIgnoreStart
if ( ! $scalarOnly) {
foreach (array_keys($this->casts()) as $key) {
$this->applyCast($key);
}
return;
}
// @codeCoverageIgnoreEnd
... | Applies casts to currently set attributes.
This updates the values stored for the attributes with a cast type.
@param bool $scalarOnly | entailment |
protected function applyCast(string $key): void
{
$casts = $this->casts();
if ( ! count($casts) || ! array_key_exists($key, $casts)) {
return;
}
if ( ! isset($this->attributes[ $key ])) {
$value = null;
} else {
$value = $this->attributes... | Applies cast for a given attribute key.
@param string $key | entailment |
protected function makeNestedDataObject(string $class, $data, $key): DataObjectInterface
{
$data = ($data instanceof Arrayable) ? $data->toArray() : $data;
if ( ! is_array($data)) {
throw new UnexpectedValueException(
"Cannot instantiate data object '{$class}' with non-... | Makes a new nested data object for a given class and data.
@param string $class
@param mixed $data
@param string $key
@return DataObjectInterface | entailment |
public function getNextValue(string $sequenceName): int
{
$sequenceValue = $this->rawCollection()->findOneAndUpdate(
['_id' => $sequenceName],
['$inc' => ['seq' => 1]],
['upsert' => true]
);
if ($sequenceValue) {
$_id = $sequenceValue->seq + 1... | Get next value for the sequence.
@param string $sequenceName sequence identifier string
@return int | entailment |
public function reduce( $degree, $lookAhead=null )
{
if ($lookAhead) {
$this->lookAhead = (int)$lookAhead;
}
$epsilon = deg2rad($degree);
$results = array();
for ($i = 0; $i < $this->count(); $i++) {
$j = min($i + $this->lookAhead, $this->lastKey());
... | Reduce points with modified version of Zhao-Saalfeld simplification.
@param double $degree Angle between 0 & 360 to compare points.
@param integer $lookAhead Number of points to include in each sector
bound iteration.
@return array Reduced set of points | entailment |
private function _theta(PointInterface $a, PointInterface $b)
{
list($x1, $y1) = $a->getCoordinates();
list($x2, $y2) = $b->getCoordinates();
return atan2($y2-$y1, $x2 - $x1) + 2 * M_PI;
} | Calculate the angle, and add 2pi to protect against underflow.
@param PointInterface $a Base coordinate point.
@param PointInterface $b Subject coordinate point.
@return double None negative radian. | entailment |
public function register(EventDispatcher $dispatcher) : void
{
$dispatcher->addListener(ControllerReadyEvent::class, function(ControllerReadyEvent $event) {
$event->addParameters($this->getParameters($event));
});
} | {@inheritdoc} | entailment |
private function getParameters(ControllerReadyEvent $event) : array
{
$controller = $event->getRouteMatch()->getControllerReflection();
$currentParameters = $event->getParameters();
$newParameters = [];
foreach ($controller->getParameters() as $parameter) {
$name = $par... | @param ControllerReadyEvent $event
@return array The value to assign to the function parameter.
@throws HttpException If the object cannot be instantiated. | entailment |
private function getParameterValue(\ReflectionParameter $parameter, $value)
{
$class = $parameter->getClass();
if ($class) {
$className = $class->getName();
if ($parameter->isVariadic()) {
$result = [];
foreach ($value as $subValue) {
... | @param \ReflectionParameter $parameter
@param mixed $value
@return mixed
@throws HttpException If the object cannot be instantiated. | entailment |
private function getObject(string $className, $value)
{
$packedObject = new PackedObject($className, $value);
try {
$object = $this->objectPacker->unpack($packedObject);
}
catch (ObjectNotConvertibleException $e) {
throw new HttpBadRequestException($e->getMes... | @param string $className The resulting object class name.
@param mixed $value The raw parameter value to convert to an object.
@return object
@throws HttpException If the object cannot be instantiated. | entailment |
public function findOrCreateState($name)
{
if (!$this->stateCollection->hasState($name)) {
if ($this->stateCollection instanceof StateCollection) {
$this->stateCollection->addState($this->createState($name));
} else {
throw new \InvalidArgumentExceptio... | @param $name
@return \MetaborStd\Statemachine\StateInterface
@throws \Exception | entailment |
protected function findTransition(StateInterface $sourceState, StateInterface $targetState, $eventName = null, ConditionInterface $condition = null)
{
$conditionName = $condition ? $condition->getName() : null;
/* @var $transition TransitionInterface */
foreach ($sourceState->getTransitions(... | @param StateInterface $sourceState
@param StateInterface $targetState
@param string $eventName
@param ConditionInterface $condition
@return TransitionInterface | entailment |
protected function addTransition(StateInterface $sourceState, TransitionInterface $sourceTransition)
{
if ($sourceState instanceof State) {
$sourceState->addTransition($sourceTransition);
} else {
throw new \InvalidArgumentException('Overwrite this method to implement a diffe... | @param StateInterface $sourceState
@param TransitionInterface $sourceTransition
@throws \InvalidArgumentException | entailment |
public function createTransition(StateInterface $sourceState, StateInterface $targetState, $eventName = null, ConditionInterface $condition = null)
{
return new Transition($targetState, $eventName, $condition);
} | @param StateInterface $sourceState
@param StateInterface $targetState
@param string $eventName
@param ConditionInterface $condition
@return TransitionInterface | entailment |
public function findOrCreateTransition($sourceStateName, $targetStateName, $eventName = null, ConditionInterface $condition = null)
{
$sourceState = $this->findOrCreateState($sourceStateName);
$targetState = $this->findOrCreateState($targetStateName);
$transition = $this->findTransition($sou... | @param string $sourceStateName
@param string $targetStateName
@param string $eventName
@param ConditionInterface $condition
@return TransitionInterface | entailment |
public function createEvent(StateInterface $sourceState, $eventName)
{
if ($sourceState instanceof State) {
return $sourceState->getEvent($eventName);
} else {
throw new \InvalidArgumentException('Overwrite this method to implement a different type!');
}
} | @param StateInterface $sourceState
@param string $eventName
@return EventInterface | entailment |
public function addCommand($sourceStateName, $eventName, \SplObserver $command)
{
$this->findOrCreateEvent($sourceStateName, $eventName)->attach($command);
} | If there is no Transition from the SourceState with this Event use addCommandAndSelfTransition().
@param $sourceStateName
@param string $eventName
@param \SplObserver $command | entailment |
public function getData()
{
$migrations = $this->migrator->status();
if (!$migrations) {
return [];
}
$data = [];
$newMigrations = [];
foreach ($migrations as $migration) {
$name = $migration->getName();
if ($migration->isNew()) {... | Run | entailment |
public function read($count)
{
$contentLength = strlen($this->data);
if ($this->position > $contentLength || $count > $contentLength - $this->position) {
throw new EndOfStreamException(
sprintf(
'End of stream reached when trying to read %d bytes. cont... | Returns the desired number of bytes.
@param int $count
@throws EndOfStreamException
@return string | entailment |
public function writeWord($value)
{
$this->write(chr(($value & 0xFFFF) >> 8));
$this->write(chr($value & 0xFF));
} | Appends a single word.
@param int $value | entailment |
public function cut()
{
$this->data = substr($this->data, $this->position);
if ($this->data === false) {
$this->data = '';
}
$this->position = 0;
} | Removes all bytes from the beginning to the current position. | entailment |
public static function where(
array $query = [],
array $projection = [],
bool $useCache = false
) {
return self::getDataMapperInstance()->where(
$query,
$projection,
$useCache
);
} | Gets a cursor of this kind of entities that matches the query from the
database.
@param array $query mongoDB selection criteria
@param array $projection fields to project in Mongo query
@param bool $useCache retrieves a CacheableCursor instead
@return \Mongolid\Cursor\Cursor | entailment |
public static function first(
$query = [],
array $projection = [],
bool $useCache = false
) {
return self::getDataMapperInstance()->first(
$query,
$projection,
$useCache
);
} | Gets the first entity of this kind that matches the query.
@param mixed $query mongoDB selection criteria
@param array $projection fields to project in Mongo query
@param bool $useCache retrieves the entity through a CacheableCursor
@return ActiveRecord | entailment |
public static function firstOrFail(
$query = [],
array $projection = [],
bool $useCache = false
) {
return self::getDataMapperInstance()->firstOrFail(
$query,
$projection,
$useCache
);
} | Gets the first entity of this kind that matches the query. If no
document was found, throws ModelNotFoundException.
@param mixed $query mongoDB selection criteria
@param array $projection fields to project in Mongo query
@param bool $useCache retrieves the entity through a CacheableCursor
@throws ModelNotFoun... | entailment |
public static function firstOrNew($id)
{
if ($entity = self::getDataMapperInstance()->first($id)) {
return $entity;
}
$entity = new static();
$entity->_id = $id;
return $entity;
} | Gets the first entity of this kind that matches the query. If no
document was found, a new entity will be returned with the
_if field filled.
@param mixed $id document id
@return ActiveRecord | entailment |
public function getDataMapper()
{
$dataMapper = Ioc::make(DataMapper::class);
$dataMapper->setSchema($this->getSchema());
return $dataMapper;
} | Returns a DataMapper configured with the Schema and collection described
in this entity.
@return DataMapper | entailment |
public function getSchema(): Schema
{
if ($schema = $this->instantiateSchemaInFields()) {
return $schema;
}
$schema = new DynamicSchema();
$schema->entityClass = get_class($this);
$schema->fields = $this->fields;
$schema->dynamic = $this->dynamic;
... | {@inheritdoc} | entailment |
protected function instantiateSchemaInFields()
{
if (is_string($this->fields)) {
if (is_subclass_of($instance = Ioc::make($this->fields), Schema::class)) {
return $instance;
}
}
} | Will check if the current value of $fields property is the name of a
Schema class and instantiate it if possible.
@return Schema|null | entailment |
protected function execute(string $action)
{
if (!$this->getCollectionName()) {
return false;
}
$options = [
'writeConcern' => new WriteConcern($this->getWriteConcern()),
];
if ($result = $this->getDataMapper()->$action($this, $options)) {
... | Performs the given action into database.
@param string $action datamapper function to execute
@return bool | entailment |
private static function getDataMapperInstance()
{
$instance = Ioc::make(get_called_class());
if (!$instance->getCollectionName()) {
throw new NoCollectionNameException();
}
return $instance->getDataMapper();
} | Returns the a valid instance from Ioc.
@throws NoCollectionNameException throws exception when has no collection filled
@return mixed | entailment |
public function loadConfiguration(): void
{
$builder = $this->getContainerBuilder();
$builder->addDefinition($this->prefix('factory'))
->setImplement(IStandaloneFormFactory::class);
} | Register services | entailment |
public function run(callable $confirmationCallback = null, $migrationName = null)
{
if ($this->logger) {
$this->service->setLogger($this->logger);
}
// Выбранную миграцию
if ($migrationName) {
if (strpos($migrationName, DIRECTORY_SEPARATOR) !== false) {
... | Run
@param callable|null $confirmationCallback - Спросить подтверждение у пользователя перед запуском каждой миграции
функция должна вернуть true/false
принимает $migrationTitle
@param string $migrationName - Название миграции которую надо явно запустить | entailment |
public function register(EventDispatcher $dispatcher) : void
{
$dispatcher->addListener(IncomingRequestEvent::class, function(IncomingRequestEvent $event) {
$this->session->handleRequest($event->getRequest());
});
$dispatcher->addListener(ResponseReceivedEvent::class, function(R... | {@inheritdoc} | entailment |
protected function succeed($result = null)
{
$this->isFinished = true;
$this->isSuccess = true;
$this->result = $result;
} | Marks the flow as successful and sets the result.
@param mixed|null $result | entailment |
protected function fail($error = '')
{
$this->isFinished = true;
$this->isSuccess = false;
$this->error = $error;
} | Marks the flow as failed and sets the error message.
@param string $error | entailment |
public static function isObjectId($value)
{
if (is_object($value) && method_exists($value, '__toString')) {
$value = (string) $value;
}
return is_string($value) && 24 == strlen($value) && ctype_xdigit($value);
} | Checks if the given value can be a valid ObjectId.
@param mixed $value string to be evaluated if it can be used as a valid ObjectID
@return bool true if is valid | entailment |
public function compile(array $classNames) : array
{
$result = [];
foreach ($classNames as $className) {
$reflectionClass = new \ReflectionClass($className);
$prefixPath = '';
$prefixRegexp = '';
$classParameterNames = [];
foreach ($this... | @param string[] $classNames An array of controller class names to get routes from.
@return array
@throws \LogicException | entailment |
public function processAnnotation(Route $annotation) : array
{
$parameterNames = [];
$regexp = preg_replace_callback('/\{([^\}]+)\}|(.+?)/', function(array $matches) use ($annotation, & $parameterNames) : string {
if (isset($matches[2])) {
return preg_quote($matches[2], ... | @todo 0.4.0 make private
Creates a path regular expression and infer the parameter names from a Route annotation.
@param Route $annotation The annotation to process.
@return array The path regexp, and the parameter names.
@throws \LogicException | entailment |
protected function getScriptPath() : string
{
$class = new \ReflectionClass($this->getClassName());
$path = $class->getFileName();
$path = preg_replace('/\.php$/', '.phtml', $path, -1, $count);
if ($count !== 1) {
throw new \RuntimeException('The class filename does not ... | Returns the view script path.
Defaults to the class file path, with a .phtml extension, but can be overridden by child classes.
@return string
@throws \RuntimeException | entailment |
public function all()
{
$finder = new \Symfony\Component\Finder\Finder;
$finder->files()->in($this->dir)->sortByName();
$found = [];
foreach ($finder as $file) {
$found[$file->getBasename()] = $file->getPath();
}
return $found;
} | Получить список всех Миграций
@return array - FILE => PATH | entailment |
public function insert(Migration $migration)
{
$fileName = $this->_getFileName($migration);
if (is_file($fileName)) {
throw new \InvalidArgumentException(__METHOD__.": Migration file `{$migration->getName()}` exists");
}
file_put_contents($fileName, $migration->getSql())... | Добавить Миграцию в файл
@param Migration $migration | entailment |
public function loadSql(Migration $migration)
{
$fileName = $this->_getFileName($migration);
if (!is_file($fileName)) {
throw new \InvalidArgumentException(__METHOD__.": migration file `{$migration->getName()}` not found in dir `{$this->dir}`");
}
$migration->setSql(file_... | Загрузить SQL
@param Migration $migration | entailment |
protected function printFormNew(){
$str = parent::printFormNew();
$str .=
"<div class=\"row\">\n".
"<div class=\"col-md-12\">\n".
"<h3>Step1: get table data</h3>\n".
"<span class=\"glyphicon glyphicon-open pull-right icon-medium\" style=\"top:-38px;\"></span>\n".
Form::open(array( 'url' => $this... | Return the form that needs to be processed | entailment |
public function processForm(array $input = null, $validator = null)
{
if($input)
{
$this->form_input = $input;
}
else
{
$this->fillFormInput();
}
$validator = ($validator) ? $validator : new ValidatorFormInputModel($this);
if ( $validator->validateInput() )
{
try
{
$table_preview = ... | Process the form
@return Boolean $is_executed if the state is executed successfully | entailment |
protected function getTableValuesSelect($dbm = null)
{
$dbm = $dbm ? $dbm : new DBM;
$table_raw = $dbm->getTableList();
return $table_raw ? array_combine(array_values($table_raw), array_values($table_raw) ) : false;
} | Return value with table names for a select
@return Array | entailment |
protected function getDataTable()
{
$data = $this->getTableData();
$header = $this->getTableHeader();
$table = new Table();
// set the configuration
$table->setConfig(array(
"table-hover"=>true,
"table-condensed"=>false,
"table-responsive" => true,
"table-striped" => true,
));
// set hea... | Return the table for the preview
@return String $table | entailment |
protected function getTableData()
{
$data = array();
$form_input = $this->getFormInput();
if( $form_input['table_name'] && $form_input['max_rows'] )
{
$connection_name = Config::get('laravel-import-export::baseconf.connection_name');
$temp_data = DB::connection($connection_name)
->table($this->form_... | Get the data from the db for the preview
@throws BadMethodCallException
@throws NoDataException
@return Array $data | entailment |
protected function getTableHeader($dbm = null)
{
$dbm = $dbm ? $dbm : new DBM;
$columns = array();
$form_input = $this->getFormInput();
if( $form_input['table_name'] )
{
$dbal_columns = $dbm->getTableColumns($this->form_input['table_name']);
foreach($dbal_columns as $column)
{
$array_columns = ... | Get the header for the preview
@throws BadMethodCallException
@return Array $columns | entailment |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.