sentence1
stringlengths 52
3.87M
| sentence2
stringlengths 1
47.2k
| label
stringclasses 1
value |
---|---|---|
public function getFileDetail(LibraryType $library, string $remoteFilePath): DirectoryItem
{
$url = $this->client->getConfig('base_uri')
. '/repos/'
. $library->id
. '/file/detail/'
. '?p=' . $this->urlEncodePath($remoteFilePath);
$response = $this->client->request('GET', $url);
$json = json_decode((string)$response->getBody());
return (new DirectoryItem)->fromJson($json);
}
|
Get file detail
@param LibraryType $library Library instance
@param string $remoteFilePath Remote file path
@return DirectoryItem
@throws \GuzzleHttp\Exception\GuzzleException
@throws Exception
|
entailment
|
public function remove(LibraryType $library, string $filePath): bool
{
// do not allow empty paths
if (empty($filePath)) {
return false;
}
$uri = sprintf(
'%s/repos/%s/file/?p=%s',
$this->clipUri($this->client->getConfig('base_uri')),
$library->id,
$this->urlEncodePath($filePath)
);
$response = $this->client->request(
'DELETE',
$uri,
[
'headers' => ['Accept' => 'application/json'],
]
);
return $response->getStatusCode() === 200;
}
|
Remove a file
@param LibraryType $library Library object
@param string $filePath File path
@return bool
@throws \GuzzleHttp\Exception\GuzzleException
|
entailment
|
public function rename(LibraryType $library, DirectoryItem $dirItem, string $newFilename): bool
{
$filePath = $dirItem->dir . $dirItem->name;
if (empty($filePath)) {
throw new \InvalidArgumentException('Invalid file path: must not be empty');
}
if (empty($newFilename) || strpos($newFilename, '/') === 0) {
throw new \InvalidArgumentException('Invalid new file name: length must be >0 and must not start with /');
}
$uri = sprintf(
'%s/repos/%s/file/?p=%s',
$this->clipUri($this->client->getConfig('base_uri')),
$library->id,
$this->urlEncodePath($filePath)
);
$response = $this->client->request(
'POST',
$uri,
[
'headers' => ['Accept' => 'application/json'],
'multipart' => [
[
'name' => 'operation',
'contents' => 'rename',
],
[
'name' => 'newname',
'contents' => $newFilename,
],
],
]
);
$success = $response->getStatusCode() === 200;
if ($success) {
$dirItem->name = $newFilename;
}
return $success;
}
|
Rename a file
@param LibraryType $library Library object
@param DirectoryItem $dirItem Directory item to rename
@param string $newFilename New file name
@return bool
@throws \GuzzleHttp\Exception\GuzzleException
|
entailment
|
public function copy(
LibraryType $srcLibrary,
string $srcFilePath,
LibraryType $dstLibrary,
string $dstDirectoryPath,
int $operation = self::OPERATION_COPY
): bool {
// do not allow empty paths
if (empty($srcFilePath) || empty($dstDirectoryPath)) {
return false;
}
$operationMode = 'copy';
$returnCode = 200;
if ($operation === self::OPERATION_MOVE) {
$operationMode = 'move';
$returnCode = 301;
}
$uri = sprintf(
'%s/repos/%s/file/?p=%s',
$this->clipUri($this->client->getConfig('base_uri')),
$srcLibrary->id,
$this->urlEncodePath($srcFilePath)
);
$response = $this->client->request(
'POST',
$uri,
[
'headers' => ['Accept' => 'application/json'],
'multipart' => [
[
'name' => 'operation',
'contents' => $operationMode,
],
[
'name' => 'dst_repo',
'contents' => $dstLibrary->id,
],
[
'name' => 'dst_dir',
'contents' => $dstDirectoryPath,
],
],
]
);
return $response->getStatusCode() === $returnCode;
}
|
Copy a file
@param LibraryType $srcLibrary Source library object
@param string $srcFilePath Source file path
@param LibraryType $dstLibrary Destination library object
@param string $dstDirectoryPath Destination directory path
@param int $operation Operation mode
@return bool
@throws \GuzzleHttp\Exception\GuzzleException
|
entailment
|
public function getFileRevisionDownloadUrl(
LibraryType $library,
DirectoryItem $dirItem,
FileHistoryItem $fileHistoryItem
) {
$url = $this->client->getConfig('base_uri')
. '/repos/'
. $library->id
. '/file/revision/'
. '?p=' . $this->urlEncodePath($dirItem->path . $dirItem->name)
. '&commit_id=' . $fileHistoryItem->id;
$response = $this->client->request('GET', $url);
return preg_replace("/\"/", '', (string)$response->getBody());
}
|
Get file revision download URL
@param LibraryType $library Source library object
@param DirectoryItem $dirItem Item instance
@param FileHistoryItem $fileHistoryItem FileHistory item instance
@return Response
@throws \GuzzleHttp\Exception\GuzzleException
|
entailment
|
public function downloadRevision(
LibraryType $library,
DirectoryItem $dirItem,
FileHistoryItem $fileHistoryItem,
string $localFilePath
): Response {
$downloadUrl = $this->getFileRevisionDownloadUrl($library, $dirItem, $fileHistoryItem);
return $this->client->request('GET', $downloadUrl, ['save_to' => $localFilePath]);
}
|
Download file revision
@param LibraryType $library Source library object
@param DirectoryItem $dirItem Item instance
@param FileHistoryItem $fileHistoryItem FileHistory item instance
@param string $localFilePath Save file to path. Existing files will be overwritten without warning
@return Response
@throws \GuzzleHttp\Exception\GuzzleException
|
entailment
|
public function getHistory(LibraryType $library, DirectoryItem $item)
{
$url = $this->client->getConfig('base_uri')
. '/repos/'
. $library->id
. '/file/history/'
. '?p=' . $this->urlEncodePath($item->path . $item->name);
$response = $this->client->request('GET', $url);
$json = json_decode($response->getBody());
$fileHistoryCollection = [];
foreach ($json->commits as $lib) {
$fileHistoryCollection[] = (new FileHistoryItem)->fromJson($lib);
}
return $fileHistoryCollection;
}
|
Get history of a file DirectoryItem
@param LibraryType $library Library instance
@param DirectoryItem $item Item instance
@return FileHistoryItem[]
@throws \GuzzleHttp\Exception\GuzzleException
@throws Exception
|
entailment
|
public function create(LibraryType $library, DirectoryItem $item): bool
{
// do not allow empty paths
if (empty($item->path) || empty($item->name)) {
return false;
}
$uri = sprintf(
'%s/repos/%s/file/?p=%s',
$this->clipUri($this->client->getConfig('base_uri')),
$library->id,
$this->urlEncodePath($item->path . $item->name)
);
$response = $this->client->request(
'POST',
$uri,
[
'headers' => ['Accept' => 'application/json'],
'multipart' => [
[
'name' => 'operation',
'contents' => 'create',
],
],
]
);
return $response->getStatusCode() === 201;
}
|
Create empty file on Seafile server
@param LibraryType $library Library instance
@param DirectoryItem $item Item instance
@return bool
@throws \GuzzleHttp\Exception\GuzzleException
|
entailment
|
public function fromArray(array $fromArray): DirectoryItem
{
$typeExists = array_key_exists('type', $fromArray);
$dirExists = array_key_exists('dir', $fromArray);
if ($typeExists === false && $dirExists === true && is_bool($fromArray['dir'])) {
$fromArray['type'] = $fromArray['dir'] === true ? self::TYPE_DIR : self::TYPE_FILE;
}
/**
* @var self $dirItem
*/
$dirItem = parent::fromArray($fromArray);
return $dirItem;
}
|
Populate from array
@param array $fromArray Create from array
@return DirectoryItem
@throws \Exception
|
entailment
|
public function getCurrentUser($getName = false)
{
if ($getName) {
return $this->userDiscriminator->getCurrentUser();
}
return $this->userDiscriminator->getCurrentUserConfig();
}
|
@param bool $getName
@return \Rollerworks\Bundle\MultiUserBundle\Model\UserConfig|string|null
|
entailment
|
public function buildMediaInfoCommandRunner($filePath, array $configuration = [])
{
if (filter_var($filePath, FILTER_VALIDATE_URL) === false) {
$fileSystem = new Filesystem();
if (!$fileSystem->exists($filePath)) {
throw new \Exception(sprintf('File "%s" does not exist', $filePath));
}
if (is_dir($filePath)) {
throw new \Exception(sprintf(
'Expected a filename, got "%s", which is a directory',
$filePath
));
}
}
$configuration = $configuration + [
'command' => null,
'use_oldxml_mediainfo_output_format' => false,
];
return new MediaInfoCommandRunner(
$filePath,
$configuration['command'],
null,
null,
$configuration['use_oldxml_mediainfo_output_format']
);
}
|
@param string $filePath
@param array $configuration
@throws \Exception
@return MediaInfoCommandRunner
|
entailment
|
public function generate($name, $parameters = array(), $referenceType = self::ABSOLUTE_PATH)
{
if (substr($name, 0, $this->prefixLen) === $this->prefix) {
$name = $this->userDiscriminator->getCurrentUserConfig()->getRoutePrefix().substr($name, $this->prefixLen);
}
return $this->generator->generate($name, $parameters, $referenceType);
}
|
{@inheritdoc}
|
entailment
|
public function create($rateMode)
{
$rateMode = (array) $rateMode;
if (!isset($rateMode[1])) {
$rateMode[1] = $rateMode[0];
}
return new Mode($rateMode[0], $rateMode[1]);
}
|
@param array|string $rateMode
@return Mode
|
entailment
|
public function getInfo($filePath, $ignoreUnknownTrackTypes = false)
{
$mediaInfoCommandBuilder = new MediaInfoCommandBuilder();
$output = $mediaInfoCommandBuilder->buildMediaInfoCommandRunner($filePath, $this->configuration)->run();
$mediaInfoOutputParser = new MediaInfoOutputParser();
$mediaInfoOutputParser->parse($output);
return $mediaInfoOutputParser->getMediaInfoContainer($ignoreUnknownTrackTypes);
}
|
@param $filePath
@param bool $ignoreUnknownTrackTypes Optional parameter used to skip unknown track types by passing true. The
default behavior (false) is throw an exception on unknown track types.
@throws \Mhor\MediaInfo\Exception\UnknownTrackTypeException
@return MediaInfoContainer
|
entailment
|
public function getInfoStartAsync($filePath)
{
$mediaInfoCommandBuilder = new MediaInfoCommandBuilder();
$this->mediaInfoCommandRunnerAsync = $mediaInfoCommandBuilder->buildMediaInfoCommandRunner(
$filePath,
$this->configuration
);
$this->mediaInfoCommandRunnerAsync->start();
}
|
Call to start asynchronous process.
Make call to MediaInfo::getInfoWaitAsync() afterwards to received MediaInfoContainer object.
@param $filePath
|
entailment
|
public function getInfoWaitAsync($ignoreUnknownTrackTypes = false)
{
if ($this->mediaInfoCommandRunnerAsync == null) {
throw new \Exception('You must run `getInfoStartAsync` before running `getInfoWaitAsync`');
}
// blocks here until process is complete
$output = $this->mediaInfoCommandRunnerAsync->wait();
$mediaInfoOutputParser = new MediaInfoOutputParser();
$mediaInfoOutputParser->parse($output);
return $mediaInfoOutputParser->getMediaInfoContainer($ignoreUnknownTrackTypes);
}
|
@param bool $ignoreUnknownTrackTypes Optional parameter used to skip unknown track types by passing true. The
default behavior (false) is throw an exception on unknown track types.
@throws \Exception If this function is called before getInfoStartAsync()
@throws \Mhor\MediaInfo\Exception\UnknownTrackTypeException
@return MediaInfoContainer
|
entailment
|
public function setConfig($key, $value)
{
if (!array_key_exists($key, $this->configuration)) {
throw new \Exception(
sprintf('key "%s" does\'t exist', $key)
);
}
$this->configuration[$key] = $value;
}
|
@param string $key
@param string $value
@throws \Exception
|
entailment
|
public function prePersist($args)
{
if (null === $this->userDiscriminator->getCurrentUser()) {
return;
}
$object = $args->getObject();
if ($object instanceof UserInterface && $this->userDiscriminator->getCurrentUserConfig()->getConfig('use_listener', true)) {
$this->updateUserFields($object);
}
}
|
{inheritdoc}.
|
entailment
|
protected function updateUserFields(UserInterface $user)
{
if (null === $this->userDiscriminator) {
$this->userDiscriminator = $this->container->get('rollerworks_multi_user.user_discriminator');
}
// Can only use the user manager when there is an user-system active
if (null === $this->userDiscriminator->getCurrentUser() || true !== $this->userDiscriminator->getCurrentUserConfig()->getConfig('use_listener', true)) {
return;
}
if (null === $this->userManager) {
$this->userManager = $this->container->get('fos_user.user_manager');
}
$this->userManager->updateCanonicalFields($user);
$this->userManager->updatePassword($user);
}
|
This must be called on prePersist and preUpdate if the event is about a
user.
@param UserInterface $user
|
entailment
|
public function getMediaInfoContainer($ignoreUnknownTrackTypes = false)
{
if ($this->parsedOutput === null) {
throw new \Exception('You must run `parse` before running `getMediaInfoContainer`');
}
$mediaInfoContainerBuilder = new MediaInfoContainerBuilder();
$mediaInfoContainerBuilder->setVersion($this->parsedOutput['@attributes']['version']);
if (false === array_key_exists('File', $this->parsedOutput)) {
throw new MediainfoOutputParsingException(
'XML format of mediainfo >=17.10 command has changed, check php-mediainfo documentation'
);
}
foreach ($this->parsedOutput['File']['track'] as $trackType) {
try {
if (isset($trackType['@attributes']['type'])) {
$mediaInfoContainerBuilder->addTrackType($trackType['@attributes']['type'], $trackType);
}
} catch (UnknownTrackTypeException $ex) {
if (!$ignoreUnknownTrackTypes) {
// rethrow exception
throw $ex;
}
// else ignore
}
}
return $mediaInfoContainerBuilder->build();
}
|
@param bool $ignoreUnknownTrackTypes Optional parameter used to skip unknown track types by passing true. The
default behavior (false) is throw an exception on unknown track types.
@return MediaInfoContainer
|
entailment
|
public function add(AbstractType $trackType)
{
switch (get_class($trackType)) {
case self::AUDIO_CLASS:
$this->addAudio($trackType);
break;
case self::VIDEO_CLASS:
$this->addVideo($trackType);
break;
case self::IMAGE_CLASS:
$this->addImage($trackType);
break;
case self::GENERAL_CLASS:
$this->setGeneral($trackType);
break;
case self::SUBTITLE_CLASS:
$this->addSubtitle($trackType);
break;
case self::MENU_CLASS:
$this->addMenu($trackType);
break;
case self::OTHER_CLASS:
$this->addOther($trackType);
break;
default:
throw new \Exception('Unknown type');
}
}
|
@param AbstractType $trackType
@throws \Exception
|
entailment
|
public function getConfigTreeBuilder()
{
$supportedDrivers = array('orm', 'mongodb', 'couchdb');
$treeBuilder = new TreeBuilder();
$rootNode = $treeBuilder->root('rollerworks_multi_user');
$rootNode
->children()
->scalarNode('db_driver')
->defaultValue('orm')
->validate()
->ifNotInArray($supportedDrivers)
->thenInvalid('The driver %s is not supported. Please choose one of: '.implode(',', $supportedDrivers))
->end()
->end()
->booleanNode('use_listener')->defaultTrue()->end()
->booleanNode('use_flash_notifications')->defaultTrue()->end()
->arrayNode('from_email')
->addDefaultsIfNotSet()
->children()
->scalarNode('address')->defaultValue('[email protected]')->cannotBeEmpty()->end()
->scalarNode('sender_name')->defaultValue('webmaster')->cannotBeEmpty()->end()
->end()
->end()
->end()
;
return $treeBuilder;
}
|
{@inheritdoc}
|
entailment
|
final public function addUserSysConfig(ArrayNodeDefinition $rootNode)
{
$rootNode
->children()
->scalarNode('db_driver')
->defaultValue('orm')
->validate()
->ifNotInArray(self::$supportedDrivers)
->thenInvalid('The driver %s is not supported. Please choose one of: '.implode(',', self::$supportedDrivers))
->end()
->end()
->booleanNode('use_listener')->defaultTrue()->end()
->scalarNode('path')->defaultNull()->end()
->scalarNode('host')->defaultNull()->end()
->scalarNode('request_matcher')->defaultNull()->end()
->scalarNode('user_class')->isRequired()->cannotBeEmpty()->end()
->scalarNode('services_prefix')
->defaultNull()
->validate()
->ifInArray(array('fos_user'))
->thenInvalid('service_service can not be "fos_user" as its already used.')
->end()
->end()
->scalarNode('routes_prefix')->defaultNull()->end()
->scalarNode('firewall_name')->defaultNull()->end()
->scalarNode('model_manager_name')->defaultValue('default')->end()
->booleanNode('use_username_form_type')->defaultTrue()->end()
->arrayNode('from_email')
->children()
->scalarNode('address')->defaultNull()->end()
->scalarNode('sender_name')->defaultNull()->end()
->end()
->end()
->end()
->validate()
->ifTrue(function ($v) { return null === $v['request_matcher'] && null === $v['host'] && null === $v['path']; })
->thenInvalid('You need to specify a "request_matcher" service-id or "host" and/or url "path" for the discriminator.')
->end()
;
$this->addSecuritySection($rootNode);
$this->addServiceSection($rootNode);
$this->addTemplateSection($rootNode);
$this->addProfileSection($rootNode);
$this->addChangePasswordSection($rootNode);
$this->addRegistrationSection($rootNode);
$this->addResettingSection($rootNode);
$this->addGroupSection($rootNode);
return $rootNode;
}
|
@param ArrayNodeDefinition $rootNode
@throws \InvalidArgumentException on unknown section
@return ArrayNodeDefinition
@internal
|
entailment
|
final public function addUserConfig(ArrayNodeDefinition $rootNode, $enableServices = self::CONFIG_ALL)
{
if (is_array($enableServices)) {
$enableServices = $this->convertArrayToBitmask($enableServices);
}
$supportedDrivers = self::$supportedDrivers;
$rootNode
->children()
->scalarNode('firewall_name')->end()
->scalarNode('model_manager_name')->end()
->booleanNode('use_username_form_type')->end()
->arrayNode('from_email')
->children()
->scalarNode('address')->end()
->scalarNode('sender_name')->end()
->end()
->end()
->end()
;
if ($enableServices & self::CONFIG_DB_DRIVER) {
$rootNode
->children()
->scalarNode('db_driver')
->validate()
->ifTrue(function ($v) use ($supportedDrivers) { return $v !== null && !in_array($v, $supportedDrivers, true); })
->thenInvalid('The driver %s is not supported. Please choose one of: '.implode(',', $supportedDrivers))
->end()
->end()
->end()
;
}
if ($enableServices & self::CONFIG_REQUEST_MATCHER) {
$rootNode
->children()
->scalarNode('path')->end()
->scalarNode('host')->end()
->scalarNode('request_matcher')->end()
->end()
;
}
if ($enableServices & self::CONFIG_USER_CLASS) {
$rootNode
->children()
->scalarNode('user_class')->end()
->end()
;
}
if ($enableServices & self::CONFIG_SECTION_PROFILE) {
$this->addProfileSection($rootNode, false);
}
if ($enableServices & self::CONFIG_SECTION_CHANGE_PASSWORD) {
$this->addChangePasswordSection($rootNode, false);
}
if ($enableServices & self::CONFIG_SECTION_REGISTRATION) {
$this->addRegistrationSection($rootNode, false);
}
if ($enableServices & self::CONFIG_SECTION_RESETTING) {
$this->addResettingSection($rootNode, false);
}
if ($enableServices & self::CONFIG_SECTION_GROUP) {
$this->addGroupSection($rootNode, false);
}
if ($enableServices & self::CONFIG_SECTION_SECURITY) {
$this->addSecuritySection($rootNode, false);
}
$this->addTemplateSection($rootNode, false);
return $rootNode;
}
|
Adds the user-configuration to the $rootNode.
To specify which configurations are added use a Bitmask value.
For example;
Configuration::CONFIG_ALL ^ Configuration::CONFIG_SECTION_PROFILE
Will enable everything except profile configuration.
Configuration::CONFIG_SECTION_PROFILE | self::CONFIG_SECTION_CHANGE_PASSWORD
Will enable only the profile and change-password.
Note. firewall_name, model_manager_name, use_username_form_type, from_email are always configurable.
When calling this method.
@param ArrayNodeDefinition $rootNode
@param array|int $enableServices Bitmask of enabled configurations or array of enabled-services (compatibility only)
Accepted array values: 'profile', 'change_password', 'registration', 'resetting', 'group'
@throws \InvalidArgumentException on unknown section
@return ArrayNodeDefinition
@internal
|
entailment
|
final public function addProfileSection(ArrayNodeDefinition $node, $defaults = true)
{
if ($defaults) {
$node
->children()
->arrayNode('profile')
->canBeUnset()
->children()
->arrayNode('form')
->addDefaultsIfNotSet()
->children()
->scalarNode('type')->defaultValue('fos_user_profile')->end()
->scalarNode('class')->defaultValue('FOS\UserBundle\Form\Type\ProfileFormType')->end()
->scalarNode('name')->defaultValue('fos_user_profile_form')->end()
->arrayNode('validation_groups')
->prototype('scalar')->end()
->defaultValue(array('Profile', 'Default'))
->end()
->end()
->end()
->arrayNode('template')
->addDefaultsIfNotSet()
->children()
->scalarNode('edit')->defaultValue('RollerworksMultiUserBundle:UserBundle/Profile:edit.html.twig')->end()
->scalarNode('show')->defaultValue('RollerworksMultiUserBundle:UserBundle/Profile:show.html.twig')->end()
->end()
->end()
->end()
->end()
->end()
;
} else {
$node
->children()
->arrayNode('profile')
->canBeUnset()
->children()
->arrayNode('form')
->children()
->scalarNode('type')->end()
->scalarNode('class')->end()
->scalarNode('name')->end()
->arrayNode('validation_groups')
->prototype('scalar')->end()
->end()
->end()
->end()
->arrayNode('template')
->children()
->scalarNode('edit')->end()
->scalarNode('show')->end()
->end()
->end()
->end()
->end()
->end()
;
}
}
|
Its only marked public for call_user_func() in addUserConfig()
|
entailment
|
public static function create($attribute, $value)
{
$attributesType = self::getAllAttributeType();
foreach ($attributesType as $attributeType) {
if ($attributeType->isMember($attribute)) {
return $attributeType->create($value);
}
}
return $value;
}
|
@param $attribute
@param $value
@return mixed
|
entailment
|
public function dispatchChangePasswordInitialize(Event $e)
{
if ($userSys = $this->userDiscriminator->getCurrentUser()) {
$this->eventDispatcher->dispatch($userSys.'.change_password.edit.initialize', $e);
}
}
|
last updated on 2014-03-06
|
entailment
|
public static function getSubscribedEvents()
{
return array(
FOSUserEvents::CHANGE_PASSWORD_INITIALIZE => 'dispatchChangePasswordInitialize',
FOSUserEvents::CHANGE_PASSWORD_SUCCESS => 'dispatchChangePasswordSuccess',
FOSUserEvents::CHANGE_PASSWORD_COMPLETED => 'dispatchChangePasswordCompleted',
FOSUserEvents::GROUP_CREATE_INITIALIZE => 'dispatchGroupCreateInitialize',
FOSUserEvents::GROUP_CREATE_SUCCESS => 'dispatchGroupCreateSuccess',
FOSUserEvents::GROUP_CREATE_COMPLETED => 'dispatchGroupCreateCompleted',
FOSUserEvents::GROUP_DELETE_COMPLETED => 'dispatchGroupDeleteCompleted',
FOSUserEvents::GROUP_EDIT_INITIALIZE => 'dispatchGroupEditInitialize',
FOSUserEvents::GROUP_EDIT_SUCCESS => 'dispatchGroupEditSuccess',
FOSUserEvents::GROUP_EDIT_COMPLETED => 'dispatchGroupEditCompleted',
FOSUserEvents::PROFILE_EDIT_INITIALIZE => 'dispatchProfileEditInitialize',
FOSUserEvents::PROFILE_EDIT_SUCCESS => 'dispatchProfileEditSuccess',
FOSUserEvents::PROFILE_EDIT_COMPLETED => 'dispatchProfileEditCompleted',
FOSUserEvents::REGISTRATION_INITIALIZE => 'dispatchRegistrationInitialize',
FOSUserEvents::REGISTRATION_SUCCESS => 'dispatchRegistrationSuccess',
FOSUserEvents::REGISTRATION_COMPLETED => 'dispatchRegistrationCompleted',
FOSUserEvents::REGISTRATION_CONFIRM => 'dispatchRegistrationConfirm',
FOSUserEvents::REGISTRATION_CONFIRMED => 'dispatchRegistrationConfirmed',
FOSUserEvents::RESETTING_RESET_INITIALIZE => 'dispatchResettingResetInitialize',
FOSUserEvents::RESETTING_RESET_SUCCESS => 'dispatchResettingResetSuccess',
FOSUserEvents::RESETTING_RESET_COMPLETED => 'dispatchResettingResetCompleted',
FOSUserEvents::SECURITY_IMPLICIT_LOGIN => 'dispatchSecurityImplicitLogin',
);
}
|
Subscribes to all events defined in FOS\UserBundle\FOSUserEvents.
@return array
|
entailment
|
public function build(ContainerBuilder $container)
{
parent::build($container);
$container->addCompilerPass(new OverrideServiceCompilerPass());
$container->addCompilerPass(new RemoveParentServicesPass());
$container->addCompilerPass(new RegisterUserPass());
}
|
{@inheritdoc}
|
entailment
|
public function process(ContainerBuilder $container)
{
if (!$container->hasDefinition('rollerworks_multi_user.user_discriminator')) {
return;
}
$requestListener = null;
$authenticationListener = null;
if ($container->hasDefinition('rollerworks_multi_user.listener.request')) {
$requestListener = $container->getDefinition('rollerworks_multi_user.listener.request');
}
if ($container->hasDefinition('rollerworks_multi_user.listener.authentication')) {
$authenticationListener = $container->getDefinition('rollerworks_multi_user.listener.authentication');
}
$userDiscriminator = $container->getDefinition('rollerworks_multi_user.user_discriminator');
foreach ($container->findTaggedServiceIds('rollerworks_multi_user.user_system') as $id => $attributes) {
$name = $attributes[0]['alias'];
if (!isset($attributes[0]['request_matcher'])) {
$requestMatcher = $this->createRequestMatcher($container, $container->getParameterBag()->resolveValue($attributes[0]['path']), $container->getParameterBag()->resolveValue($attributes[0]['host']));
} else {
$requestMatcher = new Reference($attributes[0]['request_matcher']);
}
if ($authenticationListener) {
$authenticationListener->addMethodCall('addUser', array($name, $container->getParameterBag()->resolveValue($attributes[0]['class'])));
}
if ($requestListener) {
$requestListener->addMethodCall('addUser', array($name, $requestMatcher));
}
$userDiscriminator->addMethodCall('addUser', array($name, new Reference($id)));
}
}
|
{@inheritdoc}
|
entailment
|
private function createRequestMatcher(ContainerBuilder $container, $path = null, $host = null, $methods = array(), $ip = null, array $attributes = array())
{
$serialized = serialize(array($path, $host, $methods, $ip, $attributes));
$id = 'rollerworks_multi_user.request_matcher.'.md5($serialized).sha1($serialized);
// Matcher already exist, which is not allowed
if (isset($this->requestMatchers[$id])) {
throw new \RuntimeException(sprintf(
'There is already a request-matcher for this configuration: path: "%s", host: "%s". Only one request matcher should match for the user system.',
$path,
$host
));
}
if ($methods) {
$methods = array_map('strtoupper', (array) $methods);
}
// only add arguments that are necessary
$arguments = array($path, $host, $methods, $ip, $attributes);
while (count($arguments) > 0 && !end($arguments)) {
array_pop($arguments);
}
$container
->register($id, '%rollerworks_multi_user.matcher.class%')
->setPublic(false)
->setArguments($arguments)
;
return $this->requestMatchers[$id] = new Reference($id);
}
|
Copied from the SymfonySecurityBundle.
|
entailment
|
public function setCurrentUser($name)
{
if (!isset($this->users[$name])) {
throw new \LogicException(sprintf('Impossible to set the user discriminator, because "%s" is not present in the users list.', $name));
}
$this->currentUser = $name;
}
|
{@inheritdoc}
|
entailment
|
public function run()
{
$this->process->run();
if (!$this->process->isSuccessful()) {
throw new \RuntimeException($this->process->getErrorOutput());
}
return $this->process->getOutput();
}
|
@throws \RuntimeException
@return string
|
entailment
|
public function wait()
{
if ($this->process == null) {
throw new \Exception('You must run `start` before running `wait`');
}
// blocks here until process completes
$this->process->wait();
if (!$this->process->isSuccessful()) {
throw new \RuntimeException($this->process->getErrorOutput());
}
return $this->process->getOutput();
}
|
Blocks until call is complete.
@throws \Exception If this function is called before start()
@throws \RuntimeException
@return string
|
entailment
|
protected function ensureParameterSet($name, $value)
{
if (!$this->container->getParameterBag()->has($name)) {
$this->container->getParameterBag()->set($name, $value);
}
}
|
Ensure the parameter is set, or set the $value otherwise.
@param string $name
@param mixed $value
|
entailment
|
final protected function processConfiguration(array $configs)
{
$processor = new Processor();
return $processor->process(self::$configTree->buildTree(), $configs);
}
|
@param array $configs
@return array
|
entailment
|
protected function createUserConfig(ContainerBuilder $container, $name, array $config)
{
$tagParams = array(
'alias' => $name,
'class' => $config['user_class'],
'path' => $config['path'],
'host' => $config['host'],
'db_driver' => $config['db_driver'],
);
if (null !== $config['request_matcher']) {
$tagParams['request_matcher'] = $config['request_matcher'];
}
$def = $container->register('rollerworks_multi_user.user_system.'.$name, 'Rollerworks\Bundle\MultiUserBundle\Model\UserConfig');
$def
->addArgument($this->servicePrefix)
->addArgument($this->routesPrefix)
->addArgument(new Reference(sprintf('%s.user_manager', $this->servicePrefix)))
->addArgument(new Reference(sprintf('%s.group_manager', $this->servicePrefix)))
->addMethodCall('setConfig', array('use_listener', $config['use_listener']))
->setPublic(false)
->addTag('rollerworks_multi_user.user_system', $tagParams)
;
$def->addMethodCall('setTemplate', array('layout', $config['template']['layout']));
$def->setLazy(true);
return $def;
}
|
@param ContainerBuilder $container
@param string $name
@param array $config
@return Definition
|
entailment
|
private function loadServices(array $config, ContainerBuilder $container)
{
if ('fos_user.util.canonicalizer.default' === $config['service']['username_canonicalizer']) {
$config['service']['username_canonicalizer'] = 'fos_user.util.username_canonicalizer';
}
if ('fos_user.util.canonicalizer.default' === $config['service']['email_canonicalizer']) {
$config['service']['email_canonicalizer'] = 'fos_user.util.email_canonicalizer';
}
// Only create a UserManager service when not using a custom one
if ('fos_user.user_manager.default' === $config['service']['user_manager']) {
$config['service']['user_manager'] = $this->createUserManager($config, $container);
}
if (sprintf('%s.user_manager', $this->servicePrefix) !== $config['service']['user_manager']) {
$container->setAlias(sprintf('%s.user_manager', $this->servicePrefix), $config['service']['user_manager']);
}
$container->setDefinition(sprintf('%s.user_provider.username', $this->servicePrefix), new DefinitionDecorator('fos_user.user_provider.username'))
->replaceArgument(0, new Reference(sprintf('%s.user_manager', $this->servicePrefix)))
->setPublic(false);
$container->setDefinition(sprintf('%s.user_provider.username_email', $this->servicePrefix), new DefinitionDecorator('fos_user.user_provider.username_email'))
->replaceArgument(0, new Reference(sprintf('%s.user_manager', $this->servicePrefix)))
->setPublic(false);
$container->setDefinition(sprintf('%s.user_manipulator', $this->servicePrefix), new DefinitionDecorator('fos_user.util.user_manipulator'))
->replaceArgument(0, new Reference(sprintf('%s.user_manager', $this->servicePrefix)));
$container->setDefinition(sprintf('%s.listener.authentication', $this->servicePrefix), new DefinitionDecorator('fos_user.listener.authentication'))
->replaceArgument(1, sprintf('%%%s.firewall_name%%', $this->servicePrefix))
->addTag('kernel.event_subscriber');
}
|
Loads the primary services.
@param array $config
@param ContainerBuilder $container
|
entailment
|
public function create($type)
{
switch ($type) {
case self::AUDIO:
return new Type\Audio();
case self::IMAGE:
return new Type\Image();
case self::GENERAL:
return new Type\General();
case self::VIDEO:
return new Type\Video();
case self::SUBTITLE:
return new Type\Subtitle();
case self::MENU:
return new Type\Menu();
case self::OTHER:
return new Type\Other();
default:
throw new UnknownTrackTypeException($type);
}
}
|
@param string $type
@throws \Mhor\MediaInfo\Exception\UnknownTrackTypeException
@return Type\AbstractType
|
entailment
|
public function generate($namespace, $bundle, $dir, $format, $structure, $dbDriver)
{
$dir .= '/'.strtr($namespace, '\\', '/');
if (file_exists($dir)) {
if (!is_dir($dir)) {
throw new \RuntimeException(sprintf('Unable to generate the bundle as the target directory "%s" exists but is a file.', realpath($dir)));
}
$files = scandir($dir);
if ($files != array('.', '..')) {
throw new \RuntimeException(sprintf('Unable to generate the bundle as the target directory "%s" is not empty.', realpath($dir)));
}
if (!is_writable($dir)) {
throw new \RuntimeException(sprintf('Unable to generate the bundle as the target directory "%s" is not writable.', realpath($dir)));
}
}
$driverDir = array(
'orm' => 'Entity',
'mongodb' => 'Document',
'couchdb' => 'CouchDocument',
'custom' => 'Model',
);
$basename = substr($bundle, 0, -6);
$parameters = array(
'namespace' => $namespace,
'bundle' => $bundle,
'format' => $format,
'db_driver' => $dbDriver,
'model_namespace' => $namespace.'\\'.$driverDir[$dbDriver],
'bundle_basename' => $basename,
'extension_alias' => Container::underscore($basename),
);
$this->renderFile('bundle/Bundle.php.twig', $dir.'/'.$bundle.'.php', $parameters);
$this->renderFile('bundle/Extension.php.twig', $dir.'/DependencyInjection/'.$basename.'Extension.php', $parameters);
$this->renderFile('bundle/Configuration.php.twig', $dir.'/DependencyInjection/Configuration.php', $parameters);
$this->renderFile('bundle/DefaultController.php.twig', $dir.'/Controller/DefaultController.php', $parameters);
$this->renderFile('bundle/DefaultControllerTest.php.twig', $dir.'/Tests/Controller/DefaultControllerTest.php', $parameters);
$this->renderFile('bundle/index.html.twig.twig', $dir.'/Resources/views/Default/index.html.twig', $parameters);
$this->renderFile('bundle/services.'.$format.'.twig', $dir.'/Resources/config/services.'.$format, $parameters);
$this->generateRoutes($namespace, $bundle, $dir, $format, $basename);
$this->generateModels($namespace, $bundle, $dir, $dbDriver, $basename);
$this->generateEventsClass($namespace, $bundle, $dir, $dbDriver, $basename);
if ($structure) {
$this->renderFile('bundle/messages.fr.xlf', $dir.'/Resources/translations/messages.fr.xlf', $parameters);
$this->filesystem->mkdir($dir.'/Resources/doc');
$this->filesystem->touch($dir.'/Resources/doc/index.rst');
$this->filesystem->mkdir($dir.'/Resources/translations');
$this->filesystem->mkdir($dir.'/Resources/public/css');
$this->filesystem->mkdir($dir.'/Resources/public/images');
$this->filesystem->mkdir($dir.'/Resources/public/js');
}
}
|
@param string $namespace
@param string $bundle
@param string $dir
@param string $format
@param string $structure
@param string $dbDriver
@throws \RuntimeException
|
entailment
|
public function setForm($name, $formName, $type, array $validationGroups)
{
$this->forms[$name] = array('type' => $type, 'name' => $formName, 'validation_groups' => $validationGroups);
return $this;
}
|
Set the form configuration.
@param string $name
@param string $formName
@param string $type
@param array $validationGroups
@return static
|
entailment
|
public function getFormType($name)
{
return isset($this->forms[$name]['type']) ? $this->forms[$name]['type'] : null;
}
|
Get the form-type name for the given config-name.
@param string $name
@return string|null
|
entailment
|
public function getFormName($name)
{
return isset($this->forms[$name]['name']) ? $this->forms[$name]['name'] : null;
}
|
Get the form name for the given config-name.
@param string $name
@return string|null
|
entailment
|
public function getFormValidationGroups($name)
{
return isset($this->forms[$name]['validation_groups']) ? $this->forms[$name]['validation_groups'] : null;
}
|
Get the validation groups for the given config-name.
@param string $name
@return array|null
|
entailment
|
public function getTemplate($name)
{
if (!isset($this->templates[$name])) {
throw new MissingTemplateException(sprintf('Unable to get template for "%s", there is no such template configured.', $name));
}
$template = (string) $this->templates[$name];
if ('' === $template) {
throw new MissingTemplateException(sprintf('Unable to get template for "%s", it seems the template value is empty. Make sure you enabled the proper section and configured a proper value.', $name));
}
return $template;
}
|
Get the View template for the given config-name.
@param string $name
@return string
|
entailment
|
protected function transformXmlToArray($xmlString)
{
if (mb_detect_encoding($xmlString, 'UTF-8', true) === false) {
$xmlString = utf8_encode($xmlString);
}
$xml = simplexml_load_string($xmlString);
$json = json_encode($xml);
return json_decode($json, true);
}
|
@param string $xmlString
@return array
|
entailment
|
protected function execute(InputInterface $input, OutputInterface $output)
{
$questionHelper = $this->getQuestionHelper();
$dialog = $this->getHelper('dialog');
if ($input->isInteractive()) {
if (!$dialog->askConfirmation($output, $questionHelper->getQuestion('Do you confirm generation', 'yes', '?'), true)) {
$output->writeln('<error>Command aborted</error>');
return 1;
}
}
foreach (array('namespace', 'dir') as $option) {
if (null === $input->getOption($option)) {
throw new \RuntimeException(sprintf('The "%s" option must be provided.', $option));
}
}
$namespace = Validators::validateBundleNamespace($input->getOption('namespace'));
if (!$bundle = $input->getOption('bundle-name')) {
$bundle = strtr($namespace, array('\\' => ''));
}
$bundle = Validators::validateBundleName($bundle);
$dir = Validators::validateTargetDir($input->getOption('dir'), $bundle, $namespace);
if (null === $input->getOption('format')) {
$input->setOption('format', 'xml');
}
$format = Validators::validateFormat($input->getOption('format'));
$structure = $input->getOption('structure');
if (null === $input->getOption('db-driver')) {
$input->setOption('db-driver', 'orm');
}
$dbDriver = Validators::validateDbDriver($input->getOption('db-driver'));
$questionHelper->writeSection($output, 'Bundle generation');
if (!$this->getContainer()->get('filesystem')->isAbsolutePath($dir)) {
$dir = getcwd().'/'.$dir;
}
$generator = $this->getGenerator();
$generator->generate($namespace, $bundle, $dir, $format, $structure, $dbDriver);
$output->writeln('Generating the bundle code: <info>OK</info>');
$errors = array();
$runner = $questionHelper->getRunner($output, $errors);
// check that the namespace is already autoloaded
$runner($this->checkAutoloader($output, $namespace, $bundle, $dir));
// register the bundle in the Kernel class
$runner($this->updateKernel($questionHelper, $input, $output, $this->getContainer()->get('kernel'), $namespace, $bundle));
$questionHelper->writeGeneratorSummary($output, $errors);
}
|
@see Command
@throws \InvalidArgumentException When namespace doesn't end with Bundle
@throws \RuntimeException When bundle can't be executed
|
entailment
|
protected function getSkeletonDirs(BundleInterface $bundle = null)
{
$baseSkeletonDirs = parent::getSkeletonDirs($bundle);
$skeletonDirs = array();
if (is_dir($dir = $this->getContainer()->get('kernel')->getRootdir().'/Resources/MultiUserBundleMultiUserBundle/skeleton')) {
$skeletonDirs[] = $dir;
}
$reflClass = new \ReflectionClass($this);
$dir = dirname($reflClass->getFileName());
$skeletonDirs[] = $dir.'/../Resources/skeleton';
$skeletonDirs[] = $dir.'/../Resources';
return array_merge($skeletonDirs, $baseSkeletonDirs);
}
|
add this bundle skeleton dirs to the beginning of the parent skeletonDirs array.
@param BundleInterface $bundle
@return string[]
|
entailment
|
public function addTrackType($typeName, array $attributes)
{
$trackType = $this->typeFactory->create($typeName);
$this->addAttributes($trackType, $attributes);
$this->mediaInfoContainer->add($trackType);
}
|
@param $typeName
@param array $attributes
@throws \Mhor\MediaInfo\Exception\UnknownTrackTypeException
|
entailment
|
private function sanitizeAttributes(array $attributes)
{
$sanitizeAttributes = [];
foreach ($attributes as $key => $value) {
$key = $this->formatAttribute($key);
if (isset($sanitizeAttributes[$key])) {
if (!is_array($sanitizeAttributes[$key])) {
$sanitizeAttributes[$key] = [$sanitizeAttributes[$key]];
}
if (!is_array($value)) {
$value = [$value];
}
$value = $sanitizeAttributes[$key] + $value;
}
$sanitizeAttributes[$key] = $value;
}
return $sanitizeAttributes;
}
|
@param array $attributes
@return array
|
entailment
|
public function onKernelRequest(GetResponseEvent $event)
{
// Already set
if (null !== $this->userDiscriminator->getCurrentUser()) {
return;
}
$request = $event->getRequest();
foreach ($this->users as $name => $requestMatcher) {
if ($requestMatcher->matches($request)) {
$this->userDiscriminator->setCurrentUser($name);
return;
}
}
}
|
{@inheritdoc}
|
entailment
|
public function generateAdjacentNodes(Node $node)
{
$myNode = MyNode::fromNode($node);
return $this->graph->getDirectSuccessors($myNode);
}
|
{@inheritdoc}
|
entailment
|
public function calculateRealCost(Node $node, Node $adjacent)
{
$myStartNode = MyNode::fromNode($node);
$myEndNode = MyNode::fromNode($adjacent);
if (!$this->graph->hasLink($myStartNode, $myEndNode)) {
throw new \DomainException('The provided nodes are not linked');
}
return $this->graph->getLink($myStartNode, $myEndNode)->getDistance();
}
|
{@inheritdoc}
|
entailment
|
public function calculateEstimatedCost(Node $start, Node $end)
{
$myStartNode = MyNode::fromNode($start);
$myEndNode = MyNode::fromNode($end);
$xFactor = pow($myStartNode->getX() - $myEndNode->getX(), 2);
$yFactor = pow($myStartNode->getY() - $myEndNode->getY(), 2);
$euclideanDistance = sqrt($xFactor + $yFactor);
return $euclideanDistance;
}
|
{@inheritdoc}
|
entailment
|
public function handle(Request $request, Closure $next)
{
$cors = $this->getCorsAnalysis($request);
switch ($cors->getRequestType()) {
case AnalysisResultInterface::TYPE_REQUEST_OUT_OF_CORS_SCOPE:
$response = $next($request);
break;
case AnalysisResultInterface::TYPE_PRE_FLIGHT_REQUEST:
$headers = $this->getPrepareCorsHeaders($cors->getResponseHeaders());
$response = new Response(null, Response::HTTP_OK, $headers);
break;
case AnalysisResultInterface::TYPE_ACTUAL_REQUEST:
/** @var Response $response */
$response = $next($request);
// merge CORS headers to response
foreach ($this->getPrepareCorsHeaders($cors->getResponseHeaders()) as $name => $value) {
$response->headers->set($name, $value, false);
}
break;
default:
$response = $this->getResponseOnError($cors);
break;
}
return $response;
}
|
Handle an incoming request.
@param Request $request
@param Closure $next
@return mixed
|
entailment
|
protected function getCorsAnalysis(Request $request)
{
$analysis = $this->analyzer->analyze($this->getRequestAdapter($request));
$this->container->instance(AnalysisResultInterface::class, $analysis);
return $analysis;
}
|
This method saves analysis result in Illuminate Container for
using it in other parts of the application (e.g. in exception handler).
@param Request $request
@return AnalysisResultInterface
|
entailment
|
protected function getPrepareCorsHeaders($headers)
{
if (array_key_exists(CorsResponseHeaders::EXPOSE_HEADERS, $headers) === true) {
$headers[CorsResponseHeaders::EXPOSE_HEADERS] =
implode(', ', $headers[CorsResponseHeaders::EXPOSE_HEADERS]);
}
return $headers;
}
|
There is an issue with IE which cannot work with multiple 'Access-Control-Expose-Headers' and
requires it them to be comma separated. Chrome and Firefox seem to be not affected.
@param array $headers
@return array
@see https://github.com/neomerx/cors-psr7/issues/31
|
entailment
|
public function calculateRealCost(Node $node, Node $adjacent)
{
return call_user_func(array($this->object, $this->realCostCallback), $node, $adjacent);
}
|
{@inheritdoc}
|
entailment
|
public function calculateEstimatedCost(Node $start, Node $end)
{
return call_user_func(array($this->object, $this->estimatedCostCallback), $start, $end);
}
|
{@inheritdoc}
|
entailment
|
public function generateAdjacentNodes(Node $node)
{
$adjacentNodes = array();
$myNode = MyNode::fromNode($node);
if ($myNode->getRow() === 0) {
$startingRow = 0;
} else {
$startingRow = $myNode->getRow() - 1;
}
if ($myNode->getRow() === $this->terrainCost->getTotalRows() - 1) {
$endingRow = $myNode->getRow();
} else {
$endingRow = $myNode->getRow() + 1;
}
if ($myNode->getColumn() === 0) {
$startingColumn = 0;
} else {
$startingColumn = $myNode->getColumn() - 1;
}
if ($myNode->getColumn() === $this->terrainCost->getTotalColumns() - 1) {
$endingColumn = $myNode->getColumn();
} else {
$endingColumn = $myNode->getColumn() + 1;
}
for ($row = $startingRow; $row <= $endingRow; $row++) {
for ($column = $startingColumn; $column <= $endingColumn; $column++) {
$adjacentNode = new MyNode($row, $column);
if ($adjacentNode->getID() !== $myNode->getID()) {
$adjacentNodes[] = $adjacentNode;
}
}
}
return $adjacentNodes;
}
|
{@inheritdoc}
|
entailment
|
public function calculateRealCost(Node $node, Node $adjacent)
{
$myStartNode = MyNode::fromNode($node);
$myEndNode = MyNode::fromNode($adjacent);
if ($this->areAdjacent($myStartNode, $myEndNode)) {
return $this->terrainCost->getCost($myEndNode->getRow(), $myEndNode->getColumn());
}
return TerrainCost::INFINITE;
}
|
{@inheritdoc}
|
entailment
|
public function calculateEstimatedCost(Node $start, Node $end)
{
$myStartNode = MyNode::fromNode($start);
$myEndNode = MyNode::fromNode($end);
$rowFactor = pow($myStartNode->getRow() - $myEndNode->getRow(), 2);
$columnFactor = pow($myStartNode->getColumn() - $myEndNode->getColumn(), 2);
$euclideanDistance = sqrt($rowFactor + $columnFactor);
return $euclideanDistance;
}
|
{@inheritdoc}
|
entailment
|
protected function mergeConfigs()
{
$repo = $this->getConfigRepository();
$config = $repo->get(static::CONFIG_FILE_NAME_WO_EXT, []);
$base = $this->getBaseConfig();
$result = $config + $base;
$repo->set(static::CONFIG_FILE_NAME_WO_EXT, $result);
}
|
Merge default config and config from application `config` folder.
|
entailment
|
protected function getCreateAnalyzerClosure()
{
return function ($app) {
/** @var AnalysisStrategyInterface $strategy */
$strategy = $app[AnalysisStrategyInterface::class];
$analyzer = Analyzer::instance($strategy);
$logger = $this->getLoggerIfEnabled($app);
$logger === null ?: $analyzer->setLogger($logger);
return $analyzer;
};
}
|
@return Closure
@SuppressWarnings(PHPMD.StaticAccess)
|
entailment
|
protected function getLoggerIfEnabled($app)
{
/** @var ApplicationInterface $app */
if ($this->logger === false) {
$settings = $this->getSettings();
$loggingEnabled =
array_key_exists(Settings::KEY_LOGS_ENABLED, $settings) === true &&
$settings[Settings::KEY_LOGS_ENABLED] === true;
$this->logger = $loggingEnabled === true ? $app[LoggerInterface::class] : null;
}
return $this->logger;
}
|
@param ApplicationInterface $app
@return null|LoggerInterface
|
entailment
|
public function stem($word)
{
// we do ALL in UTF-8
if (! Utf8::check($word)) {
throw new \Exception('Word must be in UTF-8');
}
$this->word = Utf8::strtolower($word);
$this->plainVowels = implode('', self::$vowels);
// First, i and u between vowels are put into upper case (so that they are treated as consonants).
$this->word = preg_replace('#(['.$this->plainVowels.'])u(['.$this->plainVowels.'])#u', '$1U$2', $this->word);
$this->word = preg_replace('#(['.$this->plainVowels.'])i(['.$this->plainVowels.'])#u', '$1I$2', $this->word);
$this->rv();
$this->r1();
$this->r2();
$this->step0();
$word1 = $this->word;
$word2 = $this->word;
do {
$word1 = $this->word;
$this->step1();
} while ($this->word != $word1);
$this->step2();
// Do step 3 if no suffix was removed either by step 1 or step 2.
if ($word2 == $this->word) {
$this->step3();
}
$this->step4();
$this->finish();
return $this->word;
}
|
{@inheritdoc}
|
entailment
|
public function step0()
{
// ul ului
// delete
if ( ($position = $this->search(array('ul', 'ului'))) !== false) {
if ($this->inR1($position)) {
$this->word = Utf8::substr($this->word, 0, $position);
}
return true;
}
// aua
// replace with a
if ( ($position = $this->search(array('aua'))) !== false) {
if ($this->inR1($position)) {
$this->word = preg_replace('#(aua)$#u', 'a', $this->word);
}
return true;
}
// ea ele elor
// replace with e
if ( ($position = $this->search(array('ea', 'ele', 'elor'))) !== false) {
if ($this->inR1($position)) {
$this->word = preg_replace('#(ea|ele|elor)$#u', 'e', $this->word);
}
return true;
}
// ii iua iei iile iilor ilor
// replace with i
if ( ($position = $this->search(array('ii', 'iua', 'iei', 'iile', 'iilor', 'ilor'))) !== false) {
if ($this->inR1($position)) {
$this->word = preg_replace('#(ii|iua|iei|iile|iilor|ilor)$#u', 'i', $this->word);
}
return true;
}
// ile
// replace with i if not preceded by ab
if ( ($position = $this->search(array('ile'))) !== false) {
if ($this->inR1($position)) {
$before = Utf8::substr($this->word, ($position-2), 2);
if ($before != 'ab') {
$this->word = preg_replace('#(ile)$#u', 'i', $this->word);
}
}
return true;
}
// atei
// replace with at
if ( ($position = $this->search(array('atei'))) != false) {
if ($this->inR1($position)) {
$this->word = preg_replace('#(atei)$#u', 'at', $this->word);
}
return true;
}
// aţie aţia
// replace with aţi
if ( ($position = $this->search(array('aţie', 'aţia'))) !== false) {
if ($this->inR1($position)) {
$this->word = preg_replace('#(aţie|aţia)$#u', 'aţi', $this->word);
}
return true;
}
return false;
}
|
Step 0: Removal of plurals (and other simplifications)
Search for the longest among the following suffixes, and, if it is in R1, perform the action indicated.
@return boolean
|
entailment
|
public function step1()
{
// abilitate abilitati abilităi abilităţi
// replace with abil
if ( ($position = $this->search(array('abilitate', 'abilitati', 'abilităi', 'abilităţi'))) !== false) {
if ($this->inR1($position)) {
$this->word = preg_replace('#(abilitate|abilitati|abilităi|abilităţi)$#u', 'abil', $this->word);
}
return true;
}
// ibilitate
// replace with ibil
if ( ($position = $this->search(array('ibilitate'))) !== false) {
if ($this->inR1($position)) {
$this->word = preg_replace('#(ibilitate)$#u', 'ibil', $this->word);
}
return true;
}
// ivitate ivitati ivităi ivităţi
// replace with iv
if ( ($position = $this->search(array('ivitate', 'ivitati', 'ivităi', 'ivităţi'))) !== false) {
if ($this->inR1($position)) {
$this->word = preg_replace('#(ivitate|ivitati|ivităi|ivităţi)$#u', 'iv', $this->word);
}
return true;
}
// icitate icitati icităi icităţi icator icatori iciv iciva icive icivi icivă ical icala icale icali icală
// replace with ic
if ( ($position = $this->search(array(
'icitate', 'icitati', 'icităi', 'icităţi', 'icatori', 'icator', 'iciva',
'icive', 'icivi', 'icivă', 'icala', 'icale', 'icali', 'icală', 'iciv', 'ical'))) !== false) {
if ($this->inR1($position)) {
$this->word = preg_replace('#(icitate|icitati|icităi|icităţi|cator|icatori|iciva|icive|icivi|icivă|icala|icale|icali|icală|ical|iciv)$#u', 'ic', $this->word);
}
return true;
}
// ativ ativa ative ativi ativă aţiune atoare ator atori ătoare ător ători
// replace with at
if ( ($position = $this->search(array('ativa', 'ative', 'ativi', 'ativă', 'ativ', 'aţiune', 'atoare', 'atori', 'ătoare', 'ători', 'ător', 'ator'))) !== false) {
if ($this->inR1($position)) {
$this->word = preg_replace('#(ativa|ative|ativi|ativă|ativ|aţiune|atoare|atori|ătoare|ători|ător|ator)$#u', 'at', $this->word);
}
return true;
}
// itiv itiva itive itivi itivă iţiune itoare itor itori
// replace with it
if ( ($position = $this->search(array('itiva', 'itive', 'itivi', 'itivă', 'itiv', 'iţiune', 'itoare', 'itori', 'itor'))) !== false) {
if ($this->inR1($position)) {
$this->word = preg_replace('#(itiva|itive|itivi|itivă|itiv|iţiune|itoare|itori|itor)$#u', 'it', $this->word);
}
return true;
}
return false;
}
|
Step 1: Reduction of combining suffixes
Search for the longest among the following suffixes, and, if it is in R1, preform the replacement action indicated.
Then repeat this step until no replacement occurs.
@return boolean
|
entailment
|
public function step2()
{
// atori itate itati, ităţi, abila abile abili abilă, ibila ibile ibili ibilă
// anta, ante, anti, antă, ator, ibil, oasa oasă oase, ităi, abil
// osi oşi ant ici ică iva ive ivi ivă ata ată ati ate, ata ată ati ate uta ută uti ute, ita ită iti ite ica ice
// at, os, iv, ut, it, ic
// delete
if ( ($position = $this->search(array(
'atori', 'itate', 'itati', 'ităţi', 'abila', 'abile', 'abili', 'abilă', 'ibila', 'ibile', 'ibili', 'ibilă',
'anta', 'ante', 'anti', 'antă', 'ator', 'ibil', 'oasa', 'oasă', 'oase', 'ităi', 'abil',
'osi', 'oşi', 'ant', 'ici', 'ică', 'iva', 'ive', 'ivi', 'ivă', 'ata', 'ată', 'ati', 'ate', 'ata', 'ată',
'ati', 'ate', 'uta', 'ută', 'uti', 'ute', 'ita', 'ită', 'iti', 'ite', 'ica', 'ice',
'at', 'os', 'iv', 'ut', 'it', 'ic'
))) !== false) {
if ($this->inR2($position)) {
$this->word = Utf8::substr($this->word, 0, $position);
}
return true;
}
// iune iuni
// delete if preceded by ţ, and replace the ţ by t.
if ( ($position = $this->search(array('iune', 'iuni'))) !== false) {
if ($this->inR2($position)) {
$before = $position - 1;
$letter = Utf8::substr($this->word, $before, 1);
if ($letter == 'ţ') {
$this->word = Utf8::substr($this->word, 0, $position);
$this->word = preg_replace('#(ţ)$#u', 't', $this->word);
}
}
return true;
}
// ism isme ist ista iste isti istă işti
// replace with ist
if ( ($position = $this->search(array('isme', 'ism', 'ista', 'iste', 'isti', 'istă', 'işti', 'ist'))) !== false) {
if ($this->inR2($position)) {
$this->word = preg_replace('#(isme|ism|ista|iste|isti|istă|işti|ist)$#u', 'ist', $this->word);
}
return true;
}
return false;
}
|
Step 2: Removal of 'standard' suffixes
Search for the longest among the following suffixes, and, if it is in R2, perform the action indicated.
@return boolean
|
entailment
|
public function step3()
{
// are ere ire âre ind ând indu ându eze ească ez ezi ează esc eşti
// eşte ăsc ăşti ăşte am ai au eam eai ea eaţi eau iam iai ia iaţi
// iau ui aşi arăm arăţi ară uşi urăm urăţi ură işi irăm irăţi iră âi
// âşi ârăm ârăţi âră asem aseşi ase aserăm aserăţi aseră isem iseşi ise
// iserăm iserăţi iseră âsem âseşi âse âserăm âserăţi âseră usem useşi use userăm userăţi useră
// delete if preceded in RV by a consonant or u
if ( ($position = $this->searchIfInRv(array(
'userăţi', 'iserăţi', 'âserăţi', 'aserăţi',
'userăm', 'iserăm', 'âserăm', 'aserăm',
'iseră', 'âseşi', 'useră', 'âseră', 'useşi', 'iseşi', 'aseră', 'aseşi', 'ârăţi', 'irăţi', 'urăţi', 'arăţi', 'ească',
'usem', 'âsem', 'isem', 'asem', 'ârăm', 'urăm', 'irăm', 'arăm', 'iaţi', 'eaţi', 'ăşte', 'ăşti', 'eşte', 'eşti', 'ează', 'ându', 'indu',
'âse', 'use', 'ise', 'ase', 'âră', 'iră', 'işi', 'ură', 'uşi', 'ară', 'aşi', 'âşi', 'iau', 'iai', 'iam', 'eau', 'eai', 'eam', 'ăsc',
'are', 'ere', 'ire', 'âre', 'ind', 'ând', 'eze', 'ezi', 'esc',
'âi', 'ui', 'ia', 'ea', 'au', 'ai', 'am', 'ez'
))) !== false) {
if ($this->inRv($position)) {
$before = $position - 1;
if ($this->inRv($before)) {
$letter = Utf8::substr($this->word, $before, 1);
if ( (!in_array($letter, self::$vowels)) || ($letter == 'u') ) {
$this->word = Utf8::substr($this->word, 0, $position);
}
}
}
return true;
}
// ăm aţi em eţi im iţi âm âţi seşi serăm serăţi seră sei se sesem seseşi sese seserăm seserăţi seseră
// delete
if ( ($position = $this->searchIfInRv(array(
'seserăm', 'seserăţi', 'seseră', 'seseşi', 'sesem', 'serăţi', 'serăm', 'seşi', 'sese', 'seră',
'aţi', 'eţi', 'iţi', 'âţi', 'sei', 'se', 'ăm', 'âm', 'em', 'im'
))) !== false) {
if ($this->inRv($position)) {
$this->word = Utf8::substr($this->word, 0, $position);
}
return true;
}
}
|
Step 3: Removal of verb suffixes
Do step 3 if no suffix was removed either by step 1 or step 2.
@return boolean
|
entailment
|
public function step4()
{
// Search for the longest among the suffixes "a e i ie ă " and, if it is in RV, delete it.
if ( ($position = $this->search(array('a', 'ie', 'e', 'i', 'ă'))) !== false) {
if ($this->inRv($position)) {
$this->word = Utf8::substr($this->word, 0, $position);
}
}
return true;
}
|
Step 4: Removal of final vowel
|
entailment
|
public static function encode_fn($file,$safe=true)
{
if($safe && preg_match('#^[a-zA-Z0-9/_\-.%]+$#',$file)){
return $file;
}
$file = urlencode($file);
$file = str_replace('%2F','/',$file);
return $file;
}
|
URL-Encode a filename to allow unicodecharacters
Slashes are not encoded
When the second parameter is true the string will
be encoded only if non ASCII characters are detected -
This makes it safe to run it multiple times on the
same string (default is true)
@author Andreas Gohr <[email protected]>
@see urlencode
|
entailment
|
public static function is_ascii($str)
{
for($i=0; $i<strlen($str); $i++){
if(ord($str{$i}) >127) return false;
}
return true;
}
|
Checks if a string contains 7bit ASCII only
@author Andreas Gohr <[email protected]>
|
entailment
|
public static function strip($str)
{
$ascii = '';
for($i=0; $i<strlen($str); $i++){
if(ord($str{$i}) <128){
$ascii .= $str{$i};
}
}
return $ascii;
}
|
Strips all highbyte chars
Returns a pure ASCII7 string
@author Andreas Gohr <[email protected]>
|
entailment
|
public static function substr_replace($string, $replacement, $start , $length=null )
{
$ret = '';
if($start>0) $ret .= self::substr($string, 0, $start);
$ret .= $replacement;
if($length!=null) $ret .= self::substr($string, $start+$length);
return $ret;
}
|
Unicode aware replacement for substr_replace()
@author Andreas Gohr <[email protected]>
@see substr_replace()
|
entailment
|
public static function explode($sep, $str)
{
if ( $sep == '' ) {
trigger_error('Empty delimiter',E_USER_WARNING);
return FALSE;
}
return preg_split('!'.preg_quote($sep,'!').'!u',$str);
}
|
Unicode aware replacement for explode
@TODO support third limit arg
@author Harry Fuecks <[email protected]>
@see explode();
|
entailment
|
public static function trim($str,$charlist='')
{
if($charlist == '') return trim($str);
return self::ltrim(self::rtrim($str));
}
|
Unicode aware replacement for trim()
@author Andreas Gohr <[email protected]>
@see trim()
@return string
|
entailment
|
public static function strtolower($string)
{
if(!defined('UTF8_NOMBSTRING') && function_exists('mb_strtolower'))
return mb_strtolower($string,'utf-8');
//global $utf8_upper_to_lower;
$utf8_upper_to_lower = array_flip(self::$utf8_lower_to_upper);
$uni = self::utf8_to_unicode($string);
$cnt = count($uni);
for ($i=0; $i < $cnt; $i++){
if($utf8_upper_to_lower[$uni[$i]]){
$uni[$i] = $utf8_upper_to_lower[$uni[$i]];
}
}
return self::unicode_to_utf8($uni);
}
|
This is a unicode aware replacement for strtolower()
Uses mb_string extension if available
@author Andreas Gohr <[email protected]>
@see strtolower()
@see utf8_strtoupper()
|
entailment
|
public static function strtoupper($string)
{
if(!defined('UTF8_NOMBSTRING') && function_exists('mb_strtolower'))
return mb_strtoupper($string,'utf-8');
//global $utf8_lower_to_upper;
$uni = self::utf8_to_unicode($string);
$cnt = count($uni);
for ($i=0; $i < $cnt; $i++){
if(self::$utf8_lower_to_upper[$uni[$i]]){
$uni[$i] = self::$utf8_lower_to_upper[$uni[$i]];
}
}
return self::unicode_to_utf8($uni);
}
|
This is a unicode aware replacement for strtoupper()
Uses mb_string extension if available
@author Andreas Gohr <[email protected]>
@see strtoupper()
@see utf8_strtoupper()
|
entailment
|
public static function deaccent($string,$case=0)
{
if($case <= 0){
//global $utf8_lower_accents;
$string = str_replace(array_keys(self::$utf8_lower_accents),array_values(self::$utf8_lower_accents),$string);
}
if($case >= 0){
//global $utf8_upper_accents;
$string = str_replace(array_keys(self::$utf8_upper_accents),array_values(self::$utf8_upper_accents),$string);
}
return $string;
}
|
Replace accented UTF-8 characters by unaccented ASCII-7 equivalents
Use the optional parameter to just deaccent lower ($case = -1) or upper ($case = 1)
letters. Default is to deaccent both cases ($case = 0)
@author Andreas Gohr <[email protected]>
|
entailment
|
public static function stripspecials($string,$repl='',$additional='')
{
//global $utf8_special_chars;
static $specials = null;
if(is_null($specials)){
$specials = preg_quote(self::unicode_to_utf8(self::$utf8_special_chars), '/');
}
return preg_replace('/['.$additional.'\x00-\x19'.$specials.']/u',$repl,$string);
}
|
Removes special characters (nonalphanumeric) from a UTF-8 string
This function adds the controlchars 0x00 to 0x19 to the array of
stripped chars (they are not included in $utf8_special_chars)
@author Andreas Gohr <[email protected]>
@param string $string The UTF8 string to strip of special chars
@param string $repl Replace special with this string
@param string $additional Additional chars to strip (used in regexp char class)
|
entailment
|
public static function strpos($haystack, $needle, $offset=0)
{
if(!defined('UTF8_NOMBSTRING') && function_exists('mb_strpos'))
return mb_strpos($haystack,$needle,$offset,'utf-8');
if(!$offset){
$ar = self::explode($needle, $haystack);
if ( count($ar) > 1 ) {
return self::strlen($ar[0]);
}
return false;
} else {
if ( !is_int($offset) ) {
trigger_error('Offset must be an integer',E_USER_WARNING);
return false;
}
$str = self::substr($haystack, $offset);
if ( false !== ($pos = self::strpos($str, $needle))){
return $pos + $offset;
}
return false;
}
}
|
This is an Unicode aware replacement for strpos
Uses mb_string extension if available
@author Harry Fuecks <[email protected]>
@see strpos()
|
entailment
|
public static function tohtml ($str)
{
$ret = '';
$max = strlen($str);
$last = 0; // keeps the index of the last regular character
for ($i=0; $i<$max; $i++) {
$c = $str{$i};
$c1 = ord($c);
if ($c1>>5 == 6) { // 110x xxxx, 110 prefix for 2 bytes unicode
$ret .= substr($str, $last, $i-$last); // append all the regular characters we've passed
$c1 &= 31; // remove the 3 bit two bytes prefix
$c2 = ord($str{++$i}); // the next byte
$c2 &= 63; // remove the 2 bit trailing byte prefix
$c2 |= (($c1 & 3) << 6); // last 2 bits of c1 become first 2 of c2
$c1 >>= 2; // c1 shifts 2 to the right
$ret .= '&#' . ($c1 * 100 + $c2) . ';'; // this is the fastest string concatenation
$last = $i+1;
}
}
return $ret . substr($str, $last, $i); // append the last batch of regular characters
}
|
Encodes UTF-8 characters to HTML entities
@author <vpribish at shopping dot com>
@link http://www.php.net/manual/en/function.utf8-decode.php
|
entailment
|
public static function unicode_to_utf8( &$str )
{
if (!is_array($str)) return '';
$utf8 = '';
foreach( $str as $unicode ) {
if ( $unicode < 128 ) {
$utf8.= chr( $unicode );
} elseif ( $unicode < 2048 ) {
$utf8.= chr( 192 + ( ( $unicode - ( $unicode % 64 ) ) / 64 ) );
$utf8.= chr( 128 + ( $unicode % 64 ) );
} else {
$utf8.= chr( 224 + ( ( $unicode - ( $unicode % 4096 ) ) / 4096 ) );
$utf8.= chr( 128 + ( ( ( $unicode % 4096 ) - ( $unicode % 64 ) ) / 64 ) );
$utf8.= chr( 128 + ( $unicode % 64 ) );
}
}
return $utf8;
}
|
This function converts a Unicode array back to its UTF-8 representation
@author Scott Michael Reynen <[email protected]>
@link http://www.randomchaos.com/document.php?source=php_and_unicode
@see utf8_to_unicode()
|
entailment
|
public static function utf8_to_utf16be(&$str, $bom = false)
{
$out = $bom ? "\xFE\xFF" : '';
if(!defined('UTF8_NOMBSTRING') && function_exists('mb_convert_encoding'))
return $out.mb_convert_encoding($str,'UTF-16BE','UTF-8');
$uni = self::utf8_to_unicode($str);
foreach($uni as $cp){
$out .= pack('n',$cp);
}
return $out;
}
|
UTF-8 to UTF-16BE conversion.
Maybe really UCS-2 without mb_string due to utf8_to_unicode limits
|
entailment
|
public function stem($word)
{
// we do ALL in UTF-8
if (! Utf8::check($word)) {
throw new \Exception('Word must be in UTF-8');
}
$this->word = Utf8::strtolower($word);
// R2 is not used: R1 is defined in the same way as in the German stemmer
$this->r1();
$this->r2();
$this->rv();
// Do each of steps 1, 2 3 and 4.
$this->step1();
$this->step2();
$this->step3();
$this->step4();
return $this->word;
}
|
{@inheritdoc}
|
entailment
|
public function step1()
{
// Search for a PERFECTIVE GERUND ending.
// group 1
if ( ($position = $this->searchIfInRv(self::$perfectiveGerund[0])) !== false) {
if ( ($this->inRv($position)) && ($this->checkGroup1($position)) ) {
$this->word = Utf8::substr($this->word, 0, $position);
return true;
}
}
// group 2
if ( ($position = $this->searchIfInRv(self::$perfectiveGerund[1])) !== false) {
if ($this->inRv($position)) {
$this->word = Utf8::substr($this->word, 0, $position);
return true;
}
}
// Otherwise try and remove a REFLEXIVE ending
if ( ($position = $this->searchIfInRv(self::$reflexive)) !== false) {
if ($this->inRv($position)) {
$this->word = Utf8::substr($this->word, 0, $position);
}
}
// then search in turn for (1) an ADJECTIVAL, (2) a VERB or (3) a NOUN ending.
// As soon as one of the endings (1) to (3) is found remove it, and terminate step 1.
if ( ($position = $this->searchIfInRv(self::$adjective)) !== false) {
if ($this->inRv($position)) {
$this->word = Utf8::substr($this->word, 0, $position);
if ( ($position2 = $this->search(self::$participle[0])) !== false) {
if ( ($this->inRv($position2)) && ($this->checkGroup1($position2)) ) {
$this->word = Utf8::substr($this->word, 0, $position2);
return true;
}
}
if ( ($position2 = $this->search(self::$participle[1])) !== false) {
if ($this->inRv($position2)) {
$this->word = Utf8::substr($this->word, 0, $position2);
return true;
}
}
return true;
}
}
if ( ($position = $this->searchIfInRv(self::$verb[0])) !== false) {
if ( ($this->inRv($position)) && ($this->checkGroup1($position)) ) {
$this->word = Utf8::substr($this->word, 0, $position);
return true;
}
}
if ( ($position = $this->searchIfInRv(self::$verb[1])) !== false) {
if ($this->inRv($position)) {
$this->word = Utf8::substr($this->word, 0, $position);
return true;
}
}
if ( ($position = $this->searchIfInRv(self::$noun)) !== false) {
if ($this->inRv($position)) {
$this->word = Utf8::substr($this->word, 0, $position);
return true;
}
}
return false;
}
|
Step 1: Search for a PERFECTIVE GERUND ending. If one is found remove it, and that is then the end of step 1.
Otherwise try and remove a REFLEXIVE ending, and then search in turn for (1) an ADJECTIVAL, (2) a VERB or (3) a NOUN ending.
As soon as one of the endings (1) to (3) is found remove it, and terminate step 1.
|
entailment
|
public function step2()
{
if ( ($position = $this->searchIfInRv(array('и'))) !== false) {
if ($this->inRv($position)) {
$this->word = Utf8::substr($this->word, 0, $position);
return true;
}
}
return false;
}
|
Step 2: If the word ends with и (i), remove it.
|
entailment
|
public function step3()
{
if ( ($position = $this->searchIfInRv(self::$derivational)) !== false) {
if ($this->inR2($position)) {
$this->word = Utf8::substr($this->word, 0, $position);
return true;
}
}
}
|
Step 3: Search for a DERIVATIONAL ending in R2 (i.e. the entire ending must lie in R2),
and if one is found, remove it.
|
entailment
|
public function step4()
{
// (2) if the word ends with a SUPERLATIVE ending, remove it
if ( ($position = $this->searchIfInRv(self::$superlative)) !== false) {
$this->word = Utf8::substr($this->word, 0, $position);
}
// (1) Undouble н (n)
if ( ($position = $this->searchIfInRv(array('нн'))) !== false) {
$this->word = Utf8::substr($this->word, 0, ($position+1));
return true;
}
// (3) if the word ends ь (') (soft sign) remove it
if ( ($position = $this->searchIfInRv(array('ь'))) !== false) {
$this->word = Utf8::substr($this->word, 0, $position);
return true;
}
}
|
Step 4: (1) Undouble н (n), or, (2) if the word ends with a SUPERLATIVE ending, remove it
and undouble н (n), or (3) if the word ends ь (') (soft sign) remove it.
|
entailment
|
protected function rv()
{
$length = Utf8::strlen($this->word);
$this->rv = '';
$this->rvIndex = $length;
for ($i=0; $i<$length; $i++) {
$letter = Utf8::substr($this->word, $i, 1);
if (in_array($letter, self::$vowels)) {
$this->rv = Utf8::substr($this->word, ($i+1));
$this->rvIndex = $i + 1;
return true;
}
}
return false;
}
|
In any word, RV is the region after the first vowel, or the end of the word if it contains no vowel.
|
entailment
|
private function checkGroup1($position)
{
if (! $this->inRv(($position-1))) {
return false;
}
$letter = Utf8::substr($this->word, ($position - 1), 1);
if ($letter == 'а' || $letter == 'я') {
return true;
}
return false;
}
|
group 1 endings must follow а (a) or я (ia)
@param integer $position
@return boolean
|
entailment
|
public function stem($word)
{
// we do ALL in UTF-8
if (! Utf8::check($word)) {
throw new \Exception('Word must be in UTF-8');
}
$this->plainVowels = implode('', self::$vowels);
$this->word = Utf8::strtolower($word);
// First, replace ß by ss
$this->word = Utf8::str_replace('ß', 'ss', $this->word);
// put u and y between vowels into upper case
$this->word = preg_replace('#(['.$this->plainVowels.'])y(['.$this->plainVowels.'])#u', '$1Y$2', $this->word);
$this->word = preg_replace('#(['.$this->plainVowels.'])u(['.$this->plainVowels.'])#u', '$1U$2', $this->word);
// R1 and R2 are first set up in the standard way
$this->r1();
$this->r2();
// but then R1 is adjusted so that the region before it contains at least 3 letters.
if ($this->r1Index < 3) {
$this->r1Index = 3;
$this->r1 = Utf8::substr($this->word, 3);
}
$this->step1();
$this->step2();
$this->step3();
$this->finish();
return $this->word;
}
|
{@inheritdoc}
|
entailment
|
public function step1()
{
// delete if in R1
if ( ($position = $this->search(array('em', 'ern', 'er'))) !== false) {
if ($this->inR1($position)) {
$this->word = Utf8::substr($this->word, 0, $position);
}
return true;
}
// delete if in R1
if ( ($position = $this->search(array('es', 'en', 'e'))) !== false) {
if ($this->inR1($position)) {
$this->word = Utf8::substr($this->word, 0, $position);
//If an ending of group (b) is deleted, and the ending is preceded by niss, delete the final s
if ($this->search(array('niss')) !== false) {
$this->word = Utf8::substr($this->word, 0, -1);
}
}
return true;
}
// s (preceded by a valid s-ending)
if ( ($position = $this->search(array('s'))) !== false) {
if ($this->inR1($position)) {
$before = $position - 1;
$letter = Utf8::substr($this->word, $before, 1);
if (in_array($letter, self::$sEndings)) {
$this->word = Utf8::substr($this->word, 0, $position);
}
}
return true;
}
return false;
}
|
Step 1
|
entailment
|
public function step2()
{
// en er est
// delete if in R1
if ( ($position = $this->search(array('en', 'er', 'est'))) !== false) {
if ($this->inR1($position)) {
$this->word = Utf8::substr($this->word, 0, $position);
}
return true;
}
// st (preceded by a valid st-ending, itself preceded by at least 3 letters)
// delete if in R1
if ( ($position = $this->search(array('st'))) !== false) {
if ($this->inR1($position)) {
$before = $position - 1;
if ($before >= 3) {
$letter = Utf8::substr($this->word, $before, 1);
if (in_array($letter, self::$stEndings)) {
$this->word = Utf8::substr($this->word, 0, $position);
}
}
}
return true;
}
return false;
}
|
Step 2
|
entailment
|
public function step3()
{
// end ung
// delete if in R2
// if preceded by ig, delete if in R2 and not preceded by e
if ( ($position = $this->search(array('end', 'ung'))) !== false) {
if ($this->inR2($position)) {
$this->word = Utf8::substr($this->word, 0, $position);
}
if ( ($position2 = $this->search(array('ig'))) !== false) {
$before = $position2 - 1;
$letter = Utf8::substr($this->word, $before, 1);
if ( ($this->inR2($position2)) && ($letter != 'e') ) {
$this->word = Utf8::substr($this->word, 0, $position2);
}
}
return true;
}
// ig ik isch
// delete if in R2 and not preceded by e
if ( ($position = $this->search(array('ig', 'ik', 'isch'))) !== false) {
$before = $position - 1;
$letter = Utf8::substr($this->word, $before, 1);
if ( ($this->inR2($position)) && ($letter != 'e') ) {
$this->word = Utf8::substr($this->word, 0, $position);
}
return true;
}
// lich heit
// delete if in R2
// if preceded by er or en, delete if in R1
if ( ($position = $this->search(array('lich', 'heit'))) != false) {
if ($this->inR2($position)) {
$this->word = Utf8::substr($this->word, 0, $position);
}
if ( ($position2 = $this->search(array('er', 'en'))) !== false) {
if ($this->inR1($position2)) {
$this->word = Utf8::substr($this->word, 0, $position2);
}
}
return true;
}
// keit
// delete if in R2
// if preceded by lich or ig, delete if in R2
if ( ($position = $this->search(array('keit'))) != false) {
if ($this->inR2($position)) {
$this->word = Utf8::substr($this->word, 0, $position);
}
if ( ($position2 = $this->search(array('lich', 'ig'))) !== false) {
if ($this->inR2($position2)) {
$this->word = Utf8::substr($this->word, 0, $position2);
}
}
return true;
}
return false;
}
|
Step 3: d-suffixes
|
entailment
|
public function finish()
{
// turn U and Y back into lower case, and remove the umlaut accent from a, o and u.
$this->word = Utf8::str_replace(array('U', 'Y', 'ä', 'ü', 'ö'), array('u', 'y', 'a', 'u', 'o'), $this->word);
}
|
Finally
|
entailment
|
public function stem($word)
{
// we do ALL in UTF-8
if (! Utf8::check($word)) {
throw new \Exception('Word must be in UTF-8');
}
$this->word = Utf8::strtolower($word);
$this->rv();
$this->r1();
$this->r2();
$this->step0();
$word = $this->word;
$this->step1();
// Do step 2a if no ending was removed by step 1.
if ($this->word == $word) {
$this->step2a();
// Do Step 2b if step 2a was done, but failed to remove a suffix.
if ($this->word == $word) {
$this->step2b();
}
}
$this->step3();
$this->finish();
return $this->word;
}
|
{@inheritdoc}
|
entailment
|
private function step0()
{
if ( ($position = $this->searchIfInRv(array('selas', 'selos', 'las', 'los', 'les', 'nos', 'selo', 'sela', 'me', 'se', 'la', 'le', 'lo' ))) != false) {
$suffixe = Utf8::substr($this->word, $position);
// a
$a = array('iéndo', 'ándo', 'ár', 'ér', 'ír');
$a = array_map(function($item) use ($suffixe) {
return $item . $suffixe;
}, $a);
if ( ($position2 = $this->searchIfInRv($a)) !== false) {
$suffixe2 = Utf8::substr($this->word, $position2);
$suffixe2 = Utf8::deaccent($suffixe2, -1);
$this->word = Utf8::substr($this->word, 0, $position2);
$this->word .= $suffixe2;
$this->word = Utf8::substr($this->word, 0, $position);
return true;
}
// b
$b = array('iendo', 'ando', 'ar', 'er', 'ir');
$b = array_map(function($item) use ($suffixe) {
return $item . $suffixe;
}, $b);
if ( ($position2 = $this->searchIfInRv($b)) !== false) {
$this->word = Utf8::substr($this->word, 0, $position);
return true;
}
// c
if ( ($position2 = $this->searchIfInRv(array('yendo' . $suffixe))) != false) {
$before = Utf8::substr($this->word, ($position2-1), 1);
if ( (isset($before)) && ($before == 'u') ) {
$this->word = Utf8::substr($this->word, 0, $position);
return true;
}
}
}
return false;
}
|
Step 0: Attached pronoun
Search for the longest among the following suffixes
me se sela selo selas selos la le lo las les los nos
and delete it, if comes after one of
(a) iéndo ándo ár ér ír
(b) ando iendo ar er ir
(c) yendo following u
in RV. In the case of (c), yendo must lie in RV, but the preceding u can be outside it.
In the case of (a), deletion is followed by removing the acute accent (for example, haciéndola -> haciendo).
|
entailment
|
private function step1()
{
// anza anzas ico ica icos icas ismo ismos able ables ible ibles ista
// istas oso osa osos osas amiento amientos imiento imientos
// delete if in R2
if ( ($position = $this->search(array(
'imientos', 'imiento', 'amientos', 'amiento', 'osas', 'osos', 'osa', 'oso', 'istas', 'ista', 'ibles',
'ible', 'ables', 'able', 'ismos', 'ismo', 'icas', 'icos', 'ica', 'ico', 'anzas', 'anza'))) != false) {
if ($this->inR2($position)) {
$this->word = Utf8::substr($this->word, 0, $position);
}
return true;
}
// adora ador ación adoras adores aciones ante antes ancia ancias
// delete if in R2
// if preceded by ic, delete if in R2
if ( ($position = $this->search(array(
'adoras', 'adora', 'aciones', 'ación', 'adores', 'ador', 'antes', 'ante', 'ancias', 'ancia'))) != false) {
if ($this->inR2($position)) {
$this->word = Utf8::substr($this->word, 0, $position);
}
if ( ($position2 = $this->searchIfInR2(array('ic')))) {
$this->word = Utf8::substr($this->word, 0, $position2);
}
return true;
}
// logía logías
// replace with log if in R2
if ( ($position = $this->search(array('logías', 'logía'))) != false) {
if ($this->inR2($position)) {
$this->word = preg_replace('#(logías|logía)$#u', 'log', $this->word);
}
return true;
}
// ución uciones
// replace with u if in R2
if ( ($position = $this->search(array('uciones', 'ución'))) != false) {
if ($this->inR2($position)) {
$this->word = preg_replace('#(uciones|ución)$#u', 'u', $this->word);
}
return true;
}
// encia encias
// replace with ente if in R2
if ( ($position = $this->search(array('encias', 'encia'))) != false) {
if ($this->inR2($position)) {
$this->word = preg_replace('#(encias|encia)$#u', 'ente', $this->word);
}
return true;
}
// amente
// delete if in R1
// if preceded by iv, delete if in R2 (and if further preceded by at, delete if in R2), otherwise,
// if preceded by os, ic or ad, delete if in R2
if ( ($position = $this->search(array('amente'))) != false) {
// delete if in R1
if ($this->inR1($position)) {
$this->word = Utf8::substr($this->word, 0, $position);
}
// if preceded by iv, delete if in R2 (and if further preceded by at, delete if in R2), otherwise,
if ( ($position2 = $this->searchIfInR2(array('iv'))) !== false) {
$this->word = Utf8::substr($this->word, 0, $position2);
if ( ($position3 = $this->searchIfInR2(array('at'))) !== false) {
$this->word = Utf8::substr($this->word, 0, $position3);
}
// if preceded by os, ic or ad, delete if in R2
} elseif ( ($position4 = $this->searchIfInR2(array('os', 'ic', 'ad'))) != false) {
$this->word = Utf8::substr($this->word, 0, $position4);
}
return true;
}
// mente
// delete if in R2
// if preceded by ante, able or ible, delete if in R2
if ( ($position = $this->search(array('mente'))) != false) {
// delete if in R2
if ($this->inR2($position)) {
$this->word = Utf8::substr($this->word, 0, $position);
}
// if preceded by ante, able or ible, delete if in R2
if ( ($position2 = $this->searchIfInR2(array('ante', 'able', 'ible'))) != false) {
$this->word = Utf8::substr($this->word, 0, $position2);
}
return true;
}
// idad idades
// delete if in R2
// if preceded by abil, ic or iv, delete if in R2
if ( ($position = $this->search(array('idades', 'idad'))) != false) {
// delete if in R2
if ($this->inR2($position)) {
$this->word = Utf8::substr($this->word, 0, $position);
}
// if preceded by abil, ic or iv, delete if in R2
if ( ($position2 = $this->searchIfInR2(array('abil', 'ic', 'iv'))) != false) {
$this->word = Utf8::substr($this->word, 0, $position2);
}
return true;
}
// iva ivo ivas ivos
// delete if in R2
// if preceded by at, delete if in R2
if ( ($position = $this->search(array('ivas', 'ivos', 'iva', 'ivo'))) != false) {
// delete if in R2
if ($this->inR2($position)) {
$this->word = Utf8::substr($this->word, 0, $position);
}
// if preceded by at, delete if in R2
if ( ($position2 = $this->searchIfInR2(array('at'))) != false) {
$this->word = Utf8::substr($this->word, 0, $position2);
}
return true;
}
return false;
}
|
Step 1
|
entailment
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.