Generate a slug from the given source string.

@param string $source
@param array $config
@param string $attribute

@return string
@throws \UnexpectedValueException
771928
protected function generateSlug(string $source, array $config, string $attribute): string
    {
        $separator = $config['separator'];
        $method = $config['method'];
        $maxLength = $config['maxLength'];
        $maxLengthKeepWords = $config['maxLengthKeepWords'];

        if ($method === null) {
            $slugEngine = $this->getSlugEngine($attribute);
            $slug = $slugEngine->slugify($source, $separator);
        } elseif (is_callable($method)) {
            $slug = call_user_func($method, $source, $separator);
        } else {
            throw new \UnexpectedValueException('Sluggable "method" for ' . get_class($this->model) . ':' . $attribute . ' is not callable nor null.');
        }

        $len = mb_strlen($slug);
        if (is_string($slug) && $maxLength && $len > $maxLength) {
            $reverseOffset = $maxLength - $len;
            $lastSeparatorPos = mb_strrpos($slug, $separator, $reverseOffset);
            if ($maxLengthKeepWords && $lastSeparatorPos !== false) {
                $slug = mb_substr($slug, 0, $lastSeparatorPos);
            } else {
                $slug = trim(mb_substr($slug, 0, $maxLength), $separator);
            }
        }

        return $slug;
    }
661450
protected function unserialize($source)
    {
        $source = base64_decode($source);
        $result = @unserialize($source);
        if ($result === false && $source !== serialize(false)) {
            throw new \UnexpectedValueException();
        }
        return $result;
    }
268821
public function generate(Config $config)
    {
        $parts = array();
        if ($config->parent) {
            $parent = $config->parent->isRepresentant() ? $config->parent->parent : $config->parent;
            $parts[] = $this->generate($parent);
        }

        $parts[] = $this->getPrefix($config);

        return implode('_', array_filter($parts));
    }
49112
protected function escapeAttributeValues($source)
    {
        $alreadyFiltered = '';
        $remainder = $source;
        $badChars = ['<', '"', '>'];
        $escapedChars = ['&lt;', '&quot;', '&gt;'];

        // Process each portion based on presence of =" and "<space>, "/>, or ">
        // See if there are any more attributes to process
        while (preg_match('#<[^>]*?=\s*?(\"|\')#s', (string) $remainder, $matches, PREG_OFFSET_CAPTURE)) {
            // Get the portion before the attribute value
            $quotePosition = $matches[0][1];
            $nextBefore = $quotePosition + strlen($matches[0][0]);

            // Figure out if we have a single or double quote and look for the matching closing quote
            // Closing quote should be "/>, ">, "<space>, or " at the end of the string
            $quote = substr($matches[0][0], -1);
            $pregMatch = ($quote === '"') ? '#(\"\s*/\s*>|\"\s*>|\"\s+|\"$)#' : "#(\'\s*/\s*>|\'\s*>|\'\s+|\'$)#";

            // Get the portion after attribute value
            if (preg_match($pregMatch, substr($remainder, $nextBefore), $matches, PREG_OFFSET_CAPTURE)) {
                // We have a closing quote
                $nextAfter = $nextBefore + $matches[0][1];
            } else {
                // No closing quote
                $nextAfter = strlen($remainder);
            }

            // Get the actual attribute value
            $attributeValue = substr($remainder, $nextBefore, $nextAfter - $nextBefore);

            // Escape bad chars
            $attributeValue = str_replace($badChars, $escapedChars, $attributeValue);
            $attributeValue = $this->stripCssExpressions($attributeValue);
            $alreadyFiltered .= substr($remainder, 0, $nextBefore) . $attributeValue . $quote;
            $remainder = substr($remainder, $nextAfter + 1);
        }

        // At this point, we just have to return the $alreadyFiltered and the $remainder
        return $alreadyFiltered . $remainder;
    }
