Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Develop #1

Open
wants to merge 9 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion .travis.yml
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ cache:
install:
- travis_retry composer self-update
- travis_retry composer clear-cache
- travis_retry composer global require "codeception/codeception:2.0.*@dev"
- travis_retry composer global require "codeception/codeception"
- travis_retry composer global require "fxp/composer-asset-plugin:~1.0"
- travis_retry composer install --prefer-dist

Expand Down
4 changes: 2 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ Configure `Manager` component
return [
'components' => [
'attachmentManager' => [
'class' => 'artkost\attachment\Manager',
'class' => 'artkost\yii2\attachment\Manager',
'storageUrl' => '@web/storage',
'storagePath' => '@webroot/storage',
'attachmentFileTable' => '{{%attachment_file}}'
Expand All @@ -32,7 +32,7 @@ Create your own type of file
```php
namespace app\modules\user\models;

use artkost\attachment\models\ImageFile;
use artkost\yii2\attachment\models\ImageFile;

class UserAvatarFile extends ImageFile
{
Expand Down
4 changes: 2 additions & 2 deletions composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -26,10 +26,10 @@
},
"autoload": {
"psr-4": {
"artkost\\attachment\\": ""
"artkost\\yii2\\attachment\\": "src"
}
},
"extra": {
"bootstrap": "artkost\\attachment\\Bootstrap"
"bootstrap": "artkost\\yii2\\attachment\\Bootstrap"
}
}
4 changes: 2 additions & 2 deletions Action.php → src/Action.php
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
<?php

namespace artkost\attachment;
namespace artkost\yii2\attachment;

use artkost\attachment\models\AttachmentFile;
use artkost\yii2\attachment\models\AttachmentFile;
use Yii;
use yii\base\InvalidConfigException;

Expand Down
9 changes: 7 additions & 2 deletions Bootstrap.php → src/Bootstrap.php
Original file line number Diff line number Diff line change
@@ -1,8 +1,9 @@
<?php

namespace artkost\attachment;
namespace artkost\yii2\attachment;

use yii\base\BootstrapInterface;
use yii\base\InvalidConfigException;

class Bootstrap implements BootstrapInterface
{
Expand All @@ -13,11 +14,15 @@ public function bootstrap($app)
{
$app->i18n->translations['attachment/*'] = [
'class' => 'yii\i18n\PhpMessageSource',
'basePath' => __DIR__,
'basePath' => __DIR__ . '/messages',
'forceTranslation' => true,
'fileMap' => [
'attachment/model' => 'model.php',
]
];

if (!$app->has('attachmentManager')) {
throw new InvalidConfigException("'attachmentManager' component not defined");
}
}
}
93 changes: 74 additions & 19 deletions Manager.php → src/Manager.php
Original file line number Diff line number Diff line change
@@ -1,10 +1,12 @@
<?php

namespace artkost\attachment;
namespace artkost\yii2\attachment;

use Yii;
use yii\base\Component;
use yii\base\InvalidConfigException;
use yii\db\ActiveQueryInterface;
use yii\db\ActiveRecord;
use yii\helpers\FileHelper;
use yii\web\UploadedFile;

Expand Down Expand Up @@ -47,21 +49,9 @@ public function init()
{
parent::init();

$this->createDirectory($this->storagePath);
$this->createDirectory($this->tempPath);
}

/**
* Ensure or create a folder
* @param $path
* @throws InvalidConfigException
* @throws \yii\base\Exception
*/
public function createDirectory($path)
{
if (!FileHelper::createDirectory($path)) {
throw new InvalidConfigException("Directory {$path} doesn't exist or cannot be created.");
}
$this
->createDirectory($this->storagePath)
->createDirectory($this->tempPath);
}

/**
Expand Down Expand Up @@ -100,7 +90,7 @@ public static function t($category, $message, $params = [], $language = null)
*/
public static function getInstance()
{
return Yii::$app->attachmentManager;
return Yii::$app->get('attachmentManager');
}

/**
Expand All @@ -119,13 +109,33 @@ public static function getUploadedFiles()
return UploadedFile::getInstancesByName(self::PARAM_NAME);
}

public function addAttachmentModel($ownerClass, $attribute, $config)
/**
* @param $owner
* @param $attribute
* @param $config
* @return mixed
* @throws InvalidConfigException
*/
public function addAttachmentModel($owner, $attribute, $config)
{
$ownerClass = get_class($owner);
$name = $ownerClass . $attribute;

return $this->modelsInstances[$name] = Yii::createObject($config);
if (!isset($this->modelsInstances[$name])) {
$this->modelsInstances[$name] = Yii::createObject($config);

$this->checkOwnerRelationExistence($owner, $attribute);
}

return $this->modelsInstances[$name];
}

/**
* @param $ownerClass
* @param $attribute
* @return null
* @throws InvalidConfigException
*/
public function getAttachmentModel($ownerClass, $attribute)
{
$name = $ownerClass . $attribute;
Expand All @@ -142,6 +152,22 @@ public function getAttachmentModel($ownerClass, $attribute)
return $this->modelsInstances[$name];
}

/**
* Ensure or create a folder
* @param $path
* @throws InvalidConfigException
* @throws \yii\base\Exception
* @return self
*/
public function createDirectory($path)
{
if (!FileHelper::createDirectory(Yii::getAlias($path))) {
throw new InvalidConfigException("Directory {$path} doesn't exist or cannot be created.");
}

return $this;
}

/**
* @return string
*/
Expand All @@ -165,4 +191,33 @@ public function getTempPath()
{
return FileHelper::normalizePath(Yii::getAlias($this->tempPath)) . DIRECTORY_SEPARATOR;
}

/**
* Check if relation with given name exists in owner model
* @param ActiveRecord $owner
* @param $attribute
* @throws InvalidConfigException
*/
protected function checkOwnerRelationExistence($owner, $attribute)
{
$getter = 'get' . ucfirst($attribute);
$class = get_class($owner);

if (method_exists($owner, $getter)) {
$owner->attachBehaviors($owner->behaviors());
/** @var ActiveQueryInterface $value */
$value = $owner->$getter();

if (!($value instanceof ActiveQueryInterface)) {
throw new InvalidConfigException("Value of relation '$getter' not valid");
}

$config = $owner->getAttachmentConfig($attribute);
$config['multiple'] = $value->multiple;

$owner->setAttachmentConfig($attribute, $config);
} else {
throw new InvalidConfigException("Relation '$class::$getter' for attribute '$attribute' does not exists");
}
}
}
106 changes: 63 additions & 43 deletions behaviors/AttachBehavior.php → src/behaviors/AttachBehavior.php
Original file line number Diff line number Diff line change
@@ -1,17 +1,14 @@
<?php

namespace artkost\attachment\behaviors;
namespace artkost\yii2\attachment\behaviors;

use artkost\attachment\Manager;
use artkost\attachment\models\AttachmentFile;
use Yii;
use artkost\yii2\attachment\Manager;
use artkost\yii2\attachment\models\AttachmentFile;
use yii\base\Behavior;
use yii\base\InvalidConfigException;
use yii\base\InvalidParamException;
use yii\db\ActiveQuery;
use yii\db\ActiveQueryInterface;
use yii\db\ActiveRecord;
use yii\helpers\Html;
use yii\web\IdentityInterface;

/**
* Class AttachBehavior
Expand All @@ -31,6 +28,13 @@ class AttachBehavior extends Behavior
* @var array Models instance config
*/
public $models = [];
protected $manager;

public function __construct(Manager $manager, $config = [])
{
$this->manager = $manager;
parent::__construct($config);
}

/**
* @inheritdoc
Expand All @@ -40,12 +44,10 @@ public function attach($owner)
parent::attach($owner);

if (!is_array($this->models) || empty($this->models)) {
throw new InvalidParamException('Invalid or empty models array.');
throw new InvalidParamException('AttachBehavior::models attribute is required and must be an array.');
} else {
foreach ($this->models as $relationName => $config) {
Manager::getInstance()->addAttachmentModel($this->owner, $relationName, $config);

$this->checkRelationExistence($relationName);
$this->manager->addAttachmentModel($this->owner, $relationName, $config);
}
}
}
Expand All @@ -63,6 +65,7 @@ public function events()
}

/**
* Get attachment model config by attribute
* @param $attribute
* @return null|array
*/
Expand All @@ -71,6 +74,25 @@ public function getAttachmentConfig($attribute)
return isset($this->models[$attribute]) ? $this->models[$attribute] : null;
}

/*
* set attachment model config by attribute for this owner
*/
public function setAttachmentConfig($attribute, array $config)
{
if (isset($this->models[$attribute])) {
$this->models[$attribute] = $config;
}
}

/**
* @param $attribute
* @return AttachmentFile
*/
public function getAttachmentModel($attribute)
{
return Manager::getInstance()->getAttachmentModel(get_class($this->owner), $attribute);
}

/**
* @param string $name
* @return mixed|null
Expand Down Expand Up @@ -112,53 +134,51 @@ protected function markFilesAsTemporary($values)
}

/**
* Check if relation with given name exists in model
* @param $name
* @throws InvalidConfigException
* Helper method for define attachment relations
* @param string $class
* @param array $link
* @param int $status
* @return static
*/
protected function checkRelationExistence($name)
public function hasOneAttachment($class, $link, $status = AttachmentFile::STATUS_PERMANENT)
{
$getter = 'get' . ucfirst($name);
$class = get_class($this->owner);
$class = isset($this->models[$class]) ? $this->models[$class]['class'] : $class;

if (method_exists($this->owner, $getter)) {
/** @var ActiveQuery $value */
$value = $this->owner->$getter();

if (!($value instanceof ActiveQueryInterface)) {
throw new InvalidConfigException("Value of relation '$getter' not valid");
}

$this->models[$name]['multiple'] = $value->multiple;
} else {
throw new InvalidConfigException("Relation '$class::$getter' for attribute '$name' does not exists");
}
return $this->owner->hasOne($class, $link)
->andWhere(['type' => $class::TYPE, 'status_id' => $status]);
}

/**
* Helper method for define attachment relations
* @param $class
* @param $link
* @param bool $status
* @param string $class full class
* @param array $link
* @param int $status
* @return static
*/
public function hasOneAttachment($class, $link, $status = false)
public function hasManyAttachments($class, $link, $status = AttachmentFile::STATUS_PERMANENT)
{
return $this->owner->hasOne($class, $link)
->andWhere(['type' => $class::type(), 'status_id' => $class::STATUS_PERMANENT]);
$class = isset($this->models[$class]) ? $this->models[$class]['class'] : $class;

return $this->owner->hasMany($class, $link)
->andWhere(['type' => $class::TYPE, 'status_id' => $status]);
}

/**
* Helper method for define attachment relations
* @param $class
* @param $link
* @param bool $status
* @return static
* Attaches file to owner model as attribute and saves it
* @param $attribute
* @param IdentityInterface $user
* @return bool
*/
public function hasManyAttachments($class, $link, $status = false)
public function attachFile($attribute, IdentityInterface $user)
{
return $this->owner->hasMany($class, $link)
->andWhere(['type' => $class::type(), 'status_id' => $class::STATUS_PERMANENT]);
$file = Manager::getUploadedFile();
$model = $this->getAttachmentModel($attribute);

if ($model && $file) {
$model->setFile($file)->setUser($user)->save();
}

return false;
}

/**
Expand Down
Loading