public const STATUS_DELETED = 1;// 0b0001
public const STATUS_INACTIVE = 2;// 0b0010
public const STATUS_ACTIVE = 4;// 0b0100
public const STATUS_LOCKED = 8;// 0b1000
public function validateStatus(string $attribute, array $params): void
{
$validFlags = self::STATUS_DELETED | self::STATUS_INACTIVE | self::STATUS_ACTIVE |
self::STATUS_LOCKED;
// If any bit outside validFlags is set, invalid
if (($this->$attribute & ~$validFlags) !== 0)
{
$this->addError($attribute, 'Status contains invalid flags.');
return;
}
// Deleted must be exclusive (only DELETED bit set)
if ($this->isDeleted() && $this->status !== self::STATUS_DELETED)
{
$this->addError($attribute, 'Deleted user cannot have other statuses.');
}
// Active and Inactive cannot coexist
if ($this->isActive() && $this->isInactive())
{
$this->addError($attribute, 'User cannot be both active and inactive.');
}
}
public function getStatusForCheckboxes(): array
{
$activeOptions = [];
// Active
if ($this->hasStatus(self::STATUS_ACTIVE))
{
$activeOptions[] = self::STATUS_ACTIVE;
}
// Inactive
if ($this->hasStatus(self::STATUS_INACTIVE))
{
$activeOptions[] = self::STATUS_INACTIVE;
}
// Locked
if ($this->hasStatus(self::STATUS_LOCKED))
{
$activeOptions[] = self::STATUS_LOCKED;
}
// Deleted
if ($this->hasStatus(self::STATUS_DELETED))
{
$activeOptions[] = self::STATUS_DELETED;
}
return $activeOptions;
}
Active
Active & Locked
Inactive
Inactive & Locked
Deleted
Assistant
Your code implements bit flags to represent user statuses, where each status corresponds to a specific bit:
STATUS_DELETED = 1 (0b0001)
STATUS_INACTIVE = 2 (0b0010)
STATUS_ACTIVE = 4 (0b0100)
STATUS_LOCKED = 8 (0b1000)
You've also put in place some validation rules:
The status bits must not include any bits outside these defined flags.
If the user is deleted, only the deleted flag must be set (exclusive).
The user cannot be both active and inactive at the same time.
Regarding your list of status cases:
Active
Active & Locked
Inactive
Inactive & Locked
Deleted
How these are represented internally:
Using bitwise OR to combine statuses:
Status
Bit Value
Binary
Active
4
0b0100
Locked
8
0b1000
Active & Locked
12
0b1100 (4
Inactive
2
0b0010
Inactive & Locked
10
0b1010 (2
Deleted
1
0b0001
What your validation enforces:
You can combine Active or Inactive with Locked (as the Locked bit is independent).
You cannot combine Deleted with any other status bits.
You cannot have both Active & Inactive bits set simultaneously.
Your code and rules allow all your listed status combinations, except combining Deleted with anything else or having active+inactive at the same time.
If you want, I can help you write tests or functions to easily generate or validate these states. Just ask!
User
make this work according:
code
public function getStatusForCheckboxes(): array
{
$activeOptions = [];
// Active
if ($this->hasStatus(self::STATUS_ACTIVE))
{
$activeOptions[] = self::STATUS_ACTIVE;
}
// Inactive
if ($this->hasStatus(self::STATUS_INACTIVE))
{
$activeOptions[] = self::STATUS_INACTIVE;
}
// Locked
if ($this->hasStatus(self::STATUS_LOCKED))
{
$activeOptions[] = self::STATUS_LOCKED;
}
// Deleted
if ($this->hasStatus(self::STATUS_DELETED))
{
$activeOptions[] = self::STATUS_DELETED;
}
return $activeOptions;
}
Assistant
To make your getStatusForCheckboxes() method work correctly given the status bits and your rules, the key is that your hasStatus() method should correctly check whether each relevant bit is set.
Assuming you have a hasStatus(int $flag): bool implemented like this:
php
public function hasStatus(int $flag): bool
{
return ($this->status & $flag) === $flag;
}
Then your current method will work as is, returning an array of active status flags from the status value.
Full example including hasStatus():
php
public function hasStatus(int $flag): bool
{
return ($this->status & $flag) === $flag;
}
public function getStatusForCheckboxes(): array
{
$activeOptions = [];
if ($this->hasStatus(self::STATUS_ACTIVE))
{
$activeOptions[] = self::STATUS_ACTIVE;
}
if ($this->hasStatus(self::STATUS_INACTIVE))
{
$activeOptions[] = self::STATUS_INACTIVE;
}
if ($this->hasStatus(self::STATUS_LOCKED))
{
$activeOptions[] = self::STATUS_LOCKED;
}
if ($this->hasStatus(self::STATUS_DELETED))
{
$activeOptions[] = self::STATUS_DELETED;
}
return $activeOptions;
}
Notes:
You can keep the order of checking as you wish.
This will correctly return all status bits that are set in your $this->status attribute.
Ensure $this->status is properly set beforehand as the combined bit flags.
Example usage:
php
$this->status = self::STATUS_ACTIVE | self::STATUS_LOCKED; // 0b1100
$options = $this->getStatusForCheckboxes();
// $options will be [4, 8] corresponding to active and locked.
If for some reason hasStatus() doesn’t exist or works differently, make sure you implement it as above or substitute the bitwise check directly in getStatusForCheckboxes():
Let me know if you want me to help you implement the full class with this logic or to improve the code further!
User
code
public function hasStatus(int $flag): bool
{
return ($this->status & $flag) === $flag;
}
public function getStatusForCheckboxes(): array
{
$activeOptions = [];
if ($this->hasStatus(self::STATUS_ACTIVE))
{
$activeOptions[] = self::STATUS_ACTIVE;
}
if ($this->hasStatus(self::STATUS_INACTIVE))
{
$activeOptions[] = self::STATUS_INACTIVE;
}
if ($this->hasStatus(self::STATUS_LOCKED))
{
$activeOptions[] = self::STATUS_LOCKED;
}
if ($this->hasStatus(self::STATUS_DELETED))
{
$activeOptions[] = self::STATUS_DELETED;
}
return $activeOptions;
}
Is it setup to work like:
Active
Active & Locked
Inactive
Inactive & Locked
Deleted
Assistant
Yes, your current setup is ready to handle these combinations:
Active
Active & Locked
Inactive
Inactive & Locked
Deleted
Why it works:
Your hasStatus() checks whether the bit(s) represented by $flag exist in $this->status using bitwise AND:
php
($this->status & $flag) === $flag
So for example:
If $this->status == STATUS_ACTIVE | STATUS_LOCKED (4 | 8 = 12), then
hasStatus(STATUS_ACTIVE) returns true since 12 & 4 === 4.
hasStatus(STATUS_LOCKED) returns true since 12 & 8 === 8.
Similarly for STATUS_INACTIVE combined with STATUS_LOCKED.
If $this->status == STATUS_DELETED (1), only that flag is set.
Key points:
Multiple flags combined:hasStatus() will correctly identify each individual flag.
Deleted is exclusive by your validation: So if STATUS_DELETED is set, other flags should not be set (validation logic enforces this). Your method will just check anyway, but the validation prevents invalid combinations.
You return an array of all flags present in the current status value, exactly as your examples require.
Summary:
The code you provided for hasStatus() and getStatusForCheckboxes() fully supports all your intended status combinations and will correctly return the active flags.
If you'd like, I can help you add some unit tests or example calls to illustrate or verify this behavior!
User
I want you to recode this:
public function hasStatus(int flag): bool
{
return (this->status & flag)===flag;
}
public function getStatusForCheckboxes(): array
{
$activeOptions = [];
code
if ($this->hasStatus(self::STATUS_ACTIVE))
{
$activeOptions[] = self::STATUS_ACTIVE;
}
if ($this->hasStatus(self::STATUS_INACTIVE))
{
$activeOptions[] = self::STATUS_INACTIVE;
}
if ($this->hasStatus(self::STATUS_LOCKED))
{
$activeOptions[] = self::STATUS_LOCKED;
}
if ($this->hasStatus(self::STATUS_DELETED))
{
$activeOptions[] = self::STATUS_DELETED;
}
return $activeOptions;
}
to work like so:
code
Active
Active & Locked
Inactive
Inactive & Locked
Deleted
Assistant
Got it! You want to refactor your hasStatus() and getStatusForCheckboxes() so that it only produces exactly these valid status combinations and no others:
Active
Active & Locked
Inactive
Inactive & Locked
Deleted (always exclusive)
What this means:
If Deleted is set, return only [Deleted].
If Active is set (and not Deleted), then return [Active] or [Active, Locked].
If Inactive is set (and not Deleted), then return [Inactive] or [Inactive, Locked].
No mixing Active & Inactive.
Locked can only appear paired with Active or Inactive.
Here is the recoded version:
php
public function getStatusForCheckboxes(): array
{
$activeOptions = [];
// Deleted is exclusive - if set, return Deleted only
if ($this->hasStatus(self::STATUS_DELETED)) {
return [self::STATUS_DELETED];
}
// Only one of Active or Inactive can be set (validation enforces this)
if ($this->hasStatus(self::STATUS_ACTIVE)) {
$activeOptions[] = self::STATUS_ACTIVE;
// Locked can appear with Active
if ($this->hasStatus(self::STATUS_LOCKED)) {
$activeOptions[] = self::STATUS_LOCKED;
}
return $activeOptions;
}
if ($this->hasStatus(self::STATUS_INACTIVE)) {
$activeOptions[] = self::STATUS_INACTIVE;
// Locked can also appear with Inactive
if ($this->hasStatus(self::STATUS_LOCKED)) {
$activeOptions[] = self::STATUS_LOCKED;
}
return $activeOptions;
}
// If none of the above status bits are set, return empty array
// or you can choose to return null or throw an error based on your use case
return [];
}
public function hasStatus(int $flag): bool
{
return ($this->status & $flag) === $flag;
}
User
code
Assistant
Your class looks well-structured and your bitflag logic, validation, getters/setters, and status helpers are consistent and solidly cover the intended behaviors. Below is a detailed review with some comments and suggestions for improvements or clarifications.
What looks good:
Using bitwise flags correctly and consistently.
Validation rule validateStatus properly ensures:
Only valid bits are used.
Deleted status is exclusive.
Active and Inactive can't coexist.
hasStatus, addStatus, and removeStatus are implemented correctly.
getStatusForCheckboxes() enforces the exclusivity of Deleted and allows Locked combined with Active or Inactive.
Clear methods for isDeleted, isInactive, etc. improve readability.
Helper setters like activateAccount(), etc. correctly manage mutually exclusive flags.
Using constants for all flags is good practice.
The rules() method suggests usage in a Yii2 framework environment and looks good.
Suggestions and observations:
getStatusLabel() — multiple statuses returned as a string:
This returns a comma-separated string of all matched statuses with no exclusivity check.
This is fine, but consider:
If the status is deleted, it returns just "Deleted", but if deleted is combined with others (ideally shouldn't happen), it will list them all, too.
You might want to add an explicit check for deleted here or rely on validation only (which you do).
getStatusList() method
php
return $statuses[$this->status];
This works only if status contains exactly one flag, i.e., no combination.
Since your $status can be combined bits (e.g., Active + Locked), this would not work correctly for combined flags (like 12).
Either remove this method or document it only works on single-flag statuses.
Alternatively, rewrite it to handle bitwise flag combinations like getStatusLabel().
In getStatusForCheckboxes()
User
resend the code how you would refactor it, with notes. complete code.
Assistant
Certainly! Below is a refactored and documented version of your User class with improvements for readability, slight code cleanup, and comments explaining key points. I also fixed getStatusList() to work only with single flags or return a fallback, and simplified getStatusForCheckboxes(). The key validation and logic remain unchanged.
php
User
why do i need:
/**
* Stub for adding error (simulate Yii model error adding).
*
* Replace with Yii's actual addError() method in your class.
*
* @param string attribute∗@paramstringmessage
*/
protected function addError(string attribute,stringmessage): void
{
// Example implementation, adapt as needed per your environment
echo "Validation error on {attribute}: {message}\n";
}
Assistant
Good question!
Why do you need the addError() stub in the standalone class?
Your validateStatus() method calls $this->addError($attribute, $message) to record validation failures.
In Yii framework’s Model or ActiveRecord classes, addError() is provided by the parent class and manages validation errors properly (collects errors that can be accessed later).
But if you use this User class outside of Yii’s Model system (like a plain PHP class or in a test without Model inheritance), there is no built-in addError() method.
So:
Including this stub method prevents fatal errors (like “call to undefined method addError()”) if you instantiate and call validateStatus() on the class standalone, e.g., for unit testing or demonstration.
It lets you simulate what would happen in a real Yii environment by outputting or logging the error.
You can replace or remove this stub when integrating the class inside Yii models where addError() already exists.
In summary:
The stub is there just to make the class self-contained and runnable outside Yii.
When used inside Yii Model or ActiveRecord subclass, you don’t need it — Yii provides addError().
So it’s optional and environment-dependent.
If you want, you can omit it if you’re sure the class is always used as part of Yii models!
User
i just dont understand
Assistant
No problem! Let me explain it in simpler terms:
What is addError()?
In Yii framework, when you create a model (for example, a User model), Yii automatically gives your model a function called addError().
This function is used to tell Yii that something is wrong with one of the model’s fields (like “status” in your code).
When you call $this->addError('status', 'Invalid status'), Yii remembers this error and later you can show it to the user.
Why does your code call $this->addError()?
Because you want to tell Yii “Hey, there is a problem with this attribute” during validation. Yii expects that method.
But what if your class doesn't inherit from Yii model?
If your User class is just a simple PHP class and does NOT extend Yii’s model or active record classes that already have addError(), then:
PHP will say: “Fatal error: Call to undefined method User::addError()”
because it can’t find that function.
That’s why I added a small "stub" method:
php
protected function addError(string $attribute, string $message): void
{
echo "Validation error on {$attribute}: {$message}\n";
}
This is a simple stand-in so the code runs without error outside Yii.
Instead of actually saving the error, it just prints a message so you can see something happened.
In real Yii apps, you don’t need this method because:
It’s already included in the base classes.
Yii handles the errors properly for you.
Summary for you:
Situation
Do you need this addError() stub?
Using User in a full Yii app
NO — Yii provides it automatically
Using User as standalone PHP class without Yii
YES — to avoid errors during validation
Let me know if you want me to explain how Yii validation works or if you want help integrating this class into Yii!
User
Lets work on the product model now, similar to User model:
code
Assistant
Your code is mostly solid and follows a similar pattern to the User model bitflag handling. However, there are a few issues and improvements I'd recommend:
Issues & suggestions:
rules() - Default for purchase_options is an array, but the property is an int
public function addPurchaseOptions(int $options): void
{
$this->purchase_options |= $options;
}
public function addPurchaseOptions(int $options): void
{
$this->purchase_options |= $options;
}
Remove one of them. It's duplicated.
Method naming for getters
Your boolean checking methods are currently named like getters but return bool:
php
public function getCart(): bool
This could be confusing, consider renaming to:
php
public function isCart(): bool
public function isInquire(): bool
public function isBuynow(): bool
to follow common naming conventions for booleans.
Naming consistency
User
"If you want, I can help you with a full refactored class including docblocks and comments similar to the User model example I provided earlier!"
yes
Assistant
Certainly! Below is a fully refactored Product model class following your requirements, incorporating bitflag purchase options, proper validation, descriptive docblocks, and clean method naming consistent with the User example previously shared.
php
User
do i not need parent::__construct($config); for the yii2 model construct?
Assistant
Yes, exactly! If your Product model extends Yii2’s Model or ActiveRecord, you generally should include a constructor like this:
php
public function __construct(array $config = [])
{
parent::__construct($config);
// Your own initialization (if any)
}
Why?
Yii2’s base Model or ActiveRecord classes expect the constructor to receive a config array.
This config is used to populate the model’s properties (mass assignment).
Calling parent::__construct($config) ensures that Yii properly populates model attributes and does any initialization needed by the framework.
Omitting the call can break core Yii features or behaviors.
Example:
php
class Product extends \yii\base\Model
{
public int $purchase_options = self::PURCHASE_OPTIONS_CART | self::PURCHASE_OPTIONS_INQUIRE;
public function __construct(array $config = [])
{
parent::__construct($config);
// additional init code here if needed
}
// ...
}
Summary
If your class does not extend Yii's Model, you can use a simpler or no constructor.
If your class extends Yii Model or ActiveRecord, always include the constructor with parent::__construct($config) to maintain Yii initialization.
Use property default values (like $purchase_options = ...) to set defaults unless you need dynamic setup.
Let me know if you want me to adjust the full code example assuming the class extends Yii Model!
but this is all you suggested? so is my user model contruct right too?!
Assistant
Great question!
Your concern:
You have a custom constructor in the Product model:
php
public function __construct(?int $purchaseOptions = null)
{
$this->purchase_options = $purchaseOptions ?? (self::PURCHASE_OPTIONS_CART | self::PURCHASE_OPTIONS_INQUIRE);
}
but you’re wondering if this is enough or correct—especially when comparing to the User model constructor, or when extending Yii’s Model.
Important distinctions:
1. Is your class extending Yii Model/ActiveRecord?
If YES:
Your constructor must call parent::__construct($config) to let Yii initialize the model properly.
The constructor signature must accept an optional config array, e.g.:
php
public function __construct(array $config = [])
{
parent::__construct($config);
// your initialization here
}
Setting defaults is usually better done directly on the property or using Yii’s default validation rule.
For example:
php
public int $purchase_options = self::PURCHASE_OPTIONS_CART | self::PURCHASE_OPTIONS_INQUIRE;
2. If your class does NOT extend Yii Model
Custom constructors like yours are fine because you control everything.
You don’t need to handle Yii’s $config array or call a parent constructor.
So specifically:
The constructor I gave you for Product is a simplified version assuming no Yii inheritance.
Your User model similarly should not have a constructor or if it does, it needs to call parent::__construct($config) if it extends Yii Model.
How to handle defaults best practice in Yii:
User
class User extends ActiveRecord implements IdentityInterface, IpRateLimitInterface
{
}
and
class Product extends ActiveRecord
{
}
Assistant
Thanks for clarifying — since both User and Product extend ActiveRecord, and in Yii2 ActiveRecord extends Model which has its own constructor expecting a config array, you should do the following:
1. Use default property values to set defaults, not the constructor
Set defaults directly in property declarations:
php
class Product extends ActiveRecord
{
public int $purchase_options = self::PURCHASE_OPTIONS_CART | self::PURCHASE_OPTIONS_INQUIRE;
// ...
}
Similarly for User:
php
class User extends ActiveRecord implements IdentityInterface, IpRateLimitInterface
{
public int $status = self::STATUS_INACTIVE;
// ...
}
2. Override the constructor only if needed, and call parent::__construct($config)
If you need a constructor, this is the correct pattern:
php
public function __construct(array $config = [])
{
parent::__construct($config);
// Your own initialization here only if needed
}
If you don’t need extra initialization, don’t override the constructor at all — default ActiveRecord behavior is perfect.
3. Avoid setting defaults inside the constructor
Why? Because Yii’s ActiveRecord accepts $config to mass assign attributes during instantiation:
php
$user = new User(['status' => User::STATUS_ACTIVE]);
If you override the constructor and set $this->status = ...without checking $config, you might accidentally override values passed on instantiation.
4. Validation rules handle defaults gracefully
Use rules like this to set default attribute values after instantiation but before validation/save:
php
User
Order status:
Order cannot have both cancellation and canceled statuses.
Order cannot be both completed and in cancellation.
Shipped orders cannot be canceled.
I think im missing code for order to work like how User works and Product, can you help? fill in the gaps, fixs any issues.
Resend complete refactored fully working code.
code
Assistant
Certainly! I've refactored and completed your Order class to work consistently with your User and Product models, enforcing the rules you described and implementing full bitflag management, validation, labels, and helper methods.
php
User
code
Assistant
Certainly! Your current Message class has some duplicate constants, syntax errors, and a quite complex getStatusForCheckboxes() method that can be simplified. Also, you want getters and setters and a complete functioning bitflag system similar to your other models.
Here's a refactored, complete, fully functional Message model class with proper constants, validation, bitflag handling, getters, setters, and fixes for your issues:
php
Not yet included in a published release.
Explanation
If Deleted is set → immediately return [Deleted].
Otherwise, check if Active is set → return [Active] plus Locked if present.
Else check if Inactive is set → return [Inactive] plus Locked if present.
No combinations beyond these will be returned.
Enforces exclusivity and no mixing of Active & Inactive here.
Example Status and Output
$this->status value
Returned array from getStatusForCheckboxes()
Meaning
0b0001 (Deleted)
[1]
Deleted only
0b0100 (Active)
[4]
Active only
0b1100 (Active + Locked)
[4, 8]
Active & Locked
0b0010 (Inactive)
[2]
Inactive only
0b1010 (Inactive + Locked)
[2, 8]
Inactive & Locked
0b1000 (Locked only)
[]
Invalid, returns empty in this logic
Optional: If Locked is set without Active/Inactive (invalid per your logic), I return empty array.
If you want to handle such cases differently (e.g., add validation errors), you can do so accordingly.
If you want me to help you test this or integrate validation logic here, just ask!
class User
{
public const STATUS_DELETED = 1;// 0b0001
public const STATUS_INACTIVE = 2;// 0b0010
public const STATUS_ACTIVE = 4;// 0b0100
public const STATUS_LOCKED = 8;// 0b1000
public function rules(): array
{
return [
['status', 'default', 'value' => self::STATUS_INACTIVE],
['status', 'validateStatus'],
];
}
public function validateStatus(string $attribute, array $params): void
{
$validFlags = self::STATUS_DELETED | self::STATUS_INACTIVE | self::STATUS_ACTIVE |
self::STATUS_LOCKED;
// If any bit outside validFlags is set, invalid
if (($this->$attribute & ~$validFlags) !== 0)
{
$this->addError($attribute, 'Status contains invalid flags.');
return;
}
// Deleted must be exclusive (only DELETED bit set)
if ($this->isDeleted() && $this->status !== self::STATUS_DELETED)
{
$this->addError($attribute, 'Deleted user cannot have other statuses.');
}
// Active and Inactive cannot coexist
if ($this->isActive() && $this->isInactive())
{
$this->addError($attribute, 'User cannot be both active and inactive.');
}
}
public static function getStatusLabels(): array
{
return [
self::STATUS_LOCKED => \Yii::t('app', 'Locked'),
self::STATUS_DELETED => \Yii::t('app', 'Deleted'),
self::STATUS_INACTIVE => \Yii::t('app', 'Inactive'),
self::STATUS_ACTIVE => \Yii::t('app', 'Active'),
];
}
public function getStatusLabel(): string
{
$labels = [];
foreach (self::getStatusLabels() as $bit => $label)
{
if ($this->hasStatus($bit))
{
$labels[] = $label;
}
}
return empty($labels) ? \Yii::t('app', 'Unknown') : implode(', ', $labels);
}
// or...
public function getStatusList(): string
{
$statuses = self::getStatusLabels();
return $statuses[$this->status];
}
public function getStatusForCheckboxes(): array
{
$activeOptions = [];
// Deleted is exclusive - if set, return Deleted only
if ($this->hasStatus(self::STATUS_DELETED))
{
return [self::STATUS_DELETED];
}
// Only one of Active or Inactive can be set (validation enforces this)
if ($this->hasStatus(self::STATUS_ACTIVE))
{
$activeOptions[] = self::STATUS_ACTIVE;
// Locked can appear with Active
if ($this->hasStatus(self::STATUS_LOCKED))
{
$activeOptions[] = self::STATUS_LOCKED;
}
return $activeOptions;
}
if ($this->hasStatus(self::STATUS_INACTIVE))
{
$activeOptions[] = self::STATUS_INACTIVE;
// Locked can appear with Active
if ($this->hasStatus(self::STATUS_LOCKED))
{
$activeOptions[] = self::STATUS_LOCKED;
}
return $activeOptions;
}
// If none of the above status bits are set, return empty array
// or you can choose to return null or throw an error based on your use case
return [];
}
public function setStatusFromCheckboxes(array $checkboxes): void
{
$this->status = 0;
foreach ($checkboxes as $value)
{
$this->addStatus((int) $value);
}
}
public function hasStatus(int $status): bool
{
return ($this->status & $status) === $status;
}
public function addStatus(int $status): void
{
$this->status |= $status;
}
public function removeStatus(int $status): void
{
$this->status &= ~$status;
}
public function isDeleted(): bool
{
return $this->hasStatus(self::STATUS_DELETED);
}
public function isInactive(): bool
{
return $this->hasStatus(self::STATUS_INACTIVE);
}
public function isActive(): bool
{
return $this->hasStatus(self::STATUS_ACTIVE);
}
public function isLocked(): bool
{
return $this->hasStatus(self::STATUS_LOCKED);
}
public function deleteAccount(): void
{
$this->status = self::STATUS_DELETED;
}
public function activateAccount(): void
{
$this->addStatus(self::STATUS_ACTIVE);
$this->removeStatus(self::STATUS_INACTIVE);
}
public function deactivateAccount(): void
{
$this->addStatus(self::STATUS_INACTIVE);
$this->removeStatus(self::STATUS_ACTIVE);
}
public function lockAccount(): void
{
$this->addStatus(self::STATUS_LOCKED);
}
public function unlockAccount(): void
{
$this->removeStatus(self::STATUS_LOCKED);
}
}
does all this look correct?
The comment "Locked can appear with Active" is duplicated in the Inactive branch.
Just style, but you could factor out the Locked check since it's the same in both places:
If you'd like, I can help you write unit tests or further refactor any parts!
<?php
class User
{
public const STATUS_DELETED = 1; // 0b0001
public const STATUS_INACTIVE = 2; // 0b0010
public const STATUS_ACTIVE = 4; // 0b0100
public const STATUS_LOCKED = 8; // 0b1000
/**
* The current status bit flags.
*
* @var int
*/
public int $status;
public function __construct(int $status = self::STATUS_INACTIVE)
{
$this->status = $status;
}
/**
* Declare validation rules (Yii-style)
*
* @return array
*/
public function rules(): array
{
return [
['status', 'default', 'value' => self::STATUS_INACTIVE],
['status', 'validateStatus'],
];
}
/**
* Validate the status flags.
*
* @param string $attribute
* @param array $params
*/
public function validateStatus(string $attribute, array $params): void
{
$validFlags = self::STATUS_DELETED | self::STATUS_INACTIVE | self::STATUS_ACTIVE | self::STATUS_LOCKED;
// Check for invalid bits outside validFlags
if (($this->$attribute & ~$validFlags) !== 0) {
$this->addError($attribute, 'Status contains invalid flags.');
return;
}
// Deleted must be exclusive (only Deleted bit set)
if ($this->isDeleted() && $this->status !== self::STATUS_DELETED) {
$this->addError($attribute, 'Deleted user cannot have other statuses.');
}
// Active and Inactive cannot coexist
if ($this->isActive() && $this->isInactive()) {
$this->addError($attribute, 'User cannot be both active and inactive.');
}
}
/**
* Returns an associative array of status bit => label,
* translated by Yii::t().
*
* @return array
*/
public static function getStatusLabels(): array
{
return [
self::STATUS_LOCKED => \Yii::t('app', 'Locked'),
self::STATUS_DELETED => \Yii::t('app', 'Deleted'),
self::STATUS_INACTIVE => \Yii::t('app', 'Inactive'),
self::STATUS_ACTIVE => \Yii::t('app', 'Active'),
];
}
/**
* Returns a comma-separated string of all current status labels.
*
* E.g. "Active, Locked"
*
* @return string
*/
public function getStatusLabel(): string
{
$labels = [];
foreach (self::getStatusLabels() as $bit => $label) {
if ($this->hasStatus($bit)) {
$labels[] = $label;
}
}
return empty($labels) ? \Yii::t('app', 'Unknown') : implode(', ', $labels);
}
/**
* Returns a single label for the current status.
* Only works if status has exactly one bit set.
* Otherwise, returns 'Unknown'.
*
* @return string
*/
public function getStatusList(): string
{
$statuses = self::getStatusLabels();
if (array_key_exists($this->status, $statuses)) {
return $statuses[$this->status];
}
return \Yii::t('app', 'Unknown');
}
/**
* Returns an array of status bits suitable for checkbox inputs.
*
* According to rules:
* - If Deleted is set, only Deleted is returned (exclusive).
* - Otherwise, return Active or Inactive (not both),
* optionally combined with Locked.
*
* @return int[]
*/
public function getStatusForCheckboxes(): array
{
// Deleted is exclusive; if set, return deleted only
if ($this->hasStatus(self::STATUS_DELETED)) {
return [self::STATUS_DELETED];
}
$activeOptions = [];
// Check for either Active or Inactive, only one allowed due to validation
if ($this->hasStatus(self::STATUS_ACTIVE)) {
$activeOptions[] = self::STATUS_ACTIVE;
} elseif ($this->hasStatus(self::STATUS_INACTIVE)) {
$activeOptions[] = self::STATUS_INACTIVE;
}
// Locked can appear with Active or Inactive
if (!empty($activeOptions) && $this->hasStatus(self::STATUS_LOCKED)) {
$activeOptions[] = self::STATUS_LOCKED;
}
return $activeOptions;
}
/**
* Set the status flags from an array of checkbox values.
*
* @param array $checkboxes Array of int flags
*/
public function setStatusFromCheckboxes(array $checkboxes): void
{
$this->status = 0;
foreach ($checkboxes as $value) {
$this->addStatus((int) $value);
}
}
/**
* Check if a specific status bit is set.
*
* @param int $flag
* @return bool
*/
public function hasStatus(int $flag): bool
{
return ($this->status & $flag) === $flag;
}
/**
* Adds a status bit flag.
*
* @param int $flag
*/
public function addStatus(int $flag): void
{
$this->status |= $flag;
}
/**
* Removes a status bit flag.
*
* @param int $flag
*/
public function removeStatus(int $flag): void
{
$this->status &= ~$flag;
}
/**
* Check if Deleted flag is set.
*
* @return bool
*/
public function isDeleted(): bool
{
return $this->hasStatus(self::STATUS_DELETED);
}
/**
* Check if Inactive flag is set.
*
* @return bool
*/
public function isInactive(): bool
{
return $this->hasStatus(self::STATUS_INACTIVE);
}
/**
* Check if Active flag is set.
*
* @return bool
*/
public function isActive(): bool
{
return $this->hasStatus(self::STATUS_ACTIVE);
}
/**
* Check if Locked flag is set.
*
* @return bool
*/
public function isLocked(): bool
{
return $this->hasStatus(self::STATUS_LOCKED);
}
/**
* Mark the account as Deleted (exclusive).
*/
public function deleteAccount(): void
{
$this->status = self::STATUS_DELETED;
}
/**
* Activate account (adding Active and removing Inactive).
*/
public function activateAccount(): void
{
$this->addStatus(self::STATUS_ACTIVE);
$this->removeStatus(self::STATUS_INACTIVE);
}
/**
* Deactivate account (adding Inactive and removing Active).
*/
public function deactivateAccount(): void
{
$this->addStatus(self::STATUS_INACTIVE);
$this->removeStatus(self::STATUS_ACTIVE);
}
/**
* Lock account (add Locked flag).
*/
public function lockAccount(): void
{
$this->addStatus(self::STATUS_LOCKED);
}
/**
* Unlock account (remove Locked flag).
*/
public function unlockAccount(): void
{
$this->removeStatus(self::STATUS_LOCKED);
}
/**
* Stub for adding error (simulate Yii model error adding).
*
* Replace with Yii's actual addError() method in your class.
*
* @param string $attribute
* @param string $message
*/
protected function addError(string $attribute, string $message): void
{
// Example implementation, adapt as needed per your environment
echo "Validation error on {$attribute}: {$message}\n";
}
}
Summary of changes and notes:
Constructor added to initialize status with the default (STATUS_INACTIVE).
getStatusList() fixed to correctly handle only single-bit statuses.
Simplified getStatusForCheckboxes() logic for clarity using early return for Deleted and combined Locked with Active/Inactive.
Added type declarations (PHP 7.4+ style).
Added docblocks for all methods and properties to clarify intent.
Added a stub for addError() to make the class somewhat runnable outside Yii.
Kept your validation and business rules intact.
Code comments added inline for clarity.
If you want, I can help you with:
Writing PHPUnit test cases for this class.
Integrating this with Yii2’s ActiveRecord or Model fully.
Extending status behavior or adding custom exceptions.
Just let me know!
/**
* Purchase Options can be:
* - Cart
* - Cart & Inquire
* - Inquire
* - Buy Now
* - Buy Now & Inquire
*/
const PURCHASE_OPTIONS_CART = 1;// 0b00001
const PURCHASE_OPTIONS_INQUIRE = 2;// 0b00010
const PURCHASE_OPTIONS_BUYNOW = 4;// 0b00100
// @var int Bitmask of purchase options
public int $purchase_options = 0;
public function rules(): array
{
return [
['purchase_options', 'default', 'value' => [
self::PURCHASE_OPTIONS_CART,
self::PURCHASE_OPTIONS_INQUIRE
]],
['status', 'validatePurchaseOptions'],
];
}
public function validatePurchaseOptions(string $attribute, array $params): void
{
$validFlags = self::PURCHASE_OPTIONS_CART | self::PURCHASE_OPTIONS_INQUIRE | self::PURCHASE_OPTIONS_BUYNOW;
// If any bit outside validFlags is set, invalid
if (($this->$attribute & ~$validFlags) !== 0)
{
$this->addError($attribute, 'Product options contains invalid flags.');
return;
}
// Cart and Buy Now cannot coexist
if ($this->isCart() && $this->isBuynow())
{
$this->addError($attribute, 'Product purchase option can not be in Cart and Buy Now.');
}
}
public function getPurchaseOptionsLabels(): array
{
return [
self::PURCHASE_OPTIONS_CART => \Yii::t('app', 'Cart'),
self::PURCHASE_OPTIONS_INQUIRE => \Yii::t('app', 'Inquire'),
self::PURCHASE_OPTIONS_BUYNOW => \Yii::t('app', 'Buy Now'),
];
}
public function getPurchaseOptionsForCheckboxes(): array
{
$activeOptions = [];
// Cart
if ($this->hasPurchaseOptions(self::PURCHASE_OPTIONS_CART))
{
$activeOptions[] = self::PURCHASE_OPTIONS_CART;
}
// Inquire
if ($this->hasPurchaseOptions(self::PURCHASE_OPTIONS_INQUIRE))
{
$activeOptions[] = self::PURCHASE_OPTIONS_INQUIRE;
}
// Buy Now
if ($this->hasPurchaseOptions(self::PURCHASE_OPTIONS_BUYNOW))
{
$activeOptions[] = self::PURCHASE_OPTIONS_BUYNOW ;
}
return $activeOptions;
}
public function setPurchaseOptionsFromCheckboxes(array $checkboxes): void
{
$this->purchase_options = 0;
foreach ($checkboxes as $value)
{
$this->addPurchaseOptions((int) $value);
}
}
public function addPurchaseOptions(int $options): void
{
$this->purchase_options |= $options;
}
public function addPurchaseOptions(int $options): void
{
$this->purchase_options |= $options;
}
public function hasPurchaseOptions(int $options): bool
{
return ($this->purchase_options & $options) === $options;
}
public function getCart(): bool
{
return $this->hasPurchaseOptions(self::PURCHASE_OPTIONS_CART);
}
public function getInquire(): bool
{
return $this->hasPurchaseOptions(self::PURCHASE_OPTIONS_INQUIRE);
}
public function getBuynow(): bool
{
return $this->hasPurchaseOptions(self::PURCHASE_OPTIONS_BUYNOW);
}
public function setCart(): void
{
$this->addPurchaseOptions(self::PURCHASE_OPTIONS_CART);
}
public function setInquire(): void
{
$this->addPurchaseOptions(self::PURCHASE_OPTIONS_INQUIRE);
}
public function setBuynow(): void
{
$this->addPurchaseOptions(self::PURCHASE_OPTIONS_BUYNOW);
}
does everything look correct
Properties use snake_case: $purchase_options
Methods use camelCase: addPurchaseOptions, hasPurchaseOptions
This is fine if consistent with your project, just be consistent elsewhere.
Validation message typo
You have:
php
$this->addError($attribute, 'Product purchase option can not be in Cart and Buy Now.');
Consider using consistent grammar:
"cannot" instead of "can not"
Also maybe say: "Product purchase options cannot include both Cart and Buy Now."
Logic in validatePurchaseOptions
Correctly disallow "Cart" and "Buy Now" together.
No check if none selected (0), consider adding this if needed.
Refactored snippet for fixes mentioned:
php
public const PURCHASE_OPTIONS_CART = 1; // 0b00001
public const PURCHASE_OPTIONS_INQUIRE = 2; // 0b00010
public const PURCHASE_OPTIONS_BUYNOW = 4; // 0b00100
// @var int Bitmask of purchase options
public int $purchase_options = 0;
public function rules(): array
{
return [
['purchase_options', 'default', 'value' => self::PURCHASE_OPTIONS_CART | self::PURCHASE_OPTIONS_INQUIRE],
['purchase_options', 'validatePurchaseOptions'],
];
}
public function validatePurchaseOptions(string $attribute, array $params): void
{
$validFlags = self::PURCHASE_OPTIONS_CART | self::PURCHASE_OPTIONS_INQUIRE | self::PURCHASE_OPTIONS_BUYNOW;
if (($this->$attribute & ~$validFlags) !== 0) {
$this->addError($attribute, 'Product options contain invalid flags.');
return;
}
if ($this->isCart() && $this->isBuynow()) {
$this->addError($attribute, 'Product purchase options cannot include both Cart and Buy Now.');
}
}
/** Labels... */
public function getPurchaseOptionsLabels(): array
{
return [
self::PURCHASE_OPTIONS_CART => \Yii::t('app', 'Cart'),
self::PURCHASE_OPTIONS_INQUIRE => \Yii::t('app', 'Inquire'),
self::PURCHASE_OPTIONS_BUYNOW => \Yii::t('app', 'Buy Now'),
];
}
/** Checkbox getters/setters */
public function getPurchaseOptionsForCheckboxes(): array
{
$activeOptions = [];
if ($this->hasPurchaseOptions(self::PURCHASE_OPTIONS_CART)) {
$activeOptions[] = self::PURCHASE_OPTIONS_CART;
}
if ($this->hasPurchaseOptions(self::PURCHASE_OPTIONS_INQUIRE)) {
$activeOptions[] = self::PURCHASE_OPTIONS_INQUIRE;
}
if ($this->hasPurchaseOptions(self::PURCHASE_OPTIONS_BUYNOW)) {
$activeOptions[] = self::PURCHASE_OPTIONS_BUYNOW;
}
return $activeOptions;
}
public function setPurchaseOptionsFromCheckboxes(array $checkboxes): void
{
$this->purchase_options = 0;
foreach ($checkboxes as $value) {
$this->addPurchaseOptions((int)$value);
}
}
public function addPurchaseOptions(int $options): void
{
$this->purchase_options |= $options;
}
public function hasPurchaseOptions(int $options): bool
{
return ($this->purchase_options & $options) === $options;
}
// Boolean isX methods (better naming)
public function isCart(): bool
{
return $this->hasPurchaseOptions(self::PURCHASE_OPTIONS_CART);
}
public function isInquire(): bool
{
return $this->hasPurchaseOptions(self::PURCHASE_OPTIONS_INQUIRE);
}
public function isBuynow(): bool
{
return $this->hasPurchaseOptions(self::PURCHASE_OPTIONS_BUYNOW);
}
// Convenience setters
public function setCart(): void
{
$this->addPurchaseOptions(self::PURCHASE_OPTIONS_CART);
}
public function setInquire(): void
{
$this->addPurchaseOptions(self::PURCHASE_OPTIONS_INQUIRE);
}
public function setBuynow(): void
{
$this->addPurchaseOptions(self::PURCHASE_OPTIONS_BUYNOW);
}
Summary
Fix your default value in rules to use bitwise OR, not an array.
Remove duplicate methods.
Rename boolean getters to isX() convention.
Tweak error messages for grammar.
Code style looks consistent and logical.
If you want, I can help you with a full refactored class including docblocks and comments similar to the User model example I provided earlier!
<?php
class Product
{
/**
* Purchase option bit flags.
*/
public const PURCHASE_OPTIONS_CART = 1; // 0b00001
public const PURCHASE_OPTIONS_INQUIRE = 2; // 0b00010
public const PURCHASE_OPTIONS_BUYNOW = 4; // 0b00100
/**
* Bitmask of purchase options currently set.
*
* @var int
*/
public int $purchase_options;
/**
* Constructor initializes purchase_options with default value.
*
* Default: Cart + Inquire selected.
*
* @param int|null $purchaseOptions Initial purchase options, defaults to Cart + Inquire.
*/
public function __construct(?int $purchaseOptions = null)
{
$this->purchase_options = $purchaseOptions ?? (self::PURCHASE_OPTIONS_CART | self::PURCHASE_OPTIONS_INQUIRE);
}
/**
* Returns validation rules (Yii style).
*
* @return array
*/
public function rules(): array
{
return [
['purchase_options', 'default', 'value' => self::PURCHASE_OPTIONS_CART | self::PURCHASE_OPTIONS_INQUIRE],
['purchase_options', 'validatePurchaseOptions'],
];
}
/**
* Validates purchase options:
* - Flags must be valid bits only.
* - Cart and Buy Now cannot coexist.
*
* @param string $attribute The attribute name to validate (usually "purchase_options").
* @param array $params Additional params (unused).
*/
public function validatePurchaseOptions(string $attribute, array $params): void
{
$validFlags = self::PURCHASE_OPTIONS_CART | self::PURCHASE_OPTIONS_INQUIRE | self::PURCHASE_OPTIONS_BUYNOW;
// Check for invalid flags (bits outside the known flags)
if (($this->$attribute & ~$validFlags) !== 0) {
$this->addError($attribute, 'Product options contain invalid flags.');
return;
}
// Cart and Buy Now cannot be selected together
if ($this->isCart() && $this->isBuynow()) {
$this->addError($attribute, 'Product purchase options cannot include both Cart and Buy Now.');
}
}
/**
* Returns an array of purchase option bit => translated label.
*
* @return array<int, string>
*/
public static function getPurchaseOptionsLabels(): array
{
return [
self::PURCHASE_OPTIONS_CART => \Yii::t('app', 'Cart'),
self::PURCHASE_OPTIONS_INQUIRE => \Yii::t('app', 'Inquire'),
self::PURCHASE_OPTIONS_BUYNOW => \Yii::t('app', 'Buy Now'),
];
}
/**
* Returns purchase options active as an array for checkboxes.
*
* @return int[]
*/
public function getPurchaseOptionsForCheckboxes(): array
{
$activeOptions = [];
if ($this->hasPurchaseOptions(self::PURCHASE_OPTIONS_CART)) {
$activeOptions[] = self::PURCHASE_OPTIONS_CART;
}
if ($this->hasPurchaseOptions(self::PURCHASE_OPTIONS_INQUIRE)) {
$activeOptions[] = self::PURCHASE_OPTIONS_INQUIRE;
}
if ($this->hasPurchaseOptions(self::PURCHASE_OPTIONS_BUYNOW)) {
$activeOptions[] = self::PURCHASE_OPTIONS_BUYNOW;
}
return $activeOptions;
}
/**
* Sets purchase options from array of bitflag values (e.g., from checkboxes).
*
* @param int[] $checkboxes Array of int bitflags.
*/
public function setPurchaseOptionsFromCheckboxes(array $checkboxes): void
{
$this->purchase_options = 0;
foreach ($checkboxes as $option) {
$this->addPurchaseOptions((int)$option);
}
}
/**
* Adds a purchase option bit flag.
*
* @param int $option Purchase option bit flag.
*/
public function addPurchaseOptions(int $option): void
{
$this->purchase_options |= $option;
}
/**
* Removes a purchase option bit flag.
*
* @param int $option Purchase option bit flag.
*/
public function removePurchaseOptions(int $option): void
{
$this->purchase_options &= ~$option;
}
/**
* Checks if specific purchase option(s) is set.
*
* @param int $option Purchase option bit flag(s).
* @return bool True if all given options are set.
*/
public function hasPurchaseOptions(int $option): bool
{
return ($this->purchase_options & $option) === $option;
}
/*
* Boolean getters for each purchase option.
*/
/**
* Checks if Cart option is active.
*
* @return bool
*/
public function isCart(): bool
{
return $this->hasPurchaseOptions(self::PURCHASE_OPTIONS_CART);
}
/**
* Checks if Inquire option is active.
*
* @return bool
*/
public function isInquire(): bool
{
return $this->hasPurchaseOptions(self::PURCHASE_OPTIONS_INQUIRE);
}
/**
* Checks if Buy Now option is active.
*
* @return bool
*/
public function isBuynow(): bool
{
return $this->hasPurchaseOptions(self::PURCHASE_OPTIONS_BUYNOW);
}
/*
* Convenience setters for each purchase option.
*/
/**
* Adds Cart option.
*/
public function setCart(): void
{
$this->addPurchaseOptions(self::PURCHASE_OPTIONS_CART);
}
/**
* Adds Inquire option.
*/
public function setInquire(): void
{
$this->addPurchaseOptions(self::PURCHASE_OPTIONS_INQUIRE);
}
/**
* Adds Buy Now option.
*/
public function setBuynow(): void
{
$this->addPurchaseOptions(self::PURCHASE_OPTIONS_BUYNOW);
}
/**
* Stub for adding validation error.
* Replace or remove when using inside Yii framework.
*
* @param string $attribute
* @param string $message
* @return void
*/
protected function addError(string $attribute, string $message): void
{
// Simple example output for standalone usage — replace in Yii model context.
echo "Validation error on {$attribute}: {$message}\n";
}
}
Explanation:
Bitflag constants defined to represent purchase options as powers of two.
$purchase_options is an int holding combined bitflags.
rules() returns Yii-style validation rules with default and custom validator method (validatePurchaseOptions).
validatePurchaseOptions() validates only valid bits and disallows Cart+Buy Now combination.
Helper methods to check if flags are set (isCart(), isBuynow(), etc.).
Helper methods to add/remove flags.
Method to convert bitflags to array for checkbox UI.
Method to set flags from array (e.g., form submission).
addError() stub to allow standalone use without Yii model.
If you integrate this into Yii one day:
Remove or override addError() method, Yii models already provide it.
Optionally extend yii\base\Model or ActiveRecord.
You may want to add localized attribute labels and messages if needed.
Feel free to ask if you'd like me to help with:
Unit tests for this class.
Integration examples with Yii.
Extending with more purchase options or other features.
Happy to help!
Avoid setting defaults in the constructor.
Set defaults on property declaration:
php
public int $purchase_options = self::PURCHASE_OPTIONS_CART | self::PURCHASE_OPTIONS_INQUIRE;
Or use Yii’s validation rule 'default'.
Let Yii instantiate the model with new Product() or new Product($config)—Yii sets attributes automatically.
Example Yii2-style Product model constructor:
php
class Product extends \yii\base\Model
{
public int $purchase_options = self::PURCHASE_OPTIONS_CART | self::PURCHASE_OPTIONS_INQUIRE;
public function __construct(array $config = [])
{
parent::__construct($config);
// Any other init code here, but avoid overwriting purchase_options here as config does it
}
}
Summary:
Scenario
Constructor recommended?
Yii2 Model/ActiveRecord
Yes, with parent::__construct($config). Use property defaults or rules for default values.
Plain PHP class (no inheritance)
Yes/no — depends on your design, your current Product constructor is fine.
Action points for you:
If your User and Product extend Yii Model or ActiveRecord, add/keep constructor with parent::__construct($config)and set default values on properties or with rules—don't override in constructor.
If you use plain PHP classes, your Product constructor is fine as is and User model constructor (if any) should match your needs.
If you want, I can refactor your User and Product classes fully assuming Yii inheritance and best practices with defaults set at the property level and correct constructors! Just ask.
public function rules()
{
return [
['status', 'default', 'value' => self::STATUS_INACTIVE],
['status', 'validateStatus'],
// other rules...
];
}
Same for purchase_options in Product:
php
public function rules()
{
return [
['purchase_options', 'default', 'value' => self::PURCHASE_OPTIONS_CART | self::PURCHASE_OPTIONS_INQUIRE],
['purchase_options', 'validatePurchaseOptions'],
// other rules...
];
}
Summary
Do not override the constructor unless necessary.
If you do override it, always call parent::__construct($config) first.
Use property declarations or validation rules to set default values.
This is the standard pattern in Yii2 ActiveRecord models.
Example of minimal correct constructor with defaults on property (recommended):
php
class User extends ActiveRecord implements IdentityInterface, IpRateLimitInterface
{
public int $status = self::STATUS_INACTIVE;
public function rules()
{
return [
['status', 'default', 'value' => self::STATUS_INACTIVE],
['status', 'validateStatus'],
// other rules...
];
}
// No constructor needed unless you have extra initialization.
}
If you want, I can help you rewrite your full User and Product classes following this Yii best practice style. Just say the word!
class Order extends ActiveRecord
{
const STATUS_PROCESSING = 1;// 0b00000001
const STATUS_PAID = 2;// 0b00000010
const STATUS_FAILED = 4;// 0b00000100
const STATUS_SHIPPED = 8;// 0b00001000
const STATUS_COMPLETED = 16;// 0b00010000
const STATUS_CANCELLATION = 32;// 0b00100000
const STATUS_CANCELED = 64;// 0b01000000
const STATUS_REFUND = 128;// 0b10000000
public function rules(): array
{
return [
['status', 'default', 'value' => self::STATUS_PROCESSING],
['status', 'validateStatus'],
];
}
public function validateStatus(string $attribute, array $params): void
{
$validFlags = self::STATUS_PROCESSING | self::STATUS_PAID | self::STATUS_FAILED | self::STATUS_SHIPPED |
self::STATUS_COMPLETED | self::STATUS_CANCELLATION | self::STATUS_CANCELED | self::STATUS_REFUND;
// If any bit outside validFlags is set, invalid
if (($this->$attribute & ~$validFlags) !== 0)
{
$this->addError($attribute, 'Status contains invalid flags.');
return;
}
$cancellationAndCanceled = self::STATUS_CANCELLATION | self::STATUS_CANCELED;
if (($this->status & $cancellationAndCanceled) === $cancellationAndCanceled)
{
$this->addError($attribute, "Order cannot have both cancellation and canceled statuses.");
}
$completedAndCancellation = self::STATUS_COMPLETED | self::STATUS_CANCELLATION;
if (($this->status & $completedAndCancellation) === $completedAndCancellation)
{
$this->addError($attribute, "Order cannot be both completed and in cancellation.");
}
$shippedAndCanceled = self::STATUS_SHIPPED | self::STATUS_CANCELED;
if (($this->status & $shippedAndCanceled) === $shippedAndCanceled) {
$this->addError($attribute, "Shipped orders cannot be canceled.");
}
}
public function getStatusLabel(): string
{
$labels = [];
foreach (self::getStatusLabels() as $bit => $label)
{
if ($this->hasStatus($bit))
{
$labels[] = $label;
}
}
return empty($labels) ? \Yii::t('app', 'Unknown') : implode(', ', $labels);
}
public function getStatusList(): string
{
$statuses = self::getStatusLabels();
return $statuses[$this->status];
}
public function getStatusForCheckboxes(): array
{
$activeStatuses = [];
}
public function setStatusFromCheckboxes(array $checkboxes): void
{
$this->status = 0;
foreach ($checkboxes as $value)
{
$this->addStatus((int) $value);
}
}
public function hasStatus(int $status): bool
{
return ($this->status & $status) === $status;
}
public function addStatus(int $status): void
{
$this->status |= $status;
}
public function removeStatus(int $status): void
{
$this->status &= ~$status;
}
}
<?php
use yii\db\ActiveRecord;
class Order extends ActiveRecord
{
public const STATUS_PROCESSING = 1; // 0b00000001
public const STATUS_PAID = 2; // 0b00000010
public const STATUS_FAILED = 4; // 0b00000100
public const STATUS_SHIPPED = 8; // 0b00001000
public const STATUS_COMPLETED = 16; // 0b00010000
public const STATUS_CANCELLATION = 32; // 0b00100000
public const STATUS_CANCELED = 64; // 0b01000000
public const STATUS_REFUND = 128; // 0b10000000
/**
* @var int Bitmask of order status flags.
*/
public int $status = self::STATUS_PROCESSING;
/**
* Validation rules.
*
* @return array
*/
public function rules(): array
{
return [
['status', 'default', 'value' => self::STATUS_PROCESSING],
['status', 'validateStatus'],
];
}
/**
* Validate the status flags.
*
* @param string $attribute attribute name
* @param array $params additional params
*/
public function validateStatus(string $attribute, array $params): void
{
$validFlags = self::STATUS_PROCESSING | self::STATUS_PAID | self::STATUS_FAILED |
self::STATUS_SHIPPED | self::STATUS_COMPLETED | self::STATUS_CANCELLATION |
self::STATUS_CANCELED | self::STATUS_REFUND;
// Check for invalid bits
if (($this->$attribute & ~$validFlags) !== 0) {
$this->addError($attribute, 'Status contains invalid flags.');
return;
}
// Rule: Order cannot have both cancellation and canceled statuses
$cancellationAndCanceled = self::STATUS_CANCELLATION | self::STATUS_CANCELED;
if (($this->status & $cancellationAndCanceled) === $cancellationAndCanceled) {
$this->addError($attribute, "Order cannot have both cancellation and canceled statuses.");
}
// Rule: Order cannot be both completed and in cancellation
$completedAndCancellation = self::STATUS_COMPLETED | self::STATUS_CANCELLATION;
if (($this->status & $completedAndCancellation) === $completedAndCancellation) {
$this->addError($attribute, "Order cannot be both completed and in cancellation.");
}
// Rule: Shipped orders cannot be canceled
$shippedAndCanceled = self::STATUS_SHIPPED | self::STATUS_CANCELED;
if (($this->status & $shippedAndCanceled) === $shippedAndCanceled) {
$this->addError($attribute, "Shipped orders cannot be canceled.");
}
}
/**
* Returns an array of status flags and their labels.
*
* @return array<int, string>
*/
public static function getStatusLabels(): array
{
return [
self::STATUS_PROCESSING => \Yii::t('app', 'Processing'),
self::STATUS_PAID => \Yii::t('app', 'Paid'),
self::STATUS_FAILED => \Yii::t('app', 'Failed'),
self::STATUS_SHIPPED => \Yii::t('app', 'Shipped'),
self::STATUS_COMPLETED => \Yii::t('app', 'Completed'),
self::STATUS_CANCELLATION => \Yii::t('app', 'Cancellation'),
self::STATUS_CANCELED => \Yii::t('app', 'Canceled'),
self::STATUS_REFUND => \Yii::t('app', 'Refund'),
];
}
/**
* Returns a comma-separated string of all current status labels.
*
* @return string
*/
public function getStatusLabel(): string
{
$labels = [];
foreach (self::getStatusLabels() as $bit => $label) {
if ($this->hasStatus($bit)) {
$labels[] = $label;
}
}
return empty($labels) ? \Yii::t('app', 'Unknown') : implode(', ', $labels);
}
/**
* Attempts to return single status label matching exactly current status.
* Falls back to "Unknown" if no exact match or multiple flags are set.
*
* @return string
*/
public function getStatusList(): string
{
$statuses = self::getStatusLabels();
return $statuses[$this->status] ?? \Yii::t('app', 'Unknown');
}
/**
* Returns array of active status flags for checkboxes.
*
* No exclusivity enforced here; validation step forbids invalid combos.
*
* @return int[]
*/
public function getStatusForCheckboxes(): array
{
$activeStatuses = [];
foreach (self::getStatusLabels() as $flag => $label) {
if ($this->hasStatus($flag)) {
$activeStatuses[] = $flag;
}
}
return $activeStatuses;
}
/**
* Sets status flags from checkbox array.
*
* @param int[] $checkboxes array of status flags
*/
public function setStatusFromCheckboxes(array $checkboxes): void
{
$this->status = 0;
foreach ($checkboxes as $value) {
$this->addStatus((int)$value);
}
}
/**
* Checks if a status flag or combination is set.
*
* @param int $status flag(s)
* @return bool whether all bits are set
*/
public function hasStatus(int $status): bool
{
return ($this->status & $status) === $status;
}
/**
* Adds a status flag by bitwise OR.
*
* @param int $status flag(s)
*/
public function addStatus(int $status): void
{
$this->status |= $status;
}
/**
* Removes a status flag by bitwise AND NOT.
*
* @param int $status flag(s)
*/
public function removeStatus(int $status): void
{
$this->status &= ~$status;
}
/*
* Convenience boolean getters for each status.
*/
public function isProcessing(): bool
{
return $this->hasStatus(self::STATUS_PROCESSING);
}
public function isPaid(): bool
{
return $this->hasStatus(self::STATUS_PAID);
}
public function isFailed(): bool
{
return $this->hasStatus(self::STATUS_FAILED);
}
public function isShipped(): bool
{
return $this->hasStatus(self::STATUS_SHIPPED);
}
public function isCompleted(): bool
{
return $this->hasStatus(self::STATUS_COMPLETED);
}
public function isCancellation(): bool
{
return $this->hasStatus(self::STATUS_CANCELLATION);
}
public function isCanceled(): bool
{
return $this->hasStatus(self::STATUS_CANCELED);
}
public function isRefund(): bool
{
return $this->hasStatus(self::STATUS_REFUND);
}
/*
* Convenience setters for statuses.
*/
public function setProcessing(): void
{
$this->addStatus(self::STATUS_PROCESSING);
}
public function setPaid(): void
{
$this->addStatus(self::STATUS_PAID);
}
public function setFailed(): void
{
$this->addStatus(self::STATUS_FAILED);
}
public function setShipped(): void
{
$this->addStatus(self::STATUS_SHIPPED);
}
public function setCompleted(): void
{
$this->addStatus(self::STATUS_COMPLETED);
}
public function setCancellation(): void
{
$this->addStatus(self::STATUS_CANCELLATION);
}
public function setCanceled(): void
{
$this->addStatus(self::STATUS_CANCELED);
}
public function setRefund(): void
{
$this->addStatus(self::STATUS_REFUND);
}
/**
* Stub for adding validation error.
* Remove or override if used within Yii ActiveRecord.
*
* @param string $attribute
* @param string $message
*/
protected function addError(string $attribute, string $message): void
{
// simple stand-in for standalone use
echo "Validation error on {$attribute}: {$message}\n";
}
}
Explanation and highlights:
Status constants defined as bitmask powers of two.
Validation disallows invalid bits and ensures your custom business rules on statuses.
getStatusLabel() returns combined, human-readable status string.
getStatusList() returns label for exact flag matches or "Unknown" otherwise.
getStatusForCheckboxes() returns all statuses that are set (useful for forms).
Helper hasStatus(), addStatus(), removeStatus() for bit manipulation.
Boolean isX() and setter setX() helpers for convenience.
Stub addError() just for standalone usage — in Yii this is provided by base model.
If you use this model inside Yii2 ActiveRecord:
You can remove or override the stub addError() method.
Validation errors will integrate fully into Yii's validation system.
Let me know if you want help with unit tests or integrating these rules into your forms/controllers!
class Message extends ActiveRecord
{
const STATUS_UNREAD = 1;// 0b00001
const STATUS_READ = 2;// 0b00010
const STATUS_IMPORTANT = 4;// 0b00100
const STATUS_RESOLVED = 8;// 0b01000
const STATUS_SPAM = 16;// 0b10000
const STATUS_ARCHIVED = 32;// 0b100000
const STATUS_FLAGGED = 64;// 0b110000
const STATUS_REPLIED = 128;// 0b10000000
const STATUS_UNREAD = 1;// 0b00001
const STATUS_READ = 2;// 0b00010
const STATUS_IMPORTANT = 4;// 0b00100
const STATUS_RESOLVED = 8;// 0b01000
const STATUS_SPAM = 16;// 0b10000
const STATUS_ARCHIVED = 32;// 0b100000
const STATUS_FLAGGED = 64;// 0b110000
const STATUS_REPLIED = 128;// 0b10000000
public int $status = self::STATUS_UNREAD;
public function validateStatus(string $attribute, array $params): void
{
$validFlags = self::STATUS_UNREAD | self::STATUS_READ | self::STATUS_IMPORTANT | self::STATUS_RESOLVED |
self::STATUS_SPAM | self::STATUS_ARCHIVED | self::STATUS_FLAGGED | self::STATUS_REPLIED;
// Check for invalid bits
if (($this->$attribute & ~$validFlags) !== 0)
{
$this->addError($attribute, 'Status contains invalid flags.');
return;
}
/**
* Unread and Read conflict.
*
$unreadAndRead = self::STATUS_UNREAD | self::STATUS_READ;
if (($this->status & $unreadAndRead) === ($unreadAndRead))
{
$this->addError($attribute, \Yii::t('app', 'Status cannot be both unread and read.'));
}//*/
// Important and Resolved conflict.
$importantAndResolved = self::STATUS_IMPORTANT | self::STATUS_RESOLVED;
if (($this->status & $importantAndResolved) === $importantAndResolved)
{
$this->addError($attribute, \Yii::t('app', 'Status cannot be both important and resolved.'));
}
// Important and Spam conflict.
if (($this->status & self::STATUS_IMPORTANT) && ($this->status & self::STATUS_SPAM))
{
$this->addError($attribute, \Yii::t('app', 'Status cannot be both important and spam.'));
}
// Resolved and Spam conflict.
if (($this->status & self::STATUS_RESOLVED) && ($this->status & self::STATUS_SPAM))
{
$this->addError($attribute, \Yii::t('app', 'Status cannot be both resolved and spam.'));
}
// Archived and Spam conflict.
if (($this->status & self::STATUS_ARCHIVED) && ($this->status & self::STATUS_SPAM))
{
$this->addError($attribute, \Yii::t('app', 'Status cannot be both archived and spam.'));
}
}
protected function addError(string $attribute, string $message): void
{
// Example implementation, adapt as needed per your environment
echo "Validation error on {$attribute}: {$message}\n";
}
public function getStatusLabels(): array
{
return [
//self::STATUS_UNREAD => \Yii::t('app', 'Unread'),// Handled within.
self::STATUS_READ => \Yii::t('app', 'Read'),
self::STATUS_IMPORTANT => \Yii::t('app', 'Important'),
self::STATUS_RESOLVED => \Yii::t('app', 'Resolved'),
self::STATUS_SPAM => \Yii::t('app', 'Spam'),
self::STATUS_ARCHIVED => \Yii::t('app', 'Archived'),
self::STATUS_FLAGGED => \Yii::t('app', 'Flagged'),
self::STATUS_REPLIED => \Yii::t('app', 'Replied'),
];
}
public function getStatusForCheckboxes(): array
{
$activeStatuses = [];
if ($this->hasStatus(self::STATUS_UNREAD) && !$this->hasStatus(self::STATUS_READ))
{
$activeStatuses[] = self::STATUS_UNREAD;
}
elseif (!$this->hasStatus(self::STATUS_UNREAD) && $this->hasStatus(self::STATUS_READ)
{
$activeStatuses[] = self::STATUS_READ;
}
if ($this->hasStatus(self::STATUS_IMPORTANT) && !$this->hasStatus(self::STATUS_RESOLVED))
{
$activeStatuses[] = self::STATUS_IMPORTANT;
}
elseif (!$this->hasStatus(self::STATUS_IMPORTANT) && $this->hasStatus(self::STATUS_RESOLVED))
{
$activeStatuses[] = self::STATUS_RESOLVED;
}
if ($this->hasStatus(self::STATUS_IMPORTANT) && !$this->hasStatus(self::STATUS_SPAM))
{
$activeStatuses[] = self::STATUS_IMPORTANT;
}
elseif (!$this->hasStatus(self::STATUS_IMPORTANT) && $this->hasStatus(self::STATUS_SPAM))
{
$activeStatuses[] = self::STATUS_SPAM;
}
if ($this->hasStatus(self::STATUS_RESOLVED) && !$this->hasStatus(self::STATUS_SPAM))
{
$activeStatuses[] = self::STATUS_RESOLVED;
}
elseif (!$this->hasStatus(self::STATUS_RESOLVED) && $this->hasStatus(self::STATUS_SPAM))
{
$activeStatuses[] = self::STATUS_SPAM;
}
if ($this->hasStatus(self::STATUS_ARCHIVED) && !$this->hasStatus(self::STATUS_SPAM))
{
$activeStatuses[] = self::STATUS_ARCHIVED;
}
elseif (!$this->hasStatus(self::STATUS_ARCHIVED) && $this->hasStatus(self::STATUS_SPAM))
{
$activeStatuses[] = self::STATUS_SPAM;
}
if ($this->hasStatus(self::STATUS_FLAGGED))
{
$activeStatuses[] = self::STATUS_FLAGGED;
}
return $activeStatuses;
}
Need the getter and setter for the message model and anything else im missing, send complete fully functioning code.
<?php
use yii\db\ActiveRecord;
class Message extends ActiveRecord
{
public const STATUS_UNREAD = 1; // 0b00000001
public const STATUS_READ = 2; // 0b00000010
public const STATUS_IMPORTANT = 4; // 0b00000100
public const STATUS_RESOLVED = 8; // 0b00001000
public const STATUS_SPAM = 16; // 0b00010000
public const STATUS_ARCHIVED = 32; // 0b00100000
public const STATUS_FLAGGED = 64; // 0b01000000
public const STATUS_REPLIED = 128; // 0b10000000
/**
* @var int Bitmask of status flags.
*/
public int $status = self::STATUS_UNREAD;
/**
* Validation rules.
*
* @return array
*/
public function rules(): array
{
return [
['status', 'default', 'value' => self::STATUS_UNREAD],
['status', 'validateStatus'],
];
}
/**
* Validate the status flags.
*
* @param string $attribute
* @param array $params
*/
public function validateStatus(string $attribute, array $params): void
{
$validFlags = self::STATUS_UNREAD | self::STATUS_READ | self::STATUS_IMPORTANT | self::STATUS_RESOLVED |
self::STATUS_SPAM | self::STATUS_ARCHIVED | self::STATUS_FLAGGED | self::STATUS_REPLIED;
// Check invalid bits
if (($this->$attribute & ~$validFlags) !== 0) {
$this->addError($attribute, 'Status contains invalid flags.');
return;
}
// Unread and Read conflict
$unreadAndRead = self::STATUS_UNREAD | self::STATUS_READ;
if (($this->status & $unreadAndRead) === $unreadAndRead) {
$this->addError($attribute, 'Status cannot be both unread and read.');
}
// Important and Resolved conflict
$importantAndResolved = self::STATUS_IMPORTANT | self::STATUS_RESOLVED;
if (($this->status & $importantAndResolved) === $importantAndResolved) {
$this->addError($attribute, 'Status cannot be both important and resolved.');
}
// Important and Spam conflict
if ($this->hasStatus(self::STATUS_IMPORTANT) && $this->hasStatus(self::STATUS_SPAM)) {
$this->addError($attribute, 'Status cannot be both important and spam.');
}
// Resolved and Spam conflict
if ($this->hasStatus(self::STATUS_RESOLVED) && $this->hasStatus(self::STATUS_SPAM)) {
$this->addError($attribute, 'Status cannot be both resolved and spam.');
}
// Archived and Spam conflict
if ($this->hasStatus(self::STATUS_ARCHIVED) && $this->hasStatus(self::STATUS_SPAM)) {
$this->addError($attribute, 'Status cannot be both archived and spam.');
}
}
/**
* Returns array of status flags and their labels.
*
* @return array<int, string>
*/
public static function getStatusLabels(): array
{
return [
self::STATUS_UNREAD => \Yii::t('app', 'Unread'),
self::STATUS_READ => \Yii::t('app', 'Read'),
self::STATUS_IMPORTANT => \Yii::t('app', 'Important'),
self::STATUS_RESOLVED => \Yii::t('app', 'Resolved'),
self::STATUS_SPAM => \Yii::t('app', 'Spam'),
self::STATUS_ARCHIVED => \Yii::t('app', 'Archived'),
self::STATUS_FLAGGED => \Yii::t('app', 'Flagged'),
self::STATUS_REPLIED => \Yii::t('app', 'Replied'),
];
}
/**
* Get current status labels as comma separated string.
*
* @return string
*/
public function getStatusLabel(): string
{
$labels = [];
foreach (self::getStatusLabels() as $flag => $label) {
if ($this->hasStatus($flag)) {
$labels[] = $label;
}
}
return empty($labels) ? \Yii::t('app', 'Unknown') : implode(', ', $labels);
}
/**
* Returns an array of active status flags suitable for checkboxes.
*
* Enforces some mutual exclusions similar to your validation:
* For example, cannot have both unread and read, includes only one.
*
* @return int[]
*/
public function getStatusForCheckboxes(): array
{
$statuses = [];
// Mutually exclusive group: Unread or Read
if ($this->hasStatus(self::STATUS_UNREAD) && !$this->hasStatus(self::STATUS_READ)) {
$statuses[] = self::STATUS_UNREAD;
} elseif (!$this->hasStatus(self::STATUS_UNREAD) && $this->hasStatus(self::STATUS_READ)) {
$statuses[] = self::STATUS_READ;
}
// Mutually exclusive: Important or Resolved
if ($this->hasStatus(self::STATUS_IMPORTANT) && !$this->hasStatus(self::STATUS_RESOLVED)) {
$statuses[] = self::STATUS_IMPORTANT;
} elseif (!$this->hasStatus(self::STATUS_IMPORTANT) && $this->hasStatus(self::STATUS_RESOLVED)) {
$statuses[] = self::STATUS_RESOLVED;
}
// Only add Spam if it's not conflicting (important, resolved, archived)
// Spam conflicts are handled at validation, so just add if set
if ($this->hasStatus(self::STATUS_SPAM)) {
$statuses[] = self::STATUS_SPAM;
}
// Archived (not mutually exclusive with anything except spam, handled by validation)
if ($this->hasStatus(self::STATUS_ARCHIVED)) {
$statuses[] = self::STATUS_ARCHIVED;
}
// Flagged and Replied just add if set
if ($this->hasStatus(self::STATUS_FLAGGED)) {
$statuses[] = self::STATUS_FLAGGED;
}
if ($this->hasStatus(self::STATUS_REPLIED)) {
$statuses[] = self::STATUS_REPLIED;
}
return array_unique($statuses);
}
/**
* Set multiple statuses from an array (e.g. checkbox inputs).
*
* @param int[] $checkboxes
*/
public function setStatusFromCheckboxes(array $checkboxes): void
{
$this->status = 0;
foreach ($checkboxes as $flag) {
$this->addStatus((int)$flag);
}
}
/**
* Checks if specific status flag(s) are set.
*
* @param int $flag
* @return bool
*/
public function hasStatus(int $flag): bool
{
return ($this->status & $flag) === $flag;
}
/**
* Adds given status flag(s).
*
* @param int $flag
*/
public function addStatus(int $flag): void
{
$this->status |= $flag;
}
/**
* Removes given status flag(s).
*
* @param int $flag
*/
public function removeStatus(int $flag): void
{
$this->status &= ~$flag;
}
/*
* Convenience boolean status getters
*/
public function isUnread(): bool { return $this->hasStatus(self::STATUS_UNREAD); }
public function isRead(): bool { return $this->hasStatus(self::STATUS_READ); }
public function isImportant(): bool{ return $this->hasStatus(self::STATUS_IMPORTANT); }
public function isResolved(): bool { return $this->hasStatus(self::STATUS_RESOLVED); }
public function isSpam(): bool { return $this->hasStatus(self::STATUS_SPAM); }
public function isArchived(): bool { return $this->hasStatus(self::STATUS_ARCHIVED); }
public function isFlagged(): bool { return $this->hasStatus(self::STATUS_FLAGGED); }
public function isReplied(): bool { return $this->hasStatus(self::STATUS_REPLIED); }
/*
* Convenience setters
*/
public function setUnread(): void { $this->addStatus(self::STATUS_UNREAD); }
public function setRead(): void { $this->addStatus(self::STATUS_READ); }
public function setImportant(): void { $this->addStatus(self::STATUS_IMPORTANT); }
public function setResolved(): void { $this->addStatus(self::STATUS_RESOLVED); }
public function setSpam(): void { $this->addStatus(self::STATUS_SPAM); }
public function setArchived(): void { $this->addStatus(self::STATUS_ARCHIVED); }
public function setFlagged(): void { $this->addStatus(self::STATUS_FLAGGED); }
public function setReplied(): void { $this->addStatus(self::STATUS_REPLIED); }
/**
* Stub for addError to allow standalone validation.
* Remove if used inside Yii ActiveRecord model.
*
* @param string $attribute
* @param string $message
* @return void
*/
protected function addError(string $attribute, string $message): void
{
echo "Validation error on {$attribute}: {$message}\n";
}
}
Notes on improvements & fixes:
Duplicate constants removed and fixed binary comments.
getStatusForCheckboxes() simplified to avoid repeated mutually exclusive checks. It selects only one of mutually exclusive pairs (Unread vs Read, Important vs Resolved), always respects validation rules (which block invalid combos).
Convenience getters / setters added for all statuses.
Simplified validation error messages; assumes Yii::t translation function available.
The addError() stub allows standalone use but should be removed if integrated with Yii ActiveRecord since Yii provides it.
Property typed with default of Unread.
If you want, I can help integrate this with your forms, or write unit tests for correctness.