497720
public function move(Config $source) {
		$files = $_FILES[$source->defaultFilesKey];
		/**
		 * @var $output File[]
		 */
		$output = [];

		try {
			if (isset($files) and is_array($files) and isset($files['name']) and is_array($files['name']) and count($files['name'])) {
				foreach ($files['name'] as $i => $file) {
					if ($files['error'][$i]) {
						throw new \Exception(isset(Helper::$upload_errors[$files['error'][$i]]) ? Helper::$upload_errors[$files['error'][$i]] : 'Error', $files['error'][$i]);
					}

					$path     = $source->getPath();
					$tmp_name = $files['tmp_name'][$i];
					$new_path = $path . Helper::makeSafe($files['name'][$i]);

					if (!move_uploaded_file($tmp_name, $new_path)) {
						if (!is_writable($path)) {
							throw new \Exception('Destination directory is not writeble', Consts::ERROR_CODE_IS_NOT_WRITEBLE);
						}

						throw new \Exception('No files have been uploaded', Consts::ERROR_CODE_NO_FILES_UPLOADED);
					}

					$file = new File($new_path);

					try {
						$this->accessControl->checkPermission($this->getUserRole(), $this->action, $source->getRoot(), pathinfo($file->getPath(), PATHINFO_EXTENSION));
					} catch (\Exception $e) {
						$file->remove();
						throw $e;
					}

					if (!$file->isGoodFile($source)) {
						$file->remove();
						throw new \Exception('File type is not in white list', Consts::ERROR_CODE_FORBIDDEN);
					}

					if ($source->maxFileSize and $file->getSize() > Helper::convertToBytes($source->maxFileSize)) {
						$file->remove();
						throw new \Exception('File size exceeds the allowable', Consts::ERROR_CODE_FORBIDDEN);
					}

					$output[] = $file;
				}
			}
		} catch (\Exception $e) {
			foreach ($output as $file) {
				$file->remove();
			}
			throw $e;
		}

		return $output;
	}
466309
public static function removeValue(array $config, string $configPath): array
    {
        if (!is_string($configPath) || $configPath === '') {
            throw new InvalidArgumentException('Path must be not be empty string', 1496759385);
        }
        // Extract parts of the path
        $path = str_getcsv($configPath, '.');
        $pathDepth = count($path);
        $currentDepth = 0;
        $pointer = &$config;
        // Find path in given array
        foreach ($path as $segment) {
            $currentDepth++;
            // Fail if the part is empty
            if ($segment === '') {
                throw new InvalidArgumentException('Invalid path segment specified', 1496759389);
            }
            if (!array_key_exists($segment, $pointer)) {
                throw new PathDoesNotExistException(sprintf('Path "%s" does not exist in array (tried removing)', $configPath), 1496759405);
            }
            if ($currentDepth === $pathDepth) {
                unset($pointer[$segment]);
            } else {
                $pointer = &$pointer[$segment];
            }
        }

        return $config;
    }
1172482
public function scopeFindSimilarSlugs(Builder $query, string $attribute, array $config, string $slug): Builder
    {
        $separator = $config['separator'];

        return $query->where(function(Builder $q) use ($attribute, $slug, $separator) {
            $q->where($attribute, '=', $slug)
                ->orWhere($attribute, 'LIKE', $slug . $separator . '%');
        });
    }
468398
protected function escapeAttributeValues($source)
	{
		$alreadyFiltered = '';
		$remainder       = $source;
		$badChars        = array('<', '"', '>');
		$escapedChars    = array('&lt;', '&quot;', '&gt;');

		// Process each portion based on presence of =" and "<space>, "/>, or ">
		// See if there are any more attributes to process
		while (preg_match('#<[^>]*?=\s*?(\"|\')#s', $remainder, $matches, PREG_OFFSET_CAPTURE))
		{
			// We have found a tag with an attribute, convert its byte position to a UTF-8 string length, using non-multibyte substr()
			$stringBeforeTag = substr($remainder, 0, $matches[0][1]);
			$tagPosition     = StringHelper::strlen($stringBeforeTag);

			// Get the character length before the attribute value
			$nextBefore = $tagPosition + StringHelper::strlen($matches[0][0]);

			// Figure out if we have a single or double quote and look for the matching closing quote
			// Closing quote should be "/>, ">, "<space>, or " at the end of the string
			$quote     = StringHelper::substr($matches[0][0], -1);
			$pregMatch = ($quote == '"') ? '#(\"\s*/\s*>|\"\s*>|\"\s+|\"$)#' : "#(\'\s*/\s*>|\'\s*>|\'\s+|\'$)#";

			// Get the portion after attribute value
			$attributeValueRemainder = StringHelper::substr($remainder, $nextBefore);

			if (preg_match($pregMatch, $attributeValueRemainder, $matches, PREG_OFFSET_CAPTURE))
			{
				// We have a closing quote, convert its byte position to a UTF-8 string length, using non-multibyte substr()
				$stringBeforeQuote = substr($attributeValueRemainder, 0, $matches[0][1]);
				$closeQuoteChars   = StringHelper::strlen($stringBeforeQuote);
				$nextAfter         = $nextBefore + $matches[0][1];
			}
			else
			{
				// No closing quote
				$nextAfter = StringHelper::strlen($remainder);
			}

			// Get the actual attribute value
			$attributeValue = StringHelper::substr($remainder, $nextBefore, $nextAfter - $nextBefore);

			// Escape bad chars
			$attributeValue = str_replace($badChars, $escapedChars, $attributeValue);
			$attributeValue = $this->stripCssExpressions($attributeValue);
			$alreadyFiltered .= StringHelper::substr($remainder, 0, $nextBefore) . $attributeValue . $quote;
			$remainder = StringHelper::substr($remainder, $nextAfter + 1);
		}

		// At this point, we just have to return the $alreadyFiltered and the $remainder
		return $alreadyFiltered . $remainder;
	}
370362
public function inline($source, $attributes = [], $secure = null)
    {

        return '<script type="text/javascript" ' . $this->attributes($attributes) . '>' . $source . '</script>' . PHP_EOL;
    }
1188084
protected function checkConfig(array $config)
    {
        if (!isset($config['dataSource']) || !is_array($config['dataSource'])) {
            throw new UnexpectedValueException($this->translate(
                'Information about data source in metadata configuration should be an array or Traversable.'
            ));
        }
        if (!isset($config['types']) || !is_array($config['types'])) {
            throw new UnexpectedValueException($this->translate(
                'Information about types in metadata configuration should be an array or Traversable.'
            ));
        }
        if (!isset($config['fields']) || !is_array($config['fields'])) {
            throw new UnexpectedValueException($this->translate(
                'Information about fields in metadata configuration should be an array or Traversable.'
            ));
        }
    }
758354
protected function createXmlResponse(array $data, array $config)
    {
        if (! \is_null($root = $config['root'] ?? null)) {
            $data = $data[$root] ?? [];
        }

        if ($data instanceof Arrayable) {
            $data = $data->toArray();
        }

        $data = \array_map([$this, 'transformToArray'], $data);

        return function () use ($data, $config) {
            return ArrayToXml::convert($data, $config['document-root'] ?? $root);
        };
    }
466326
public function updateBySlug(array $attributes, $slug)
    {
        $album = $this->findBySlug($slug);

        return $this->update($attributes, $album->id);
    }
6153
public static function generateNameValueList( $config = [] ) {

		$modelClass	= static::$modelClass;
		$modelTable = $modelClass::tableName();

		$site	= Yii::$app->core->site;
		$theme	= $site->theme;

		$config[ 'ignoreSite' ] = true;

		$config[ 'conditions' ][] = isset( $theme ) ? "$modelTable.themeId={$theme->id} OR $modelTable.siteId={$site->id} OR ($modelTable.themeId IS NULL AND $modelTable.siteId IS NULL)" : "$modelTable.siteId={$site->id} OR ($modelTable.themeId IS NULL AND $modelTable.siteId IS NULL)";

		return parent::generateNameValueList( $config );
	}
95093
public function get_slug( $config_name, $suffix = '-' ) {
		if ( ! isset( self::$_slugs[ $this->app->plugin_name ][ $config_name ] ) ) {
			$default = $this->app->slug_name . $suffix;
			$slug    = $this->app->get_config( 'slug', $config_name, $default );
			if ( empty( $slug ) ) {
				$slug = $default;
			}
			self::$_slugs[ $this->app->plugin_name ][ $config_name ] = $slug;
		}

		return self::$_slugs[ $this->app->plugin_name ][ $config_name ];
	}
1319584
public function to(string $content, $url, array $attributes = []) : string
    {
        return $this->create($content, $url, $attributes);
    }
545434
public function handle(Config $config)
    {
        $sampleOption = $this->option('sample');

        $type = 'empty';
        if( $sampleOption )
        {
            $type = 'sample';
        }

        $from = __DIR__ . '/../../resources/'.$type.'_schema.xml';
        $to = $config->get('propel.propel.paths.schemaDir') . '/' . $config->get('propel.propel.generator.schema.basename') . '.xml';

        if( ! copy($from, $to) )
        {
            throw new \Exception('Failed to copy a file "' . $from . '" to "' . $to . '"');
        }

        $content = file_get_contents($to);

        $name = $config->get('propel.propel.generator.defaultConnection');
        $content = str_replace('**NAME**', $name, $content);

        $nameSpace = $this->laravel->getNamespace() . str_replace(app_path().DIRECTORY_SEPARATOR, '', $config->get('propel.propel.paths.phpDir'));
        $content = str_replace('**NAMESPACE**', $nameSpace, $content);

        file_put_contents($to, $content);

        $this->comment(PHP_EOL . 'Create ' . $to . PHP_EOL);
    }
1371021
public function makeFiles($input, array $attributes = array(), array $config = array()) {
		$files = array();
		$uploads = hypeApps()->uploader->handle($input, $attributes, $config);
		foreach ($uploads as $upload) {
			if ($upload->file instanceof \ElggEntity) {
				$files[] = $upload->file;
			}
		}
		return $files;
	}